This commit is contained in:
parent
e7ed525da5
commit
4637a847ea
|
|
@ -1 +0,0 @@
|
||||||
../acorn/bin/acorn
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../atob/bin/atob.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../escodegen/bin/escodegen.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../escodegen/bin/esgenerate.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../handlebars/bin/handlebars
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../import-local/fixtures/cli.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../is-ci/bin.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../jest/bin/jest.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../jest-runtime/bin/jest-runtime.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../jsesc/bin/jsesc
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../json5/lib/cli.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../loose-envify/cli.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../mkdirp/bin/cmd.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../@babel/parser/bin/babel-parser.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../prettier/bin-prettier.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../rimraf/bin.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../sane/src/cli.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../semver/bin/semver
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
@IF EXIST "%~dp0\node.exe" (
|
|
||||||
"%~dp0\node.exe" "%~dp0\..\semver\bin\semver" %*
|
|
||||||
) ELSE (
|
|
||||||
@SETLOCAL
|
|
||||||
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
|
||||||
node "%~dp0\..\semver\bin\semver" %*
|
|
||||||
)
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../sshpk/bin/sshpk-conv
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../sshpk/bin/sshpk-sign
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../sshpk/bin/sshpk-verify
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../ts-jest/cli.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../typescript/bin/tsc
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../typescript/bin/tsserver
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../uglify-js/bin/uglifyjs
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../uuid/bin/uuid
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
@IF EXIST "%~dp0\node.exe" (
|
|
||||||
"%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %*
|
|
||||||
) ELSE (
|
|
||||||
@SETLOCAL
|
|
||||||
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
|
||||||
node "%~dp0\..\uuid\bin\uuid" %*
|
|
||||||
)
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../@cnakazawa/watch/cli.js
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../which/bin/which
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
@IF EXIST "%~dp0\node.exe" (
|
|
||||||
"%~dp0\node.exe" "%~dp0\..\which\bin\which" %*
|
|
||||||
) ELSE (
|
|
||||||
@SETLOCAL
|
|
||||||
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
|
||||||
node "%~dp0\..\which\bin\which" %*
|
|
||||||
)
|
|
||||||
|
|
@ -1,140 +0,0 @@
|
||||||
# `@actions/core`
|
|
||||||
|
|
||||||
> Core functions for setting results, logging, registering secrets and exporting variables across actions
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
### Import the package
|
|
||||||
|
|
||||||
```js
|
|
||||||
// javascript
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
// typescript
|
|
||||||
import * as core from '@actions/core';
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Inputs/Outputs
|
|
||||||
|
|
||||||
Action inputs can be read with `getInput`. Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const myInput = core.getInput('inputName', { required: true });
|
|
||||||
|
|
||||||
core.setOutput('outputKey', 'outputVal');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Exporting variables
|
|
||||||
|
|
||||||
Since each step runs in a separate process, you can use `exportVariable` to add it to this step and future steps environment blocks.
|
|
||||||
|
|
||||||
```js
|
|
||||||
core.exportVariable('envVar', 'Val');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Setting a secret
|
|
||||||
|
|
||||||
Setting a secret registers the secret with the runner to ensure it is masked in logs.
|
|
||||||
|
|
||||||
```js
|
|
||||||
core.setSecret('myPassword');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### PATH Manipulation
|
|
||||||
|
|
||||||
To make a tool's path available in the path for the remainder of the job (without altering the machine or containers state), use `addPath`. The runner will prepend the path given to the jobs PATH.
|
|
||||||
|
|
||||||
```js
|
|
||||||
core.addPath('/path/to/mytool');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Exit codes
|
|
||||||
|
|
||||||
You should use this library to set the failing exit code for your action. If status is not set and the script runs to completion, that will lead to a success.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Do stuff
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
// setFailed logs the message and sets a failing exit code
|
|
||||||
core.setFailed(`Action failed with error ${err}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
Note that `setNeutral` is not yet implemented in actions V2 but equivalent functionality is being planned.
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Logging
|
|
||||||
|
|
||||||
Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the [Step Debug Logs](../../docs/action-debugging.md#step-debug-logs).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
const myInput = core.getInput('input');
|
|
||||||
try {
|
|
||||||
core.debug('Inside try block');
|
|
||||||
|
|
||||||
if (!myInput) {
|
|
||||||
core.warning('myInput was not set');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do stuff
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
core.error(`Error ${err}, action may still succeed though`);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This library can also wrap chunks of output in foldable groups.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const core = require('@actions/core')
|
|
||||||
|
|
||||||
// Manually wrap output
|
|
||||||
core.startGroup('Do some function')
|
|
||||||
doSomeFunction()
|
|
||||||
core.endGroup()
|
|
||||||
|
|
||||||
// Wrap an asynchronous function call
|
|
||||||
const result = await core.group('Do something async', async () => {
|
|
||||||
const response = await doSomeHTTPRequest()
|
|
||||||
return response
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Action state
|
|
||||||
|
|
||||||
You can use this library to save state and get state for sharing information between a given wrapper action:
|
|
||||||
|
|
||||||
**action.yml**
|
|
||||||
```yaml
|
|
||||||
name: 'Wrapper action sample'
|
|
||||||
inputs:
|
|
||||||
name:
|
|
||||||
default: 'GitHub'
|
|
||||||
runs:
|
|
||||||
using: 'node12'
|
|
||||||
main: 'main.js'
|
|
||||||
post: 'cleanup.js'
|
|
||||||
```
|
|
||||||
|
|
||||||
In action's `main.js`:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
core.saveState("pidToKill", 12345);
|
|
||||||
```
|
|
||||||
|
|
||||||
In action's `cleanup.js`:
|
|
||||||
```js
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
var pid = core.getState("pidToKill");
|
|
||||||
|
|
||||||
process.kill(pid);
|
|
||||||
```
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
interface CommandProperties {
|
|
||||||
[key: string]: string;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Commands
|
|
||||||
*
|
|
||||||
* Command Format:
|
|
||||||
* ::name key=value,key=value::message
|
|
||||||
*
|
|
||||||
* Examples:
|
|
||||||
* ::warning::This is the message
|
|
||||||
* ::set-env name=MY_VAR::some value
|
|
||||||
*/
|
|
||||||
export declare function issueCommand(command: string, properties: CommandProperties, message: string): void;
|
|
||||||
export declare function issue(name: string, message?: string): void;
|
|
||||||
export {};
|
|
||||||
|
|
@ -1,78 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __importStar = (this && this.__importStar) || function (mod) {
|
|
||||||
if (mod && mod.__esModule) return mod;
|
|
||||||
var result = {};
|
|
||||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
|
||||||
result["default"] = mod;
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const os = __importStar(require("os"));
|
|
||||||
/**
|
|
||||||
* Commands
|
|
||||||
*
|
|
||||||
* Command Format:
|
|
||||||
* ::name key=value,key=value::message
|
|
||||||
*
|
|
||||||
* Examples:
|
|
||||||
* ::warning::This is the message
|
|
||||||
* ::set-env name=MY_VAR::some value
|
|
||||||
*/
|
|
||||||
function issueCommand(command, properties, message) {
|
|
||||||
const cmd = new Command(command, properties, message);
|
|
||||||
process.stdout.write(cmd.toString() + os.EOL);
|
|
||||||
}
|
|
||||||
exports.issueCommand = issueCommand;
|
|
||||||
function issue(name, message = '') {
|
|
||||||
issueCommand(name, {}, message);
|
|
||||||
}
|
|
||||||
exports.issue = issue;
|
|
||||||
const CMD_STRING = '::';
|
|
||||||
class Command {
|
|
||||||
constructor(command, properties, message) {
|
|
||||||
if (!command) {
|
|
||||||
command = 'missing.command';
|
|
||||||
}
|
|
||||||
this.command = command;
|
|
||||||
this.properties = properties;
|
|
||||||
this.message = message;
|
|
||||||
}
|
|
||||||
toString() {
|
|
||||||
let cmdStr = CMD_STRING + this.command;
|
|
||||||
if (this.properties && Object.keys(this.properties).length > 0) {
|
|
||||||
cmdStr += ' ';
|
|
||||||
let first = true;
|
|
||||||
for (const key in this.properties) {
|
|
||||||
if (this.properties.hasOwnProperty(key)) {
|
|
||||||
const val = this.properties[key];
|
|
||||||
if (val) {
|
|
||||||
if (first) {
|
|
||||||
first = false;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
cmdStr += ',';
|
|
||||||
}
|
|
||||||
cmdStr += `${key}=${escapeProperty(val)}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cmdStr += `${CMD_STRING}${escapeData(this.message)}`;
|
|
||||||
return cmdStr;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function escapeData(s) {
|
|
||||||
return (s || '')
|
|
||||||
.replace(/%/g, '%25')
|
|
||||||
.replace(/\r/g, '%0D')
|
|
||||||
.replace(/\n/g, '%0A');
|
|
||||||
}
|
|
||||||
function escapeProperty(s) {
|
|
||||||
return (s || '')
|
|
||||||
.replace(/%/g, '%25')
|
|
||||||
.replace(/\r/g, '%0D')
|
|
||||||
.replace(/\n/g, '%0A')
|
|
||||||
.replace(/:/g, '%3A')
|
|
||||||
.replace(/,/g, '%2C');
|
|
||||||
}
|
|
||||||
//# sourceMappingURL=command.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAwB;AAQxB;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAe;IAEf,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,UAAkB,EAAE;IACtD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;SACb,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAS;IAC/B,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;SACb,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"}
|
|
||||||
|
|
@ -1,112 +0,0 @@
|
||||||
/**
|
|
||||||
* Interface for getInput options
|
|
||||||
*/
|
|
||||||
export interface InputOptions {
|
|
||||||
/** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */
|
|
||||||
required?: boolean;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* The code to exit an action
|
|
||||||
*/
|
|
||||||
export declare enum ExitCode {
|
|
||||||
/**
|
|
||||||
* A code indicating that the action was successful
|
|
||||||
*/
|
|
||||||
Success = 0,
|
|
||||||
/**
|
|
||||||
* A code indicating that the action was a failure
|
|
||||||
*/
|
|
||||||
Failure = 1
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Sets env variable for this action and future actions in the job
|
|
||||||
* @param name the name of the variable to set
|
|
||||||
* @param val the value of the variable
|
|
||||||
*/
|
|
||||||
export declare function exportVariable(name: string, val: string): void;
|
|
||||||
/**
|
|
||||||
* Registers a secret which will get masked from logs
|
|
||||||
* @param secret value of the secret
|
|
||||||
*/
|
|
||||||
export declare function setSecret(secret: string): void;
|
|
||||||
/**
|
|
||||||
* Prepends inputPath to the PATH (for this action and future actions)
|
|
||||||
* @param inputPath
|
|
||||||
*/
|
|
||||||
export declare function addPath(inputPath: string): void;
|
|
||||||
/**
|
|
||||||
* Gets the value of an input. The value is also trimmed.
|
|
||||||
*
|
|
||||||
* @param name name of the input to get
|
|
||||||
* @param options optional. See InputOptions.
|
|
||||||
* @returns string
|
|
||||||
*/
|
|
||||||
export declare function getInput(name: string, options?: InputOptions): string;
|
|
||||||
/**
|
|
||||||
* Sets the value of an output.
|
|
||||||
*
|
|
||||||
* @param name name of the output to set
|
|
||||||
* @param value value to store
|
|
||||||
*/
|
|
||||||
export declare function setOutput(name: string, value: string): void;
|
|
||||||
/**
|
|
||||||
* Sets the action status to failed.
|
|
||||||
* When the action exits it will be with an exit code of 1
|
|
||||||
* @param message add error issue message
|
|
||||||
*/
|
|
||||||
export declare function setFailed(message: string): void;
|
|
||||||
/**
|
|
||||||
* Writes debug message to user log
|
|
||||||
* @param message debug message
|
|
||||||
*/
|
|
||||||
export declare function debug(message: string): void;
|
|
||||||
/**
|
|
||||||
* Adds an error issue
|
|
||||||
* @param message error issue message
|
|
||||||
*/
|
|
||||||
export declare function error(message: string): void;
|
|
||||||
/**
|
|
||||||
* Adds an warning issue
|
|
||||||
* @param message warning issue message
|
|
||||||
*/
|
|
||||||
export declare function warning(message: string): void;
|
|
||||||
/**
|
|
||||||
* Writes info to log with console.log.
|
|
||||||
* @param message info message
|
|
||||||
*/
|
|
||||||
export declare function info(message: string): void;
|
|
||||||
/**
|
|
||||||
* Begin an output group.
|
|
||||||
*
|
|
||||||
* Output until the next `groupEnd` will be foldable in this group
|
|
||||||
*
|
|
||||||
* @param name The name of the output group
|
|
||||||
*/
|
|
||||||
export declare function startGroup(name: string): void;
|
|
||||||
/**
|
|
||||||
* End an output group.
|
|
||||||
*/
|
|
||||||
export declare function endGroup(): void;
|
|
||||||
/**
|
|
||||||
* Wrap an asynchronous function call in a group.
|
|
||||||
*
|
|
||||||
* Returns the same type as the function itself.
|
|
||||||
*
|
|
||||||
* @param name The name of the group
|
|
||||||
* @param fn The function to wrap in the group
|
|
||||||
*/
|
|
||||||
export declare function group<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
|
||||||
/**
|
|
||||||
* Saves state for current action, the state can only be retrieved by this action's post job execution.
|
|
||||||
*
|
|
||||||
* @param name name of the state to store
|
|
||||||
* @param value value to store
|
|
||||||
*/
|
|
||||||
export declare function saveState(name: string, value: string): void;
|
|
||||||
/**
|
|
||||||
* Gets the value of an state set by this action's main execution.
|
|
||||||
*
|
|
||||||
* @param name name of the state to get
|
|
||||||
* @returns string
|
|
||||||
*/
|
|
||||||
export declare function getState(name: string): string;
|
|
||||||
|
|
@ -1,202 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importStar = (this && this.__importStar) || function (mod) {
|
|
||||||
if (mod && mod.__esModule) return mod;
|
|
||||||
var result = {};
|
|
||||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
|
||||||
result["default"] = mod;
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const command_1 = require("./command");
|
|
||||||
const os = __importStar(require("os"));
|
|
||||||
const path = __importStar(require("path"));
|
|
||||||
/**
|
|
||||||
* The code to exit an action
|
|
||||||
*/
|
|
||||||
var ExitCode;
|
|
||||||
(function (ExitCode) {
|
|
||||||
/**
|
|
||||||
* A code indicating that the action was successful
|
|
||||||
*/
|
|
||||||
ExitCode[ExitCode["Success"] = 0] = "Success";
|
|
||||||
/**
|
|
||||||
* A code indicating that the action was a failure
|
|
||||||
*/
|
|
||||||
ExitCode[ExitCode["Failure"] = 1] = "Failure";
|
|
||||||
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
// Variables
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
/**
|
|
||||||
* Sets env variable for this action and future actions in the job
|
|
||||||
* @param name the name of the variable to set
|
|
||||||
* @param val the value of the variable
|
|
||||||
*/
|
|
||||||
function exportVariable(name, val) {
|
|
||||||
process.env[name] = val;
|
|
||||||
command_1.issueCommand('set-env', { name }, val);
|
|
||||||
}
|
|
||||||
exports.exportVariable = exportVariable;
|
|
||||||
/**
|
|
||||||
* Registers a secret which will get masked from logs
|
|
||||||
* @param secret value of the secret
|
|
||||||
*/
|
|
||||||
function setSecret(secret) {
|
|
||||||
command_1.issueCommand('add-mask', {}, secret);
|
|
||||||
}
|
|
||||||
exports.setSecret = setSecret;
|
|
||||||
/**
|
|
||||||
* Prepends inputPath to the PATH (for this action and future actions)
|
|
||||||
* @param inputPath
|
|
||||||
*/
|
|
||||||
function addPath(inputPath) {
|
|
||||||
command_1.issueCommand('add-path', {}, inputPath);
|
|
||||||
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
|
|
||||||
}
|
|
||||||
exports.addPath = addPath;
|
|
||||||
/**
|
|
||||||
* Gets the value of an input. The value is also trimmed.
|
|
||||||
*
|
|
||||||
* @param name name of the input to get
|
|
||||||
* @param options optional. See InputOptions.
|
|
||||||
* @returns string
|
|
||||||
*/
|
|
||||||
function getInput(name, options) {
|
|
||||||
const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
|
|
||||||
if (options && options.required && !val) {
|
|
||||||
throw new Error(`Input required and not supplied: ${name}`);
|
|
||||||
}
|
|
||||||
return val.trim();
|
|
||||||
}
|
|
||||||
exports.getInput = getInput;
|
|
||||||
/**
|
|
||||||
* Sets the value of an output.
|
|
||||||
*
|
|
||||||
* @param name name of the output to set
|
|
||||||
* @param value value to store
|
|
||||||
*/
|
|
||||||
function setOutput(name, value) {
|
|
||||||
command_1.issueCommand('set-output', { name }, value);
|
|
||||||
}
|
|
||||||
exports.setOutput = setOutput;
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
// Results
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
/**
|
|
||||||
* Sets the action status to failed.
|
|
||||||
* When the action exits it will be with an exit code of 1
|
|
||||||
* @param message add error issue message
|
|
||||||
*/
|
|
||||||
function setFailed(message) {
|
|
||||||
process.exitCode = ExitCode.Failure;
|
|
||||||
error(message);
|
|
||||||
}
|
|
||||||
exports.setFailed = setFailed;
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
// Logging Commands
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
/**
|
|
||||||
* Writes debug message to user log
|
|
||||||
* @param message debug message
|
|
||||||
*/
|
|
||||||
function debug(message) {
|
|
||||||
command_1.issueCommand('debug', {}, message);
|
|
||||||
}
|
|
||||||
exports.debug = debug;
|
|
||||||
/**
|
|
||||||
* Adds an error issue
|
|
||||||
* @param message error issue message
|
|
||||||
*/
|
|
||||||
function error(message) {
|
|
||||||
command_1.issue('error', message);
|
|
||||||
}
|
|
||||||
exports.error = error;
|
|
||||||
/**
|
|
||||||
* Adds an warning issue
|
|
||||||
* @param message warning issue message
|
|
||||||
*/
|
|
||||||
function warning(message) {
|
|
||||||
command_1.issue('warning', message);
|
|
||||||
}
|
|
||||||
exports.warning = warning;
|
|
||||||
/**
|
|
||||||
* Writes info to log with console.log.
|
|
||||||
* @param message info message
|
|
||||||
*/
|
|
||||||
function info(message) {
|
|
||||||
process.stdout.write(message + os.EOL);
|
|
||||||
}
|
|
||||||
exports.info = info;
|
|
||||||
/**
|
|
||||||
* Begin an output group.
|
|
||||||
*
|
|
||||||
* Output until the next `groupEnd` will be foldable in this group
|
|
||||||
*
|
|
||||||
* @param name The name of the output group
|
|
||||||
*/
|
|
||||||
function startGroup(name) {
|
|
||||||
command_1.issue('group', name);
|
|
||||||
}
|
|
||||||
exports.startGroup = startGroup;
|
|
||||||
/**
|
|
||||||
* End an output group.
|
|
||||||
*/
|
|
||||||
function endGroup() {
|
|
||||||
command_1.issue('endgroup');
|
|
||||||
}
|
|
||||||
exports.endGroup = endGroup;
|
|
||||||
/**
|
|
||||||
* Wrap an asynchronous function call in a group.
|
|
||||||
*
|
|
||||||
* Returns the same type as the function itself.
|
|
||||||
*
|
|
||||||
* @param name The name of the group
|
|
||||||
* @param fn The function to wrap in the group
|
|
||||||
*/
|
|
||||||
function group(name, fn) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
startGroup(name);
|
|
||||||
let result;
|
|
||||||
try {
|
|
||||||
result = yield fn();
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
endGroup();
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.group = group;
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
// Wrapper action state
|
|
||||||
//-----------------------------------------------------------------------
|
|
||||||
/**
|
|
||||||
* Saves state for current action, the state can only be retrieved by this action's post job execution.
|
|
||||||
*
|
|
||||||
* @param name name of the state to store
|
|
||||||
* @param value value to store
|
|
||||||
*/
|
|
||||||
function saveState(name, value) {
|
|
||||||
command_1.issueCommand('save-state', { name }, value);
|
|
||||||
}
|
|
||||||
exports.saveState = saveState;
|
|
||||||
/**
|
|
||||||
* Gets the value of an state set by this action's main execution.
|
|
||||||
*
|
|
||||||
* @param name name of the state to get
|
|
||||||
* @returns string
|
|
||||||
*/
|
|
||||||
function getState(name) {
|
|
||||||
return process.env[`STATE_${name}`] || '';
|
|
||||||
}
|
|
||||||
exports.getState = getState;
|
|
||||||
//# sourceMappingURL=core.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,uCAA6C;AAE7C,uCAAwB;AACxB,2CAA4B;AAU5B;;GAEG;AACH,IAAY,QAUX;AAVD,WAAY,QAAQ;IAClB;;OAEG;IACH,6CAAW,CAAA;IAEX;;OAEG;IACH,6CAAW,CAAA;AACb,CAAC,EAVW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAUnB;AAED,yEAAyE;AACzE,YAAY;AACZ,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,cAAc,CAAC,IAAY,EAAE,GAAW;IACtD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,CAAA;IACvB,sBAAY,CAAC,SAAS,EAAE,EAAC,IAAI,EAAC,EAAE,GAAG,CAAC,CAAA;AACtC,CAAC;AAHD,wCAGC;AAED;;;GAGG;AACH,SAAgB,SAAS,CAAC,MAAc;IACtC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,MAAM,CAAC,CAAA;AACtC,CAAC;AAFD,8BAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,SAAiB;IACvC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,SAAS,CAAC,CAAA;IACvC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAA;AAC7E,CAAC;AAHD,0BAGC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,IAAY,EAAE,OAAsB;IAC3D,MAAM,GAAG,GACP,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,IAAI,EAAE,CAAA;IACrE,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE;QACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAA;KAC5D;IAED,OAAO,GAAG,CAAC,IAAI,EAAE,CAAA;AACnB,CAAC;AARD,4BAQC;AAED;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAa;IACnD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED,yEAAyE;AACzE,UAAU;AACV,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,SAAS,CAAC,OAAe;IACvC,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAA;IACnC,KAAK,CAAC,OAAO,CAAC,CAAA;AAChB,CAAC;AAHD,8BAGC;AAED,yEAAyE;AACzE,mBAAmB;AACnB,yEAAyE;AAEzE;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAe;IACnC,sBAAY,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAe;IACnC,eAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;AACzB,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,OAAe;IACrC,eAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;AAC3B,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,IAAI,CAAC,OAAe;IAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AACxC,CAAC;AAFD,oBAEC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,IAAY;IACrC,eAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,QAAQ;IACtB,eAAK,CAAC,UAAU,CAAC,CAAA;AACnB,CAAC;AAFD,4BAEC;AAED;;;;;;;GAOG;AACH,SAAsB,KAAK,CAAI,IAAY,EAAE,EAAoB;;QAC/D,UAAU,CAAC,IAAI,CAAC,CAAA;QAEhB,IAAI,MAAS,CAAA;QAEb,IAAI;YACF,MAAM,GAAG,MAAM,EAAE,EAAE,CAAA;SACpB;gBAAS;YACR,QAAQ,EAAE,CAAA;SACX;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAZD,sBAYC;AAED,yEAAyE;AACzE,uBAAuB;AACvB,yEAAyE;AAEzE;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAa;IACnD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,IAAI,EAAE,CAAA;AAC3C,CAAC;AAFD,4BAEC"}
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
{
|
|
||||||
"name": "@actions/core",
|
|
||||||
"version": "1.2.2",
|
|
||||||
"description": "Actions core lib",
|
|
||||||
"keywords": [
|
|
||||||
"github",
|
|
||||||
"actions",
|
|
||||||
"core"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/core",
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "lib/core.js",
|
|
||||||
"types": "lib/core.d.ts",
|
|
||||||
"directories": {
|
|
||||||
"lib": "lib",
|
|
||||||
"test": "__tests__"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib"
|
|
||||||
],
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/actions/toolkit.git",
|
|
||||||
"directory": "packages/core"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"audit-moderate": "npm install && npm audit --audit-level=moderate",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
|
||||||
"tsc": "tsc"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^12.0.2"
|
|
||||||
}
|
|
||||||
|
|
||||||
,"_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.2.tgz"
|
|
||||||
,"_integrity": "sha512-IbCx7oefq+Gi6FWbSs2Fnw8VkEI6Y4gvjrYprY3RV//ksq/KPMlClOerJ4jRosyal6zkUIc8R9fS/cpRMlGClg=="
|
|
||||||
,"_from": "@actions/core@1.2.2"
|
|
||||||
}
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
# `@actions/exec`
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
#### Basic
|
|
||||||
|
|
||||||
You can use this package to execute tools in a cross platform way:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const exec = require('@actions/exec');
|
|
||||||
|
|
||||||
await exec.exec('node index.js');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Args
|
|
||||||
|
|
||||||
You can also pass in arg arrays:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const exec = require('@actions/exec');
|
|
||||||
|
|
||||||
await exec.exec('node', ['index.js', 'foo=bar']);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Output/options
|
|
||||||
|
|
||||||
Capture output or specify [other options](https://github.com/actions/toolkit/blob/d9347d4ab99fd507c0b9104b2cf79fb44fcc827d/packages/exec/src/interfaces.ts#L5):
|
|
||||||
|
|
||||||
```js
|
|
||||||
const exec = require('@actions/exec');
|
|
||||||
|
|
||||||
let myOutput = '';
|
|
||||||
let myError = '';
|
|
||||||
|
|
||||||
const options = {};
|
|
||||||
options.listeners = {
|
|
||||||
stdout: (data: Buffer) => {
|
|
||||||
myOutput += data.toString();
|
|
||||||
},
|
|
||||||
stderr: (data: Buffer) => {
|
|
||||||
myError += data.toString();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
options.cwd = './lib';
|
|
||||||
|
|
||||||
await exec.exec('node', ['index.js', 'foo=bar'], options);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Exec tools not in the PATH
|
|
||||||
|
|
||||||
You can specify the full path for tools not in the PATH:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const exec = require('@actions/exec');
|
|
||||||
|
|
||||||
await exec.exec('"/path/to/my-tool"', ['arg1']);
|
|
||||||
```
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
import * as im from './interfaces';
|
|
||||||
/**
|
|
||||||
* Exec a command.
|
|
||||||
* Output will be streamed to the live console.
|
|
||||||
* Returns promise with return code
|
|
||||||
*
|
|
||||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
|
||||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
|
||||||
* @param options optional exec options. See ExecOptions
|
|
||||||
* @returns Promise<number> exit code
|
|
||||||
*/
|
|
||||||
export declare function exec(commandLine: string, args?: string[], options?: im.ExecOptions): Promise<number>;
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const tr = require("./toolrunner");
|
|
||||||
/**
|
|
||||||
* Exec a command.
|
|
||||||
* Output will be streamed to the live console.
|
|
||||||
* Returns promise with return code
|
|
||||||
*
|
|
||||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
|
||||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
|
||||||
* @param options optional exec options. See ExecOptions
|
|
||||||
* @returns Promise<number> exit code
|
|
||||||
*/
|
|
||||||
function exec(commandLine, args, options) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
const commandArgs = tr.argStringToArray(commandLine);
|
|
||||||
if (commandArgs.length === 0) {
|
|
||||||
throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
|
|
||||||
}
|
|
||||||
// Path to tool to execute should be first arg
|
|
||||||
const toolPath = commandArgs[0];
|
|
||||||
args = commandArgs.slice(1).concat(args || []);
|
|
||||||
const runner = new tr.ToolRunner(toolPath, args, options);
|
|
||||||
return runner.exec();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.exec = exec;
|
|
||||||
//# sourceMappingURL=exec.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,mCAAkC;AAElC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAwB;;QAExB,MAAM,WAAW,GAAG,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAA;QACpD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;SACpE;QACD,8CAA8C;QAC9C,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QAC/B,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;QAC9C,MAAM,MAAM,GAAkB,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QACxE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;CAAA;AAdD,oBAcC"}
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
/// <reference types="node" />
|
|
||||||
import * as stream from 'stream';
|
|
||||||
/**
|
|
||||||
* Interface for exec options
|
|
||||||
*/
|
|
||||||
export interface ExecOptions {
|
|
||||||
/** optional working directory. defaults to current */
|
|
||||||
cwd?: string;
|
|
||||||
/** optional envvar dictionary. defaults to current process's env */
|
|
||||||
env?: {
|
|
||||||
[key: string]: string;
|
|
||||||
};
|
|
||||||
/** optional. defaults to false */
|
|
||||||
silent?: boolean;
|
|
||||||
/** optional out stream to use. Defaults to process.stdout */
|
|
||||||
outStream?: stream.Writable;
|
|
||||||
/** optional err stream to use. Defaults to process.stderr */
|
|
||||||
errStream?: stream.Writable;
|
|
||||||
/** optional. whether to skip quoting/escaping arguments if needed. defaults to false. */
|
|
||||||
windowsVerbatimArguments?: boolean;
|
|
||||||
/** optional. whether to fail if output to stderr. defaults to false */
|
|
||||||
failOnStdErr?: boolean;
|
|
||||||
/** optional. defaults to failing on non zero. ignore will not fail leaving it up to the caller */
|
|
||||||
ignoreReturnCode?: boolean;
|
|
||||||
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
|
|
||||||
delay?: number;
|
|
||||||
/** optional. Listeners for output. Callback functions that will be called on these events */
|
|
||||||
listeners?: {
|
|
||||||
stdout?: (data: Buffer) => void;
|
|
||||||
stderr?: (data: Buffer) => void;
|
|
||||||
stdline?: (data: string) => void;
|
|
||||||
errline?: (data: string) => void;
|
|
||||||
debug?: (data: string) => void;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
//# sourceMappingURL=interfaces.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":""}
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
/// <reference types="node" />
|
|
||||||
import * as events from 'events';
|
|
||||||
import * as im from './interfaces';
|
|
||||||
export declare class ToolRunner extends events.EventEmitter {
|
|
||||||
constructor(toolPath: string, args?: string[], options?: im.ExecOptions);
|
|
||||||
private toolPath;
|
|
||||||
private args;
|
|
||||||
private options;
|
|
||||||
private _debug;
|
|
||||||
private _getCommandString;
|
|
||||||
private _processLineBuffer;
|
|
||||||
private _getSpawnFileName;
|
|
||||||
private _getSpawnArgs;
|
|
||||||
private _endsWith;
|
|
||||||
private _isCmdFile;
|
|
||||||
private _windowsQuoteCmdArg;
|
|
||||||
private _uvQuoteCmdArg;
|
|
||||||
private _cloneExecOptions;
|
|
||||||
private _getSpawnOptions;
|
|
||||||
/**
|
|
||||||
* Exec a tool.
|
|
||||||
* Output will be streamed to the live console.
|
|
||||||
* Returns promise with return code
|
|
||||||
*
|
|
||||||
* @param tool path to tool to exec
|
|
||||||
* @param options optional exec options. See ExecOptions
|
|
||||||
* @returns number
|
|
||||||
*/
|
|
||||||
exec(): Promise<number>;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Convert an arg string to an array of args. Handles escaping
|
|
||||||
*
|
|
||||||
* @param argString string of arguments
|
|
||||||
* @returns string[] array of arguments
|
|
||||||
*/
|
|
||||||
export declare function argStringToArray(argString: string): string[];
|
|
||||||
|
|
@ -1,587 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const os = require("os");
|
|
||||||
const events = require("events");
|
|
||||||
const child = require("child_process");
|
|
||||||
const path = require("path");
|
|
||||||
const io = require("@actions/io");
|
|
||||||
const ioUtil = require("@actions/io/lib/io-util");
|
|
||||||
/* eslint-disable @typescript-eslint/unbound-method */
|
|
||||||
const IS_WINDOWS = process.platform === 'win32';
|
|
||||||
/*
|
|
||||||
* Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.
|
|
||||||
*/
|
|
||||||
class ToolRunner extends events.EventEmitter {
|
|
||||||
constructor(toolPath, args, options) {
|
|
||||||
super();
|
|
||||||
if (!toolPath) {
|
|
||||||
throw new Error("Parameter 'toolPath' cannot be null or empty.");
|
|
||||||
}
|
|
||||||
this.toolPath = toolPath;
|
|
||||||
this.args = args || [];
|
|
||||||
this.options = options || {};
|
|
||||||
}
|
|
||||||
_debug(message) {
|
|
||||||
if (this.options.listeners && this.options.listeners.debug) {
|
|
||||||
this.options.listeners.debug(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_getCommandString(options, noPrefix) {
|
|
||||||
const toolPath = this._getSpawnFileName();
|
|
||||||
const args = this._getSpawnArgs(options);
|
|
||||||
let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
|
|
||||||
if (IS_WINDOWS) {
|
|
||||||
// Windows + cmd file
|
|
||||||
if (this._isCmdFile()) {
|
|
||||||
cmd += toolPath;
|
|
||||||
for (const a of args) {
|
|
||||||
cmd += ` ${a}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Windows + verbatim
|
|
||||||
else if (options.windowsVerbatimArguments) {
|
|
||||||
cmd += `"${toolPath}"`;
|
|
||||||
for (const a of args) {
|
|
||||||
cmd += ` ${a}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Windows (regular)
|
|
||||||
else {
|
|
||||||
cmd += this._windowsQuoteCmdArg(toolPath);
|
|
||||||
for (const a of args) {
|
|
||||||
cmd += ` ${this._windowsQuoteCmdArg(a)}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// OSX/Linux - this can likely be improved with some form of quoting.
|
|
||||||
// creating processes on Unix is fundamentally different than Windows.
|
|
||||||
// on Unix, execvp() takes an arg array.
|
|
||||||
cmd += toolPath;
|
|
||||||
for (const a of args) {
|
|
||||||
cmd += ` ${a}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return cmd;
|
|
||||||
}
|
|
||||||
_processLineBuffer(data, strBuffer, onLine) {
|
|
||||||
try {
|
|
||||||
let s = strBuffer + data.toString();
|
|
||||||
let n = s.indexOf(os.EOL);
|
|
||||||
while (n > -1) {
|
|
||||||
const line = s.substring(0, n);
|
|
||||||
onLine(line);
|
|
||||||
// the rest of the string ...
|
|
||||||
s = s.substring(n + os.EOL.length);
|
|
||||||
n = s.indexOf(os.EOL);
|
|
||||||
}
|
|
||||||
strBuffer = s;
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
// streaming lines to console is best effort. Don't fail a build.
|
|
||||||
this._debug(`error processing line. Failed with error ${err}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_getSpawnFileName() {
|
|
||||||
if (IS_WINDOWS) {
|
|
||||||
if (this._isCmdFile()) {
|
|
||||||
return process.env['COMSPEC'] || 'cmd.exe';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return this.toolPath;
|
|
||||||
}
|
|
||||||
_getSpawnArgs(options) {
|
|
||||||
if (IS_WINDOWS) {
|
|
||||||
if (this._isCmdFile()) {
|
|
||||||
let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
|
|
||||||
for (const a of this.args) {
|
|
||||||
argline += ' ';
|
|
||||||
argline += options.windowsVerbatimArguments
|
|
||||||
? a
|
|
||||||
: this._windowsQuoteCmdArg(a);
|
|
||||||
}
|
|
||||||
argline += '"';
|
|
||||||
return [argline];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return this.args;
|
|
||||||
}
|
|
||||||
_endsWith(str, end) {
|
|
||||||
return str.endsWith(end);
|
|
||||||
}
|
|
||||||
_isCmdFile() {
|
|
||||||
const upperToolPath = this.toolPath.toUpperCase();
|
|
||||||
return (this._endsWith(upperToolPath, '.CMD') ||
|
|
||||||
this._endsWith(upperToolPath, '.BAT'));
|
|
||||||
}
|
|
||||||
_windowsQuoteCmdArg(arg) {
|
|
||||||
// for .exe, apply the normal quoting rules that libuv applies
|
|
||||||
if (!this._isCmdFile()) {
|
|
||||||
return this._uvQuoteCmdArg(arg);
|
|
||||||
}
|
|
||||||
// otherwise apply quoting rules specific to the cmd.exe command line parser.
|
|
||||||
// the libuv rules are generic and are not designed specifically for cmd.exe
|
|
||||||
// command line parser.
|
|
||||||
//
|
|
||||||
// for a detailed description of the cmd.exe command line parser, refer to
|
|
||||||
// http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
|
|
||||||
// need quotes for empty arg
|
|
||||||
if (!arg) {
|
|
||||||
return '""';
|
|
||||||
}
|
|
||||||
// determine whether the arg needs to be quoted
|
|
||||||
const cmdSpecialChars = [
|
|
||||||
' ',
|
|
||||||
'\t',
|
|
||||||
'&',
|
|
||||||
'(',
|
|
||||||
')',
|
|
||||||
'[',
|
|
||||||
']',
|
|
||||||
'{',
|
|
||||||
'}',
|
|
||||||
'^',
|
|
||||||
'=',
|
|
||||||
';',
|
|
||||||
'!',
|
|
||||||
"'",
|
|
||||||
'+',
|
|
||||||
',',
|
|
||||||
'`',
|
|
||||||
'~',
|
|
||||||
'|',
|
|
||||||
'<',
|
|
||||||
'>',
|
|
||||||
'"'
|
|
||||||
];
|
|
||||||
let needsQuotes = false;
|
|
||||||
for (const char of arg) {
|
|
||||||
if (cmdSpecialChars.some(x => x === char)) {
|
|
||||||
needsQuotes = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// short-circuit if quotes not needed
|
|
||||||
if (!needsQuotes) {
|
|
||||||
return arg;
|
|
||||||
}
|
|
||||||
// the following quoting rules are very similar to the rules that by libuv applies.
|
|
||||||
//
|
|
||||||
// 1) wrap the string in quotes
|
|
||||||
//
|
|
||||||
// 2) double-up quotes - i.e. " => ""
|
|
||||||
//
|
|
||||||
// this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
|
|
||||||
// doesn't work well with a cmd.exe command line.
|
|
||||||
//
|
|
||||||
// note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
|
|
||||||
// for example, the command line:
|
|
||||||
// foo.exe "myarg:""my val"""
|
|
||||||
// is parsed by a .NET console app into an arg array:
|
|
||||||
// [ "myarg:\"my val\"" ]
|
|
||||||
// which is the same end result when applying libuv quoting rules. although the actual
|
|
||||||
// command line from libuv quoting rules would look like:
|
|
||||||
// foo.exe "myarg:\"my val\""
|
|
||||||
//
|
|
||||||
// 3) double-up slashes that precede a quote,
|
|
||||||
// e.g. hello \world => "hello \world"
|
|
||||||
// hello\"world => "hello\\""world"
|
|
||||||
// hello\\"world => "hello\\\\""world"
|
|
||||||
// hello world\ => "hello world\\"
|
|
||||||
//
|
|
||||||
// technically this is not required for a cmd.exe command line, or the batch argument parser.
|
|
||||||
// the reasons for including this as a .cmd quoting rule are:
|
|
||||||
//
|
|
||||||
// a) this is optimized for the scenario where the argument is passed from the .cmd file to an
|
|
||||||
// external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
|
|
||||||
//
|
|
||||||
// b) it's what we've been doing previously (by deferring to node default behavior) and we
|
|
||||||
// haven't heard any complaints about that aspect.
|
|
||||||
//
|
|
||||||
// note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
|
|
||||||
// escaped when used on the command line directly - even though within a .cmd file % can be escaped
|
|
||||||
// by using %%.
|
|
||||||
//
|
|
||||||
// the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
|
|
||||||
// the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
|
|
||||||
//
|
|
||||||
// one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
|
|
||||||
// often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
|
|
||||||
// variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
|
|
||||||
// to an external program.
|
|
||||||
//
|
|
||||||
// an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
|
|
||||||
// % can be escaped within a .cmd file.
|
|
||||||
let reverse = '"';
|
|
||||||
let quoteHit = true;
|
|
||||||
for (let i = arg.length; i > 0; i--) {
|
|
||||||
// walk the string in reverse
|
|
||||||
reverse += arg[i - 1];
|
|
||||||
if (quoteHit && arg[i - 1] === '\\') {
|
|
||||||
reverse += '\\'; // double the slash
|
|
||||||
}
|
|
||||||
else if (arg[i - 1] === '"') {
|
|
||||||
quoteHit = true;
|
|
||||||
reverse += '"'; // double the quote
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
quoteHit = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
reverse += '"';
|
|
||||||
return reverse
|
|
||||||
.split('')
|
|
||||||
.reverse()
|
|
||||||
.join('');
|
|
||||||
}
|
|
||||||
_uvQuoteCmdArg(arg) {
|
|
||||||
// Tool runner wraps child_process.spawn() and needs to apply the same quoting as
|
|
||||||
// Node in certain cases where the undocumented spawn option windowsVerbatimArguments
|
|
||||||
// is used.
|
|
||||||
//
|
|
||||||
// Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
|
|
||||||
// see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
|
|
||||||
// pasting copyright notice from Node within this function:
|
|
||||||
//
|
|
||||||
// Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
|
||||||
//
|
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
// of this software and associated documentation files (the "Software"), to
|
|
||||||
// deal in the Software without restriction, including without limitation the
|
|
||||||
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
|
||||||
// sell copies of the Software, and to permit persons to whom the Software is
|
|
||||||
// furnished to do so, subject to the following conditions:
|
|
||||||
//
|
|
||||||
// The above copyright notice and this permission notice shall be included in
|
|
||||||
// all copies or substantial portions of the Software.
|
|
||||||
//
|
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
|
||||||
// IN THE SOFTWARE.
|
|
||||||
if (!arg) {
|
|
||||||
// Need double quotation for empty argument
|
|
||||||
return '""';
|
|
||||||
}
|
|
||||||
if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
|
|
||||||
// No quotation needed
|
|
||||||
return arg;
|
|
||||||
}
|
|
||||||
if (!arg.includes('"') && !arg.includes('\\')) {
|
|
||||||
// No embedded double quotes or backslashes, so I can just wrap
|
|
||||||
// quote marks around the whole thing.
|
|
||||||
return `"${arg}"`;
|
|
||||||
}
|
|
||||||
// Expected input/output:
|
|
||||||
// input : hello"world
|
|
||||||
// output: "hello\"world"
|
|
||||||
// input : hello""world
|
|
||||||
// output: "hello\"\"world"
|
|
||||||
// input : hello\world
|
|
||||||
// output: hello\world
|
|
||||||
// input : hello\\world
|
|
||||||
// output: hello\\world
|
|
||||||
// input : hello\"world
|
|
||||||
// output: "hello\\\"world"
|
|
||||||
// input : hello\\"world
|
|
||||||
// output: "hello\\\\\"world"
|
|
||||||
// input : hello world\
|
|
||||||
// output: "hello world\\" - note the comment in libuv actually reads "hello world\"
|
|
||||||
// but it appears the comment is wrong, it should be "hello world\\"
|
|
||||||
let reverse = '"';
|
|
||||||
let quoteHit = true;
|
|
||||||
for (let i = arg.length; i > 0; i--) {
|
|
||||||
// walk the string in reverse
|
|
||||||
reverse += arg[i - 1];
|
|
||||||
if (quoteHit && arg[i - 1] === '\\') {
|
|
||||||
reverse += '\\';
|
|
||||||
}
|
|
||||||
else if (arg[i - 1] === '"') {
|
|
||||||
quoteHit = true;
|
|
||||||
reverse += '\\';
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
quoteHit = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
reverse += '"';
|
|
||||||
return reverse
|
|
||||||
.split('')
|
|
||||||
.reverse()
|
|
||||||
.join('');
|
|
||||||
}
|
|
||||||
_cloneExecOptions(options) {
|
|
||||||
options = options || {};
|
|
||||||
const result = {
|
|
||||||
cwd: options.cwd || process.cwd(),
|
|
||||||
env: options.env || process.env,
|
|
||||||
silent: options.silent || false,
|
|
||||||
windowsVerbatimArguments: options.windowsVerbatimArguments || false,
|
|
||||||
failOnStdErr: options.failOnStdErr || false,
|
|
||||||
ignoreReturnCode: options.ignoreReturnCode || false,
|
|
||||||
delay: options.delay || 10000
|
|
||||||
};
|
|
||||||
result.outStream = options.outStream || process.stdout;
|
|
||||||
result.errStream = options.errStream || process.stderr;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
_getSpawnOptions(options, toolPath) {
|
|
||||||
options = options || {};
|
|
||||||
const result = {};
|
|
||||||
result.cwd = options.cwd;
|
|
||||||
result.env = options.env;
|
|
||||||
result['windowsVerbatimArguments'] =
|
|
||||||
options.windowsVerbatimArguments || this._isCmdFile();
|
|
||||||
if (options.windowsVerbatimArguments) {
|
|
||||||
result.argv0 = `"${toolPath}"`;
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Exec a tool.
|
|
||||||
* Output will be streamed to the live console.
|
|
||||||
* Returns promise with return code
|
|
||||||
*
|
|
||||||
* @param tool path to tool to exec
|
|
||||||
* @param options optional exec options. See ExecOptions
|
|
||||||
* @returns number
|
|
||||||
*/
|
|
||||||
exec() {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// root the tool path if it is unrooted and contains relative pathing
|
|
||||||
if (!ioUtil.isRooted(this.toolPath) &&
|
|
||||||
(this.toolPath.includes('/') ||
|
|
||||||
(IS_WINDOWS && this.toolPath.includes('\\')))) {
|
|
||||||
// prefer options.cwd if it is specified, however options.cwd may also need to be rooted
|
|
||||||
this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
|
|
||||||
}
|
|
||||||
// if the tool is only a file name, then resolve it from the PATH
|
|
||||||
// otherwise verify it exists (add extension on Windows if necessary)
|
|
||||||
this.toolPath = yield io.which(this.toolPath, true);
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
this._debug(`exec tool: ${this.toolPath}`);
|
|
||||||
this._debug('arguments:');
|
|
||||||
for (const arg of this.args) {
|
|
||||||
this._debug(` ${arg}`);
|
|
||||||
}
|
|
||||||
const optionsNonNull = this._cloneExecOptions(this.options);
|
|
||||||
if (!optionsNonNull.silent && optionsNonNull.outStream) {
|
|
||||||
optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
|
|
||||||
}
|
|
||||||
const state = new ExecState(optionsNonNull, this.toolPath);
|
|
||||||
state.on('debug', (message) => {
|
|
||||||
this._debug(message);
|
|
||||||
});
|
|
||||||
const fileName = this._getSpawnFileName();
|
|
||||||
const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
|
|
||||||
const stdbuffer = '';
|
|
||||||
if (cp.stdout) {
|
|
||||||
cp.stdout.on('data', (data) => {
|
|
||||||
if (this.options.listeners && this.options.listeners.stdout) {
|
|
||||||
this.options.listeners.stdout(data);
|
|
||||||
}
|
|
||||||
if (!optionsNonNull.silent && optionsNonNull.outStream) {
|
|
||||||
optionsNonNull.outStream.write(data);
|
|
||||||
}
|
|
||||||
this._processLineBuffer(data, stdbuffer, (line) => {
|
|
||||||
if (this.options.listeners && this.options.listeners.stdline) {
|
|
||||||
this.options.listeners.stdline(line);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const errbuffer = '';
|
|
||||||
if (cp.stderr) {
|
|
||||||
cp.stderr.on('data', (data) => {
|
|
||||||
state.processStderr = true;
|
|
||||||
if (this.options.listeners && this.options.listeners.stderr) {
|
|
||||||
this.options.listeners.stderr(data);
|
|
||||||
}
|
|
||||||
if (!optionsNonNull.silent &&
|
|
||||||
optionsNonNull.errStream &&
|
|
||||||
optionsNonNull.outStream) {
|
|
||||||
const s = optionsNonNull.failOnStdErr
|
|
||||||
? optionsNonNull.errStream
|
|
||||||
: optionsNonNull.outStream;
|
|
||||||
s.write(data);
|
|
||||||
}
|
|
||||||
this._processLineBuffer(data, errbuffer, (line) => {
|
|
||||||
if (this.options.listeners && this.options.listeners.errline) {
|
|
||||||
this.options.listeners.errline(line);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
cp.on('error', (err) => {
|
|
||||||
state.processError = err.message;
|
|
||||||
state.processExited = true;
|
|
||||||
state.processClosed = true;
|
|
||||||
state.CheckComplete();
|
|
||||||
});
|
|
||||||
cp.on('exit', (code) => {
|
|
||||||
state.processExitCode = code;
|
|
||||||
state.processExited = true;
|
|
||||||
this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
|
|
||||||
state.CheckComplete();
|
|
||||||
});
|
|
||||||
cp.on('close', (code) => {
|
|
||||||
state.processExitCode = code;
|
|
||||||
state.processExited = true;
|
|
||||||
state.processClosed = true;
|
|
||||||
this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
|
|
||||||
state.CheckComplete();
|
|
||||||
});
|
|
||||||
state.on('done', (error, exitCode) => {
|
|
||||||
if (stdbuffer.length > 0) {
|
|
||||||
this.emit('stdline', stdbuffer);
|
|
||||||
}
|
|
||||||
if (errbuffer.length > 0) {
|
|
||||||
this.emit('errline', errbuffer);
|
|
||||||
}
|
|
||||||
cp.removeAllListeners();
|
|
||||||
if (error) {
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
resolve(exitCode);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.ToolRunner = ToolRunner;
|
|
||||||
/**
|
|
||||||
* Convert an arg string to an array of args. Handles escaping
|
|
||||||
*
|
|
||||||
* @param argString string of arguments
|
|
||||||
* @returns string[] array of arguments
|
|
||||||
*/
|
|
||||||
function argStringToArray(argString) {
|
|
||||||
const args = [];
|
|
||||||
let inQuotes = false;
|
|
||||||
let escaped = false;
|
|
||||||
let arg = '';
|
|
||||||
function append(c) {
|
|
||||||
// we only escape double quotes.
|
|
||||||
if (escaped && c !== '"') {
|
|
||||||
arg += '\\';
|
|
||||||
}
|
|
||||||
arg += c;
|
|
||||||
escaped = false;
|
|
||||||
}
|
|
||||||
for (let i = 0; i < argString.length; i++) {
|
|
||||||
const c = argString.charAt(i);
|
|
||||||
if (c === '"') {
|
|
||||||
if (!escaped) {
|
|
||||||
inQuotes = !inQuotes;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
append(c);
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (c === '\\' && escaped) {
|
|
||||||
append(c);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (c === '\\' && inQuotes) {
|
|
||||||
escaped = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (c === ' ' && !inQuotes) {
|
|
||||||
if (arg.length > 0) {
|
|
||||||
args.push(arg);
|
|
||||||
arg = '';
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
append(c);
|
|
||||||
}
|
|
||||||
if (arg.length > 0) {
|
|
||||||
args.push(arg.trim());
|
|
||||||
}
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
exports.argStringToArray = argStringToArray;
|
|
||||||
class ExecState extends events.EventEmitter {
|
|
||||||
constructor(options, toolPath) {
|
|
||||||
super();
|
|
||||||
this.processClosed = false; // tracks whether the process has exited and stdio is closed
|
|
||||||
this.processError = '';
|
|
||||||
this.processExitCode = 0;
|
|
||||||
this.processExited = false; // tracks whether the process has exited
|
|
||||||
this.processStderr = false; // tracks whether stderr was written to
|
|
||||||
this.delay = 10000; // 10 seconds
|
|
||||||
this.done = false;
|
|
||||||
this.timeout = null;
|
|
||||||
if (!toolPath) {
|
|
||||||
throw new Error('toolPath must not be empty');
|
|
||||||
}
|
|
||||||
this.options = options;
|
|
||||||
this.toolPath = toolPath;
|
|
||||||
if (options.delay) {
|
|
||||||
this.delay = options.delay;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
CheckComplete() {
|
|
||||||
if (this.done) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (this.processClosed) {
|
|
||||||
this._setResult();
|
|
||||||
}
|
|
||||||
else if (this.processExited) {
|
|
||||||
this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_debug(message) {
|
|
||||||
this.emit('debug', message);
|
|
||||||
}
|
|
||||||
_setResult() {
|
|
||||||
// determine whether there is an error
|
|
||||||
let error;
|
|
||||||
if (this.processExited) {
|
|
||||||
if (this.processError) {
|
|
||||||
error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);
|
|
||||||
}
|
|
||||||
else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {
|
|
||||||
error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);
|
|
||||||
}
|
|
||||||
else if (this.processStderr && this.options.failOnStdErr) {
|
|
||||||
error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// clear the timeout
|
|
||||||
if (this.timeout) {
|
|
||||||
clearTimeout(this.timeout);
|
|
||||||
this.timeout = null;
|
|
||||||
}
|
|
||||||
this.done = true;
|
|
||||||
this.emit('done', error, this.processExitCode);
|
|
||||||
}
|
|
||||||
static HandleTimeout(state) {
|
|
||||||
if (state.done) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!state.processClosed && state.processExited) {
|
|
||||||
const message = `The STDIO streams did not close within ${state.delay /
|
|
||||||
1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;
|
|
||||||
state._debug(message);
|
|
||||||
}
|
|
||||||
state._setResult();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//# sourceMappingURL=toolrunner.js.map
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1,44 +0,0 @@
|
||||||
{
|
|
||||||
"name": "@actions/exec",
|
|
||||||
"version": "1.0.3",
|
|
||||||
"description": "Actions exec lib",
|
|
||||||
"keywords": [
|
|
||||||
"github",
|
|
||||||
"actions",
|
|
||||||
"exec"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "lib/exec.js",
|
|
||||||
"types": "lib/exec.d.ts",
|
|
||||||
"directories": {
|
|
||||||
"lib": "lib",
|
|
||||||
"test": "__tests__"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib"
|
|
||||||
],
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/actions/toolkit.git",
|
|
||||||
"directory": "packages/exec"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"audit-moderate": "npm install && npm audit --audit-level=moderate",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
|
||||||
"tsc": "tsc"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@actions/io": "^1.0.1"
|
|
||||||
}
|
|
||||||
|
|
||||||
,"_resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.3.tgz"
|
|
||||||
,"_integrity": "sha512-TogJGnueOmM7ntCi0ASTUj4LapRRtDfj57Ja4IhPmg2fls28uVOPbAn8N+JifaOumN2UG3oEO/Ixek2A4NcYSA=="
|
|
||||||
,"_from": "@actions/exec@1.0.3"
|
|
||||||
}
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
Copyright 2019 GitHub
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
# `@actions/github`
|
|
||||||
|
|
||||||
> A hydrated Octokit client.
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
Returns an Octokit client. See https://octokit.github.io/rest.js for the API.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const github = require('@actions/github');
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
// This should be a token with access to your repository scoped in as a secret.
|
|
||||||
const myToken = core.getInput('myToken');
|
|
||||||
|
|
||||||
const octokit = new github.GitHub(myToken);
|
|
||||||
|
|
||||||
const { data: pullRequest } = await octokit.pulls.get({
|
|
||||||
owner: 'octokit',
|
|
||||||
repo: 'rest.js',
|
|
||||||
pull_number: 123,
|
|
||||||
mediaType: {
|
|
||||||
format: 'diff'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(pullRequest);
|
|
||||||
```
|
|
||||||
|
|
||||||
You can pass client options (except `auth`, which is handled by the token argument), as specified by [Octokit](https://octokit.github.io/rest.js/), as a second argument to the `GitHub` constructor.
|
|
||||||
|
|
||||||
You can also make GraphQL requests. See https://github.com/octokit/graphql.js for the API.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const result = await octokit.graphql(query, variables);
|
|
||||||
```
|
|
||||||
|
|
||||||
Finally, you can get the context of the current action:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const github = require('@actions/github');
|
|
||||||
|
|
||||||
const context = github.context;
|
|
||||||
|
|
||||||
const newIssue = await octokit.issues.create({
|
|
||||||
...context.repo,
|
|
||||||
title: 'New issue!',
|
|
||||||
body: 'Hello Universe!'
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
import { WebhookPayload } from './interfaces';
|
|
||||||
export declare class Context {
|
|
||||||
/**
|
|
||||||
* Webhook payload object that triggered the workflow
|
|
||||||
*/
|
|
||||||
payload: WebhookPayload;
|
|
||||||
eventName: string;
|
|
||||||
sha: string;
|
|
||||||
ref: string;
|
|
||||||
workflow: string;
|
|
||||||
action: string;
|
|
||||||
actor: string;
|
|
||||||
/**
|
|
||||||
* Hydrate the context from the environment
|
|
||||||
*/
|
|
||||||
constructor();
|
|
||||||
readonly issue: {
|
|
||||||
owner: string;
|
|
||||||
repo: string;
|
|
||||||
number: number;
|
|
||||||
};
|
|
||||||
readonly repo: {
|
|
||||||
owner: string;
|
|
||||||
repo: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,45 +0,0 @@
|
||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const fs_1 = require("fs");
|
|
||||||
const os_1 = require("os");
|
|
||||||
class Context {
|
|
||||||
/**
|
|
||||||
* Hydrate the context from the environment
|
|
||||||
*/
|
|
||||||
constructor() {
|
|
||||||
this.payload = {};
|
|
||||||
if (process.env.GITHUB_EVENT_PATH) {
|
|
||||||
if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) {
|
|
||||||
this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' }));
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
process.stdout.write(`GITHUB_EVENT_PATH ${process.env.GITHUB_EVENT_PATH} does not exist${os_1.EOL}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.eventName = process.env.GITHUB_EVENT_NAME;
|
|
||||||
this.sha = process.env.GITHUB_SHA;
|
|
||||||
this.ref = process.env.GITHUB_REF;
|
|
||||||
this.workflow = process.env.GITHUB_WORKFLOW;
|
|
||||||
this.action = process.env.GITHUB_ACTION;
|
|
||||||
this.actor = process.env.GITHUB_ACTOR;
|
|
||||||
}
|
|
||||||
get issue() {
|
|
||||||
const payload = this.payload;
|
|
||||||
return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pullRequest || payload).number });
|
|
||||||
}
|
|
||||||
get repo() {
|
|
||||||
if (process.env.GITHUB_REPOSITORY) {
|
|
||||||
const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');
|
|
||||||
return { owner, repo };
|
|
||||||
}
|
|
||||||
if (this.payload.repository) {
|
|
||||||
return {
|
|
||||||
owner: this.payload.repository.owner.login,
|
|
||||||
repo: this.payload.repository.name
|
|
||||||
};
|
|
||||||
}
|
|
||||||
throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.Context = Context;
|
|
||||||
//# sourceMappingURL=context.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":";;AAEA,2BAA2C;AAC3C,2BAAsB;AAEtB,MAAa,OAAO;IAalB;;OAEG;IACH;QACE,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;QACjB,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE;YACjC,IAAI,eAAU,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,EAAE;gBAC7C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CACvB,iBAAY,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,EAAC,QAAQ,EAAE,MAAM,EAAC,CAAC,CAChE,CAAA;aACF;iBAAM;gBACL,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,qBACE,OAAO,CAAC,GAAG,CAAC,iBACd,kBAAkB,QAAG,EAAE,CACxB,CAAA;aACF;SACF;QACD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,iBAA2B,CAAA;QACxD,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAA;QAC3C,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,UAAoB,CAAA;QAC3C,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,eAAyB,CAAA;QACrD,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,aAAuB,CAAA;QACjD,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,YAAsB,CAAA;IACjD,CAAC;IAED,IAAI,KAAK;QACP,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;QAE5B,uCACK,IAAI,CAAC,IAAI,KACZ,MAAM,EAAE,CAAC,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,CAAC,MAAM,IACjE;IACH,CAAC;IAED,IAAI,IAAI;QACN,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE;YACjC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;YAC9D,OAAO,EAAC,KAAK,EAAE,IAAI,EAAC,CAAA;SACrB;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE;YAC3B,OAAO;gBACL,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,KAAK;gBAC1C,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI;aACnC,CAAA;SACF;QAED,MAAM,IAAI,KAAK,CACb,kFAAkF,CACnF,CAAA;IACH,CAAC;CACF;AAjED,0BAiEC"}
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
import { GraphQlQueryResponse, Variables } from '@octokit/graphql';
|
|
||||||
import Octokit from '@octokit/rest';
|
|
||||||
import * as Context from './context';
|
|
||||||
export declare const context: Context.Context;
|
|
||||||
export declare class GitHub extends Octokit {
|
|
||||||
graphql: (query: string, variables?: Variables) => Promise<GraphQlQueryResponse>;
|
|
||||||
constructor(token: string, opts?: Omit<Octokit.Options, 'auth'>);
|
|
||||||
}
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
var __importStar = (this && this.__importStar) || function (mod) {
|
|
||||||
if (mod && mod.__esModule) return mod;
|
|
||||||
var result = {};
|
|
||||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
|
||||||
result["default"] = mod;
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
// Originally pulled from https://github.com/JasonEtco/actions-toolkit/blob/master/src/github.ts
|
|
||||||
const graphql_1 = require("@octokit/graphql");
|
|
||||||
const rest_1 = __importDefault(require("@octokit/rest"));
|
|
||||||
const Context = __importStar(require("./context"));
|
|
||||||
// We need this in order to extend Octokit
|
|
||||||
rest_1.default.prototype = new rest_1.default();
|
|
||||||
exports.context = new Context.Context();
|
|
||||||
class GitHub extends rest_1.default {
|
|
||||||
constructor(token, opts = {}) {
|
|
||||||
super(Object.assign(Object.assign({}, opts), { auth: `token ${token}` }));
|
|
||||||
this.graphql = graphql_1.defaults({
|
|
||||||
headers: { authorization: `token ${token}` }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.GitHub = GitHub;
|
|
||||||
//# sourceMappingURL=github.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"github.js","sourceRoot":"","sources":["../src/github.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,gGAAgG;AAChG,8CAA0E;AAC1E,yDAAmC;AACnC,mDAAoC;AAEpC,0CAA0C;AAC1C,cAAO,CAAC,SAAS,GAAG,IAAI,cAAO,EAAE,CAAA;AAEpB,QAAA,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;AAE5C,MAAa,MAAO,SAAQ,cAAO;IAMjC,YAAY,KAAa,EAAE,OAAsC,EAAE;QACjE,KAAK,iCAAK,IAAI,KAAE,IAAI,EAAE,SAAS,KAAK,EAAE,IAAE,CAAA;QACxC,IAAI,CAAC,OAAO,GAAG,kBAAQ,CAAC;YACtB,OAAO,EAAE,EAAC,aAAa,EAAE,SAAS,KAAK,EAAE,EAAC;SAC3C,CAAC,CAAA;IACJ,CAAC;CACF;AAZD,wBAYC"}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
export interface PayloadRepository {
|
|
||||||
[key: string]: any;
|
|
||||||
full_name?: string;
|
|
||||||
name: string;
|
|
||||||
owner: {
|
|
||||||
[key: string]: any;
|
|
||||||
login: string;
|
|
||||||
name?: string;
|
|
||||||
};
|
|
||||||
html_url?: string;
|
|
||||||
}
|
|
||||||
export interface WebhookPayload {
|
|
||||||
[key: string]: any;
|
|
||||||
repository?: PayloadRepository;
|
|
||||||
issue?: {
|
|
||||||
[key: string]: any;
|
|
||||||
number: number;
|
|
||||||
html_url?: string;
|
|
||||||
body?: string;
|
|
||||||
};
|
|
||||||
pull_request?: {
|
|
||||||
[key: string]: any;
|
|
||||||
number: number;
|
|
||||||
html_url?: string;
|
|
||||||
body?: string;
|
|
||||||
};
|
|
||||||
sender?: {
|
|
||||||
[key: string]: any;
|
|
||||||
type: string;
|
|
||||||
};
|
|
||||||
action?: string;
|
|
||||||
installation?: {
|
|
||||||
id: number;
|
|
||||||
[key: string]: any;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
"use strict";
|
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
//# sourceMappingURL=interfaces.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":";AAAA,uDAAuD"}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
{
|
|
||||||
"name": "@actions/github",
|
|
||||||
"version": "1.1.0",
|
|
||||||
"description": "Actions github lib",
|
|
||||||
"keywords": [
|
|
||||||
"github",
|
|
||||||
"actions"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/github",
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "lib/github.js",
|
|
||||||
"directories": {
|
|
||||||
"lib": "lib",
|
|
||||||
"test": "__tests__"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib"
|
|
||||||
],
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/actions/toolkit.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"test": "jest",
|
|
||||||
"build": "tsc",
|
|
||||||
"tsc": "tsc"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@octokit/graphql": "^2.0.1",
|
|
||||||
"@octokit/rest": "^16.15.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"jest": "^24.7.1"
|
|
||||||
},
|
|
||||||
"gitHead": "a2ab4bcf78e4f7080f0d45856e6eeba16f0bbc52"
|
|
||||||
|
|
||||||
,"_resolved": "https://registry.npmjs.org/@actions/github/-/github-1.1.0.tgz"
|
|
||||||
,"_integrity": "sha512-cHf6PyoNMdei13jEdGPhKprIMFmjVVW/dnM5/9QmQDJ1ZTaGVyezUSCUIC/ySNLRvDUpeFwPYMdThSEJldSbUw=="
|
|
||||||
,"_from": "@actions/github@1.1.0"
|
|
||||||
}
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
Actions Http Client for Node.js
|
|
||||||
|
|
||||||
Copyright (c) GitHub, Inc.
|
|
||||||
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
MIT License
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
|
||||||
associated documentation files (the "Software"), to deal in the Software without restriction,
|
|
||||||
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
||||||
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
|
|
||||||
subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
|
||||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
|
||||||
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
||||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
@ -1,73 +0,0 @@
|
||||||
|
|
||||||
<p align="center">
|
|
||||||
<img src="actions.png">
|
|
||||||
</p>
|
|
||||||
|
|
||||||
# Actions Http-Client
|
|
||||||
|
|
||||||
[](https://github.com/actions/http-client/actions)
|
|
||||||
|
|
||||||
A lightweight HTTP client optimized for use with actions, TypeScript with generics and async await.
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- HTTP client with TypeScript generics and async/await/Promises
|
|
||||||
- Typings included so no need to acquire separately (great for intellisense and no versioning drift)
|
|
||||||
- [Proxy support](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/about-self-hosted-runners#using-a-proxy-server-with-self-hosted-runners) just works with actions and the runner
|
|
||||||
- Targets ES2019 (runner runs actions with node 12+). Only supported on node 12+.
|
|
||||||
- Basic, Bearer and PAT Support out of the box. Extensible handlers for others.
|
|
||||||
- Redirects supported
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
```
|
|
||||||
npm install @actions/http-client --save
|
|
||||||
```
|
|
||||||
|
|
||||||
## Samples
|
|
||||||
|
|
||||||
See the [HTTP](./__tests__) tests for detailed examples.
|
|
||||||
|
|
||||||
## Errors
|
|
||||||
|
|
||||||
### HTTP
|
|
||||||
|
|
||||||
The HTTP client does not throw unless truly exceptional.
|
|
||||||
|
|
||||||
* A request that successfully executes resulting in a 404, 500 etc... will return a response object with a status code and a body.
|
|
||||||
* Redirects (3xx) will be followed by default.
|
|
||||||
|
|
||||||
See [HTTP tests](./__tests__) for detailed examples.
|
|
||||||
|
|
||||||
## Debugging
|
|
||||||
|
|
||||||
To enable detailed console logging of all HTTP requests and responses, set the NODE_DEBUG environment varible:
|
|
||||||
|
|
||||||
```
|
|
||||||
export NODE_DEBUG=http
|
|
||||||
```
|
|
||||||
|
|
||||||
## Node support
|
|
||||||
|
|
||||||
The http-client is built using the latest LTS version of Node 12. We also support the latest LTS for Node 6, 8 and Node 10.
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
We welcome PRs. Please create an issue and if applicable, a design before proceeding with code.
|
|
||||||
|
|
||||||
once:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ npm install
|
|
||||||
```
|
|
||||||
|
|
||||||
To build:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
To run all tests:
|
|
||||||
```bash
|
|
||||||
$ npm test
|
|
||||||
```
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 33 KiB |
|
|
@ -1,23 +0,0 @@
|
||||||
import ifm = require('./interfaces');
|
|
||||||
export declare class BasicCredentialHandler implements ifm.IRequestHandler {
|
|
||||||
username: string;
|
|
||||||
password: string;
|
|
||||||
constructor(username: string, password: string);
|
|
||||||
prepareRequest(options: any): void;
|
|
||||||
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
export declare class BearerCredentialHandler implements ifm.IRequestHandler {
|
|
||||||
token: string;
|
|
||||||
constructor(token: string);
|
|
||||||
prepareRequest(options: any): void;
|
|
||||||
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
export declare class PersonalAccessTokenCredentialHandler implements ifm.IRequestHandler {
|
|
||||||
token: string;
|
|
||||||
constructor(token: string);
|
|
||||||
prepareRequest(options: any): void;
|
|
||||||
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
class BasicCredentialHandler {
|
|
||||||
constructor(username, password) {
|
|
||||||
this.username = username;
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
prepareRequest(options) {
|
|
||||||
options.headers['Authorization'] = 'Basic ' + Buffer.from(this.username + ':' + this.password).toString('base64');
|
|
||||||
}
|
|
||||||
// This handler cannot handle 401
|
|
||||||
canHandleAuthentication(response) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
handleAuthentication(httpClient, requestInfo, objs) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.BasicCredentialHandler = BasicCredentialHandler;
|
|
||||||
class BearerCredentialHandler {
|
|
||||||
constructor(token) {
|
|
||||||
this.token = token;
|
|
||||||
}
|
|
||||||
// currently implements pre-authorization
|
|
||||||
// TODO: support preAuth = false where it hooks on 401
|
|
||||||
prepareRequest(options) {
|
|
||||||
options.headers['Authorization'] = 'Bearer ' + this.token;
|
|
||||||
}
|
|
||||||
// This handler cannot handle 401
|
|
||||||
canHandleAuthentication(response) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
handleAuthentication(httpClient, requestInfo, objs) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.BearerCredentialHandler = BearerCredentialHandler;
|
|
||||||
class PersonalAccessTokenCredentialHandler {
|
|
||||||
constructor(token) {
|
|
||||||
this.token = token;
|
|
||||||
}
|
|
||||||
// currently implements pre-authorization
|
|
||||||
// TODO: support preAuth = false where it hooks on 401
|
|
||||||
prepareRequest(options) {
|
|
||||||
options.headers['Authorization'] = 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64');
|
|
||||||
}
|
|
||||||
// This handler cannot handle 401
|
|
||||||
canHandleAuthentication(response) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
handleAuthentication(httpClient, requestInfo, objs) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
|
|
||||||
|
|
@ -1,100 +0,0 @@
|
||||||
/// <reference types="node" />
|
|
||||||
import http = require("http");
|
|
||||||
import ifm = require('./interfaces');
|
|
||||||
export declare enum HttpCodes {
|
|
||||||
OK = 200,
|
|
||||||
MultipleChoices = 300,
|
|
||||||
MovedPermanently = 301,
|
|
||||||
ResourceMoved = 302,
|
|
||||||
SeeOther = 303,
|
|
||||||
NotModified = 304,
|
|
||||||
UseProxy = 305,
|
|
||||||
SwitchProxy = 306,
|
|
||||||
TemporaryRedirect = 307,
|
|
||||||
PermanentRedirect = 308,
|
|
||||||
BadRequest = 400,
|
|
||||||
Unauthorized = 401,
|
|
||||||
PaymentRequired = 402,
|
|
||||||
Forbidden = 403,
|
|
||||||
NotFound = 404,
|
|
||||||
MethodNotAllowed = 405,
|
|
||||||
NotAcceptable = 406,
|
|
||||||
ProxyAuthenticationRequired = 407,
|
|
||||||
RequestTimeout = 408,
|
|
||||||
Conflict = 409,
|
|
||||||
Gone = 410,
|
|
||||||
InternalServerError = 500,
|
|
||||||
NotImplemented = 501,
|
|
||||||
BadGateway = 502,
|
|
||||||
ServiceUnavailable = 503,
|
|
||||||
GatewayTimeout = 504
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
|
|
||||||
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
|
|
||||||
*/
|
|
||||||
export declare function getProxyUrl(serverUrl: string): string;
|
|
||||||
export declare class HttpClientResponse implements ifm.IHttpClientResponse {
|
|
||||||
constructor(message: http.IncomingMessage);
|
|
||||||
message: http.IncomingMessage;
|
|
||||||
readBody(): Promise<string>;
|
|
||||||
}
|
|
||||||
export declare function isHttps(requestUrl: string): boolean;
|
|
||||||
export declare class HttpClient {
|
|
||||||
userAgent: string | undefined;
|
|
||||||
handlers: ifm.IRequestHandler[];
|
|
||||||
requestOptions: ifm.IRequestOptions;
|
|
||||||
private _ignoreSslError;
|
|
||||||
private _socketTimeout;
|
|
||||||
private _allowRedirects;
|
|
||||||
private _allowRedirectDowngrade;
|
|
||||||
private _maxRedirects;
|
|
||||||
private _allowRetries;
|
|
||||||
private _maxRetries;
|
|
||||||
private _agent;
|
|
||||||
private _proxyAgent;
|
|
||||||
private _keepAlive;
|
|
||||||
private _disposed;
|
|
||||||
constructor(userAgent?: string, handlers?: ifm.IRequestHandler[], requestOptions?: ifm.IRequestOptions);
|
|
||||||
options(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
get(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
del(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
post(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
patch(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
put(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
head(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
/**
|
|
||||||
* Makes a raw http request.
|
|
||||||
* All other methods such as get, post, patch, and request ultimately call this.
|
|
||||||
* Prefer get, del, post and patch
|
|
||||||
*/
|
|
||||||
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
|
|
||||||
/**
|
|
||||||
* Needs to be called if keepAlive is set to true in request options.
|
|
||||||
*/
|
|
||||||
dispose(): void;
|
|
||||||
/**
|
|
||||||
* Raw request.
|
|
||||||
* @param info
|
|
||||||
* @param data
|
|
||||||
*/
|
|
||||||
requestRaw(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream): Promise<ifm.IHttpClientResponse>;
|
|
||||||
/**
|
|
||||||
* Raw request with callback.
|
|
||||||
* @param info
|
|
||||||
* @param data
|
|
||||||
* @param onResult
|
|
||||||
*/
|
|
||||||
requestRawWithCallback(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: ifm.IHttpClientResponse) => void): void;
|
|
||||||
/**
|
|
||||||
* Gets an http agent. This function is useful when you need an http agent that handles
|
|
||||||
* routing through a proxy server - depending upon the url and proxy environment variables.
|
|
||||||
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
|
|
||||||
*/
|
|
||||||
getAgent(serverUrl: string): http.Agent;
|
|
||||||
private _prepareRequest;
|
|
||||||
private _mergeHeaders;
|
|
||||||
private _getAgent;
|
|
||||||
private _performExponentialBackoff;
|
|
||||||
}
|
|
||||||
|
|
@ -1,386 +0,0 @@
|
||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const url = require("url");
|
|
||||||
const http = require("http");
|
|
||||||
const https = require("https");
|
|
||||||
const pm = require("./proxy");
|
|
||||||
let tunnel;
|
|
||||||
var HttpCodes;
|
|
||||||
(function (HttpCodes) {
|
|
||||||
HttpCodes[HttpCodes["OK"] = 200] = "OK";
|
|
||||||
HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
|
|
||||||
HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
|
|
||||||
HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
|
|
||||||
HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
|
|
||||||
HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
|
|
||||||
HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
|
|
||||||
HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
|
|
||||||
HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
|
|
||||||
HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
|
|
||||||
HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
|
|
||||||
HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
|
|
||||||
HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
|
|
||||||
HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
|
|
||||||
HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
|
|
||||||
HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
|
|
||||||
HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
|
|
||||||
HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
|
|
||||||
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
|
|
||||||
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
|
|
||||||
HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
|
|
||||||
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
|
|
||||||
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
|
|
||||||
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
|
|
||||||
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
|
|
||||||
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
|
|
||||||
})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
|
|
||||||
/**
|
|
||||||
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
|
|
||||||
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
|
|
||||||
*/
|
|
||||||
function getProxyUrl(serverUrl) {
|
|
||||||
let proxyUrl = pm.getProxyUrl(url.parse(serverUrl));
|
|
||||||
return proxyUrl ? proxyUrl.href : '';
|
|
||||||
}
|
|
||||||
exports.getProxyUrl = getProxyUrl;
|
|
||||||
const HttpRedirectCodes = [HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect];
|
|
||||||
const HttpResponseRetryCodes = [HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout];
|
|
||||||
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
|
|
||||||
const ExponentialBackoffCeiling = 10;
|
|
||||||
const ExponentialBackoffTimeSlice = 5;
|
|
||||||
class HttpClientResponse {
|
|
||||||
constructor(message) {
|
|
||||||
this.message = message;
|
|
||||||
}
|
|
||||||
readBody() {
|
|
||||||
return new Promise(async (resolve, reject) => {
|
|
||||||
let output = Buffer.alloc(0);
|
|
||||||
this.message.on('data', (chunk) => {
|
|
||||||
output = Buffer.concat([output, chunk]);
|
|
||||||
});
|
|
||||||
this.message.on('end', () => {
|
|
||||||
resolve(output.toString());
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.HttpClientResponse = HttpClientResponse;
|
|
||||||
function isHttps(requestUrl) {
|
|
||||||
let parsedUrl = url.parse(requestUrl);
|
|
||||||
return parsedUrl.protocol === 'https:';
|
|
||||||
}
|
|
||||||
exports.isHttps = isHttps;
|
|
||||||
class HttpClient {
|
|
||||||
constructor(userAgent, handlers, requestOptions) {
|
|
||||||
this._ignoreSslError = false;
|
|
||||||
this._allowRedirects = true;
|
|
||||||
this._allowRedirectDowngrade = false;
|
|
||||||
this._maxRedirects = 50;
|
|
||||||
this._allowRetries = false;
|
|
||||||
this._maxRetries = 1;
|
|
||||||
this._keepAlive = false;
|
|
||||||
this._disposed = false;
|
|
||||||
this.userAgent = userAgent;
|
|
||||||
this.handlers = handlers || [];
|
|
||||||
this.requestOptions = requestOptions;
|
|
||||||
if (requestOptions) {
|
|
||||||
if (requestOptions.ignoreSslError != null) {
|
|
||||||
this._ignoreSslError = requestOptions.ignoreSslError;
|
|
||||||
}
|
|
||||||
this._socketTimeout = requestOptions.socketTimeout;
|
|
||||||
if (requestOptions.allowRedirects != null) {
|
|
||||||
this._allowRedirects = requestOptions.allowRedirects;
|
|
||||||
}
|
|
||||||
if (requestOptions.allowRedirectDowngrade != null) {
|
|
||||||
this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
|
|
||||||
}
|
|
||||||
if (requestOptions.maxRedirects != null) {
|
|
||||||
this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
|
|
||||||
}
|
|
||||||
if (requestOptions.keepAlive != null) {
|
|
||||||
this._keepAlive = requestOptions.keepAlive;
|
|
||||||
}
|
|
||||||
if (requestOptions.allowRetries != null) {
|
|
||||||
this._allowRetries = requestOptions.allowRetries;
|
|
||||||
}
|
|
||||||
if (requestOptions.maxRetries != null) {
|
|
||||||
this._maxRetries = requestOptions.maxRetries;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
options(requestUrl, additionalHeaders) {
|
|
||||||
return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
|
|
||||||
}
|
|
||||||
get(requestUrl, additionalHeaders) {
|
|
||||||
return this.request('GET', requestUrl, null, additionalHeaders || {});
|
|
||||||
}
|
|
||||||
del(requestUrl, additionalHeaders) {
|
|
||||||
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
|
|
||||||
}
|
|
||||||
post(requestUrl, data, additionalHeaders) {
|
|
||||||
return this.request('POST', requestUrl, data, additionalHeaders || {});
|
|
||||||
}
|
|
||||||
patch(requestUrl, data, additionalHeaders) {
|
|
||||||
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
|
|
||||||
}
|
|
||||||
put(requestUrl, data, additionalHeaders) {
|
|
||||||
return this.request('PUT', requestUrl, data, additionalHeaders || {});
|
|
||||||
}
|
|
||||||
head(requestUrl, additionalHeaders) {
|
|
||||||
return this.request('HEAD', requestUrl, null, additionalHeaders || {});
|
|
||||||
}
|
|
||||||
sendStream(verb, requestUrl, stream, additionalHeaders) {
|
|
||||||
return this.request(verb, requestUrl, stream, additionalHeaders);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Makes a raw http request.
|
|
||||||
* All other methods such as get, post, patch, and request ultimately call this.
|
|
||||||
* Prefer get, del, post and patch
|
|
||||||
*/
|
|
||||||
async request(verb, requestUrl, data, headers) {
|
|
||||||
if (this._disposed) {
|
|
||||||
throw new Error("Client has already been disposed.");
|
|
||||||
}
|
|
||||||
let parsedUrl = url.parse(requestUrl);
|
|
||||||
let info = this._prepareRequest(verb, parsedUrl, headers);
|
|
||||||
// Only perform retries on reads since writes may not be idempotent.
|
|
||||||
let maxTries = (this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1) ? this._maxRetries + 1 : 1;
|
|
||||||
let numTries = 0;
|
|
||||||
let response;
|
|
||||||
while (numTries < maxTries) {
|
|
||||||
response = await this.requestRaw(info, data);
|
|
||||||
// Check if it's an authentication challenge
|
|
||||||
if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) {
|
|
||||||
let authenticationHandler;
|
|
||||||
for (let i = 0; i < this.handlers.length; i++) {
|
|
||||||
if (this.handlers[i].canHandleAuthentication(response)) {
|
|
||||||
authenticationHandler = this.handlers[i];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (authenticationHandler) {
|
|
||||||
return authenticationHandler.handleAuthentication(this, info, data);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// We have received an unauthorized response but have no handlers to handle it.
|
|
||||||
// Let the response return to the caller.
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let redirectsRemaining = this._maxRedirects;
|
|
||||||
while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1
|
|
||||||
&& this._allowRedirects
|
|
||||||
&& redirectsRemaining > 0) {
|
|
||||||
const redirectUrl = response.message.headers["location"];
|
|
||||||
if (!redirectUrl) {
|
|
||||||
// if there's no location to redirect to, we won't
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let parsedRedirectUrl = url.parse(redirectUrl);
|
|
||||||
if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) {
|
|
||||||
throw new Error("Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.");
|
|
||||||
}
|
|
||||||
// we need to finish reading the response before reassigning response
|
|
||||||
// which will leak the open socket.
|
|
||||||
await response.readBody();
|
|
||||||
// let's make the request with the new redirectUrl
|
|
||||||
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
|
|
||||||
response = await this.requestRaw(info, data);
|
|
||||||
redirectsRemaining--;
|
|
||||||
}
|
|
||||||
if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {
|
|
||||||
// If not a retry code, return immediately instead of retrying
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
numTries += 1;
|
|
||||||
if (numTries < maxTries) {
|
|
||||||
await response.readBody();
|
|
||||||
await this._performExponentialBackoff(numTries);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Needs to be called if keepAlive is set to true in request options.
|
|
||||||
*/
|
|
||||||
dispose() {
|
|
||||||
if (this._agent) {
|
|
||||||
this._agent.destroy();
|
|
||||||
}
|
|
||||||
this._disposed = true;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Raw request.
|
|
||||||
* @param info
|
|
||||||
* @param data
|
|
||||||
*/
|
|
||||||
requestRaw(info, data) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
let callbackForResult = function (err, res) {
|
|
||||||
if (err) {
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
resolve(res);
|
|
||||||
};
|
|
||||||
this.requestRawWithCallback(info, data, callbackForResult);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Raw request with callback.
|
|
||||||
* @param info
|
|
||||||
* @param data
|
|
||||||
* @param onResult
|
|
||||||
*/
|
|
||||||
requestRawWithCallback(info, data, onResult) {
|
|
||||||
let socket;
|
|
||||||
if (typeof (data) === 'string') {
|
|
||||||
info.options.headers["Content-Length"] = Buffer.byteLength(data, 'utf8');
|
|
||||||
}
|
|
||||||
let callbackCalled = false;
|
|
||||||
let handleResult = (err, res) => {
|
|
||||||
if (!callbackCalled) {
|
|
||||||
callbackCalled = true;
|
|
||||||
onResult(err, res);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let req = info.httpModule.request(info.options, (msg) => {
|
|
||||||
let res = new HttpClientResponse(msg);
|
|
||||||
handleResult(null, res);
|
|
||||||
});
|
|
||||||
req.on('socket', (sock) => {
|
|
||||||
socket = sock;
|
|
||||||
});
|
|
||||||
// If we ever get disconnected, we want the socket to timeout eventually
|
|
||||||
req.setTimeout(this._socketTimeout || 3 * 60000, () => {
|
|
||||||
if (socket) {
|
|
||||||
socket.end();
|
|
||||||
}
|
|
||||||
handleResult(new Error('Request timeout: ' + info.options.path), null);
|
|
||||||
});
|
|
||||||
req.on('error', function (err) {
|
|
||||||
// err has statusCode property
|
|
||||||
// res should have headers
|
|
||||||
handleResult(err, null);
|
|
||||||
});
|
|
||||||
if (data && typeof (data) === 'string') {
|
|
||||||
req.write(data, 'utf8');
|
|
||||||
}
|
|
||||||
if (data && typeof (data) !== 'string') {
|
|
||||||
data.on('close', function () {
|
|
||||||
req.end();
|
|
||||||
});
|
|
||||||
data.pipe(req);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
req.end();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Gets an http agent. This function is useful when you need an http agent that handles
|
|
||||||
* routing through a proxy server - depending upon the url and proxy environment variables.
|
|
||||||
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
|
|
||||||
*/
|
|
||||||
getAgent(serverUrl) {
|
|
||||||
let parsedUrl = url.parse(serverUrl);
|
|
||||||
return this._getAgent(parsedUrl);
|
|
||||||
}
|
|
||||||
_prepareRequest(method, requestUrl, headers) {
|
|
||||||
const info = {};
|
|
||||||
info.parsedUrl = requestUrl;
|
|
||||||
const usingSsl = info.parsedUrl.protocol === 'https:';
|
|
||||||
info.httpModule = usingSsl ? https : http;
|
|
||||||
const defaultPort = usingSsl ? 443 : 80;
|
|
||||||
info.options = {};
|
|
||||||
info.options.host = info.parsedUrl.hostname;
|
|
||||||
info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort;
|
|
||||||
info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
|
|
||||||
info.options.method = method;
|
|
||||||
info.options.headers = this._mergeHeaders(headers);
|
|
||||||
if (this.userAgent != null) {
|
|
||||||
info.options.headers["user-agent"] = this.userAgent;
|
|
||||||
}
|
|
||||||
info.options.agent = this._getAgent(info.parsedUrl);
|
|
||||||
// gives handlers an opportunity to participate
|
|
||||||
if (this.handlers) {
|
|
||||||
this.handlers.forEach((handler) => {
|
|
||||||
handler.prepareRequest(info.options);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return info;
|
|
||||||
}
|
|
||||||
_mergeHeaders(headers) {
|
|
||||||
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => (c[k.toLowerCase()] = obj[k], c), {});
|
|
||||||
if (this.requestOptions && this.requestOptions.headers) {
|
|
||||||
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
|
|
||||||
}
|
|
||||||
return lowercaseKeys(headers || {});
|
|
||||||
}
|
|
||||||
_getAgent(parsedUrl) {
|
|
||||||
let agent;
|
|
||||||
let proxyUrl = pm.getProxyUrl(parsedUrl);
|
|
||||||
let useProxy = proxyUrl && proxyUrl.hostname;
|
|
||||||
if (this._keepAlive && useProxy) {
|
|
||||||
agent = this._proxyAgent;
|
|
||||||
}
|
|
||||||
if (this._keepAlive && !useProxy) {
|
|
||||||
agent = this._agent;
|
|
||||||
}
|
|
||||||
// if agent is already assigned use that agent.
|
|
||||||
if (!!agent) {
|
|
||||||
return agent;
|
|
||||||
}
|
|
||||||
const usingSsl = parsedUrl.protocol === 'https:';
|
|
||||||
let maxSockets = 100;
|
|
||||||
if (!!this.requestOptions) {
|
|
||||||
maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
|
|
||||||
}
|
|
||||||
if (useProxy) {
|
|
||||||
// If using proxy, need tunnel
|
|
||||||
if (!tunnel) {
|
|
||||||
tunnel = require('tunnel');
|
|
||||||
}
|
|
||||||
const agentOptions = {
|
|
||||||
maxSockets: maxSockets,
|
|
||||||
keepAlive: this._keepAlive,
|
|
||||||
proxy: {
|
|
||||||
proxyAuth: proxyUrl.auth,
|
|
||||||
host: proxyUrl.hostname,
|
|
||||||
port: proxyUrl.port
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let tunnelAgent;
|
|
||||||
const overHttps = proxyUrl.protocol === 'https:';
|
|
||||||
if (usingSsl) {
|
|
||||||
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
|
|
||||||
}
|
|
||||||
agent = tunnelAgent(agentOptions);
|
|
||||||
this._proxyAgent = agent;
|
|
||||||
}
|
|
||||||
// if reusing agent across request and tunneling agent isn't assigned create a new agent
|
|
||||||
if (this._keepAlive && !agent) {
|
|
||||||
const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };
|
|
||||||
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
|
|
||||||
this._agent = agent;
|
|
||||||
}
|
|
||||||
// if not using private agent and tunnel agent isn't setup then use global agent
|
|
||||||
if (!agent) {
|
|
||||||
agent = usingSsl ? https.globalAgent : http.globalAgent;
|
|
||||||
}
|
|
||||||
if (usingSsl && this._ignoreSslError) {
|
|
||||||
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
|
|
||||||
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
|
|
||||||
// we have to cast it to any and change it directly
|
|
||||||
agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false });
|
|
||||||
}
|
|
||||||
return agent;
|
|
||||||
}
|
|
||||||
_performExponentialBackoff(retryNumber) {
|
|
||||||
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
|
|
||||||
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
|
|
||||||
return new Promise(resolve => setTimeout(() => resolve(), ms));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.HttpClient = HttpClient;
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
/// <reference types="node" />
|
|
||||||
import http = require("http");
|
|
||||||
import url = require("url");
|
|
||||||
export interface IHeaders {
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
export interface IHttpClient {
|
|
||||||
options(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
get(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
del(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
post(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
patch(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
put(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: IHeaders): Promise<IHttpClientResponse>;
|
|
||||||
requestRaw(info: IRequestInfo, data: string | NodeJS.ReadableStream): Promise<IHttpClientResponse>;
|
|
||||||
requestRawWithCallback(info: IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: IHttpClientResponse) => void): void;
|
|
||||||
}
|
|
||||||
export interface IRequestHandler {
|
|
||||||
prepareRequest(options: http.RequestOptions): void;
|
|
||||||
canHandleAuthentication(response: IHttpClientResponse): boolean;
|
|
||||||
handleAuthentication(httpClient: IHttpClient, requestInfo: IRequestInfo, objs: any): Promise<IHttpClientResponse>;
|
|
||||||
}
|
|
||||||
export interface IHttpClientResponse {
|
|
||||||
message: http.IncomingMessage;
|
|
||||||
readBody(): Promise<string>;
|
|
||||||
}
|
|
||||||
export interface IRequestInfo {
|
|
||||||
options: http.RequestOptions;
|
|
||||||
parsedUrl: url.Url;
|
|
||||||
httpModule: any;
|
|
||||||
}
|
|
||||||
export interface IRequestOptions {
|
|
||||||
headers?: IHeaders;
|
|
||||||
socketTimeout?: number;
|
|
||||||
ignoreSslError?: boolean;
|
|
||||||
allowRedirects?: boolean;
|
|
||||||
allowRedirectDowngrade?: boolean;
|
|
||||||
maxRedirects?: number;
|
|
||||||
maxSockets?: number;
|
|
||||||
keepAlive?: boolean;
|
|
||||||
allowRetries?: boolean;
|
|
||||||
maxRetries?: number;
|
|
||||||
}
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
;
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
{
|
|
||||||
"name": "@actions/http-client",
|
|
||||||
"version": "1.0.3",
|
|
||||||
"description": "Actions Http Client",
|
|
||||||
"main": "index.js",
|
|
||||||
"scripts": {
|
|
||||||
"build": "rm -Rf ./_out && tsc && cp package*.json ./_out && cp *.md ./_out && cp LICENSE ./_out && cp actions.png ./_out",
|
|
||||||
"test": "jest"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/actions/http-client.git"
|
|
||||||
},
|
|
||||||
"keywords": [
|
|
||||||
"Actions",
|
|
||||||
"Http"
|
|
||||||
],
|
|
||||||
"author": "GitHub, Inc.",
|
|
||||||
"license": "MIT",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/actions/http-client/issues"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/actions/http-client#readme",
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/jest": "^24.0.25",
|
|
||||||
"@types/node": "^12.12.24",
|
|
||||||
"jest": "^24.9.0",
|
|
||||||
"proxy": "^1.0.1",
|
|
||||||
"ts-jest": "^24.3.0",
|
|
||||||
"typescript": "^3.7.4"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"tunnel": "0.0.6"
|
|
||||||
}
|
|
||||||
|
|
||||||
,"_resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.3.tgz"
|
|
||||||
,"_integrity": "sha512-wFwh1U4adB/Zsk4cc9kVqaBOHoknhp/pJQk+aWTocbAZWpIl4Zx/At83WFRLXvxB+5HVTWOACM6qjULMZfQSfw=="
|
|
||||||
,"_from": "@actions/http-client@1.0.3"
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +0,0 @@
|
||||||
/// <reference types="node" />
|
|
||||||
import * as url from 'url';
|
|
||||||
export declare function getProxyUrl(reqUrl: url.Url): url.Url | undefined;
|
|
||||||
export declare function checkBypass(reqUrl: url.Url): boolean;
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const url = require("url");
|
|
||||||
function getProxyUrl(reqUrl) {
|
|
||||||
let usingSsl = reqUrl.protocol === 'https:';
|
|
||||||
let proxyUrl;
|
|
||||||
if (checkBypass(reqUrl)) {
|
|
||||||
return proxyUrl;
|
|
||||||
}
|
|
||||||
let proxyVar;
|
|
||||||
if (usingSsl) {
|
|
||||||
proxyVar = process.env["https_proxy"] ||
|
|
||||||
process.env["HTTPS_PROXY"];
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
proxyVar = process.env["http_proxy"] ||
|
|
||||||
process.env["HTTP_PROXY"];
|
|
||||||
}
|
|
||||||
if (proxyVar) {
|
|
||||||
proxyUrl = url.parse(proxyVar);
|
|
||||||
}
|
|
||||||
return proxyUrl;
|
|
||||||
}
|
|
||||||
exports.getProxyUrl = getProxyUrl;
|
|
||||||
function checkBypass(reqUrl) {
|
|
||||||
if (!reqUrl.hostname) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let noProxy = process.env["no_proxy"] || process.env["NO_PROXY"] || '';
|
|
||||||
if (!noProxy) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// Determine the request port
|
|
||||||
let reqPort;
|
|
||||||
if (reqUrl.port) {
|
|
||||||
reqPort = Number(reqUrl.port);
|
|
||||||
}
|
|
||||||
else if (reqUrl.protocol === 'http:') {
|
|
||||||
reqPort = 80;
|
|
||||||
}
|
|
||||||
else if (reqUrl.protocol === 'https:') {
|
|
||||||
reqPort = 443;
|
|
||||||
}
|
|
||||||
// Format the request hostname and hostname with port
|
|
||||||
let upperReqHosts = [reqUrl.hostname.toUpperCase()];
|
|
||||||
if (typeof reqPort === 'number') {
|
|
||||||
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
|
|
||||||
}
|
|
||||||
// Compare request host against noproxy
|
|
||||||
for (let upperNoProxyItem of noProxy.split(',').map(x => x.trim().toUpperCase()).filter(x => x)) {
|
|
||||||
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
exports.checkBypass = checkBypass;
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
# `@actions/io`
|
|
||||||
|
|
||||||
> Core functions for cli filesystem scenarios
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
#### mkdir -p
|
|
||||||
|
|
||||||
Recursively make a directory. Follows rules specified in [man mkdir](https://linux.die.net/man/1/mkdir) with the `-p` option specified:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const io = require('@actions/io');
|
|
||||||
|
|
||||||
await io.mkdirP('path/to/make');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### cp/mv
|
|
||||||
|
|
||||||
Copy or move files or folders. Follows rules specified in [man cp](https://linux.die.net/man/1/cp) and [man mv](https://linux.die.net/man/1/mv):
|
|
||||||
|
|
||||||
```js
|
|
||||||
const io = require('@actions/io');
|
|
||||||
|
|
||||||
// Recursive must be true for directories
|
|
||||||
const options = { recursive: true, force: false }
|
|
||||||
|
|
||||||
await io.cp('path/to/directory', 'path/to/dest', options);
|
|
||||||
await io.mv('path/to/file', 'path/to/dest');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### rm -rf
|
|
||||||
|
|
||||||
Remove a file or folder recursively. Follows rules specified in [man rm](https://linux.die.net/man/1/rm) with the `-r` and `-f` rules specified.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const io = require('@actions/io');
|
|
||||||
|
|
||||||
await io.rmRF('path/to/directory');
|
|
||||||
await io.rmRF('path/to/file');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### which
|
|
||||||
|
|
||||||
Get the path to a tool and resolves via paths. Follows the rules specified in [man which](https://linux.die.net/man/1/which).
|
|
||||||
|
|
||||||
```js
|
|
||||||
const exec = require('@actions/exec');
|
|
||||||
const io = require('@actions/io');
|
|
||||||
|
|
||||||
const pythonPath: string = await io.which('python', true)
|
|
||||||
|
|
||||||
await exec.exec(`"${pythonPath}"`, ['main.py']);
|
|
||||||
```
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
/// <reference types="node" />
|
|
||||||
import * as fs from 'fs';
|
|
||||||
export declare const chmod: typeof fs.promises.chmod, copyFile: typeof fs.promises.copyFile, lstat: typeof fs.promises.lstat, mkdir: typeof fs.promises.mkdir, readdir: typeof fs.promises.readdir, readlink: typeof fs.promises.readlink, rename: typeof fs.promises.rename, rmdir: typeof fs.promises.rmdir, stat: typeof fs.promises.stat, symlink: typeof fs.promises.symlink, unlink: typeof fs.promises.unlink;
|
|
||||||
export declare const IS_WINDOWS: boolean;
|
|
||||||
export declare function exists(fsPath: string): Promise<boolean>;
|
|
||||||
export declare function isDirectory(fsPath: string, useStat?: boolean): Promise<boolean>;
|
|
||||||
/**
|
|
||||||
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
|
||||||
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
|
||||||
*/
|
|
||||||
export declare function isRooted(p: string): boolean;
|
|
||||||
/**
|
|
||||||
* Recursively create a directory at `fsPath`.
|
|
||||||
*
|
|
||||||
* This implementation is optimistic, meaning it attempts to create the full
|
|
||||||
* path first, and backs up the path stack from there.
|
|
||||||
*
|
|
||||||
* @param fsPath The path to create
|
|
||||||
* @param maxDepth The maximum recursion depth
|
|
||||||
* @param depth The current recursion depth
|
|
||||||
*/
|
|
||||||
export declare function mkdirP(fsPath: string, maxDepth?: number, depth?: number): Promise<void>;
|
|
||||||
/**
|
|
||||||
* Best effort attempt to determine whether a file exists and is executable.
|
|
||||||
* @param filePath file path to check
|
|
||||||
* @param extensions additional file extensions to try
|
|
||||||
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
|
||||||
*/
|
|
||||||
export declare function tryGetExecutablePath(filePath: string, extensions: string[]): Promise<string>;
|
|
||||||
|
|
@ -1,195 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var _a;
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const assert_1 = require("assert");
|
|
||||||
const fs = require("fs");
|
|
||||||
const path = require("path");
|
|
||||||
_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
|
|
||||||
exports.IS_WINDOWS = process.platform === 'win32';
|
|
||||||
function exists(fsPath) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
try {
|
|
||||||
yield exports.stat(fsPath);
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
if (err.code === 'ENOENT') {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.exists = exists;
|
|
||||||
function isDirectory(fsPath, useStat = false) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);
|
|
||||||
return stats.isDirectory();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.isDirectory = isDirectory;
|
|
||||||
/**
|
|
||||||
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
|
||||||
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
|
||||||
*/
|
|
||||||
function isRooted(p) {
|
|
||||||
p = normalizeSeparators(p);
|
|
||||||
if (!p) {
|
|
||||||
throw new Error('isRooted() parameter "p" cannot be empty');
|
|
||||||
}
|
|
||||||
if (exports.IS_WINDOWS) {
|
|
||||||
return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
|
|
||||||
); // e.g. C: or C:\hello
|
|
||||||
}
|
|
||||||
return p.startsWith('/');
|
|
||||||
}
|
|
||||||
exports.isRooted = isRooted;
|
|
||||||
/**
|
|
||||||
* Recursively create a directory at `fsPath`.
|
|
||||||
*
|
|
||||||
* This implementation is optimistic, meaning it attempts to create the full
|
|
||||||
* path first, and backs up the path stack from there.
|
|
||||||
*
|
|
||||||
* @param fsPath The path to create
|
|
||||||
* @param maxDepth The maximum recursion depth
|
|
||||||
* @param depth The current recursion depth
|
|
||||||
*/
|
|
||||||
function mkdirP(fsPath, maxDepth = 1000, depth = 1) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
assert_1.ok(fsPath, 'a path argument must be provided');
|
|
||||||
fsPath = path.resolve(fsPath);
|
|
||||||
if (depth >= maxDepth)
|
|
||||||
return exports.mkdir(fsPath);
|
|
||||||
try {
|
|
||||||
yield exports.mkdir(fsPath);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
switch (err.code) {
|
|
||||||
case 'ENOENT': {
|
|
||||||
yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1);
|
|
||||||
yield exports.mkdir(fsPath);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
default: {
|
|
||||||
let stats;
|
|
||||||
try {
|
|
||||||
stats = yield exports.stat(fsPath);
|
|
||||||
}
|
|
||||||
catch (err2) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
if (!stats.isDirectory())
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.mkdirP = mkdirP;
|
|
||||||
/**
|
|
||||||
* Best effort attempt to determine whether a file exists and is executable.
|
|
||||||
* @param filePath file path to check
|
|
||||||
* @param extensions additional file extensions to try
|
|
||||||
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
|
||||||
*/
|
|
||||||
function tryGetExecutablePath(filePath, extensions) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
let stats = undefined;
|
|
||||||
try {
|
|
||||||
// test file exists
|
|
||||||
stats = yield exports.stat(filePath);
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
if (err.code !== 'ENOENT') {
|
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (stats && stats.isFile()) {
|
|
||||||
if (exports.IS_WINDOWS) {
|
|
||||||
// on Windows, test for valid extension
|
|
||||||
const upperExt = path.extname(filePath).toUpperCase();
|
|
||||||
if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
|
|
||||||
return filePath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (isUnixExecutable(stats)) {
|
|
||||||
return filePath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// try each extension
|
|
||||||
const originalFilePath = filePath;
|
|
||||||
for (const extension of extensions) {
|
|
||||||
filePath = originalFilePath + extension;
|
|
||||||
stats = undefined;
|
|
||||||
try {
|
|
||||||
stats = yield exports.stat(filePath);
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
if (err.code !== 'ENOENT') {
|
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (stats && stats.isFile()) {
|
|
||||||
if (exports.IS_WINDOWS) {
|
|
||||||
// preserve the case of the actual file (since an extension was appended)
|
|
||||||
try {
|
|
||||||
const directory = path.dirname(filePath);
|
|
||||||
const upperName = path.basename(filePath).toUpperCase();
|
|
||||||
for (const actualName of yield exports.readdir(directory)) {
|
|
||||||
if (upperName === actualName.toUpperCase()) {
|
|
||||||
filePath = path.join(directory, actualName);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
|
|
||||||
}
|
|
||||||
return filePath;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (isUnixExecutable(stats)) {
|
|
||||||
return filePath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.tryGetExecutablePath = tryGetExecutablePath;
|
|
||||||
function normalizeSeparators(p) {
|
|
||||||
p = p || '';
|
|
||||||
if (exports.IS_WINDOWS) {
|
|
||||||
// convert slashes on Windows
|
|
||||||
p = p.replace(/\//g, '\\');
|
|
||||||
// remove redundant slashes
|
|
||||||
return p.replace(/\\\\+/g, '\\');
|
|
||||||
}
|
|
||||||
// remove redundant slashes
|
|
||||||
return p.replace(/\/\/+/g, '/');
|
|
||||||
}
|
|
||||||
// on Mac/Linux, test the execute bit
|
|
||||||
// R W X R W X R W X
|
|
||||||
// 256 128 64 32 16 8 4 2 1
|
|
||||||
function isUnixExecutable(stats) {
|
|
||||||
return ((stats.mode & 1) > 0 ||
|
|
||||||
((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||
|
|
||||||
((stats.mode & 64) > 0 && stats.uid === process.getuid()));
|
|
||||||
}
|
|
||||||
//# sourceMappingURL=io-util.js.map
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"version":3,"file":"io-util.js","sourceRoot":"","sources":["../src/io-util.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAAyB;AACzB,yBAAwB;AACxB,6BAA4B;AAEf,gBAYE,qTAAA;AAEF,QAAA,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;AAEtD,SAAsB,MAAM,CAAC,MAAc;;QACzC,IAAI;YACF,MAAM,YAAI,CAAC,MAAM,CAAC,CAAA;SACnB;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,OAAO,KAAK,CAAA;aACb;YAED,MAAM,GAAG,CAAA;SACV;QAED,OAAO,IAAI,CAAA;IACb,CAAC;CAAA;AAZD,wBAYC;AAED,SAAsB,WAAW,CAC/B,MAAc,EACd,UAAmB,KAAK;;QAExB,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,YAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;QAChE,OAAO,KAAK,CAAC,WAAW,EAAE,CAAA;IAC5B,CAAC;CAAA;AAND,kCAMC;AAED;;;GAGG;AACH,SAAgB,QAAQ,CAAC,CAAS;IAChC,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAA;IAC1B,IAAI,CAAC,CAAC,EAAE;QACN,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;KAC5D;IAED,IAAI,kBAAU,EAAE;QACd,OAAO,CACL,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,8BAA8B;SACxE,CAAA,CAAC,sBAAsB;KACzB;IAED,OAAO,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;AAC1B,CAAC;AAbD,4BAaC;AAED;;;;;;;;;GASG;AACH,SAAsB,MAAM,CAC1B,MAAc,EACd,WAAmB,IAAI,EACvB,QAAgB,CAAC;;QAEjB,WAAE,CAAC,MAAM,EAAE,kCAAkC,CAAC,CAAA;QAE9C,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;QAE7B,IAAI,KAAK,IAAI,QAAQ;YAAE,OAAO,aAAK,CAAC,MAAM,CAAC,CAAA;QAE3C,IAAI;YACF,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;YACnB,OAAM;SACP;QAAC,OAAO,GAAG,EAAE;YACZ,QAAQ,GAAG,CAAC,IAAI,EAAE;gBAChB,KAAK,QAAQ,CAAC,CAAC;oBACb,MAAM,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,KAAK,GAAG,CAAC,CAAC,CAAA;oBACvD,MAAM,aAAK,CAAC,MAAM,CAAC,CAAA;oBACnB,OAAM;iBACP;gBACD,OAAO,CAAC,CAAC;oBACP,IAAI,KAAe,CAAA;oBAEnB,IAAI;wBACF,KAAK,GAAG,MAAM,YAAI,CAAC,MAAM,CAAC,CAAA;qBAC3B;oBAAC,OAAO,IAAI,EAAE;wBACb,MAAM,GAAG,CAAA;qBACV;oBAED,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE;wBAAE,MAAM,GAAG,CAAA;iBACpC;aACF;SACF;IACH,CAAC;CAAA;AAlCD,wBAkCC;AAED;;;;;GAKG;AACH,SAAsB,oBAAoB,CACxC,QAAgB,EAChB,UAAoB;;QAEpB,IAAI,KAAK,GAAyB,SAAS,CAAA;QAC3C,IAAI;YACF,mBAAmB;YACnB,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;SAC7B;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACzB,sCAAsC;gBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;aACF;SACF;QACD,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;YAC3B,IAAI,kBAAU,EAAE;gBACd,uCAAuC;gBACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;gBACrD,IAAI,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,EAAE,KAAK,QAAQ,CAAC,EAAE;oBACpE,OAAO,QAAQ,CAAA;iBAChB;aACF;iBAAM;gBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;oBAC3B,OAAO,QAAQ,CAAA;iBAChB;aACF;SACF;QAED,qBAAqB;QACrB,MAAM,gBAAgB,GAAG,QAAQ,CAAA;QACjC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE;YAClC,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CAAA;YAEvC,KAAK,GAAG,SAAS,CAAA;YACjB,IAAI;gBACF,KAAK,GAAG,MAAM,YAAI,CAAC,QAAQ,CAAC,CAAA;aAC7B;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;oBACzB,sCAAsC;oBACtC,OAAO,CAAC,GAAG,CACT,uEAAuE,QAAQ,MAAM,GAAG,EAAE,CAC3F,CAAA;iBACF;aACF;YAED,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE;gBAC3B,IAAI,kBAAU,EAAE;oBACd,yEAAyE;oBACzE,IAAI;wBACF,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;wBACxC,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,CAAA;wBACvD,KAAK,MAAM,UAAU,IAAI,MAAM,eAAO,CAAC,SAAS,CAAC,EAAE;4BACjD,IAAI,SAAS,KAAK,UAAU,CAAC,WAAW,EAAE,EAAE;gCAC1C,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;gCAC3C,MAAK;6BACN;yBACF;qBACF;oBAAC,OAAO,GAAG,EAAE;wBACZ,sCAAsC;wBACtC,OAAO,CAAC,GAAG,CACT,yEAAyE,QAAQ,MAAM,GAAG,EAAE,CAC7F,CAAA;qBACF;oBAED,OAAO,QAAQ,CAAA;iBAChB;qBAAM;oBACL,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;wBAC3B,OAAO,QAAQ,CAAA;qBAChB;iBACF;aACF;SACF;QAED,OAAO,EAAE,CAAA;IACX,CAAC;CAAA;AA5ED,oDA4EC;AAED,SAAS,mBAAmB,CAAC,CAAS;IACpC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;IACX,IAAI,kBAAU,EAAE;QACd,6BAA6B;QAC7B,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QAE1B,2BAA2B;QAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;KACjC;IAED,2BAA2B;IAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjC,CAAC;AAED,qCAAqC;AACrC,6BAA6B;AAC7B,6BAA6B;AAC7B,SAAS,gBAAgB,CAAC,KAAe;IACvC,OAAO,CACL,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC;QACpB,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC;QACxD,CAAC,CAAC,KAAK,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAC1D,CAAA;AACH,CAAC"}
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
/**
|
|
||||||
* Interface for cp/mv options
|
|
||||||
*/
|
|
||||||
export interface CopyOptions {
|
|
||||||
/** Optional. Whether to recursively copy all subdirectories. Defaults to false */
|
|
||||||
recursive?: boolean;
|
|
||||||
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
|
||||||
force?: boolean;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Interface for cp/mv options
|
|
||||||
*/
|
|
||||||
export interface MoveOptions {
|
|
||||||
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
|
||||||
force?: boolean;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Copies a file or folder.
|
|
||||||
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
|
||||||
*
|
|
||||||
* @param source source path
|
|
||||||
* @param dest destination path
|
|
||||||
* @param options optional. See CopyOptions.
|
|
||||||
*/
|
|
||||||
export declare function cp(source: string, dest: string, options?: CopyOptions): Promise<void>;
|
|
||||||
/**
|
|
||||||
* Moves a path.
|
|
||||||
*
|
|
||||||
* @param source source path
|
|
||||||
* @param dest destination path
|
|
||||||
* @param options optional. See MoveOptions.
|
|
||||||
*/
|
|
||||||
export declare function mv(source: string, dest: string, options?: MoveOptions): Promise<void>;
|
|
||||||
/**
|
|
||||||
* Remove a path recursively with force
|
|
||||||
*
|
|
||||||
* @param inputPath path to remove
|
|
||||||
*/
|
|
||||||
export declare function rmRF(inputPath: string): Promise<void>;
|
|
||||||
/**
|
|
||||||
* Make a directory. Creates the full path with folders in between
|
|
||||||
* Will throw if it fails
|
|
||||||
*
|
|
||||||
* @param fsPath path to create
|
|
||||||
* @returns Promise<void>
|
|
||||||
*/
|
|
||||||
export declare function mkdirP(fsPath: string): Promise<void>;
|
|
||||||
/**
|
|
||||||
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
|
||||||
* If you check and the tool does not exist, it will throw.
|
|
||||||
*
|
|
||||||
* @param tool name of the tool
|
|
||||||
* @param check whether to check if tool exists
|
|
||||||
* @returns Promise<string> path to tool
|
|
||||||
*/
|
|
||||||
export declare function which(tool: string, check?: boolean): Promise<string>;
|
|
||||||
|
|
@ -1,290 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const childProcess = require("child_process");
|
|
||||||
const path = require("path");
|
|
||||||
const util_1 = require("util");
|
|
||||||
const ioUtil = require("./io-util");
|
|
||||||
const exec = util_1.promisify(childProcess.exec);
|
|
||||||
/**
|
|
||||||
* Copies a file or folder.
|
|
||||||
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
|
||||||
*
|
|
||||||
* @param source source path
|
|
||||||
* @param dest destination path
|
|
||||||
* @param options optional. See CopyOptions.
|
|
||||||
*/
|
|
||||||
function cp(source, dest, options = {}) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
const { force, recursive } = readCopyOptions(options);
|
|
||||||
const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;
|
|
||||||
// Dest is an existing file, but not forcing
|
|
||||||
if (destStat && destStat.isFile() && !force) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// If dest is an existing directory, should copy inside.
|
|
||||||
const newDest = destStat && destStat.isDirectory()
|
|
||||||
? path.join(dest, path.basename(source))
|
|
||||||
: dest;
|
|
||||||
if (!(yield ioUtil.exists(source))) {
|
|
||||||
throw new Error(`no such file or directory: ${source}`);
|
|
||||||
}
|
|
||||||
const sourceStat = yield ioUtil.stat(source);
|
|
||||||
if (sourceStat.isDirectory()) {
|
|
||||||
if (!recursive) {
|
|
||||||
throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
yield cpDirRecursive(source, newDest, 0, force);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (path.relative(source, newDest) === '') {
|
|
||||||
// a file cannot be copied to itself
|
|
||||||
throw new Error(`'${newDest}' and '${source}' are the same file`);
|
|
||||||
}
|
|
||||||
yield copyFile(source, newDest, force);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.cp = cp;
|
|
||||||
/**
|
|
||||||
* Moves a path.
|
|
||||||
*
|
|
||||||
* @param source source path
|
|
||||||
* @param dest destination path
|
|
||||||
* @param options optional. See MoveOptions.
|
|
||||||
*/
|
|
||||||
function mv(source, dest, options = {}) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if (yield ioUtil.exists(dest)) {
|
|
||||||
let destExists = true;
|
|
||||||
if (yield ioUtil.isDirectory(dest)) {
|
|
||||||
// If dest is directory copy src into dest
|
|
||||||
dest = path.join(dest, path.basename(source));
|
|
||||||
destExists = yield ioUtil.exists(dest);
|
|
||||||
}
|
|
||||||
if (destExists) {
|
|
||||||
if (options.force == null || options.force) {
|
|
||||||
yield rmRF(dest);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new Error('Destination already exists');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
yield mkdirP(path.dirname(dest));
|
|
||||||
yield ioUtil.rename(source, dest);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.mv = mv;
|
|
||||||
/**
|
|
||||||
* Remove a path recursively with force
|
|
||||||
*
|
|
||||||
* @param inputPath path to remove
|
|
||||||
*/
|
|
||||||
function rmRF(inputPath) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if (ioUtil.IS_WINDOWS) {
|
|
||||||
// Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another
|
|
||||||
// program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.
|
|
||||||
try {
|
|
||||||
if (yield ioUtil.isDirectory(inputPath, true)) {
|
|
||||||
yield exec(`rd /s /q "${inputPath}"`);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
yield exec(`del /f /a "${inputPath}"`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
|
||||||
// other errors are valid
|
|
||||||
if (err.code !== 'ENOENT')
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
// Shelling out fails to remove a symlink folder with missing source, this unlink catches that
|
|
||||||
try {
|
|
||||||
yield ioUtil.unlink(inputPath);
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
|
||||||
// other errors are valid
|
|
||||||
if (err.code !== 'ENOENT')
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
let isDir = false;
|
|
||||||
try {
|
|
||||||
isDir = yield ioUtil.isDirectory(inputPath);
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
|
||||||
// other errors are valid
|
|
||||||
if (err.code !== 'ENOENT')
|
|
||||||
throw err;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (isDir) {
|
|
||||||
yield exec(`rm -rf "${inputPath}"`);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
yield ioUtil.unlink(inputPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.rmRF = rmRF;
|
|
||||||
/**
|
|
||||||
* Make a directory. Creates the full path with folders in between
|
|
||||||
* Will throw if it fails
|
|
||||||
*
|
|
||||||
* @param fsPath path to create
|
|
||||||
* @returns Promise<void>
|
|
||||||
*/
|
|
||||||
function mkdirP(fsPath) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
yield ioUtil.mkdirP(fsPath);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.mkdirP = mkdirP;
|
|
||||||
/**
|
|
||||||
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
|
||||||
* If you check and the tool does not exist, it will throw.
|
|
||||||
*
|
|
||||||
* @param tool name of the tool
|
|
||||||
* @param check whether to check if tool exists
|
|
||||||
* @returns Promise<string> path to tool
|
|
||||||
*/
|
|
||||||
function which(tool, check) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if (!tool) {
|
|
||||||
throw new Error("parameter 'tool' is required");
|
|
||||||
}
|
|
||||||
// recursive when check=true
|
|
||||||
if (check) {
|
|
||||||
const result = yield which(tool, false);
|
|
||||||
if (!result) {
|
|
||||||
if (ioUtil.IS_WINDOWS) {
|
|
||||||
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
// build the list of extensions to try
|
|
||||||
const extensions = [];
|
|
||||||
if (ioUtil.IS_WINDOWS && process.env.PATHEXT) {
|
|
||||||
for (const extension of process.env.PATHEXT.split(path.delimiter)) {
|
|
||||||
if (extension) {
|
|
||||||
extensions.push(extension);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// if it's rooted, return it if exists. otherwise return empty.
|
|
||||||
if (ioUtil.isRooted(tool)) {
|
|
||||||
const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);
|
|
||||||
if (filePath) {
|
|
||||||
return filePath;
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
// if any path separators, return empty
|
|
||||||
if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
// build the list of directories
|
|
||||||
//
|
|
||||||
// Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
|
|
||||||
// it feels like we should not do this. Checking the current directory seems like more of a use
|
|
||||||
// case of a shell, and the which() function exposed by the toolkit should strive for consistency
|
|
||||||
// across platforms.
|
|
||||||
const directories = [];
|
|
||||||
if (process.env.PATH) {
|
|
||||||
for (const p of process.env.PATH.split(path.delimiter)) {
|
|
||||||
if (p) {
|
|
||||||
directories.push(p);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// return the first match
|
|
||||||
for (const directory of directories) {
|
|
||||||
const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions);
|
|
||||||
if (filePath) {
|
|
||||||
return filePath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
throw new Error(`which failed with message ${err.message}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.which = which;
|
|
||||||
function readCopyOptions(options) {
|
|
||||||
const force = options.force == null ? true : options.force;
|
|
||||||
const recursive = Boolean(options.recursive);
|
|
||||||
return { force, recursive };
|
|
||||||
}
|
|
||||||
function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// Ensure there is not a run away recursive copy
|
|
||||||
if (currentDepth >= 255)
|
|
||||||
return;
|
|
||||||
currentDepth++;
|
|
||||||
yield mkdirP(destDir);
|
|
||||||
const files = yield ioUtil.readdir(sourceDir);
|
|
||||||
for (const fileName of files) {
|
|
||||||
const srcFile = `${sourceDir}/${fileName}`;
|
|
||||||
const destFile = `${destDir}/${fileName}`;
|
|
||||||
const srcFileStat = yield ioUtil.lstat(srcFile);
|
|
||||||
if (srcFileStat.isDirectory()) {
|
|
||||||
// Recurse
|
|
||||||
yield cpDirRecursive(srcFile, destFile, currentDepth, force);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
yield copyFile(srcFile, destFile, force);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Change the mode for the newly created directory
|
|
||||||
yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Buffered file copy
|
|
||||||
function copyFile(srcFile, destFile, force) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {
|
|
||||||
// unlink/re-link it
|
|
||||||
try {
|
|
||||||
yield ioUtil.lstat(destFile);
|
|
||||||
yield ioUtil.unlink(destFile);
|
|
||||||
}
|
|
||||||
catch (e) {
|
|
||||||
// Try to override file permission
|
|
||||||
if (e.code === 'EPERM') {
|
|
||||||
yield ioUtil.chmod(destFile, '0666');
|
|
||||||
yield ioUtil.unlink(destFile);
|
|
||||||
}
|
|
||||||
// other errors = it doesn't exist, no work to do
|
|
||||||
}
|
|
||||||
// Copy over symlink
|
|
||||||
const symlinkFull = yield ioUtil.readlink(srcFile);
|
|
||||||
yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);
|
|
||||||
}
|
|
||||||
else if (!(yield ioUtil.exists(destFile)) || force) {
|
|
||||||
yield ioUtil.copyFile(srcFile, destFile);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
//# sourceMappingURL=io.js.map
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1,41 +0,0 @@
|
||||||
{
|
|
||||||
"name": "@actions/io",
|
|
||||||
"version": "1.0.2",
|
|
||||||
"description": "Actions io lib",
|
|
||||||
"keywords": [
|
|
||||||
"github",
|
|
||||||
"actions",
|
|
||||||
"io"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/io",
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "lib/io.js",
|
|
||||||
"types": "lib/io.d.ts",
|
|
||||||
"directories": {
|
|
||||||
"lib": "lib",
|
|
||||||
"test": "__tests__"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib"
|
|
||||||
],
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/actions/toolkit.git",
|
|
||||||
"directory": "packages/io"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"audit-moderate": "npm install && npm audit --audit-level=moderate",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
|
||||||
"tsc": "tsc"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
|
||||||
}
|
|
||||||
|
|
||||||
,"_resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.2.tgz"
|
|
||||||
,"_integrity": "sha512-J8KuFqVPr3p6U8W93DOXlXW6zFvrQAJANdS+vw0YhusLIq+bszW8zmK2Fh1C2kDPX8FMvwIl1OUcFgvJoXLbAg=="
|
|
||||||
,"_from": "@actions/io@1.0.2"
|
|
||||||
}
|
|
||||||
|
|
@ -1,82 +0,0 @@
|
||||||
# `@actions/tool-cache`
|
|
||||||
|
|
||||||
> Functions necessary for downloading and caching tools.
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
#### Download
|
|
||||||
|
|
||||||
You can use this to download tools (or other files) from a download URL:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const tc = require('@actions/tool-cache');
|
|
||||||
|
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Extract
|
|
||||||
|
|
||||||
These can then be extracted in platform specific ways:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const tc = require('@actions/tool-cache');
|
|
||||||
|
|
||||||
if (process.platform === 'win32') {
|
|
||||||
const node12Path = tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
|
|
||||||
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
|
|
||||||
|
|
||||||
// Or alternately
|
|
||||||
const node12Path = tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
|
|
||||||
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
|
||||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Cache
|
|
||||||
|
|
||||||
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for private runners (private runners are still in development but are on the roadmap).
|
|
||||||
|
|
||||||
You'll often want to add it to the path as part of this step:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const tc = require('@actions/tool-cache');
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
|
||||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
|
||||||
|
|
||||||
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
|
|
||||||
core.addPath(cachedPath);
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also cache files for reuse.
|
|
||||||
|
|
||||||
```js
|
|
||||||
const tc = require('@actions/tool-cache');
|
|
||||||
|
|
||||||
const cachedPath = await tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Find
|
|
||||||
|
|
||||||
Finally, you can find directories and files you've previously cached:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const tc = require('@actions/tool-cache');
|
|
||||||
const core = require('@actions/core');
|
|
||||||
|
|
||||||
const nodeDirectory = tc.find('node', '12.x', 'x64');
|
|
||||||
core.addPath(nodeDirectory);
|
|
||||||
```
|
|
||||||
|
|
||||||
You can even find all cached versions of a tool:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const tc = require('@actions/tool-cache');
|
|
||||||
|
|
||||||
const allNodeVersions = tc.findAllVersions('node');
|
|
||||||
console.log(`Versions of node available: ${allNodeVersions}`);
|
|
||||||
```
|
|
||||||
|
|
@ -1,80 +0,0 @@
|
||||||
export declare class HTTPError extends Error {
|
|
||||||
readonly httpStatusCode: number | undefined;
|
|
||||||
constructor(httpStatusCode: number | undefined);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Download a tool from an url and stream it into a file
|
|
||||||
*
|
|
||||||
* @param url url of tool to download
|
|
||||||
* @param dest path to download tool
|
|
||||||
* @returns path to downloaded tool
|
|
||||||
*/
|
|
||||||
export declare function downloadTool(url: string, dest?: string): Promise<string>;
|
|
||||||
/**
|
|
||||||
* Extract a .7z file
|
|
||||||
*
|
|
||||||
* @param file path to the .7z file
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
|
||||||
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
|
||||||
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
|
||||||
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
|
||||||
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
|
||||||
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
|
||||||
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
|
||||||
* to 7zr.exe can be pass to this function.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
|
|
||||||
/**
|
|
||||||
* Extract a compressed tar archive
|
|
||||||
*
|
|
||||||
* @param file path to the tar
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
export declare function extractTar(file: string, dest?: string, flags?: string): Promise<string>;
|
|
||||||
/**
|
|
||||||
* Extract a zip
|
|
||||||
*
|
|
||||||
* @param file path to the zip
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
export declare function extractZip(file: string, dest?: string): Promise<string>;
|
|
||||||
/**
|
|
||||||
* Caches a directory and installs it into the tool cacheDir
|
|
||||||
*
|
|
||||||
* @param sourceDir the directory to cache into tools
|
|
||||||
* @param tool tool name
|
|
||||||
* @param version version of the tool. semver format
|
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
|
||||||
*/
|
|
||||||
export declare function cacheDir(sourceDir: string, tool: string, version: string, arch?: string): Promise<string>;
|
|
||||||
/**
|
|
||||||
* Caches a downloaded file (GUID) and installs it
|
|
||||||
* into the tool cache with a given targetName
|
|
||||||
*
|
|
||||||
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
|
||||||
* @param targetFile the name of the file name in the tools directory
|
|
||||||
* @param tool tool name
|
|
||||||
* @param version version of the tool. semver format
|
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
|
||||||
*/
|
|
||||||
export declare function cacheFile(sourceFile: string, targetFile: string, tool: string, version: string, arch?: string): Promise<string>;
|
|
||||||
/**
|
|
||||||
* Finds the path to a tool version in the local installed tool cache
|
|
||||||
*
|
|
||||||
* @param toolName name of the tool
|
|
||||||
* @param versionSpec version of the tool
|
|
||||||
* @param arch optional arch. defaults to arch of computer
|
|
||||||
*/
|
|
||||||
export declare function find(toolName: string, versionSpec: string, arch?: string): string;
|
|
||||||
/**
|
|
||||||
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
|
||||||
*
|
|
||||||
* @param toolName name of the tool
|
|
||||||
* @param arch optional arch. defaults to arch of computer
|
|
||||||
*/
|
|
||||||
export declare function findAllVersions(toolName: string, arch?: string): string[];
|
|
||||||
|
|
@ -1,475 +0,0 @@
|
||||||
"use strict";
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importStar = (this && this.__importStar) || function (mod) {
|
|
||||||
if (mod && mod.__esModule) return mod;
|
|
||||||
var result = {};
|
|
||||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
|
||||||
result["default"] = mod;
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const core = __importStar(require("@actions/core"));
|
|
||||||
const io = __importStar(require("@actions/io"));
|
|
||||||
const fs = __importStar(require("fs"));
|
|
||||||
const os = __importStar(require("os"));
|
|
||||||
const path = __importStar(require("path"));
|
|
||||||
const httpm = __importStar(require("@actions/http-client"));
|
|
||||||
const semver = __importStar(require("semver"));
|
|
||||||
const v4_1 = __importDefault(require("uuid/v4"));
|
|
||||||
const exec_1 = require("@actions/exec/lib/exec");
|
|
||||||
const assert_1 = require("assert");
|
|
||||||
class HTTPError extends Error {
|
|
||||||
constructor(httpStatusCode) {
|
|
||||||
super(`Unexpected HTTP response: ${httpStatusCode}`);
|
|
||||||
this.httpStatusCode = httpStatusCode;
|
|
||||||
Object.setPrototypeOf(this, new.target.prototype);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.HTTPError = HTTPError;
|
|
||||||
const IS_WINDOWS = process.platform === 'win32';
|
|
||||||
const userAgent = 'actions/tool-cache';
|
|
||||||
// On load grab temp directory and cache directory and remove them from env (currently don't want to expose this)
|
|
||||||
let tempDirectory = process.env['RUNNER_TEMP'] || '';
|
|
||||||
let cacheRoot = process.env['RUNNER_TOOL_CACHE'] || '';
|
|
||||||
// If directories not found, place them in common temp locations
|
|
||||||
if (!tempDirectory || !cacheRoot) {
|
|
||||||
let baseLocation;
|
|
||||||
if (IS_WINDOWS) {
|
|
||||||
// On windows use the USERPROFILE env variable
|
|
||||||
baseLocation = process.env['USERPROFILE'] || 'C:\\';
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (process.platform === 'darwin') {
|
|
||||||
baseLocation = '/Users';
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
baseLocation = '/home';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!tempDirectory) {
|
|
||||||
tempDirectory = path.join(baseLocation, 'actions', 'temp');
|
|
||||||
}
|
|
||||||
if (!cacheRoot) {
|
|
||||||
cacheRoot = path.join(baseLocation, 'actions', 'cache');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Download a tool from an url and stream it into a file
|
|
||||||
*
|
|
||||||
* @param url url of tool to download
|
|
||||||
* @param dest path to download tool
|
|
||||||
* @returns path to downloaded tool
|
|
||||||
*/
|
|
||||||
function downloadTool(url, dest) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// Wrap in a promise so that we can resolve from within stream callbacks
|
|
||||||
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
|
||||||
try {
|
|
||||||
const http = new httpm.HttpClient(userAgent, [], {
|
|
||||||
allowRetries: true,
|
|
||||||
maxRetries: 3
|
|
||||||
});
|
|
||||||
dest = dest || path.join(tempDirectory, v4_1.default());
|
|
||||||
yield io.mkdirP(path.dirname(dest));
|
|
||||||
core.debug(`Downloading ${url}`);
|
|
||||||
core.debug(`Downloading ${dest}`);
|
|
||||||
if (fs.existsSync(dest)) {
|
|
||||||
throw new Error(`Destination file path ${dest} already exists`);
|
|
||||||
}
|
|
||||||
const response = yield http.get(url);
|
|
||||||
if (response.message.statusCode !== 200) {
|
|
||||||
const err = new HTTPError(response.message.statusCode);
|
|
||||||
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
const file = fs.createWriteStream(dest);
|
|
||||||
file.on('open', () => __awaiter(this, void 0, void 0, function* () {
|
|
||||||
try {
|
|
||||||
const stream = response.message.pipe(file);
|
|
||||||
stream.on('close', () => {
|
|
||||||
core.debug('download complete');
|
|
||||||
resolve(dest);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
file.on('error', err => {
|
|
||||||
file.end();
|
|
||||||
reject(err);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
catch (err) {
|
|
||||||
reject(err);
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.downloadTool = downloadTool;
|
|
||||||
/**
|
|
||||||
* Extract a .7z file
|
|
||||||
*
|
|
||||||
* @param file path to the .7z file
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
|
||||||
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
|
||||||
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
|
||||||
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
|
||||||
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
|
||||||
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
|
||||||
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
|
||||||
* to 7zr.exe can be pass to this function.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
function extract7z(file, dest, _7zPath) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
|
|
||||||
assert_1.ok(file, 'parameter "file" is required');
|
|
||||||
dest = yield _createExtractFolder(dest);
|
|
||||||
const originalCwd = process.cwd();
|
|
||||||
process.chdir(dest);
|
|
||||||
if (_7zPath) {
|
|
||||||
try {
|
|
||||||
const args = [
|
|
||||||
'x',
|
|
||||||
'-bb1',
|
|
||||||
'-bd',
|
|
||||||
'-sccUTF-8',
|
|
||||||
file
|
|
||||||
];
|
|
||||||
const options = {
|
|
||||||
silent: true
|
|
||||||
};
|
|
||||||
yield exec_1.exec(`"${_7zPath}"`, args, options);
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
process.chdir(originalCwd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
const escapedScript = path
|
|
||||||
.join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1')
|
|
||||||
.replace(/'/g, "''")
|
|
||||||
.replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
|
||||||
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
|
||||||
const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
|
||||||
const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
|
|
||||||
const args = [
|
|
||||||
'-NoLogo',
|
|
||||||
'-Sta',
|
|
||||||
'-NoProfile',
|
|
||||||
'-NonInteractive',
|
|
||||||
'-ExecutionPolicy',
|
|
||||||
'Unrestricted',
|
|
||||||
'-Command',
|
|
||||||
command
|
|
||||||
];
|
|
||||||
const options = {
|
|
||||||
silent: true
|
|
||||||
};
|
|
||||||
try {
|
|
||||||
const powershellPath = yield io.which('powershell', true);
|
|
||||||
yield exec_1.exec(`"${powershellPath}"`, args, options);
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
process.chdir(originalCwd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return dest;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.extract7z = extract7z;
|
|
||||||
/**
|
|
||||||
* Extract a compressed tar archive
|
|
||||||
*
|
|
||||||
* @param file path to the tar
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
function extractTar(file, dest, flags = 'xz') {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if (!file) {
|
|
||||||
throw new Error("parameter 'file' is required");
|
|
||||||
}
|
|
||||||
// Create dest
|
|
||||||
dest = yield _createExtractFolder(dest);
|
|
||||||
// Determine whether GNU tar
|
|
||||||
let versionOutput = '';
|
|
||||||
yield exec_1.exec('tar --version', [], {
|
|
||||||
ignoreReturnCode: true,
|
|
||||||
listeners: {
|
|
||||||
stdout: (data) => (versionOutput += data.toString()),
|
|
||||||
stderr: (data) => (versionOutput += data.toString())
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR');
|
|
||||||
// Initialize args
|
|
||||||
const args = [flags];
|
|
||||||
let destArg = dest;
|
|
||||||
let fileArg = file;
|
|
||||||
if (IS_WINDOWS && isGnuTar) {
|
|
||||||
args.push('--force-local');
|
|
||||||
destArg = dest.replace(/\\/g, '/');
|
|
||||||
// Technically only the dest needs to have `/` but for aesthetic consistency
|
|
||||||
// convert slashes in the file arg too.
|
|
||||||
fileArg = file.replace(/\\/g, '/');
|
|
||||||
}
|
|
||||||
if (isGnuTar) {
|
|
||||||
// Suppress warnings when using GNU tar to extract archives created by BSD tar
|
|
||||||
args.push('--warning=no-unknown-keyword');
|
|
||||||
}
|
|
||||||
args.push('-C', destArg, '-f', fileArg);
|
|
||||||
yield exec_1.exec(`tar`, args);
|
|
||||||
return dest;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.extractTar = extractTar;
|
|
||||||
/**
|
|
||||||
* Extract a zip
|
|
||||||
*
|
|
||||||
* @param file path to the zip
|
|
||||||
* @param dest destination directory. Optional.
|
|
||||||
* @returns path to the destination directory
|
|
||||||
*/
|
|
||||||
function extractZip(file, dest) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if (!file) {
|
|
||||||
throw new Error("parameter 'file' is required");
|
|
||||||
}
|
|
||||||
dest = yield _createExtractFolder(dest);
|
|
||||||
if (IS_WINDOWS) {
|
|
||||||
yield extractZipWin(file, dest);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
yield extractZipNix(file, dest);
|
|
||||||
}
|
|
||||||
return dest;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.extractZip = extractZip;
|
|
||||||
function extractZipWin(file, dest) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
// build the powershell command
|
|
||||||
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
|
||||||
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
|
||||||
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
|
|
||||||
// run powershell
|
|
||||||
const powershellPath = yield io.which('powershell');
|
|
||||||
const args = [
|
|
||||||
'-NoLogo',
|
|
||||||
'-Sta',
|
|
||||||
'-NoProfile',
|
|
||||||
'-NonInteractive',
|
|
||||||
'-ExecutionPolicy',
|
|
||||||
'Unrestricted',
|
|
||||||
'-Command',
|
|
||||||
command
|
|
||||||
];
|
|
||||||
yield exec_1.exec(`"${powershellPath}"`, args);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function extractZipNix(file, dest) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
const unzipPath = yield io.which('unzip');
|
|
||||||
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Caches a directory and installs it into the tool cacheDir
|
|
||||||
*
|
|
||||||
* @param sourceDir the directory to cache into tools
|
|
||||||
* @param tool tool name
|
|
||||||
* @param version version of the tool. semver format
|
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
|
||||||
*/
|
|
||||||
function cacheDir(sourceDir, tool, version, arch) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
version = semver.clean(version) || version;
|
|
||||||
arch = arch || os.arch();
|
|
||||||
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
|
||||||
core.debug(`source dir: ${sourceDir}`);
|
|
||||||
if (!fs.statSync(sourceDir).isDirectory()) {
|
|
||||||
throw new Error('sourceDir is not a directory');
|
|
||||||
}
|
|
||||||
// Create the tool dir
|
|
||||||
const destPath = yield _createToolPath(tool, version, arch);
|
|
||||||
// copy each child item. do not move. move can fail on Windows
|
|
||||||
// due to anti-virus software having an open handle on a file.
|
|
||||||
for (const itemName of fs.readdirSync(sourceDir)) {
|
|
||||||
const s = path.join(sourceDir, itemName);
|
|
||||||
yield io.cp(s, destPath, { recursive: true });
|
|
||||||
}
|
|
||||||
// write .complete
|
|
||||||
_completeToolPath(tool, version, arch);
|
|
||||||
return destPath;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.cacheDir = cacheDir;
|
|
||||||
/**
|
|
||||||
* Caches a downloaded file (GUID) and installs it
|
|
||||||
* into the tool cache with a given targetName
|
|
||||||
*
|
|
||||||
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
|
||||||
* @param targetFile the name of the file name in the tools directory
|
|
||||||
* @param tool tool name
|
|
||||||
* @param version version of the tool. semver format
|
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
|
||||||
*/
|
|
||||||
function cacheFile(sourceFile, targetFile, tool, version, arch) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
version = semver.clean(version) || version;
|
|
||||||
arch = arch || os.arch();
|
|
||||||
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
|
||||||
core.debug(`source file: ${sourceFile}`);
|
|
||||||
if (!fs.statSync(sourceFile).isFile()) {
|
|
||||||
throw new Error('sourceFile is not a file');
|
|
||||||
}
|
|
||||||
// create the tool dir
|
|
||||||
const destFolder = yield _createToolPath(tool, version, arch);
|
|
||||||
// copy instead of move. move can fail on Windows due to
|
|
||||||
// anti-virus software having an open handle on a file.
|
|
||||||
const destPath = path.join(destFolder, targetFile);
|
|
||||||
core.debug(`destination file ${destPath}`);
|
|
||||||
yield io.cp(sourceFile, destPath);
|
|
||||||
// write .complete
|
|
||||||
_completeToolPath(tool, version, arch);
|
|
||||||
return destFolder;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
exports.cacheFile = cacheFile;
|
|
||||||
/**
|
|
||||||
* Finds the path to a tool version in the local installed tool cache
|
|
||||||
*
|
|
||||||
* @param toolName name of the tool
|
|
||||||
* @param versionSpec version of the tool
|
|
||||||
* @param arch optional arch. defaults to arch of computer
|
|
||||||
*/
|
|
||||||
function find(toolName, versionSpec, arch) {
|
|
||||||
if (!toolName) {
|
|
||||||
throw new Error('toolName parameter is required');
|
|
||||||
}
|
|
||||||
if (!versionSpec) {
|
|
||||||
throw new Error('versionSpec parameter is required');
|
|
||||||
}
|
|
||||||
arch = arch || os.arch();
|
|
||||||
// attempt to resolve an explicit version
|
|
||||||
if (!_isExplicitVersion(versionSpec)) {
|
|
||||||
const localVersions = findAllVersions(toolName, arch);
|
|
||||||
const match = _evaluateVersions(localVersions, versionSpec);
|
|
||||||
versionSpec = match;
|
|
||||||
}
|
|
||||||
// check for the explicit version in the cache
|
|
||||||
let toolPath = '';
|
|
||||||
if (versionSpec) {
|
|
||||||
versionSpec = semver.clean(versionSpec) || '';
|
|
||||||
const cachePath = path.join(cacheRoot, toolName, versionSpec, arch);
|
|
||||||
core.debug(`checking cache: ${cachePath}`);
|
|
||||||
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
|
|
||||||
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
|
|
||||||
toolPath = cachePath;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
core.debug('not found');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return toolPath;
|
|
||||||
}
|
|
||||||
exports.find = find;
|
|
||||||
/**
|
|
||||||
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
|
||||||
*
|
|
||||||
* @param toolName name of the tool
|
|
||||||
* @param arch optional arch. defaults to arch of computer
|
|
||||||
*/
|
|
||||||
function findAllVersions(toolName, arch) {
|
|
||||||
const versions = [];
|
|
||||||
arch = arch || os.arch();
|
|
||||||
const toolPath = path.join(cacheRoot, toolName);
|
|
||||||
if (fs.existsSync(toolPath)) {
|
|
||||||
const children = fs.readdirSync(toolPath);
|
|
||||||
for (const child of children) {
|
|
||||||
if (_isExplicitVersion(child)) {
|
|
||||||
const fullPath = path.join(toolPath, child, arch || '');
|
|
||||||
if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) {
|
|
||||||
versions.push(child);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return versions;
|
|
||||||
}
|
|
||||||
exports.findAllVersions = findAllVersions;
|
|
||||||
function _createExtractFolder(dest) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
if (!dest) {
|
|
||||||
// create a temp dir
|
|
||||||
dest = path.join(tempDirectory, v4_1.default());
|
|
||||||
}
|
|
||||||
yield io.mkdirP(dest);
|
|
||||||
return dest;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function _createToolPath(tool, version, arch) {
|
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
|
||||||
core.debug(`destination ${folderPath}`);
|
|
||||||
const markerPath = `${folderPath}.complete`;
|
|
||||||
yield io.rmRF(folderPath);
|
|
||||||
yield io.rmRF(markerPath);
|
|
||||||
yield io.mkdirP(folderPath);
|
|
||||||
return folderPath;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function _completeToolPath(tool, version, arch) {
|
|
||||||
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
|
||||||
const markerPath = `${folderPath}.complete`;
|
|
||||||
fs.writeFileSync(markerPath, '');
|
|
||||||
core.debug('finished caching tool');
|
|
||||||
}
|
|
||||||
function _isExplicitVersion(versionSpec) {
|
|
||||||
const c = semver.clean(versionSpec) || '';
|
|
||||||
core.debug(`isExplicit: ${c}`);
|
|
||||||
const valid = semver.valid(c) != null;
|
|
||||||
core.debug(`explicit? ${valid}`);
|
|
||||||
return valid;
|
|
||||||
}
|
|
||||||
function _evaluateVersions(versions, versionSpec) {
|
|
||||||
let version = '';
|
|
||||||
core.debug(`evaluating ${versions.length} versions`);
|
|
||||||
versions = versions.sort((a, b) => {
|
|
||||||
if (semver.gt(a, b)) {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
});
|
|
||||||
for (let i = versions.length - 1; i >= 0; i--) {
|
|
||||||
const potential = versions[i];
|
|
||||||
const satisfied = semver.satisfies(potential, versionSpec);
|
|
||||||
if (satisfied) {
|
|
||||||
version = potential;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (version) {
|
|
||||||
core.debug(`matched: ${version}`);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
core.debug('match not found');
|
|
||||||
}
|
|
||||||
return version;
|
|
||||||
}
|
|
||||||
//# sourceMappingURL=tool-cache.js.map
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -1,56 +0,0 @@
|
||||||
{
|
|
||||||
"name": "@actions/tool-cache",
|
|
||||||
"version": "1.3.1",
|
|
||||||
"description": "Actions tool-cache lib",
|
|
||||||
"keywords": [
|
|
||||||
"github",
|
|
||||||
"actions",
|
|
||||||
"exec"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "lib/tool-cache.js",
|
|
||||||
"types": "lib/tool-cache.d.ts",
|
|
||||||
"directories": {
|
|
||||||
"lib": "lib",
|
|
||||||
"test": "__tests__"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"lib",
|
|
||||||
"scripts"
|
|
||||||
],
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/actions/toolkit.git",
|
|
||||||
"directory": "packages/tool-cache"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"audit-moderate": "npm install && npm audit --audit-level=moderate",
|
|
||||||
"test": "echo \"Error: run tests from root\" && exit 1",
|
|
||||||
"tsc": "tsc"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/actions/toolkit/issues"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@actions/core": "^1.2.0",
|
|
||||||
"@actions/exec": "^1.0.0",
|
|
||||||
"@actions/http-client": "^1.0.3",
|
|
||||||
"@actions/io": "^1.0.1",
|
|
||||||
"semver": "^6.1.0",
|
|
||||||
"uuid": "^3.3.2"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/nock": "^10.0.3",
|
|
||||||
"@types/semver": "^6.0.0",
|
|
||||||
"@types/uuid": "^3.4.4",
|
|
||||||
"nock": "^10.0.6"
|
|
||||||
}
|
|
||||||
|
|
||||||
,"_resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.3.1.tgz"
|
|
||||||
,"_integrity": "sha512-sKoEJv0/c7WzjPEq2PO12Sc8QdEp58XIBHMm3c4lUn/iZWgLz9HBeCuFGpLQjDvXJNfLZ4g+WD+rMjgOmpH4Ag=="
|
|
||||||
,"_from": "@actions/tool-cache@1.3.1"
|
|
||||||
}
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
[CmdletBinding()]
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory = $true)]
|
|
||||||
[string]$Source,
|
|
||||||
|
|
||||||
[Parameter(Mandatory = $true)]
|
|
||||||
[string]$Target)
|
|
||||||
|
|
||||||
# This script translates the output from 7zdec into UTF8. Node has limited
|
|
||||||
# built-in support for encodings.
|
|
||||||
#
|
|
||||||
# 7zdec uses the system default code page. The system default code page varies
|
|
||||||
# depending on the locale configuration. On an en-US box, the system default code
|
|
||||||
# page is Windows-1252.
|
|
||||||
#
|
|
||||||
# Note, on a typical en-US box, testing with the 'ç' character is a good way to
|
|
||||||
# determine whether data is passed correctly between processes. This is because
|
|
||||||
# the 'ç' character has a different code point across each of the common encodings
|
|
||||||
# on a typical en-US box, i.e.
|
|
||||||
# 1) the default console-output code page (IBM437)
|
|
||||||
# 2) the system default code page (i.e. CP_ACP) (Windows-1252)
|
|
||||||
# 3) UTF8
|
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
|
|
||||||
# Redefine the wrapper over STDOUT to use UTF8. Node expects UTF8 by default.
|
|
||||||
$stdout = [System.Console]::OpenStandardOutput()
|
|
||||||
$utf8 = New-Object System.Text.UTF8Encoding($false) # do not emit BOM
|
|
||||||
$writer = New-Object System.IO.StreamWriter($stdout, $utf8)
|
|
||||||
[System.Console]::SetOut($writer)
|
|
||||||
|
|
||||||
# All subsequent output must be written using [System.Console]::WriteLine(). In
|
|
||||||
# PowerShell 4, Write-Host and Out-Default do not consider the updated stream writer.
|
|
||||||
|
|
||||||
Set-Location -LiteralPath $Target
|
|
||||||
|
|
||||||
# Print the ##command.
|
|
||||||
$_7zdec = Join-Path -Path "$PSScriptRoot" -ChildPath "externals/7zdec.exe"
|
|
||||||
[System.Console]::WriteLine("##[command]$_7zdec x `"$Source`"")
|
|
||||||
|
|
||||||
# The $OutputEncoding variable instructs PowerShell how to interpret the output
|
|
||||||
# from the external command.
|
|
||||||
$OutputEncoding = [System.Text.Encoding]::Default
|
|
||||||
|
|
||||||
# Note, the output from 7zdec.exe needs to be iterated over. Otherwise PowerShell.exe
|
|
||||||
# will launch the external command in such a way that it inherits the streams.
|
|
||||||
& $_7zdec x $Source 2>&1 |
|
|
||||||
ForEach-Object {
|
|
||||||
if ($_ -is [System.Management.Automation.ErrorRecord]) {
|
|
||||||
[System.Console]::WriteLine($_.Exception.Message)
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
[System.Console]::WriteLine($_)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
[System.Console]::WriteLine("##[debug]7zdec.exe exit code '$LASTEXITCODE'")
|
|
||||||
[System.Console]::Out.Flush()
|
|
||||||
if ($LASTEXITCODE -ne 0) {
|
|
||||||
exit $LASTEXITCODE
|
|
||||||
}
|
|
||||||
Binary file not shown.
|
|
@ -1,22 +0,0 @@
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2014-2018 Sebastian McKenzie <sebmck@gmail.com>
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of this software and associated documentation files (the
|
|
||||||
"Software"), to deal in the Software without restriction, including
|
|
||||||
without limitation the rights to use, copy, modify, merge, publish,
|
|
||||||
distribute, sublicense, and/or sell copies of the Software, and to
|
|
||||||
permit persons to whom the Software is furnished to do so, subject to
|
|
||||||
the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be
|
|
||||||
included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
||||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
||||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
||||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
||||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
# @babel/code-frame
|
|
||||||
|
|
||||||
> Generate errors that contain a code frame that point to source locations.
|
|
||||||
|
|
||||||
See our website [@babel/code-frame](https://babeljs.io/docs/en/next/babel-code-frame.html) for more information.
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
Using npm:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --save-dev @babel/code-frame
|
|
||||||
```
|
|
||||||
|
|
||||||
or using yarn:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
yarn add @babel/code-frame --dev
|
|
||||||
```
|
|
||||||
|
|
@ -1,173 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.codeFrameColumns = codeFrameColumns;
|
|
||||||
exports.default = _default;
|
|
||||||
|
|
||||||
function _highlight() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/highlight"));
|
|
||||||
|
|
||||||
_highlight = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
let deprecationWarningShown = false;
|
|
||||||
|
|
||||||
function getDefs(chalk) {
|
|
||||||
return {
|
|
||||||
gutter: chalk.grey,
|
|
||||||
marker: chalk.red.bold,
|
|
||||||
message: chalk.red.bold
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
|
|
||||||
|
|
||||||
function getMarkerLines(loc, source, opts) {
|
|
||||||
const startLoc = Object.assign({
|
|
||||||
column: 0,
|
|
||||||
line: -1
|
|
||||||
}, loc.start);
|
|
||||||
const endLoc = Object.assign({}, startLoc, loc.end);
|
|
||||||
const {
|
|
||||||
linesAbove = 2,
|
|
||||||
linesBelow = 3
|
|
||||||
} = opts || {};
|
|
||||||
const startLine = startLoc.line;
|
|
||||||
const startColumn = startLoc.column;
|
|
||||||
const endLine = endLoc.line;
|
|
||||||
const endColumn = endLoc.column;
|
|
||||||
let start = Math.max(startLine - (linesAbove + 1), 0);
|
|
||||||
let end = Math.min(source.length, endLine + linesBelow);
|
|
||||||
|
|
||||||
if (startLine === -1) {
|
|
||||||
start = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (endLine === -1) {
|
|
||||||
end = source.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lineDiff = endLine - startLine;
|
|
||||||
const markerLines = {};
|
|
||||||
|
|
||||||
if (lineDiff) {
|
|
||||||
for (let i = 0; i <= lineDiff; i++) {
|
|
||||||
const lineNumber = i + startLine;
|
|
||||||
|
|
||||||
if (!startColumn) {
|
|
||||||
markerLines[lineNumber] = true;
|
|
||||||
} else if (i === 0) {
|
|
||||||
const sourceLength = source[lineNumber - 1].length;
|
|
||||||
markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
|
|
||||||
} else if (i === lineDiff) {
|
|
||||||
markerLines[lineNumber] = [0, endColumn];
|
|
||||||
} else {
|
|
||||||
const sourceLength = source[lineNumber - i].length;
|
|
||||||
markerLines[lineNumber] = [0, sourceLength];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (startColumn === endColumn) {
|
|
||||||
if (startColumn) {
|
|
||||||
markerLines[startLine] = [startColumn, 0];
|
|
||||||
} else {
|
|
||||||
markerLines[startLine] = true;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
markerLines[startLine] = [startColumn, endColumn - startColumn];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
markerLines
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function codeFrameColumns(rawLines, loc, opts = {}) {
|
|
||||||
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts);
|
|
||||||
const chalk = (0, _highlight().getChalk)(opts);
|
|
||||||
const defs = getDefs(chalk);
|
|
||||||
|
|
||||||
const maybeHighlight = (chalkFn, string) => {
|
|
||||||
return highlighted ? chalkFn(string) : string;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (highlighted) rawLines = (0, _highlight().default)(rawLines, opts);
|
|
||||||
const lines = rawLines.split(NEWLINE);
|
|
||||||
const {
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
markerLines
|
|
||||||
} = getMarkerLines(loc, lines, opts);
|
|
||||||
const hasColumns = loc.start && typeof loc.start.column === "number";
|
|
||||||
const numberMaxWidth = String(end).length;
|
|
||||||
let frame = lines.slice(start, end).map((line, index) => {
|
|
||||||
const number = start + 1 + index;
|
|
||||||
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
|
|
||||||
const gutter = ` ${paddedNumber} | `;
|
|
||||||
const hasMarker = markerLines[number];
|
|
||||||
const lastMarkerLine = !markerLines[number + 1];
|
|
||||||
|
|
||||||
if (hasMarker) {
|
|
||||||
let markerLine = "";
|
|
||||||
|
|
||||||
if (Array.isArray(hasMarker)) {
|
|
||||||
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
|
|
||||||
const numberOfMarkers = hasMarker[1] || 1;
|
|
||||||
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
|
|
||||||
|
|
||||||
if (lastMarkerLine && opts.message) {
|
|
||||||
markerLine += " " + maybeHighlight(defs.message, opts.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
|
|
||||||
} else {
|
|
||||||
return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
|
|
||||||
}
|
|
||||||
}).join("\n");
|
|
||||||
|
|
||||||
if (opts.message && !hasColumns) {
|
|
||||||
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (highlighted) {
|
|
||||||
return chalk.reset(frame);
|
|
||||||
} else {
|
|
||||||
return frame;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function _default(rawLines, lineNumber, colNumber, opts = {}) {
|
|
||||||
if (!deprecationWarningShown) {
|
|
||||||
deprecationWarningShown = true;
|
|
||||||
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
|
|
||||||
|
|
||||||
if (process.emitWarning) {
|
|
||||||
process.emitWarning(message, "DeprecationWarning");
|
|
||||||
} else {
|
|
||||||
const deprecationError = new Error(message);
|
|
||||||
deprecationError.name = "DeprecationWarning";
|
|
||||||
console.warn(new Error(message));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
colNumber = Math.max(colNumber, 0);
|
|
||||||
const location = {
|
|
||||||
start: {
|
|
||||||
column: colNumber,
|
|
||||||
line: lineNumber
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return codeFrameColumns(rawLines, location, opts);
|
|
||||||
}
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"@babel/code-frame@7.0.0",
|
|
||||||
"/Users/eric/repos/actions/setup-node"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_development": true,
|
|
||||||
"_from": "@babel/code-frame@7.0.0",
|
|
||||||
"_id": "@babel/code-frame@7.0.0",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==",
|
|
||||||
"_location": "/@babel/code-frame",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "@babel/code-frame@7.0.0",
|
|
||||||
"name": "@babel/code-frame",
|
|
||||||
"escapedName": "@babel%2fcode-frame",
|
|
||||||
"scope": "@babel",
|
|
||||||
"rawSpec": "7.0.0",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "7.0.0"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/@babel/core",
|
|
||||||
"/@babel/template",
|
|
||||||
"/@babel/traverse",
|
|
||||||
"/jest-message-util"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz",
|
|
||||||
"_spec": "7.0.0",
|
|
||||||
"_where": "/Users/eric/repos/actions/setup-node",
|
|
||||||
"author": {
|
|
||||||
"name": "Sebastian McKenzie",
|
|
||||||
"email": "sebmck@gmail.com"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/highlight": "^7.0.0"
|
|
||||||
},
|
|
||||||
"description": "Generate errors that contain a code frame that point to source locations.",
|
|
||||||
"devDependencies": {
|
|
||||||
"chalk": "^2.0.0",
|
|
||||||
"strip-ansi": "^4.0.0"
|
|
||||||
},
|
|
||||||
"homepage": "https://babeljs.io/",
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "lib/index.js",
|
|
||||||
"name": "@babel/code-frame",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame"
|
|
||||||
},
|
|
||||||
"version": "7.0.0"
|
|
||||||
}
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2014-present Sebastian McKenzie and other contributors
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of this software and associated documentation files (the
|
|
||||||
"Software"), to deal in the Software without restriction, including
|
|
||||||
without limitation the rights to use, copy, modify, merge, publish,
|
|
||||||
distribute, sublicense, and/or sell copies of the Software, and to
|
|
||||||
permit persons to whom the Software is furnished to do so, subject to
|
|
||||||
the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be
|
|
||||||
included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
||||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
||||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
||||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
||||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
# @babel/core
|
|
||||||
|
|
||||||
> Babel compiler core.
|
|
||||||
|
|
||||||
See our website [@babel/core](https://babeljs.io/docs/en/next/babel-core.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package.
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
Using npm:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --save-dev @babel/core
|
|
||||||
```
|
|
||||||
|
|
||||||
or using yarn:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
yarn add @babel/core --dev
|
|
||||||
```
|
|
||||||
|
|
@ -1,199 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.makeStrongCache = makeStrongCache;
|
|
||||||
exports.makeWeakCache = makeWeakCache;
|
|
||||||
exports.assertSimpleType = assertSimpleType;
|
|
||||||
|
|
||||||
function makeStrongCache(handler) {
|
|
||||||
return makeCachedFunction(new Map(), handler);
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeWeakCache(handler) {
|
|
||||||
return makeCachedFunction(new WeakMap(), handler);
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeCachedFunction(callCache, handler) {
|
|
||||||
return function cachedFunction(arg, data) {
|
|
||||||
let cachedValue = callCache.get(arg);
|
|
||||||
|
|
||||||
if (cachedValue) {
|
|
||||||
for (const _ref of cachedValue) {
|
|
||||||
const {
|
|
||||||
value,
|
|
||||||
valid
|
|
||||||
} = _ref;
|
|
||||||
if (valid(data)) return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const cache = new CacheConfigurator(data);
|
|
||||||
const value = handler(arg, cache);
|
|
||||||
if (!cache.configured()) cache.forever();
|
|
||||||
cache.deactivate();
|
|
||||||
|
|
||||||
switch (cache.mode()) {
|
|
||||||
case "forever":
|
|
||||||
cachedValue = [{
|
|
||||||
value,
|
|
||||||
valid: () => true
|
|
||||||
}];
|
|
||||||
callCache.set(arg, cachedValue);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "invalidate":
|
|
||||||
cachedValue = [{
|
|
||||||
value,
|
|
||||||
valid: cache.validator()
|
|
||||||
}];
|
|
||||||
callCache.set(arg, cachedValue);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "valid":
|
|
||||||
if (cachedValue) {
|
|
||||||
cachedValue.push({
|
|
||||||
value,
|
|
||||||
valid: cache.validator()
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
cachedValue = [{
|
|
||||||
value,
|
|
||||||
valid: cache.validator()
|
|
||||||
}];
|
|
||||||
callCache.set(arg, cachedValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
class CacheConfigurator {
|
|
||||||
constructor(data) {
|
|
||||||
this._active = true;
|
|
||||||
this._never = false;
|
|
||||||
this._forever = false;
|
|
||||||
this._invalidate = false;
|
|
||||||
this._configured = false;
|
|
||||||
this._pairs = [];
|
|
||||||
this._data = data;
|
|
||||||
}
|
|
||||||
|
|
||||||
simple() {
|
|
||||||
return makeSimpleConfigurator(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
mode() {
|
|
||||||
if (this._never) return "never";
|
|
||||||
if (this._forever) return "forever";
|
|
||||||
if (this._invalidate) return "invalidate";
|
|
||||||
return "valid";
|
|
||||||
}
|
|
||||||
|
|
||||||
forever() {
|
|
||||||
if (!this._active) {
|
|
||||||
throw new Error("Cannot change caching after evaluation has completed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._never) {
|
|
||||||
throw new Error("Caching has already been configured with .never()");
|
|
||||||
}
|
|
||||||
|
|
||||||
this._forever = true;
|
|
||||||
this._configured = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
never() {
|
|
||||||
if (!this._active) {
|
|
||||||
throw new Error("Cannot change caching after evaluation has completed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._forever) {
|
|
||||||
throw new Error("Caching has already been configured with .forever()");
|
|
||||||
}
|
|
||||||
|
|
||||||
this._never = true;
|
|
||||||
this._configured = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
using(handler) {
|
|
||||||
if (!this._active) {
|
|
||||||
throw new Error("Cannot change caching after evaluation has completed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._never || this._forever) {
|
|
||||||
throw new Error("Caching has already been configured with .never or .forever()");
|
|
||||||
}
|
|
||||||
|
|
||||||
this._configured = true;
|
|
||||||
const key = handler(this._data);
|
|
||||||
|
|
||||||
this._pairs.push([key, handler]);
|
|
||||||
|
|
||||||
return key;
|
|
||||||
}
|
|
||||||
|
|
||||||
invalidate(handler) {
|
|
||||||
if (!this._active) {
|
|
||||||
throw new Error("Cannot change caching after evaluation has completed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._never || this._forever) {
|
|
||||||
throw new Error("Caching has already been configured with .never or .forever()");
|
|
||||||
}
|
|
||||||
|
|
||||||
this._invalidate = true;
|
|
||||||
this._configured = true;
|
|
||||||
const key = handler(this._data);
|
|
||||||
|
|
||||||
this._pairs.push([key, handler]);
|
|
||||||
|
|
||||||
return key;
|
|
||||||
}
|
|
||||||
|
|
||||||
validator() {
|
|
||||||
const pairs = this._pairs;
|
|
||||||
return data => pairs.every(([key, fn]) => key === fn(data));
|
|
||||||
}
|
|
||||||
|
|
||||||
deactivate() {
|
|
||||||
this._active = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
configured() {
|
|
||||||
return this._configured;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeSimpleConfigurator(cache) {
|
|
||||||
function cacheFn(val) {
|
|
||||||
if (typeof val === "boolean") {
|
|
||||||
if (val) cache.forever();else cache.never();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
return cache.using(() => assertSimpleType(val()));
|
|
||||||
}
|
|
||||||
|
|
||||||
cacheFn.forever = () => cache.forever();
|
|
||||||
|
|
||||||
cacheFn.never = () => cache.never();
|
|
||||||
|
|
||||||
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
|
|
||||||
|
|
||||||
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
|
|
||||||
|
|
||||||
return cacheFn;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertSimpleType(value) {
|
|
||||||
if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") {
|
|
||||||
throw new Error("Cache keys must be either string, boolean, number, null, or undefined.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
@ -1,439 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.buildPresetChain = buildPresetChain;
|
|
||||||
exports.buildRootChain = buildRootChain;
|
|
||||||
exports.buildPresetChainWalker = void 0;
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _debug() {
|
|
||||||
const data = _interopRequireDefault(require("debug"));
|
|
||||||
|
|
||||||
_debug = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _options = require("./validation/options");
|
|
||||||
|
|
||||||
var _patternToRegex = _interopRequireDefault(require("./pattern-to-regex"));
|
|
||||||
|
|
||||||
var _files = require("./files");
|
|
||||||
|
|
||||||
var _caching = require("./caching");
|
|
||||||
|
|
||||||
var _configDescriptors = require("./config-descriptors");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const debug = (0, _debug().default)("babel:config:config-chain");
|
|
||||||
|
|
||||||
function buildPresetChain(arg, context) {
|
|
||||||
const chain = buildPresetChainWalker(arg, context);
|
|
||||||
if (!chain) return null;
|
|
||||||
return {
|
|
||||||
plugins: dedupDescriptors(chain.plugins),
|
|
||||||
presets: dedupDescriptors(chain.presets),
|
|
||||||
options: chain.options.map(o => normalizeOptions(o))
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const buildPresetChainWalker = makeChainWalker({
|
|
||||||
init: arg => arg,
|
|
||||||
root: preset => loadPresetDescriptors(preset),
|
|
||||||
env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),
|
|
||||||
overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),
|
|
||||||
overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName)
|
|
||||||
});
|
|
||||||
exports.buildPresetChainWalker = buildPresetChainWalker;
|
|
||||||
const loadPresetDescriptors = (0, _caching.makeWeakCache)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors));
|
|
||||||
const loadPresetEnvDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName)));
|
|
||||||
const loadPresetOverridesDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index)));
|
|
||||||
const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(index => (0, _caching.makeStrongCache)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName))));
|
|
||||||
|
|
||||||
function buildRootChain(opts, context) {
|
|
||||||
const programmaticChain = loadProgrammaticChain({
|
|
||||||
options: opts,
|
|
||||||
dirname: context.cwd
|
|
||||||
}, context);
|
|
||||||
if (!programmaticChain) return null;
|
|
||||||
let configFile;
|
|
||||||
|
|
||||||
if (typeof opts.configFile === "string") {
|
|
||||||
configFile = (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller);
|
|
||||||
} else if (opts.configFile !== false) {
|
|
||||||
configFile = (0, _files.findRootConfig)(context.root, context.envName, context.caller);
|
|
||||||
}
|
|
||||||
|
|
||||||
let {
|
|
||||||
babelrc,
|
|
||||||
babelrcRoots
|
|
||||||
} = opts;
|
|
||||||
let babelrcRootsDirectory = context.cwd;
|
|
||||||
const configFileChain = emptyChain();
|
|
||||||
|
|
||||||
if (configFile) {
|
|
||||||
const validatedFile = validateConfigFile(configFile);
|
|
||||||
const result = loadFileChain(validatedFile, context);
|
|
||||||
if (!result) return null;
|
|
||||||
|
|
||||||
if (babelrc === undefined) {
|
|
||||||
babelrc = validatedFile.options.babelrc;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (babelrcRoots === undefined) {
|
|
||||||
babelrcRootsDirectory = validatedFile.dirname;
|
|
||||||
babelrcRoots = validatedFile.options.babelrcRoots;
|
|
||||||
}
|
|
||||||
|
|
||||||
mergeChain(configFileChain, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
const pkgData = typeof context.filename === "string" ? (0, _files.findPackageData)(context.filename) : null;
|
|
||||||
let ignoreFile, babelrcFile;
|
|
||||||
const fileChain = emptyChain();
|
|
||||||
|
|
||||||
if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) {
|
|
||||||
({
|
|
||||||
ignore: ignoreFile,
|
|
||||||
config: babelrcFile
|
|
||||||
} = (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller));
|
|
||||||
|
|
||||||
if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (babelrcFile) {
|
|
||||||
const result = loadFileChain(validateBabelrcFile(babelrcFile), context);
|
|
||||||
if (!result) return null;
|
|
||||||
mergeChain(fileChain, result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain);
|
|
||||||
return {
|
|
||||||
plugins: dedupDescriptors(chain.plugins),
|
|
||||||
presets: dedupDescriptors(chain.presets),
|
|
||||||
options: chain.options.map(o => normalizeOptions(o)),
|
|
||||||
ignore: ignoreFile || undefined,
|
|
||||||
babelrc: babelrcFile || undefined,
|
|
||||||
config: configFile || undefined
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) {
|
|
||||||
if (typeof babelrcRoots === "boolean") return babelrcRoots;
|
|
||||||
const absoluteRoot = context.root;
|
|
||||||
|
|
||||||
if (babelrcRoots === undefined) {
|
|
||||||
return pkgData.directories.indexOf(absoluteRoot) !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let babelrcPatterns = babelrcRoots;
|
|
||||||
if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns];
|
|
||||||
babelrcPatterns = babelrcPatterns.map(pat => {
|
|
||||||
return typeof pat === "string" ? _path().default.resolve(babelrcRootsDirectory, pat) : pat;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {
|
|
||||||
return pkgData.directories.indexOf(absoluteRoot) !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return babelrcPatterns.some(pat => {
|
|
||||||
if (typeof pat === "string") {
|
|
||||||
pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory);
|
|
||||||
}
|
|
||||||
|
|
||||||
return pkgData.directories.some(directory => {
|
|
||||||
return matchPattern(pat, babelrcRootsDirectory, directory, context);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const validateConfigFile = (0, _caching.makeWeakCache)(file => ({
|
|
||||||
filepath: file.filepath,
|
|
||||||
dirname: file.dirname,
|
|
||||||
options: (0, _options.validate)("configfile", file.options)
|
|
||||||
}));
|
|
||||||
const validateBabelrcFile = (0, _caching.makeWeakCache)(file => ({
|
|
||||||
filepath: file.filepath,
|
|
||||||
dirname: file.dirname,
|
|
||||||
options: (0, _options.validate)("babelrcfile", file.options)
|
|
||||||
}));
|
|
||||||
const validateExtendFile = (0, _caching.makeWeakCache)(file => ({
|
|
||||||
filepath: file.filepath,
|
|
||||||
dirname: file.dirname,
|
|
||||||
options: (0, _options.validate)("extendsfile", file.options)
|
|
||||||
}));
|
|
||||||
const loadProgrammaticChain = makeChainWalker({
|
|
||||||
root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors),
|
|
||||||
env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName),
|
|
||||||
overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index),
|
|
||||||
overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName)
|
|
||||||
});
|
|
||||||
const loadFileChain = makeChainWalker({
|
|
||||||
root: file => loadFileDescriptors(file),
|
|
||||||
env: (file, envName) => loadFileEnvDescriptors(file)(envName),
|
|
||||||
overrides: (file, index) => loadFileOverridesDescriptors(file)(index),
|
|
||||||
overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName)
|
|
||||||
});
|
|
||||||
const loadFileDescriptors = (0, _caching.makeWeakCache)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors));
|
|
||||||
const loadFileEnvDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName)));
|
|
||||||
const loadFileOverridesDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index)));
|
|
||||||
const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(index => (0, _caching.makeStrongCache)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName))));
|
|
||||||
|
|
||||||
function buildRootDescriptors({
|
|
||||||
dirname,
|
|
||||||
options
|
|
||||||
}, alias, descriptors) {
|
|
||||||
return descriptors(dirname, options, alias);
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildEnvDescriptors({
|
|
||||||
dirname,
|
|
||||||
options
|
|
||||||
}, alias, descriptors, envName) {
|
|
||||||
const opts = options.env && options.env[envName];
|
|
||||||
return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildOverrideDescriptors({
|
|
||||||
dirname,
|
|
||||||
options
|
|
||||||
}, alias, descriptors, index) {
|
|
||||||
const opts = options.overrides && options.overrides[index];
|
|
||||||
if (!opts) throw new Error("Assertion failure - missing override");
|
|
||||||
return descriptors(dirname, opts, `${alias}.overrides[${index}]`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildOverrideEnvDescriptors({
|
|
||||||
dirname,
|
|
||||||
options
|
|
||||||
}, alias, descriptors, index, envName) {
|
|
||||||
const override = options.overrides && options.overrides[index];
|
|
||||||
if (!override) throw new Error("Assertion failure - missing override");
|
|
||||||
const opts = override.env && override.env[envName];
|
|
||||||
return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeChainWalker({
|
|
||||||
root,
|
|
||||||
env,
|
|
||||||
overrides,
|
|
||||||
overridesEnv
|
|
||||||
}) {
|
|
||||||
return (input, context, files = new Set()) => {
|
|
||||||
const {
|
|
||||||
dirname
|
|
||||||
} = input;
|
|
||||||
const flattenedConfigs = [];
|
|
||||||
const rootOpts = root(input);
|
|
||||||
|
|
||||||
if (configIsApplicable(rootOpts, dirname, context)) {
|
|
||||||
flattenedConfigs.push(rootOpts);
|
|
||||||
const envOpts = env(input, context.envName);
|
|
||||||
|
|
||||||
if (envOpts && configIsApplicable(envOpts, dirname, context)) {
|
|
||||||
flattenedConfigs.push(envOpts);
|
|
||||||
}
|
|
||||||
|
|
||||||
(rootOpts.options.overrides || []).forEach((_, index) => {
|
|
||||||
const overrideOps = overrides(input, index);
|
|
||||||
|
|
||||||
if (configIsApplicable(overrideOps, dirname, context)) {
|
|
||||||
flattenedConfigs.push(overrideOps);
|
|
||||||
const overrideEnvOpts = overridesEnv(input, index, context.envName);
|
|
||||||
|
|
||||||
if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) {
|
|
||||||
flattenedConfigs.push(overrideEnvOpts);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flattenedConfigs.some(({
|
|
||||||
options: {
|
|
||||||
ignore,
|
|
||||||
only
|
|
||||||
}
|
|
||||||
}) => shouldIgnore(context, ignore, only, dirname))) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const chain = emptyChain();
|
|
||||||
|
|
||||||
for (const op of flattenedConfigs) {
|
|
||||||
if (!mergeExtendsChain(chain, op.options, dirname, context, files)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
mergeChainOpts(chain, op);
|
|
||||||
}
|
|
||||||
|
|
||||||
return chain;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeExtendsChain(chain, opts, dirname, context, files) {
|
|
||||||
if (opts.extends === undefined) return true;
|
|
||||||
const file = (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller);
|
|
||||||
|
|
||||||
if (files.has(file)) {
|
|
||||||
throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
files.add(file);
|
|
||||||
const fileChain = loadFileChain(validateExtendFile(file), context, files);
|
|
||||||
files.delete(file);
|
|
||||||
if (!fileChain) return false;
|
|
||||||
mergeChain(chain, fileChain);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeChain(target, source) {
|
|
||||||
target.options.push(...source.options);
|
|
||||||
target.plugins.push(...source.plugins);
|
|
||||||
target.presets.push(...source.presets);
|
|
||||||
return target;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeChainOpts(target, {
|
|
||||||
options,
|
|
||||||
plugins,
|
|
||||||
presets
|
|
||||||
}) {
|
|
||||||
target.options.push(options);
|
|
||||||
target.plugins.push(...plugins());
|
|
||||||
target.presets.push(...presets());
|
|
||||||
return target;
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptyChain() {
|
|
||||||
return {
|
|
||||||
options: [],
|
|
||||||
presets: [],
|
|
||||||
plugins: []
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeOptions(opts) {
|
|
||||||
const options = Object.assign({}, opts);
|
|
||||||
delete options.extends;
|
|
||||||
delete options.env;
|
|
||||||
delete options.overrides;
|
|
||||||
delete options.plugins;
|
|
||||||
delete options.presets;
|
|
||||||
delete options.passPerPreset;
|
|
||||||
delete options.ignore;
|
|
||||||
delete options.only;
|
|
||||||
delete options.test;
|
|
||||||
delete options.include;
|
|
||||||
delete options.exclude;
|
|
||||||
|
|
||||||
if (options.hasOwnProperty("sourceMap")) {
|
|
||||||
options.sourceMaps = options.sourceMap;
|
|
||||||
delete options.sourceMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
return options;
|
|
||||||
}
|
|
||||||
|
|
||||||
function dedupDescriptors(items) {
|
|
||||||
const map = new Map();
|
|
||||||
const descriptors = [];
|
|
||||||
|
|
||||||
for (const item of items) {
|
|
||||||
if (typeof item.value === "function") {
|
|
||||||
const fnKey = item.value;
|
|
||||||
let nameMap = map.get(fnKey);
|
|
||||||
|
|
||||||
if (!nameMap) {
|
|
||||||
nameMap = new Map();
|
|
||||||
map.set(fnKey, nameMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
let desc = nameMap.get(item.name);
|
|
||||||
|
|
||||||
if (!desc) {
|
|
||||||
desc = {
|
|
||||||
value: item
|
|
||||||
};
|
|
||||||
descriptors.push(desc);
|
|
||||||
if (!item.ownPass) nameMap.set(item.name, desc);
|
|
||||||
} else {
|
|
||||||
desc.value = item;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
descriptors.push({
|
|
||||||
value: item
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return descriptors.reduce((acc, desc) => {
|
|
||||||
acc.push(desc.value);
|
|
||||||
return acc;
|
|
||||||
}, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
function configIsApplicable({
|
|
||||||
options
|
|
||||||
}, dirname, context) {
|
|
||||||
return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname));
|
|
||||||
}
|
|
||||||
|
|
||||||
function configFieldIsApplicable(context, test, dirname) {
|
|
||||||
const patterns = Array.isArray(test) ? test : [test];
|
|
||||||
return matchesPatterns(context, patterns, dirname);
|
|
||||||
}
|
|
||||||
|
|
||||||
function shouldIgnore(context, ignore, only, dirname) {
|
|
||||||
if (ignore && matchesPatterns(context, ignore, dirname)) {
|
|
||||||
debug("Ignored %o because it matched one of %O from %o", context.filename, ignore, dirname);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (only && !matchesPatterns(context, only, dirname)) {
|
|
||||||
debug("Ignored %o because it failed to match one of %O from %o", context.filename, only, dirname);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchesPatterns(context, patterns, dirname) {
|
|
||||||
return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context));
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchPattern(pattern, dirname, pathToTest, context) {
|
|
||||||
if (typeof pattern === "function") {
|
|
||||||
return !!pattern(pathToTest, {
|
|
||||||
dirname,
|
|
||||||
envName: context.envName,
|
|
||||||
caller: context.caller
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof pathToTest !== "string") {
|
|
||||||
throw new Error(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof pattern === "string") {
|
|
||||||
pattern = (0, _patternToRegex.default)(pattern, dirname);
|
|
||||||
}
|
|
||||||
|
|
||||||
return pattern.test(pathToTest);
|
|
||||||
}
|
|
||||||
|
|
@ -1,210 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.createCachedDescriptors = createCachedDescriptors;
|
|
||||||
exports.createUncachedDescriptors = createUncachedDescriptors;
|
|
||||||
exports.createDescriptor = createDescriptor;
|
|
||||||
|
|
||||||
var _files = require("./files");
|
|
||||||
|
|
||||||
var _item = require("./item");
|
|
||||||
|
|
||||||
var _caching = require("./caching");
|
|
||||||
|
|
||||||
function isEqualDescriptor(a, b) {
|
|
||||||
return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createCachedDescriptors(dirname, options, alias) {
|
|
||||||
const {
|
|
||||||
plugins,
|
|
||||||
presets,
|
|
||||||
passPerPreset
|
|
||||||
} = options;
|
|
||||||
return {
|
|
||||||
options,
|
|
||||||
plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => [],
|
|
||||||
presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => []
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createUncachedDescriptors(dirname, options, alias) {
|
|
||||||
let plugins;
|
|
||||||
let presets;
|
|
||||||
return {
|
|
||||||
options,
|
|
||||||
plugins: () => {
|
|
||||||
if (!plugins) {
|
|
||||||
plugins = createPluginDescriptors(options.plugins || [], dirname, alias);
|
|
||||||
}
|
|
||||||
|
|
||||||
return plugins;
|
|
||||||
},
|
|
||||||
presets: () => {
|
|
||||||
if (!presets) {
|
|
||||||
presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset);
|
|
||||||
}
|
|
||||||
|
|
||||||
return presets;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const PRESET_DESCRIPTOR_CACHE = new WeakMap();
|
|
||||||
const createCachedPresetDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
|
|
||||||
const dirname = cache.using(dir => dir);
|
|
||||||
return (0, _caching.makeStrongCache)(alias => (0, _caching.makeStrongCache)(passPerPreset => createPresetDescriptors(items, dirname, alias, passPerPreset).map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc))));
|
|
||||||
});
|
|
||||||
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
|
|
||||||
const createCachedPluginDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
|
|
||||||
const dirname = cache.using(dir => dir);
|
|
||||||
return (0, _caching.makeStrongCache)(alias => createPluginDescriptors(items, dirname, alias).map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)));
|
|
||||||
});
|
|
||||||
const DEFAULT_OPTIONS = {};
|
|
||||||
|
|
||||||
function loadCachedDescriptor(cache, desc) {
|
|
||||||
const {
|
|
||||||
value,
|
|
||||||
options = DEFAULT_OPTIONS
|
|
||||||
} = desc;
|
|
||||||
if (options === false) return desc;
|
|
||||||
let cacheByOptions = cache.get(value);
|
|
||||||
|
|
||||||
if (!cacheByOptions) {
|
|
||||||
cacheByOptions = new WeakMap();
|
|
||||||
cache.set(value, cacheByOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
let possibilities = cacheByOptions.get(options);
|
|
||||||
|
|
||||||
if (!possibilities) {
|
|
||||||
possibilities = [];
|
|
||||||
cacheByOptions.set(options, possibilities);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (possibilities.indexOf(desc) === -1) {
|
|
||||||
const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc));
|
|
||||||
|
|
||||||
if (matches.length > 0) {
|
|
||||||
return matches[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
possibilities.push(desc);
|
|
||||||
}
|
|
||||||
|
|
||||||
return desc;
|
|
||||||
}
|
|
||||||
|
|
||||||
function createPresetDescriptors(items, dirname, alias, passPerPreset) {
|
|
||||||
return createDescriptors("preset", items, dirname, alias, passPerPreset);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createPluginDescriptors(items, dirname, alias) {
|
|
||||||
return createDescriptors("plugin", items, dirname, alias);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createDescriptors(type, items, dirname, alias, ownPass) {
|
|
||||||
const descriptors = items.map((item, index) => createDescriptor(item, dirname, {
|
|
||||||
type,
|
|
||||||
alias: `${alias}$${index}`,
|
|
||||||
ownPass: !!ownPass
|
|
||||||
}));
|
|
||||||
assertNoDuplicates(descriptors);
|
|
||||||
return descriptors;
|
|
||||||
}
|
|
||||||
|
|
||||||
function createDescriptor(pair, dirname, {
|
|
||||||
type,
|
|
||||||
alias,
|
|
||||||
ownPass
|
|
||||||
}) {
|
|
||||||
const desc = (0, _item.getItemDescriptor)(pair);
|
|
||||||
|
|
||||||
if (desc) {
|
|
||||||
return desc;
|
|
||||||
}
|
|
||||||
|
|
||||||
let name;
|
|
||||||
let options;
|
|
||||||
let value = pair;
|
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
if (value.length === 3) {
|
|
||||||
[value, options, name] = value;
|
|
||||||
} else {
|
|
||||||
[value, options] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let file = undefined;
|
|
||||||
let filepath = null;
|
|
||||||
|
|
||||||
if (typeof value === "string") {
|
|
||||||
if (typeof type !== "string") {
|
|
||||||
throw new Error("To resolve a string-based item, the type of item must be given");
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset;
|
|
||||||
const request = value;
|
|
||||||
({
|
|
||||||
filepath,
|
|
||||||
value
|
|
||||||
} = resolver(value, dirname));
|
|
||||||
file = {
|
|
||||||
request,
|
|
||||||
resolved: filepath
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!value) {
|
|
||||||
throw new Error(`Unexpected falsy value: ${String(value)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof value === "object" && value.__esModule) {
|
|
||||||
if (value.default) {
|
|
||||||
value = value.default;
|
|
||||||
} else {
|
|
||||||
throw new Error("Must export a default export when using ES6 modules.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof value !== "object" && typeof value !== "function") {
|
|
||||||
throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filepath !== null && typeof value === "object" && value) {
|
|
||||||
throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
name,
|
|
||||||
alias: filepath || alias,
|
|
||||||
value,
|
|
||||||
options,
|
|
||||||
dirname,
|
|
||||||
ownPass,
|
|
||||||
file
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertNoDuplicates(items) {
|
|
||||||
const map = new Map();
|
|
||||||
|
|
||||||
for (const item of items) {
|
|
||||||
if (typeof item.value !== "function") continue;
|
|
||||||
let nameMap = map.get(item.value);
|
|
||||||
|
|
||||||
if (!nameMap) {
|
|
||||||
nameMap = new Set();
|
|
||||||
map.set(item.value, nameMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (nameMap.has(item.name)) {
|
|
||||||
throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`].join("\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
nameMap.add(item.name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,323 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.findConfigUpwards = findConfigUpwards;
|
|
||||||
exports.findRelativeConfig = findRelativeConfig;
|
|
||||||
exports.findRootConfig = findRootConfig;
|
|
||||||
exports.loadConfig = loadConfig;
|
|
||||||
|
|
||||||
function _debug() {
|
|
||||||
const data = _interopRequireDefault(require("debug"));
|
|
||||||
|
|
||||||
_debug = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _fs() {
|
|
||||||
const data = _interopRequireDefault(require("fs"));
|
|
||||||
|
|
||||||
_fs = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _json() {
|
|
||||||
const data = _interopRequireDefault(require("json5"));
|
|
||||||
|
|
||||||
_json = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _resolve() {
|
|
||||||
const data = _interopRequireDefault(require("resolve"));
|
|
||||||
|
|
||||||
_resolve = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _caching = require("../caching");
|
|
||||||
|
|
||||||
var _configApi = _interopRequireDefault(require("../helpers/config-api"));
|
|
||||||
|
|
||||||
var _utils = require("./utils");
|
|
||||||
|
|
||||||
var _patternToRegex = _interopRequireDefault(require("../pattern-to-regex"));
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const debug = (0, _debug().default)("babel:config:loading:files:configuration");
|
|
||||||
const BABEL_CONFIG_JS_FILENAME = "babel.config.js";
|
|
||||||
const BABELRC_FILENAME = ".babelrc";
|
|
||||||
const BABELRC_JS_FILENAME = ".babelrc.js";
|
|
||||||
const BABELIGNORE_FILENAME = ".babelignore";
|
|
||||||
|
|
||||||
function findConfigUpwards(rootDir) {
|
|
||||||
let dirname = rootDir;
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
if (_fs().default.existsSync(_path().default.join(dirname, BABEL_CONFIG_JS_FILENAME))) {
|
|
||||||
return dirname;
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextDir = _path().default.dirname(dirname);
|
|
||||||
|
|
||||||
if (dirname === nextDir) break;
|
|
||||||
dirname = nextDir;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function findRelativeConfig(packageData, envName, caller) {
|
|
||||||
let config = null;
|
|
||||||
let ignore = null;
|
|
||||||
|
|
||||||
const dirname = _path().default.dirname(packageData.filepath);
|
|
||||||
|
|
||||||
for (const loc of packageData.directories) {
|
|
||||||
if (!config) {
|
|
||||||
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce((previousConfig, name) => {
|
|
||||||
const filepath = _path().default.join(loc, name);
|
|
||||||
|
|
||||||
const config = readConfig(filepath, envName, caller);
|
|
||||||
|
|
||||||
if (config && previousConfig) {
|
|
||||||
throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().default.basename(previousConfig.filepath)}\n` + ` - ${name}\n` + `from ${loc}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return config || previousConfig;
|
|
||||||
}, null);
|
|
||||||
const pkgConfig = packageData.pkg && packageData.pkg.dirname === loc ? packageToBabelConfig(packageData.pkg) : null;
|
|
||||||
|
|
||||||
if (pkgConfig) {
|
|
||||||
if (config) {
|
|
||||||
throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().default.basename(pkgConfig.filepath)}#babel\n` + ` - ${_path().default.basename(config.filepath)}\n` + `from ${loc}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
config = pkgConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (config) {
|
|
||||||
debug("Found configuration %o from %o.", config.filepath, dirname);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!ignore) {
|
|
||||||
const ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME);
|
|
||||||
|
|
||||||
ignore = readIgnoreConfig(ignoreLoc);
|
|
||||||
|
|
||||||
if (ignore) {
|
|
||||||
debug("Found ignore %o from %o.", ignore.filepath, dirname);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
config,
|
|
||||||
ignore
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function findRootConfig(dirname, envName, caller) {
|
|
||||||
const filepath = _path().default.resolve(dirname, BABEL_CONFIG_JS_FILENAME);
|
|
||||||
|
|
||||||
const conf = readConfig(filepath, envName, caller);
|
|
||||||
|
|
||||||
if (conf) {
|
|
||||||
debug("Found root config %o in $o.", BABEL_CONFIG_JS_FILENAME, dirname);
|
|
||||||
}
|
|
||||||
|
|
||||||
return conf;
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadConfig(name, dirname, envName, caller) {
|
|
||||||
const filepath = _resolve().default.sync(name, {
|
|
||||||
basedir: dirname
|
|
||||||
});
|
|
||||||
|
|
||||||
const conf = readConfig(filepath, envName, caller);
|
|
||||||
|
|
||||||
if (!conf) {
|
|
||||||
throw new Error(`Config file ${filepath} contains no configuration data`);
|
|
||||||
}
|
|
||||||
|
|
||||||
debug("Loaded config %o from $o.", name, dirname);
|
|
||||||
return conf;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readConfig(filepath, envName, caller) {
|
|
||||||
return _path().default.extname(filepath) === ".js" ? readConfigJS(filepath, {
|
|
||||||
envName,
|
|
||||||
caller
|
|
||||||
}) : readConfigJSON5(filepath);
|
|
||||||
}
|
|
||||||
|
|
||||||
const LOADING_CONFIGS = new Set();
|
|
||||||
const readConfigJS = (0, _caching.makeStrongCache)((filepath, cache) => {
|
|
||||||
if (!_fs().default.existsSync(filepath)) {
|
|
||||||
cache.forever();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (LOADING_CONFIGS.has(filepath)) {
|
|
||||||
cache.never();
|
|
||||||
debug("Auto-ignoring usage of config %o.", filepath);
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
dirname: _path().default.dirname(filepath),
|
|
||||||
options: {}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let options;
|
|
||||||
|
|
||||||
try {
|
|
||||||
LOADING_CONFIGS.add(filepath);
|
|
||||||
|
|
||||||
const configModule = require(filepath);
|
|
||||||
|
|
||||||
options = configModule && configModule.__esModule ? configModule.default || undefined : configModule;
|
|
||||||
} catch (err) {
|
|
||||||
err.message = `${filepath}: Error while loading config - ${err.message}`;
|
|
||||||
throw err;
|
|
||||||
} finally {
|
|
||||||
LOADING_CONFIGS.delete(filepath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof options === "function") {
|
|
||||||
options = options((0, _configApi.default)(cache));
|
|
||||||
if (!cache.configured()) throwConfigError();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
|
||||||
throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof options.then === "function") {
|
|
||||||
throw new Error(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
dirname: _path().default.dirname(filepath),
|
|
||||||
options
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const packageToBabelConfig = (0, _caching.makeWeakCache)(file => {
|
|
||||||
const babel = file.options["babel"];
|
|
||||||
if (typeof babel === "undefined") return null;
|
|
||||||
|
|
||||||
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
|
|
||||||
throw new Error(`${file.filepath}: .babel property must be an object`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
filepath: file.filepath,
|
|
||||||
dirname: file.dirname,
|
|
||||||
options: babel
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => {
|
|
||||||
let options;
|
|
||||||
|
|
||||||
try {
|
|
||||||
options = _json().default.parse(content);
|
|
||||||
} catch (err) {
|
|
||||||
err.message = `${filepath}: Error while parsing config - ${err.message}`;
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!options) throw new Error(`${filepath}: No config detected`);
|
|
||||||
|
|
||||||
if (typeof options !== "object") {
|
|
||||||
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Array.isArray(options)) {
|
|
||||||
throw new Error(`${filepath}: Expected config object but found array`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
dirname: _path().default.dirname(filepath),
|
|
||||||
options
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => {
|
|
||||||
const ignoreDir = _path().default.dirname(filepath);
|
|
||||||
|
|
||||||
const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line);
|
|
||||||
|
|
||||||
for (const pattern of ignorePatterns) {
|
|
||||||
if (pattern[0] === "!") {
|
|
||||||
throw new Error(`Negation of file paths is not supported.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
dirname: _path().default.dirname(filepath),
|
|
||||||
ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir))
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
function throwConfigError() {
|
|
||||||
throw new Error(`\
|
|
||||||
Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
|
|
||||||
for various types of caching, using the first param of their handler functions:
|
|
||||||
|
|
||||||
module.exports = function(api) {
|
|
||||||
// The API exposes the following:
|
|
||||||
|
|
||||||
// Cache the returned value forever and don't call this function again.
|
|
||||||
api.cache(true);
|
|
||||||
|
|
||||||
// Don't cache at all. Not recommended because it will be very slow.
|
|
||||||
api.cache(false);
|
|
||||||
|
|
||||||
// Cached based on the value of some function. If this function returns a value different from
|
|
||||||
// a previously-encountered value, the plugins will re-evaluate.
|
|
||||||
var env = api.cache(() => process.env.NODE_ENV);
|
|
||||||
|
|
||||||
// If testing for a specific env, we recommend specifics to avoid instantiating a plugin for
|
|
||||||
// any possible NODE_ENV value that might come up during plugin execution.
|
|
||||||
var isProd = api.cache(() => process.env.NODE_ENV === "production");
|
|
||||||
|
|
||||||
// .cache(fn) will perform a linear search though instances to find the matching plugin based
|
|
||||||
// based on previous instantiated plugins. If you want to recreate the plugin and discard the
|
|
||||||
// previous instance whenever something changes, you may use:
|
|
||||||
var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");
|
|
||||||
|
|
||||||
// Note, we also expose the following more-verbose versions of the above examples:
|
|
||||||
api.cache.forever(); // api.cache(true)
|
|
||||||
api.cache.never(); // api.cache(false)
|
|
||||||
api.cache.using(fn); // api.cache(fn)
|
|
||||||
|
|
||||||
// Return the value that will be cached.
|
|
||||||
return { };
|
|
||||||
};`);
|
|
||||||
}
|
|
||||||
|
|
@ -1,59 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.findConfigUpwards = findConfigUpwards;
|
|
||||||
exports.findPackageData = findPackageData;
|
|
||||||
exports.findRelativeConfig = findRelativeConfig;
|
|
||||||
exports.findRootConfig = findRootConfig;
|
|
||||||
exports.loadConfig = loadConfig;
|
|
||||||
exports.resolvePlugin = resolvePlugin;
|
|
||||||
exports.resolvePreset = resolvePreset;
|
|
||||||
exports.loadPlugin = loadPlugin;
|
|
||||||
exports.loadPreset = loadPreset;
|
|
||||||
|
|
||||||
function findConfigUpwards(rootDir) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function findPackageData(filepath) {
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
directories: [],
|
|
||||||
pkg: null,
|
|
||||||
isPackage: false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function findRelativeConfig(pkgData, envName, caller) {
|
|
||||||
return {
|
|
||||||
pkg: null,
|
|
||||||
config: null,
|
|
||||||
ignore: null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function findRootConfig(dirname, envName, caller) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadConfig(name, dirname, envName, caller) {
|
|
||||||
throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolvePlugin(name, dirname) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolvePreset(name, dirname) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadPlugin(name, dirname) {
|
|
||||||
throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadPreset(name, dirname) {
|
|
||||||
throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`);
|
|
||||||
}
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "findPackageData", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _package.findPackageData;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "findConfigUpwards", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _configuration.findConfigUpwards;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "findRelativeConfig", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _configuration.findRelativeConfig;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "findRootConfig", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _configuration.findRootConfig;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "loadConfig", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _configuration.loadConfig;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "resolvePlugin", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _plugins.resolvePlugin;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "resolvePreset", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _plugins.resolvePreset;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "loadPlugin", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _plugins.loadPlugin;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "loadPreset", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _plugins.loadPreset;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
var _package = require("./package");
|
|
||||||
|
|
||||||
var _configuration = require("./configuration");
|
|
||||||
|
|
||||||
var _plugins = require("./plugins");
|
|
||||||
|
|
||||||
({});
|
|
||||||
|
|
@ -1,76 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.findPackageData = findPackageData;
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _utils = require("./utils");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const PACKAGE_FILENAME = "package.json";
|
|
||||||
|
|
||||||
function findPackageData(filepath) {
|
|
||||||
let pkg = null;
|
|
||||||
const directories = [];
|
|
||||||
let isPackage = true;
|
|
||||||
|
|
||||||
let dirname = _path().default.dirname(filepath);
|
|
||||||
|
|
||||||
while (!pkg && _path().default.basename(dirname) !== "node_modules") {
|
|
||||||
directories.push(dirname);
|
|
||||||
pkg = readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME));
|
|
||||||
|
|
||||||
const nextLoc = _path().default.dirname(dirname);
|
|
||||||
|
|
||||||
if (dirname === nextLoc) {
|
|
||||||
isPackage = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
dirname = nextLoc;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
directories,
|
|
||||||
pkg,
|
|
||||||
isPackage
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const readConfigPackage = (0, _utils.makeStaticFileCache)((filepath, content) => {
|
|
||||||
let options;
|
|
||||||
|
|
||||||
try {
|
|
||||||
options = JSON.parse(content);
|
|
||||||
} catch (err) {
|
|
||||||
err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof options !== "object") {
|
|
||||||
throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Array.isArray(options)) {
|
|
||||||
throw new Error(`${filepath}: Expected config object but found array`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
dirname: _path().default.dirname(filepath),
|
|
||||||
options
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
@ -1,169 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.resolvePlugin = resolvePlugin;
|
|
||||||
exports.resolvePreset = resolvePreset;
|
|
||||||
exports.loadPlugin = loadPlugin;
|
|
||||||
exports.loadPreset = loadPreset;
|
|
||||||
|
|
||||||
function _debug() {
|
|
||||||
const data = _interopRequireDefault(require("debug"));
|
|
||||||
|
|
||||||
_debug = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _resolve() {
|
|
||||||
const data = _interopRequireDefault(require("resolve"));
|
|
||||||
|
|
||||||
_resolve = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const debug = (0, _debug().default)("babel:config:loading:files:plugins");
|
|
||||||
const EXACT_RE = /^module:/;
|
|
||||||
const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
|
|
||||||
const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
|
|
||||||
const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
|
|
||||||
const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
|
|
||||||
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
|
|
||||||
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
|
|
||||||
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
|
|
||||||
|
|
||||||
function resolvePlugin(name, dirname) {
|
|
||||||
return resolveStandardizedName("plugin", name, dirname);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolvePreset(name, dirname) {
|
|
||||||
return resolveStandardizedName("preset", name, dirname);
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadPlugin(name, dirname) {
|
|
||||||
const filepath = resolvePlugin(name, dirname);
|
|
||||||
|
|
||||||
if (!filepath) {
|
|
||||||
throw new Error(`Plugin ${name} not found relative to ${dirname}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const value = requireModule("plugin", filepath);
|
|
||||||
debug("Loaded plugin %o from %o.", name, dirname);
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
value
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadPreset(name, dirname) {
|
|
||||||
const filepath = resolvePreset(name, dirname);
|
|
||||||
|
|
||||||
if (!filepath) {
|
|
||||||
throw new Error(`Preset ${name} not found relative to ${dirname}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const value = requireModule("preset", filepath);
|
|
||||||
debug("Loaded preset %o from %o.", name, dirname);
|
|
||||||
return {
|
|
||||||
filepath,
|
|
||||||
value
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function standardizeName(type, name) {
|
|
||||||
if (_path().default.isAbsolute(name)) return name;
|
|
||||||
const isPreset = type === "preset";
|
|
||||||
return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveStandardizedName(type, name, dirname = process.cwd()) {
|
|
||||||
const standardizedName = standardizeName(type, name);
|
|
||||||
|
|
||||||
try {
|
|
||||||
return _resolve().default.sync(standardizedName, {
|
|
||||||
basedir: dirname
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
if (e.code !== "MODULE_NOT_FOUND") throw e;
|
|
||||||
|
|
||||||
if (standardizedName !== name) {
|
|
||||||
let resolvedOriginal = false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
_resolve().default.sync(name, {
|
|
||||||
basedir: dirname
|
|
||||||
});
|
|
||||||
|
|
||||||
resolvedOriginal = true;
|
|
||||||
} catch (e2) {}
|
|
||||||
|
|
||||||
if (resolvedOriginal) {
|
|
||||||
e.message += `\n- If you want to resolve "${name}", use "module:${name}"`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let resolvedBabel = false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
_resolve().default.sync(standardizeName(type, "@babel/" + name), {
|
|
||||||
basedir: dirname
|
|
||||||
});
|
|
||||||
|
|
||||||
resolvedBabel = true;
|
|
||||||
} catch (e2) {}
|
|
||||||
|
|
||||||
if (resolvedBabel) {
|
|
||||||
e.message += `\n- Did you mean "@babel/${name}"?`;
|
|
||||||
}
|
|
||||||
|
|
||||||
let resolvedOppositeType = false;
|
|
||||||
const oppositeType = type === "preset" ? "plugin" : "preset";
|
|
||||||
|
|
||||||
try {
|
|
||||||
_resolve().default.sync(standardizeName(oppositeType, name), {
|
|
||||||
basedir: dirname
|
|
||||||
});
|
|
||||||
|
|
||||||
resolvedOppositeType = true;
|
|
||||||
} catch (e2) {}
|
|
||||||
|
|
||||||
if (resolvedOppositeType) {
|
|
||||||
e.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const LOADING_MODULES = new Set();
|
|
||||||
|
|
||||||
function requireModule(type, name) {
|
|
||||||
if (LOADING_MODULES.has(name)) {
|
|
||||||
throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.');
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
LOADING_MODULES.add(name);
|
|
||||||
return require(name);
|
|
||||||
} finally {
|
|
||||||
LOADING_MODULES.delete(name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.makeStaticFileCache = makeStaticFileCache;
|
|
||||||
|
|
||||||
function _fs() {
|
|
||||||
const data = _interopRequireDefault(require("fs"));
|
|
||||||
|
|
||||||
_fs = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _caching = require("../caching");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function makeStaticFileCache(fn) {
|
|
||||||
return (0, _caching.makeStrongCache)((filepath, cache) => {
|
|
||||||
if (cache.invalidate(() => fileMtime(filepath)) === null) {
|
|
||||||
cache.forever();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return fn(filepath, _fs().default.readFileSync(filepath, "utf8"));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function fileMtime(filepath) {
|
|
||||||
try {
|
|
||||||
return +_fs().default.statSync(filepath).mtime;
|
|
||||||
} catch (e) {
|
|
||||||
if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
@ -1,258 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = loadFullConfig;
|
|
||||||
|
|
||||||
var _util = require("./util");
|
|
||||||
|
|
||||||
var context = _interopRequireWildcard(require("../index"));
|
|
||||||
|
|
||||||
var _plugin = _interopRequireDefault(require("./plugin"));
|
|
||||||
|
|
||||||
var _item = require("./item");
|
|
||||||
|
|
||||||
var _configChain = require("./config-chain");
|
|
||||||
|
|
||||||
function _traverse() {
|
|
||||||
const data = _interopRequireDefault(require("@babel/traverse"));
|
|
||||||
|
|
||||||
_traverse = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _caching = require("./caching");
|
|
||||||
|
|
||||||
var _options = require("./validation/options");
|
|
||||||
|
|
||||||
var _plugins = require("./validation/plugins");
|
|
||||||
|
|
||||||
var _configApi = _interopRequireDefault(require("./helpers/config-api"));
|
|
||||||
|
|
||||||
var _partial = _interopRequireDefault(require("./partial"));
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function loadFullConfig(inputOpts) {
|
|
||||||
const result = (0, _partial.default)(inputOpts);
|
|
||||||
|
|
||||||
if (!result) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
options,
|
|
||||||
context
|
|
||||||
} = result;
|
|
||||||
const optionDefaults = {};
|
|
||||||
const passes = [[]];
|
|
||||||
|
|
||||||
try {
|
|
||||||
const {
|
|
||||||
plugins,
|
|
||||||
presets
|
|
||||||
} = options;
|
|
||||||
|
|
||||||
if (!plugins || !presets) {
|
|
||||||
throw new Error("Assertion failure - plugins and presets exist");
|
|
||||||
}
|
|
||||||
|
|
||||||
const ignored = function recurseDescriptors(config, pass) {
|
|
||||||
const plugins = config.plugins.reduce((acc, descriptor) => {
|
|
||||||
if (descriptor.options !== false) {
|
|
||||||
acc.push(loadPluginDescriptor(descriptor, context));
|
|
||||||
}
|
|
||||||
|
|
||||||
return acc;
|
|
||||||
}, []);
|
|
||||||
const presets = config.presets.reduce((acc, descriptor) => {
|
|
||||||
if (descriptor.options !== false) {
|
|
||||||
acc.push({
|
|
||||||
preset: loadPresetDescriptor(descriptor, context),
|
|
||||||
pass: descriptor.ownPass ? [] : pass
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return acc;
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (presets.length > 0) {
|
|
||||||
passes.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pass));
|
|
||||||
|
|
||||||
for (const _ref of presets) {
|
|
||||||
const {
|
|
||||||
preset,
|
|
||||||
pass
|
|
||||||
} = _ref;
|
|
||||||
if (!preset) return true;
|
|
||||||
const ignored = recurseDescriptors({
|
|
||||||
plugins: preset.plugins,
|
|
||||||
presets: preset.presets
|
|
||||||
}, pass);
|
|
||||||
if (ignored) return true;
|
|
||||||
preset.options.forEach(opts => {
|
|
||||||
(0, _util.mergeOptions)(optionDefaults, opts);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (plugins.length > 0) {
|
|
||||||
pass.unshift(...plugins);
|
|
||||||
}
|
|
||||||
}({
|
|
||||||
plugins: plugins.map(item => {
|
|
||||||
const desc = (0, _item.getItemDescriptor)(item);
|
|
||||||
|
|
||||||
if (!desc) {
|
|
||||||
throw new Error("Assertion failure - must be config item");
|
|
||||||
}
|
|
||||||
|
|
||||||
return desc;
|
|
||||||
}),
|
|
||||||
presets: presets.map(item => {
|
|
||||||
const desc = (0, _item.getItemDescriptor)(item);
|
|
||||||
|
|
||||||
if (!desc) {
|
|
||||||
throw new Error("Assertion failure - must be config item");
|
|
||||||
}
|
|
||||||
|
|
||||||
return desc;
|
|
||||||
})
|
|
||||||
}, passes[0]);
|
|
||||||
|
|
||||||
if (ignored) return null;
|
|
||||||
} catch (e) {
|
|
||||||
if (!/^\[BABEL\]/.test(e.message)) {
|
|
||||||
e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
|
|
||||||
const opts = optionDefaults;
|
|
||||||
(0, _util.mergeOptions)(opts, options);
|
|
||||||
opts.plugins = passes[0];
|
|
||||||
opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({
|
|
||||||
plugins
|
|
||||||
}));
|
|
||||||
opts.passPerPreset = opts.presets.length > 0;
|
|
||||||
return {
|
|
||||||
options: opts,
|
|
||||||
passes: passes
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const loadDescriptor = (0, _caching.makeWeakCache)(({
|
|
||||||
value,
|
|
||||||
options,
|
|
||||||
dirname,
|
|
||||||
alias
|
|
||||||
}, cache) => {
|
|
||||||
if (options === false) throw new Error("Assertion failure");
|
|
||||||
options = options || {};
|
|
||||||
let item = value;
|
|
||||||
|
|
||||||
if (typeof value === "function") {
|
|
||||||
const api = Object.assign({}, context, (0, _configApi.default)(cache));
|
|
||||||
|
|
||||||
try {
|
|
||||||
item = value(api, options, dirname);
|
|
||||||
} catch (e) {
|
|
||||||
if (alias) {
|
|
||||||
e.message += ` (While processing: ${JSON.stringify(alias)})`;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!item || typeof item !== "object") {
|
|
||||||
throw new Error("Plugin/Preset did not return an object.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof item.then === "function") {
|
|
||||||
throw new Error(`You appear to be using an async plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
value: item,
|
|
||||||
options,
|
|
||||||
dirname,
|
|
||||||
alias
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
function loadPluginDescriptor(descriptor, context) {
|
|
||||||
if (descriptor.value instanceof _plugin.default) {
|
|
||||||
if (descriptor.options) {
|
|
||||||
throw new Error("Passed options to an existing Plugin instance will not work.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return descriptor.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return instantiatePlugin(loadDescriptor(descriptor, context), context);
|
|
||||||
}
|
|
||||||
|
|
||||||
const instantiatePlugin = (0, _caching.makeWeakCache)(({
|
|
||||||
value,
|
|
||||||
options,
|
|
||||||
dirname,
|
|
||||||
alias
|
|
||||||
}, cache) => {
|
|
||||||
const pluginObj = (0, _plugins.validatePluginObject)(value);
|
|
||||||
const plugin = Object.assign({}, pluginObj);
|
|
||||||
|
|
||||||
if (plugin.visitor) {
|
|
||||||
plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (plugin.inherits) {
|
|
||||||
const inheritsDescriptor = {
|
|
||||||
name: undefined,
|
|
||||||
alias: `${alias}$inherits`,
|
|
||||||
value: plugin.inherits,
|
|
||||||
options,
|
|
||||||
dirname
|
|
||||||
};
|
|
||||||
const inherits = cache.invalidate(data => loadPluginDescriptor(inheritsDescriptor, data));
|
|
||||||
plugin.pre = chain(inherits.pre, plugin.pre);
|
|
||||||
plugin.post = chain(inherits.post, plugin.post);
|
|
||||||
plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions);
|
|
||||||
plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new _plugin.default(plugin, options, alias);
|
|
||||||
});
|
|
||||||
|
|
||||||
const loadPresetDescriptor = (descriptor, context) => {
|
|
||||||
return (0, _configChain.buildPresetChain)(instantiatePreset(loadDescriptor(descriptor, context)), context);
|
|
||||||
};
|
|
||||||
|
|
||||||
const instantiatePreset = (0, _caching.makeWeakCache)(({
|
|
||||||
value,
|
|
||||||
dirname,
|
|
||||||
alias
|
|
||||||
}) => {
|
|
||||||
return {
|
|
||||||
options: (0, _options.validate)("preset", value),
|
|
||||||
alias,
|
|
||||||
dirname
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
function chain(a, b) {
|
|
||||||
const fns = [a, b].filter(Boolean);
|
|
||||||
if (fns.length <= 1) return fns[0];
|
|
||||||
return function (...args) {
|
|
||||||
for (const fn of fns) {
|
|
||||||
fn.apply(this, args);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = makeAPI;
|
|
||||||
|
|
||||||
function _semver() {
|
|
||||||
const data = _interopRequireDefault(require("semver"));
|
|
||||||
|
|
||||||
_semver = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ = require("../../");
|
|
||||||
|
|
||||||
var _caching = require("../caching");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function makeAPI(cache) {
|
|
||||||
const env = value => cache.using(data => {
|
|
||||||
if (typeof value === "undefined") return data.envName;
|
|
||||||
|
|
||||||
if (typeof value === "function") {
|
|
||||||
return (0, _caching.assertSimpleType)(value(data.envName));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!Array.isArray(value)) value = [value];
|
|
||||||
return value.some(entry => {
|
|
||||||
if (typeof entry !== "string") {
|
|
||||||
throw new Error("Unexpected non-string value");
|
|
||||||
}
|
|
||||||
|
|
||||||
return entry === data.envName;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller)));
|
|
||||||
|
|
||||||
return {
|
|
||||||
version: _.version,
|
|
||||||
cache: cache.simple(),
|
|
||||||
env,
|
|
||||||
async: () => false,
|
|
||||||
caller,
|
|
||||||
assertVersion,
|
|
||||||
tokTypes: undefined
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertVersion(range) {
|
|
||||||
if (typeof range === "number") {
|
|
||||||
if (!Number.isInteger(range)) {
|
|
||||||
throw new Error("Expected string or integer value.");
|
|
||||||
}
|
|
||||||
|
|
||||||
range = `^${range}.0.0-0`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof range !== "string") {
|
|
||||||
throw new Error("Expected string or integer value.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (_semver().default.satisfies(_.version, range)) return;
|
|
||||||
const limit = Error.stackTraceLimit;
|
|
||||||
|
|
||||||
if (typeof limit === "number" && limit < 25) {
|
|
||||||
Error.stackTraceLimit = 25;
|
|
||||||
}
|
|
||||||
|
|
||||||
const err = new Error(`Requires Babel "${range}", but was loaded with "${_.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`);
|
|
||||||
|
|
||||||
if (typeof limit === "number") {
|
|
||||||
Error.stackTraceLimit = limit;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw Object.assign(err, {
|
|
||||||
code: "BABEL_VERSION_UNSUPPORTED",
|
|
||||||
version: _.version,
|
|
||||||
range
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.getEnv = getEnv;
|
|
||||||
|
|
||||||
function getEnv(defaultValue = "development") {
|
|
||||||
return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;
|
|
||||||
}
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.loadOptions = loadOptions;
|
|
||||||
Object.defineProperty(exports, "default", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _full.default;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "loadPartialConfig", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _partial.loadPartialConfig;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
var _full = _interopRequireDefault(require("./full"));
|
|
||||||
|
|
||||||
var _partial = require("./partial");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function loadOptions(opts) {
|
|
||||||
const config = (0, _full.default)(opts);
|
|
||||||
return config ? config.options : null;
|
|
||||||
}
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.createItemFromDescriptor = createItemFromDescriptor;
|
|
||||||
exports.createConfigItem = createConfigItem;
|
|
||||||
exports.getItemDescriptor = getItemDescriptor;
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _configDescriptors = require("./config-descriptors");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function createItemFromDescriptor(desc) {
|
|
||||||
return new ConfigItem(desc);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createConfigItem(value, {
|
|
||||||
dirname = ".",
|
|
||||||
type
|
|
||||||
} = {}) {
|
|
||||||
const descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), {
|
|
||||||
type,
|
|
||||||
alias: "programmatic item"
|
|
||||||
});
|
|
||||||
return createItemFromDescriptor(descriptor);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getItemDescriptor(item) {
|
|
||||||
if (item instanceof ConfigItem) {
|
|
||||||
return item._descriptor;
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
class ConfigItem {
|
|
||||||
constructor(descriptor) {
|
|
||||||
this._descriptor = descriptor;
|
|
||||||
Object.defineProperty(this, "_descriptor", {
|
|
||||||
enumerable: false
|
|
||||||
});
|
|
||||||
this.value = this._descriptor.value;
|
|
||||||
this.options = this._descriptor.options;
|
|
||||||
this.dirname = this._descriptor.dirname;
|
|
||||||
this.name = this._descriptor.name;
|
|
||||||
this.file = this._descriptor.file ? {
|
|
||||||
request: this._descriptor.file.request,
|
|
||||||
resolved: this._descriptor.file.resolved
|
|
||||||
} : undefined;
|
|
||||||
Object.freeze(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.freeze(ConfigItem.prototype);
|
|
||||||
|
|
@ -1,141 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = loadPrivatePartialConfig;
|
|
||||||
exports.loadPartialConfig = loadPartialConfig;
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _plugin = _interopRequireDefault(require("./plugin"));
|
|
||||||
|
|
||||||
var _util = require("./util");
|
|
||||||
|
|
||||||
var _item = require("./item");
|
|
||||||
|
|
||||||
var _configChain = require("./config-chain");
|
|
||||||
|
|
||||||
var _environment = require("./helpers/environment");
|
|
||||||
|
|
||||||
var _options = require("./validation/options");
|
|
||||||
|
|
||||||
var _files = require("./files");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function resolveRootMode(rootDir, rootMode) {
|
|
||||||
switch (rootMode) {
|
|
||||||
case "root":
|
|
||||||
return rootDir;
|
|
||||||
|
|
||||||
case "upward-optional":
|
|
||||||
{
|
|
||||||
const upwardRootDir = (0, _files.findConfigUpwards)(rootDir);
|
|
||||||
return upwardRootDir === null ? rootDir : upwardRootDir;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "upward":
|
|
||||||
{
|
|
||||||
const upwardRootDir = (0, _files.findConfigUpwards)(rootDir);
|
|
||||||
if (upwardRootDir !== null) return upwardRootDir;
|
|
||||||
throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}"`), {
|
|
||||||
code: "BABEL_ROOT_NOT_FOUND",
|
|
||||||
dirname: rootDir
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error(`Assertion failure - unknown rootMode value`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadPrivatePartialConfig(inputOpts) {
|
|
||||||
if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) {
|
|
||||||
throw new Error("Babel options must be an object, null, or undefined");
|
|
||||||
}
|
|
||||||
|
|
||||||
const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {};
|
|
||||||
const {
|
|
||||||
envName = (0, _environment.getEnv)(),
|
|
||||||
cwd = ".",
|
|
||||||
root: rootDir = ".",
|
|
||||||
rootMode = "root",
|
|
||||||
caller
|
|
||||||
} = args;
|
|
||||||
|
|
||||||
const absoluteCwd = _path().default.resolve(cwd);
|
|
||||||
|
|
||||||
const absoluteRootDir = resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode);
|
|
||||||
const context = {
|
|
||||||
filename: typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined,
|
|
||||||
cwd: absoluteCwd,
|
|
||||||
root: absoluteRootDir,
|
|
||||||
envName,
|
|
||||||
caller
|
|
||||||
};
|
|
||||||
const configChain = (0, _configChain.buildRootChain)(args, context);
|
|
||||||
if (!configChain) return null;
|
|
||||||
const options = {};
|
|
||||||
configChain.options.forEach(opts => {
|
|
||||||
(0, _util.mergeOptions)(options, opts);
|
|
||||||
});
|
|
||||||
options.babelrc = false;
|
|
||||||
options.configFile = false;
|
|
||||||
options.passPerPreset = false;
|
|
||||||
options.envName = context.envName;
|
|
||||||
options.cwd = context.cwd;
|
|
||||||
options.root = context.root;
|
|
||||||
options.filename = typeof context.filename === "string" ? context.filename : undefined;
|
|
||||||
options.plugins = configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
|
|
||||||
options.presets = configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
|
|
||||||
return {
|
|
||||||
options,
|
|
||||||
context,
|
|
||||||
ignore: configChain.ignore,
|
|
||||||
babelrc: configChain.babelrc,
|
|
||||||
config: configChain.config
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadPartialConfig(inputOpts) {
|
|
||||||
const result = loadPrivatePartialConfig(inputOpts);
|
|
||||||
if (!result) return null;
|
|
||||||
const {
|
|
||||||
options,
|
|
||||||
babelrc,
|
|
||||||
ignore,
|
|
||||||
config
|
|
||||||
} = result;
|
|
||||||
(options.plugins || []).forEach(item => {
|
|
||||||
if (item.value instanceof _plugin.default) {
|
|
||||||
throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
class PartialConfig {
|
|
||||||
constructor(options, babelrc, ignore, config) {
|
|
||||||
this.options = options;
|
|
||||||
this.babelignore = ignore;
|
|
||||||
this.babelrc = babelrc;
|
|
||||||
this.config = config;
|
|
||||||
Object.freeze(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
hasFilesystemConfig() {
|
|
||||||
return this.babelrc !== undefined || this.config !== undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.freeze(PartialConfig.prototype);
|
|
||||||
|
|
@ -1,52 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = pathToPattern;
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _escapeRegExp() {
|
|
||||||
const data = _interopRequireDefault(require("lodash/escapeRegExp"));
|
|
||||||
|
|
||||||
_escapeRegExp = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const sep = `\\${_path().default.sep}`;
|
|
||||||
const endSep = `(?:${sep}|$)`;
|
|
||||||
const substitution = `[^${sep}]+`;
|
|
||||||
const starPat = `(?:${substitution}${sep})`;
|
|
||||||
const starPatLast = `(?:${substitution}${endSep})`;
|
|
||||||
const starStarPat = `${starPat}*?`;
|
|
||||||
const starStarPatLast = `${starPat}*?${starPatLast}?`;
|
|
||||||
|
|
||||||
function pathToPattern(pattern, dirname) {
|
|
||||||
const parts = _path().default.resolve(dirname, pattern).split(_path().default.sep);
|
|
||||||
|
|
||||||
return new RegExp(["^", ...parts.map((part, i) => {
|
|
||||||
const last = i === parts.length - 1;
|
|
||||||
if (part === "**") return last ? starStarPatLast : starStarPat;
|
|
||||||
if (part === "*") return last ? starPatLast : starPat;
|
|
||||||
|
|
||||||
if (part.indexOf("*.") === 0) {
|
|
||||||
return substitution + (0, _escapeRegExp().default)(part.slice(1)) + (last ? endSep : sep);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (0, _escapeRegExp().default)(part) + (last ? endSep : sep);
|
|
||||||
})].join(""));
|
|
||||||
}
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = void 0;
|
|
||||||
|
|
||||||
class Plugin {
|
|
||||||
constructor(plugin, options, key) {
|
|
||||||
this.key = plugin.name || key;
|
|
||||||
this.manipulateOptions = plugin.manipulateOptions;
|
|
||||||
this.post = plugin.post;
|
|
||||||
this.pre = plugin.pre;
|
|
||||||
this.visitor = plugin.visitor || {};
|
|
||||||
this.parserOverride = plugin.parserOverride;
|
|
||||||
this.generatorOverride = plugin.generatorOverride;
|
|
||||||
this.options = options;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.default = Plugin;
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.mergeOptions = mergeOptions;
|
|
||||||
|
|
||||||
function mergeOptions(target, source) {
|
|
||||||
for (const k of Object.keys(source)) {
|
|
||||||
if (k === "parserOpts" && source.parserOpts) {
|
|
||||||
const parserOpts = source.parserOpts;
|
|
||||||
const targetObj = target.parserOpts = target.parserOpts || {};
|
|
||||||
mergeDefaultFields(targetObj, parserOpts);
|
|
||||||
} else if (k === "generatorOpts" && source.generatorOpts) {
|
|
||||||
const generatorOpts = source.generatorOpts;
|
|
||||||
const targetObj = target.generatorOpts = target.generatorOpts || {};
|
|
||||||
mergeDefaultFields(targetObj, generatorOpts);
|
|
||||||
} else {
|
|
||||||
const val = source[k];
|
|
||||||
if (val !== undefined) target[k] = val;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeDefaultFields(target, source) {
|
|
||||||
for (const k of Object.keys(source)) {
|
|
||||||
const val = source[k];
|
|
||||||
if (val !== undefined) target[k] = val;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,268 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.msg = msg;
|
|
||||||
exports.access = access;
|
|
||||||
exports.assertRootMode = assertRootMode;
|
|
||||||
exports.assertSourceMaps = assertSourceMaps;
|
|
||||||
exports.assertCompact = assertCompact;
|
|
||||||
exports.assertSourceType = assertSourceType;
|
|
||||||
exports.assertCallerMetadata = assertCallerMetadata;
|
|
||||||
exports.assertInputSourceMap = assertInputSourceMap;
|
|
||||||
exports.assertString = assertString;
|
|
||||||
exports.assertFunction = assertFunction;
|
|
||||||
exports.assertBoolean = assertBoolean;
|
|
||||||
exports.assertObject = assertObject;
|
|
||||||
exports.assertArray = assertArray;
|
|
||||||
exports.assertIgnoreList = assertIgnoreList;
|
|
||||||
exports.assertConfigApplicableTest = assertConfigApplicableTest;
|
|
||||||
exports.assertConfigFileSearch = assertConfigFileSearch;
|
|
||||||
exports.assertBabelrcSearch = assertBabelrcSearch;
|
|
||||||
exports.assertPluginList = assertPluginList;
|
|
||||||
|
|
||||||
function msg(loc) {
|
|
||||||
switch (loc.type) {
|
|
||||||
case "root":
|
|
||||||
return ``;
|
|
||||||
|
|
||||||
case "env":
|
|
||||||
return `${msg(loc.parent)}.env["${loc.name}"]`;
|
|
||||||
|
|
||||||
case "overrides":
|
|
||||||
return `${msg(loc.parent)}.overrides[${loc.index}]`;
|
|
||||||
|
|
||||||
case "option":
|
|
||||||
return `${msg(loc.parent)}.${loc.name}`;
|
|
||||||
|
|
||||||
case "access":
|
|
||||||
return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`;
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error(`Assertion failure: Unknown type ${loc.type}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function access(loc, name) {
|
|
||||||
return {
|
|
||||||
type: "access",
|
|
||||||
name,
|
|
||||||
parent: loc
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertRootMode(loc, value) {
|
|
||||||
if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") {
|
|
||||||
throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertSourceMaps(loc, value) {
|
|
||||||
if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") {
|
|
||||||
throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertCompact(loc, value) {
|
|
||||||
if (value !== undefined && typeof value !== "boolean" && value !== "auto") {
|
|
||||||
throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertSourceType(loc, value) {
|
|
||||||
if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") {
|
|
||||||
throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertCallerMetadata(loc, value) {
|
|
||||||
const obj = assertObject(loc, value);
|
|
||||||
|
|
||||||
if (obj) {
|
|
||||||
if (typeof obj["name"] !== "string") {
|
|
||||||
throw new Error(`${msg(loc)} set but does not contain "name" property string`);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const prop of Object.keys(obj)) {
|
|
||||||
const propLoc = access(loc, prop);
|
|
||||||
const value = obj[prop];
|
|
||||||
|
|
||||||
if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") {
|
|
||||||
throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertInputSourceMap(loc, value) {
|
|
||||||
if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) {
|
|
||||||
throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertString(loc, value) {
|
|
||||||
if (value !== undefined && typeof value !== "string") {
|
|
||||||
throw new Error(`${msg(loc)} must be a string, or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertFunction(loc, value) {
|
|
||||||
if (value !== undefined && typeof value !== "function") {
|
|
||||||
throw new Error(`${msg(loc)} must be a function, or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertBoolean(loc, value) {
|
|
||||||
if (value !== undefined && typeof value !== "boolean") {
|
|
||||||
throw new Error(`${msg(loc)} must be a boolean, or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertObject(loc, value) {
|
|
||||||
if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) {
|
|
||||||
throw new Error(`${msg(loc)} must be an object, or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertArray(loc, value) {
|
|
||||||
if (value != null && !Array.isArray(value)) {
|
|
||||||
throw new Error(`${msg(loc)} must be an array, or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertIgnoreList(loc, value) {
|
|
||||||
const arr = assertArray(loc, value);
|
|
||||||
|
|
||||||
if (arr) {
|
|
||||||
arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item));
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertIgnoreItem(loc, value) {
|
|
||||||
if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) {
|
|
||||||
throw new Error(`${msg(loc)} must be an array of string/Funtion/RegExp values, or undefined`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertConfigApplicableTest(loc, value) {
|
|
||||||
if (value === undefined) return value;
|
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
value.forEach((item, i) => {
|
|
||||||
if (!checkValidTest(item)) {
|
|
||||||
throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else if (!checkValidTest(value)) {
|
|
||||||
throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function checkValidTest(value) {
|
|
||||||
return typeof value === "string" || typeof value === "function" || value instanceof RegExp;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertConfigFileSearch(loc, value) {
|
|
||||||
if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") {
|
|
||||||
throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertBabelrcSearch(loc, value) {
|
|
||||||
if (value === undefined || typeof value === "boolean") return value;
|
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
value.forEach((item, i) => {
|
|
||||||
if (!checkValidTest(item)) {
|
|
||||||
throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else if (!checkValidTest(value)) {
|
|
||||||
throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertPluginList(loc, value) {
|
|
||||||
const arr = assertArray(loc, value);
|
|
||||||
|
|
||||||
if (arr) {
|
|
||||||
arr.forEach((item, i) => assertPluginItem(access(loc, i), item));
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertPluginItem(loc, value) {
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
if (value.length === 0) {
|
|
||||||
throw new Error(`${msg(loc)} must include an object`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (value.length > 3) {
|
|
||||||
throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);
|
|
||||||
}
|
|
||||||
|
|
||||||
assertPluginTarget(access(loc, 0), value[0]);
|
|
||||||
|
|
||||||
if (value.length > 1) {
|
|
||||||
const opts = value[1];
|
|
||||||
|
|
||||||
if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) {
|
|
||||||
throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (value.length === 3) {
|
|
||||||
const name = value[2];
|
|
||||||
|
|
||||||
if (name !== undefined && typeof name !== "string") {
|
|
||||||
throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
assertPluginTarget(loc, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertPluginTarget(loc, value) {
|
|
||||||
if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") {
|
|
||||||
throw new Error(`${msg(loc)} must be a string, object, function`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
@ -1,188 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.validate = validate;
|
|
||||||
|
|
||||||
var _plugin = _interopRequireDefault(require("../plugin"));
|
|
||||||
|
|
||||||
var _removed = _interopRequireDefault(require("./removed"));
|
|
||||||
|
|
||||||
var _optionAssertions = require("./option-assertions");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const ROOT_VALIDATORS = {
|
|
||||||
cwd: _optionAssertions.assertString,
|
|
||||||
root: _optionAssertions.assertString,
|
|
||||||
rootMode: _optionAssertions.assertRootMode,
|
|
||||||
configFile: _optionAssertions.assertConfigFileSearch,
|
|
||||||
caller: _optionAssertions.assertCallerMetadata,
|
|
||||||
filename: _optionAssertions.assertString,
|
|
||||||
filenameRelative: _optionAssertions.assertString,
|
|
||||||
code: _optionAssertions.assertBoolean,
|
|
||||||
ast: _optionAssertions.assertBoolean,
|
|
||||||
envName: _optionAssertions.assertString
|
|
||||||
};
|
|
||||||
const BABELRC_VALIDATORS = {
|
|
||||||
babelrc: _optionAssertions.assertBoolean,
|
|
||||||
babelrcRoots: _optionAssertions.assertBabelrcSearch
|
|
||||||
};
|
|
||||||
const NONPRESET_VALIDATORS = {
|
|
||||||
extends: _optionAssertions.assertString,
|
|
||||||
ignore: _optionAssertions.assertIgnoreList,
|
|
||||||
only: _optionAssertions.assertIgnoreList
|
|
||||||
};
|
|
||||||
const COMMON_VALIDATORS = {
|
|
||||||
inputSourceMap: _optionAssertions.assertInputSourceMap,
|
|
||||||
presets: _optionAssertions.assertPluginList,
|
|
||||||
plugins: _optionAssertions.assertPluginList,
|
|
||||||
passPerPreset: _optionAssertions.assertBoolean,
|
|
||||||
env: assertEnvSet,
|
|
||||||
overrides: assertOverridesList,
|
|
||||||
test: _optionAssertions.assertConfigApplicableTest,
|
|
||||||
include: _optionAssertions.assertConfigApplicableTest,
|
|
||||||
exclude: _optionAssertions.assertConfigApplicableTest,
|
|
||||||
retainLines: _optionAssertions.assertBoolean,
|
|
||||||
comments: _optionAssertions.assertBoolean,
|
|
||||||
shouldPrintComment: _optionAssertions.assertFunction,
|
|
||||||
compact: _optionAssertions.assertCompact,
|
|
||||||
minified: _optionAssertions.assertBoolean,
|
|
||||||
auxiliaryCommentBefore: _optionAssertions.assertString,
|
|
||||||
auxiliaryCommentAfter: _optionAssertions.assertString,
|
|
||||||
sourceType: _optionAssertions.assertSourceType,
|
|
||||||
wrapPluginVisitorMethod: _optionAssertions.assertFunction,
|
|
||||||
highlightCode: _optionAssertions.assertBoolean,
|
|
||||||
sourceMaps: _optionAssertions.assertSourceMaps,
|
|
||||||
sourceMap: _optionAssertions.assertSourceMaps,
|
|
||||||
sourceFileName: _optionAssertions.assertString,
|
|
||||||
sourceRoot: _optionAssertions.assertString,
|
|
||||||
getModuleId: _optionAssertions.assertFunction,
|
|
||||||
moduleRoot: _optionAssertions.assertString,
|
|
||||||
moduleIds: _optionAssertions.assertBoolean,
|
|
||||||
moduleId: _optionAssertions.assertString,
|
|
||||||
parserOpts: _optionAssertions.assertObject,
|
|
||||||
generatorOpts: _optionAssertions.assertObject
|
|
||||||
};
|
|
||||||
|
|
||||||
function getSource(loc) {
|
|
||||||
return loc.type === "root" ? loc.source : getSource(loc.parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function validate(type, opts) {
|
|
||||||
return validateNested({
|
|
||||||
type: "root",
|
|
||||||
source: type
|
|
||||||
}, opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
function validateNested(loc, opts) {
|
|
||||||
const type = getSource(loc);
|
|
||||||
assertNoDuplicateSourcemap(opts);
|
|
||||||
Object.keys(opts).forEach(key => {
|
|
||||||
const optLoc = {
|
|
||||||
type: "option",
|
|
||||||
name: key,
|
|
||||||
parent: loc
|
|
||||||
};
|
|
||||||
|
|
||||||
if (type === "preset" && NONPRESET_VALIDATORS[key]) {
|
|
||||||
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in preset options`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (type !== "arguments" && ROOT_VALIDATORS[key]) {
|
|
||||||
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) {
|
|
||||||
if (type === "babelrcfile" || type === "extendsfile") {
|
|
||||||
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError;
|
|
||||||
validator(optLoc, opts[key]);
|
|
||||||
});
|
|
||||||
return opts;
|
|
||||||
}
|
|
||||||
|
|
||||||
function throwUnknownError(loc) {
|
|
||||||
const key = loc.name;
|
|
||||||
|
|
||||||
if (_removed.default[key]) {
|
|
||||||
const {
|
|
||||||
message,
|
|
||||||
version = 5
|
|
||||||
} = _removed.default[key];
|
|
||||||
throw new ReferenceError(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`);
|
|
||||||
} else {
|
|
||||||
const unknownOptErr = `Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`;
|
|
||||||
throw new ReferenceError(unknownOptErr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function has(obj, key) {
|
|
||||||
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertNoDuplicateSourcemap(opts) {
|
|
||||||
if (has(opts, "sourceMap") && has(opts, "sourceMaps")) {
|
|
||||||
throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertEnvSet(loc, value) {
|
|
||||||
if (loc.parent.type === "env") {
|
|
||||||
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside of another .env block`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const parent = loc.parent;
|
|
||||||
const obj = (0, _optionAssertions.assertObject)(loc, value);
|
|
||||||
|
|
||||||
if (obj) {
|
|
||||||
for (const envName of Object.keys(obj)) {
|
|
||||||
const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]);
|
|
||||||
if (!env) continue;
|
|
||||||
const envLoc = {
|
|
||||||
type: "env",
|
|
||||||
name: envName,
|
|
||||||
parent
|
|
||||||
};
|
|
||||||
validateNested(envLoc, env);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertOverridesList(loc, value) {
|
|
||||||
if (loc.parent.type === "env") {
|
|
||||||
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loc.parent.type === "overrides") {
|
|
||||||
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const parent = loc.parent;
|
|
||||||
const arr = (0, _optionAssertions.assertArray)(loc, value);
|
|
||||||
|
|
||||||
if (arr) {
|
|
||||||
for (const [index, item] of arr.entries()) {
|
|
||||||
const objLoc = (0, _optionAssertions.access)(loc, index);
|
|
||||||
const env = (0, _optionAssertions.assertObject)(objLoc, item);
|
|
||||||
if (!env) throw new Error(`${(0, _optionAssertions.msg)(objLoc)} must be an object`);
|
|
||||||
const overridesLoc = {
|
|
||||||
type: "overrides",
|
|
||||||
index,
|
|
||||||
parent
|
|
||||||
};
|
|
||||||
validateNested(overridesLoc, env);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr;
|
|
||||||
}
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.validatePluginObject = validatePluginObject;
|
|
||||||
|
|
||||||
var _optionAssertions = require("./option-assertions");
|
|
||||||
|
|
||||||
const VALIDATORS = {
|
|
||||||
name: _optionAssertions.assertString,
|
|
||||||
manipulateOptions: _optionAssertions.assertFunction,
|
|
||||||
pre: _optionAssertions.assertFunction,
|
|
||||||
post: _optionAssertions.assertFunction,
|
|
||||||
inherits: _optionAssertions.assertFunction,
|
|
||||||
visitor: assertVisitorMap,
|
|
||||||
parserOverride: _optionAssertions.assertFunction,
|
|
||||||
generatorOverride: _optionAssertions.assertFunction
|
|
||||||
};
|
|
||||||
|
|
||||||
function assertVisitorMap(key, value) {
|
|
||||||
const obj = (0, _optionAssertions.assertObject)(key, value);
|
|
||||||
|
|
||||||
if (obj) {
|
|
||||||
Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));
|
|
||||||
|
|
||||||
if (obj.enter || obj.exit) {
|
|
||||||
throw new Error(`.${key} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertVisitorHandler(key, value) {
|
|
||||||
if (value && typeof value === "object") {
|
|
||||||
Object.keys(value).forEach(handler => {
|
|
||||||
if (handler !== "enter" && handler !== "exit") {
|
|
||||||
throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else if (typeof value !== "function") {
|
|
||||||
throw new Error(`.visitor["${key}"] must be a function`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function validatePluginObject(obj) {
|
|
||||||
Object.keys(obj).forEach(key => {
|
|
||||||
const validator = VALIDATORS[key];
|
|
||||||
if (validator) validator(key, obj[key]);else throw new Error(`.${key} is not a valid Plugin property`);
|
|
||||||
});
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = void 0;
|
|
||||||
var _default = {
|
|
||||||
auxiliaryComment: {
|
|
||||||
message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"
|
|
||||||
},
|
|
||||||
blacklist: {
|
|
||||||
message: "Put the specific transforms you want in the `plugins` option"
|
|
||||||
},
|
|
||||||
breakConfig: {
|
|
||||||
message: "This is not a necessary option in Babel 6"
|
|
||||||
},
|
|
||||||
experimental: {
|
|
||||||
message: "Put the specific transforms you want in the `plugins` option"
|
|
||||||
},
|
|
||||||
externalHelpers: {
|
|
||||||
message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/"
|
|
||||||
},
|
|
||||||
extra: {
|
|
||||||
message: ""
|
|
||||||
},
|
|
||||||
jsxPragma: {
|
|
||||||
message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/"
|
|
||||||
},
|
|
||||||
loose: {
|
|
||||||
message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option."
|
|
||||||
},
|
|
||||||
metadataUsedHelpers: {
|
|
||||||
message: "Not required anymore as this is enabled by default"
|
|
||||||
},
|
|
||||||
modules: {
|
|
||||||
message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules"
|
|
||||||
},
|
|
||||||
nonStandard: {
|
|
||||||
message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"
|
|
||||||
},
|
|
||||||
optional: {
|
|
||||||
message: "Put the specific transforms you want in the `plugins` option"
|
|
||||||
},
|
|
||||||
sourceMapName: {
|
|
||||||
message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves."
|
|
||||||
},
|
|
||||||
stage: {
|
|
||||||
message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"
|
|
||||||
},
|
|
||||||
whitelist: {
|
|
||||||
message: "Put the specific transforms you want in the `plugins` option"
|
|
||||||
},
|
|
||||||
resolveModuleSource: {
|
|
||||||
version: 6,
|
|
||||||
message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options"
|
|
||||||
},
|
|
||||||
metadata: {
|
|
||||||
version: 6,
|
|
||||||
message: "Generated plugin metadata is always included in the output result"
|
|
||||||
},
|
|
||||||
sourceMapTarget: {
|
|
||||||
version: 6,
|
|
||||||
message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves."
|
|
||||||
}
|
|
||||||
};
|
|
||||||
exports.default = _default;
|
|
||||||
|
|
@ -1,240 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.Plugin = Plugin;
|
|
||||||
Object.defineProperty(exports, "File", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _file.default;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "buildExternalHelpers", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _buildExternalHelpers.default;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "resolvePlugin", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _files.resolvePlugin;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "resolvePreset", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _files.resolvePreset;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "version", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _package.version;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "getEnv", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _environment.getEnv;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "tokTypes", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _parser().tokTypes;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "traverse", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _traverse().default;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "template", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _template().default;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "createConfigItem", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _item.createConfigItem;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "loadPartialConfig", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _config.loadPartialConfig;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "loadOptions", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _config.loadOptions;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transform", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transform.transform;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformSync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transform.transformSync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformAsync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transform.transformAsync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformFile", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transformFile.transformFile;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformFileSync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transformFile.transformFileSync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformFileAsync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transformFile.transformFileAsync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformFromAst", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transformAst.transformFromAst;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformFromAstSync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transformAst.transformFromAstSync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "transformFromAstAsync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _transformAst.transformFromAstAsync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "parse", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _parse.parse;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "parseSync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _parse.parseSync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "parseAsync", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _parse.parseAsync;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = void 0;
|
|
||||||
|
|
||||||
var _file = _interopRequireDefault(require("./transformation/file/file"));
|
|
||||||
|
|
||||||
var _buildExternalHelpers = _interopRequireDefault(require("./tools/build-external-helpers"));
|
|
||||||
|
|
||||||
var _files = require("./config/files");
|
|
||||||
|
|
||||||
var _package = require("../package.json");
|
|
||||||
|
|
||||||
var _environment = require("./config/helpers/environment");
|
|
||||||
|
|
||||||
function _types() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
_types = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "types", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _types();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function _parser() {
|
|
||||||
const data = require("@babel/parser");
|
|
||||||
|
|
||||||
_parser = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _traverse() {
|
|
||||||
const data = _interopRequireDefault(require("@babel/traverse"));
|
|
||||||
|
|
||||||
_traverse = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _template() {
|
|
||||||
const data = _interopRequireDefault(require("@babel/template"));
|
|
||||||
|
|
||||||
_template = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _item = require("./config/item");
|
|
||||||
|
|
||||||
var _config = require("./config");
|
|
||||||
|
|
||||||
var _transform = require("./transform");
|
|
||||||
|
|
||||||
var _transformFile = require("./transform-file");
|
|
||||||
|
|
||||||
var _transformAst = require("./transform-ast");
|
|
||||||
|
|
||||||
var _parse = require("./parse");
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]);
|
|
||||||
exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
|
|
||||||
|
|
||||||
class OptionManager {
|
|
||||||
init(opts) {
|
|
||||||
return (0, _config.loadOptions)(opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.OptionManager = OptionManager;
|
|
||||||
|
|
||||||
function Plugin(alias) {
|
|
||||||
throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`);
|
|
||||||
}
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.parseSync = parseSync;
|
|
||||||
exports.parseAsync = parseAsync;
|
|
||||||
exports.parse = void 0;
|
|
||||||
|
|
||||||
var _config = _interopRequireDefault(require("./config"));
|
|
||||||
|
|
||||||
var _normalizeFile = _interopRequireDefault(require("./transformation/normalize-file"));
|
|
||||||
|
|
||||||
var _normalizeOpts = _interopRequireDefault(require("./transformation/normalize-opts"));
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const parse = function parse(code, opts, callback) {
|
|
||||||
if (typeof opts === "function") {
|
|
||||||
callback = opts;
|
|
||||||
opts = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (callback === undefined) return parseSync(code, opts);
|
|
||||||
const config = (0, _config.default)(opts);
|
|
||||||
|
|
||||||
if (config === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cb = callback;
|
|
||||||
process.nextTick(() => {
|
|
||||||
let ast = null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const cfg = (0, _config.default)(opts);
|
|
||||||
if (cfg === null) return cb(null, null);
|
|
||||||
ast = (0, _normalizeFile.default)(cfg.passes, (0, _normalizeOpts.default)(cfg), code).ast;
|
|
||||||
} catch (err) {
|
|
||||||
return cb(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
cb(null, ast);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.parse = parse;
|
|
||||||
|
|
||||||
function parseSync(code, opts) {
|
|
||||||
const config = (0, _config.default)(opts);
|
|
||||||
|
|
||||||
if (config === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code).ast;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseAsync(code, opts) {
|
|
||||||
return new Promise((res, rej) => {
|
|
||||||
parse(code, opts, (err, result) => {
|
|
||||||
if (err == null) res(result);else rej(err);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,143 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = _default;
|
|
||||||
|
|
||||||
function helpers() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/helpers"));
|
|
||||||
|
|
||||||
helpers = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _generator() {
|
|
||||||
const data = _interopRequireDefault(require("@babel/generator"));
|
|
||||||
|
|
||||||
_generator = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _template() {
|
|
||||||
const data = _interopRequireDefault(require("@babel/template"));
|
|
||||||
|
|
||||||
_template = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
const buildUmdWrapper = replacements => _template().default`
|
|
||||||
(function (root, factory) {
|
|
||||||
if (typeof define === "function" && define.amd) {
|
|
||||||
define(AMD_ARGUMENTS, factory);
|
|
||||||
} else if (typeof exports === "object") {
|
|
||||||
factory(COMMON_ARGUMENTS);
|
|
||||||
} else {
|
|
||||||
factory(BROWSER_ARGUMENTS);
|
|
||||||
}
|
|
||||||
})(UMD_ROOT, function (FACTORY_PARAMETERS) {
|
|
||||||
FACTORY_BODY
|
|
||||||
});
|
|
||||||
`(replacements);
|
|
||||||
|
|
||||||
function buildGlobal(whitelist) {
|
|
||||||
const namespace = t().identifier("babelHelpers");
|
|
||||||
const body = [];
|
|
||||||
const container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body));
|
|
||||||
const tree = t().program([t().expressionStatement(t().callExpression(container, [t().conditionalExpression(t().binaryExpression("===", t().unaryExpression("typeof", t().identifier("global")), t().stringLiteral("undefined")), t().identifier("self"), t().identifier("global"))]))]);
|
|
||||||
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))]));
|
|
||||||
buildHelpers(body, namespace, whitelist);
|
|
||||||
return tree;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildModule(whitelist) {
|
|
||||||
const body = [];
|
|
||||||
const refs = buildHelpers(body, null, whitelist);
|
|
||||||
body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(name => {
|
|
||||||
return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name));
|
|
||||||
})));
|
|
||||||
return t().program(body, [], "module");
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildUmd(whitelist) {
|
|
||||||
const namespace = t().identifier("babelHelpers");
|
|
||||||
const body = [];
|
|
||||||
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))]));
|
|
||||||
buildHelpers(body, namespace, whitelist);
|
|
||||||
return t().program([buildUmdWrapper({
|
|
||||||
FACTORY_PARAMETERS: t().identifier("global"),
|
|
||||||
BROWSER_ARGUMENTS: t().assignmentExpression("=", t().memberExpression(t().identifier("root"), namespace), t().objectExpression([])),
|
|
||||||
COMMON_ARGUMENTS: t().identifier("exports"),
|
|
||||||
AMD_ARGUMENTS: t().arrayExpression([t().stringLiteral("exports")]),
|
|
||||||
FACTORY_BODY: body,
|
|
||||||
UMD_ROOT: t().identifier("this")
|
|
||||||
})]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildVar(whitelist) {
|
|
||||||
const namespace = t().identifier("babelHelpers");
|
|
||||||
const body = [];
|
|
||||||
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))]));
|
|
||||||
const tree = t().program(body);
|
|
||||||
buildHelpers(body, namespace, whitelist);
|
|
||||||
body.push(t().expressionStatement(namespace));
|
|
||||||
return tree;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildHelpers(body, namespace, whitelist) {
|
|
||||||
const getHelperReference = name => {
|
|
||||||
return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const refs = {};
|
|
||||||
helpers().list.forEach(function (name) {
|
|
||||||
if (whitelist && whitelist.indexOf(name) < 0) return;
|
|
||||||
const ref = refs[name] = getHelperReference(name);
|
|
||||||
const {
|
|
||||||
nodes
|
|
||||||
} = helpers().get(name, getHelperReference, ref);
|
|
||||||
body.push(...nodes);
|
|
||||||
});
|
|
||||||
return refs;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _default(whitelist, outputType = "global") {
|
|
||||||
let tree;
|
|
||||||
const build = {
|
|
||||||
global: buildGlobal,
|
|
||||||
module: buildModule,
|
|
||||||
umd: buildUmd,
|
|
||||||
var: buildVar
|
|
||||||
}[outputType];
|
|
||||||
|
|
||||||
if (build) {
|
|
||||||
tree = build(whitelist);
|
|
||||||
} else {
|
|
||||||
throw new Error(`Unsupported output type ${outputType}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (0, _generator().default)(tree).code;
|
|
||||||
}
|
|
||||||
|
|
@ -1,54 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.transformFromAstSync = transformFromAstSync;
|
|
||||||
exports.transformFromAstAsync = transformFromAstAsync;
|
|
||||||
exports.transformFromAst = void 0;
|
|
||||||
|
|
||||||
var _config = _interopRequireDefault(require("./config"));
|
|
||||||
|
|
||||||
var _transformation = require("./transformation");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const transformFromAst = function transformFromAst(ast, code, opts, callback) {
|
|
||||||
if (typeof opts === "function") {
|
|
||||||
callback = opts;
|
|
||||||
opts = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (callback === undefined) return transformFromAstSync(ast, code, opts);
|
|
||||||
const cb = callback;
|
|
||||||
process.nextTick(() => {
|
|
||||||
let cfg;
|
|
||||||
|
|
||||||
try {
|
|
||||||
cfg = (0, _config.default)(opts);
|
|
||||||
if (cfg === null) return cb(null, null);
|
|
||||||
} catch (err) {
|
|
||||||
return cb(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!ast) return cb(new Error("No AST given"));
|
|
||||||
(0, _transformation.runAsync)(cfg, code, ast, cb);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.transformFromAst = transformFromAst;
|
|
||||||
|
|
||||||
function transformFromAstSync(ast, code, opts) {
|
|
||||||
const config = (0, _config.default)(opts);
|
|
||||||
if (config === null) return null;
|
|
||||||
if (!ast) throw new Error("No AST given");
|
|
||||||
return (0, _transformation.runSync)(config, code, ast);
|
|
||||||
}
|
|
||||||
|
|
||||||
function transformFromAstAsync(ast, code, opts) {
|
|
||||||
return new Promise((res, rej) => {
|
|
||||||
transformFromAst(ast, code, opts, (err, result) => {
|
|
||||||
if (err == null) res(result);else rej(err);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.transformFileSync = transformFileSync;
|
|
||||||
exports.transformFileAsync = transformFileAsync;
|
|
||||||
exports.transformFile = void 0;
|
|
||||||
|
|
||||||
const transformFile = function transformFile(filename, opts, callback) {
|
|
||||||
if (typeof opts === "function") {
|
|
||||||
callback = opts;
|
|
||||||
}
|
|
||||||
|
|
||||||
callback(new Error("Transforming files is not supported in browsers"), null);
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.transformFile = transformFile;
|
|
||||||
|
|
||||||
function transformFileSync() {
|
|
||||||
throw new Error("Transforming files is not supported in browsers");
|
|
||||||
}
|
|
||||||
|
|
||||||
function transformFileAsync() {
|
|
||||||
return Promise.reject(new Error("Transforming files is not supported in browsers"));
|
|
||||||
}
|
|
||||||
|
|
@ -1,91 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.transformFileSync = transformFileSync;
|
|
||||||
exports.transformFileAsync = transformFileAsync;
|
|
||||||
exports.transformFile = void 0;
|
|
||||||
|
|
||||||
function _fs() {
|
|
||||||
const data = _interopRequireDefault(require("fs"));
|
|
||||||
|
|
||||||
_fs = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _config = _interopRequireDefault(require("./config"));
|
|
||||||
|
|
||||||
var _transformation = require("./transformation");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
({});
|
|
||||||
|
|
||||||
const transformFile = function transformFile(filename, opts, callback) {
|
|
||||||
let options;
|
|
||||||
|
|
||||||
if (typeof opts === "function") {
|
|
||||||
callback = opts;
|
|
||||||
opts = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts == null) {
|
|
||||||
options = {
|
|
||||||
filename
|
|
||||||
};
|
|
||||||
} else if (opts && typeof opts === "object") {
|
|
||||||
options = Object.assign({}, opts, {
|
|
||||||
filename
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
process.nextTick(() => {
|
|
||||||
let cfg;
|
|
||||||
|
|
||||||
try {
|
|
||||||
cfg = (0, _config.default)(options);
|
|
||||||
if (cfg === null) return callback(null, null);
|
|
||||||
} catch (err) {
|
|
||||||
return callback(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = cfg;
|
|
||||||
|
|
||||||
_fs().default.readFile(filename, "utf8", function (err, code) {
|
|
||||||
if (err) return callback(err, null);
|
|
||||||
(0, _transformation.runAsync)(config, code, null, callback);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.transformFile = transformFile;
|
|
||||||
|
|
||||||
function transformFileSync(filename, opts) {
|
|
||||||
let options;
|
|
||||||
|
|
||||||
if (opts == null) {
|
|
||||||
options = {
|
|
||||||
filename
|
|
||||||
};
|
|
||||||
} else if (opts && typeof opts === "object") {
|
|
||||||
options = Object.assign({}, opts, {
|
|
||||||
filename
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = (0, _config.default)(options);
|
|
||||||
if (config === null) return null;
|
|
||||||
return (0, _transformation.runSync)(config, _fs().default.readFileSync(filename, "utf8"));
|
|
||||||
}
|
|
||||||
|
|
||||||
function transformFileAsync(filename, opts) {
|
|
||||||
return new Promise((res, rej) => {
|
|
||||||
transformFile(filename, opts, (err, result) => {
|
|
||||||
if (err == null) res(result);else rej(err);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,52 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.transformSync = transformSync;
|
|
||||||
exports.transformAsync = transformAsync;
|
|
||||||
exports.transform = void 0;
|
|
||||||
|
|
||||||
var _config = _interopRequireDefault(require("./config"));
|
|
||||||
|
|
||||||
var _transformation = require("./transformation");
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const transform = function transform(code, opts, callback) {
|
|
||||||
if (typeof opts === "function") {
|
|
||||||
callback = opts;
|
|
||||||
opts = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (callback === undefined) return transformSync(code, opts);
|
|
||||||
const cb = callback;
|
|
||||||
process.nextTick(() => {
|
|
||||||
let cfg;
|
|
||||||
|
|
||||||
try {
|
|
||||||
cfg = (0, _config.default)(opts);
|
|
||||||
if (cfg === null) return cb(null, null);
|
|
||||||
} catch (err) {
|
|
||||||
return cb(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
(0, _transformation.runAsync)(cfg, code, null, cb);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.transform = transform;
|
|
||||||
|
|
||||||
function transformSync(code, opts) {
|
|
||||||
const config = (0, _config.default)(opts);
|
|
||||||
if (config === null) return null;
|
|
||||||
return (0, _transformation.runSync)(config, code);
|
|
||||||
}
|
|
||||||
|
|
||||||
function transformAsync(code, opts) {
|
|
||||||
return new Promise((res, rej) => {
|
|
||||||
transform(code, opts, (err, result) => {
|
|
||||||
if (err == null) res(result);else rej(err);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = loadBlockHoistPlugin;
|
|
||||||
|
|
||||||
function _sortBy() {
|
|
||||||
const data = _interopRequireDefault(require("lodash/sortBy"));
|
|
||||||
|
|
||||||
_sortBy = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _config = _interopRequireDefault(require("../config"));
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
let LOADED_PLUGIN;
|
|
||||||
|
|
||||||
function loadBlockHoistPlugin() {
|
|
||||||
if (!LOADED_PLUGIN) {
|
|
||||||
const config = (0, _config.default)({
|
|
||||||
babelrc: false,
|
|
||||||
configFile: false,
|
|
||||||
plugins: [blockHoistPlugin]
|
|
||||||
});
|
|
||||||
LOADED_PLUGIN = config ? config.passes[0][0] : undefined;
|
|
||||||
if (!LOADED_PLUGIN) throw new Error("Assertion failure");
|
|
||||||
}
|
|
||||||
|
|
||||||
return LOADED_PLUGIN;
|
|
||||||
}
|
|
||||||
|
|
||||||
const blockHoistPlugin = {
|
|
||||||
name: "internal.blockHoist",
|
|
||||||
visitor: {
|
|
||||||
Block: {
|
|
||||||
exit({
|
|
||||||
node
|
|
||||||
}) {
|
|
||||||
let hasChange = false;
|
|
||||||
|
|
||||||
for (let i = 0; i < node.body.length; i++) {
|
|
||||||
const bodyNode = node.body[i];
|
|
||||||
|
|
||||||
if (bodyNode && bodyNode._blockHoist != null) {
|
|
||||||
hasChange = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!hasChange) return;
|
|
||||||
node.body = (0, _sortBy().default)(node.body, function (bodyNode) {
|
|
||||||
let priority = bodyNode && bodyNode._blockHoist;
|
|
||||||
if (priority == null) priority = 1;
|
|
||||||
if (priority === true) priority = 2;
|
|
||||||
return -1 * priority;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
@ -1,266 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = void 0;
|
|
||||||
|
|
||||||
function helpers() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/helpers"));
|
|
||||||
|
|
||||||
helpers = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _traverse() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/traverse"));
|
|
||||||
|
|
||||||
_traverse = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _codeFrame() {
|
|
||||||
const data = require("@babel/code-frame");
|
|
||||||
|
|
||||||
_codeFrame = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _semver() {
|
|
||||||
const data = _interopRequireDefault(require("semver"));
|
|
||||||
|
|
||||||
_semver = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
const errorVisitor = {
|
|
||||||
enter(path, state) {
|
|
||||||
const loc = path.node.loc;
|
|
||||||
|
|
||||||
if (loc) {
|
|
||||||
state.loc = loc;
|
|
||||||
path.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
class File {
|
|
||||||
constructor(options, {
|
|
||||||
code,
|
|
||||||
ast,
|
|
||||||
inputMap
|
|
||||||
}) {
|
|
||||||
this._map = new Map();
|
|
||||||
this.declarations = {};
|
|
||||||
this.path = null;
|
|
||||||
this.ast = {};
|
|
||||||
this.metadata = {};
|
|
||||||
this.code = "";
|
|
||||||
this.inputMap = null;
|
|
||||||
this.hub = {
|
|
||||||
file: this,
|
|
||||||
getCode: () => this.code,
|
|
||||||
getScope: () => this.scope,
|
|
||||||
addHelper: this.addHelper.bind(this),
|
|
||||||
buildError: this.buildCodeFrameError.bind(this)
|
|
||||||
};
|
|
||||||
this.opts = options;
|
|
||||||
this.code = code;
|
|
||||||
this.ast = ast;
|
|
||||||
this.inputMap = inputMap;
|
|
||||||
this.path = _traverse().NodePath.get({
|
|
||||||
hub: this.hub,
|
|
||||||
parentPath: null,
|
|
||||||
parent: this.ast,
|
|
||||||
container: this.ast,
|
|
||||||
key: "program"
|
|
||||||
}).setContext();
|
|
||||||
this.scope = this.path.scope;
|
|
||||||
}
|
|
||||||
|
|
||||||
get shebang() {
|
|
||||||
const {
|
|
||||||
interpreter
|
|
||||||
} = this.path.node;
|
|
||||||
return interpreter ? interpreter.value : "";
|
|
||||||
}
|
|
||||||
|
|
||||||
set shebang(value) {
|
|
||||||
if (value) {
|
|
||||||
this.path.get("interpreter").replaceWith(t().interpreterDirective(value));
|
|
||||||
} else {
|
|
||||||
this.path.get("interpreter").remove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
set(key, val) {
|
|
||||||
if (key === "helpersNamespace") {
|
|
||||||
throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
this._map.set(key, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
get(key) {
|
|
||||||
return this._map.get(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
has(key) {
|
|
||||||
return this._map.has(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
getModuleName() {
|
|
||||||
const {
|
|
||||||
filename,
|
|
||||||
filenameRelative = filename,
|
|
||||||
moduleId,
|
|
||||||
moduleIds = !!moduleId,
|
|
||||||
getModuleId,
|
|
||||||
sourceRoot: sourceRootTmp,
|
|
||||||
moduleRoot = sourceRootTmp,
|
|
||||||
sourceRoot = moduleRoot
|
|
||||||
} = this.opts;
|
|
||||||
if (!moduleIds) return null;
|
|
||||||
|
|
||||||
if (moduleId != null && !getModuleId) {
|
|
||||||
return moduleId;
|
|
||||||
}
|
|
||||||
|
|
||||||
let moduleName = moduleRoot != null ? moduleRoot + "/" : "";
|
|
||||||
|
|
||||||
if (filenameRelative) {
|
|
||||||
const sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : "";
|
|
||||||
moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
moduleName = moduleName.replace(/\\/g, "/");
|
|
||||||
|
|
||||||
if (getModuleId) {
|
|
||||||
return getModuleId(moduleName) || moduleName;
|
|
||||||
} else {
|
|
||||||
return moduleName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
addImport() {
|
|
||||||
throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
availableHelper(name, versionRange) {
|
|
||||||
let minVersion;
|
|
||||||
|
|
||||||
try {
|
|
||||||
minVersion = helpers().minVersion(name);
|
|
||||||
} catch (err) {
|
|
||||||
if (err.code !== "BABEL_HELPER_UNKNOWN") throw err;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof versionRange !== "string") return true;
|
|
||||||
if (_semver().default.valid(versionRange)) versionRange = `^${versionRange}`;
|
|
||||||
return !_semver().default.intersects(`<${minVersion}`, versionRange) && !_semver().default.intersects(`>=8.0.0`, versionRange);
|
|
||||||
}
|
|
||||||
|
|
||||||
addHelper(name) {
|
|
||||||
const declar = this.declarations[name];
|
|
||||||
if (declar) return t().cloneNode(declar);
|
|
||||||
const generator = this.get("helperGenerator");
|
|
||||||
|
|
||||||
if (generator) {
|
|
||||||
const res = generator(name);
|
|
||||||
if (res) return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
|
|
||||||
const dependencies = {};
|
|
||||||
|
|
||||||
for (const dep of helpers().getDependencies(name)) {
|
|
||||||
dependencies[dep] = this.addHelper(dep);
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
nodes,
|
|
||||||
globals
|
|
||||||
} = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings()));
|
|
||||||
globals.forEach(name => {
|
|
||||||
if (this.path.scope.hasBinding(name, true)) {
|
|
||||||
this.path.scope.rename(name);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
nodes.forEach(node => {
|
|
||||||
node._compact = true;
|
|
||||||
});
|
|
||||||
this.path.unshiftContainer("body", nodes);
|
|
||||||
this.path.get("body").forEach(path => {
|
|
||||||
if (nodes.indexOf(path.node) === -1) return;
|
|
||||||
if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);
|
|
||||||
});
|
|
||||||
return uid;
|
|
||||||
}
|
|
||||||
|
|
||||||
addTemplateObject() {
|
|
||||||
throw new Error("This function has been moved into the template literal transform itself.");
|
|
||||||
}
|
|
||||||
|
|
||||||
buildCodeFrameError(node, msg, Error = SyntaxError) {
|
|
||||||
let loc = node && (node.loc || node._loc);
|
|
||||||
msg = `${this.opts.filename}: ${msg}`;
|
|
||||||
|
|
||||||
if (!loc && node) {
|
|
||||||
const state = {
|
|
||||||
loc: null
|
|
||||||
};
|
|
||||||
(0, _traverse().default)(node, errorVisitor, this.scope, state);
|
|
||||||
loc = state.loc;
|
|
||||||
let txt = "This is an error on an internal node. Probably an internal error.";
|
|
||||||
if (loc) txt += " Location has been estimated.";
|
|
||||||
msg += ` (${txt})`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loc) {
|
|
||||||
const {
|
|
||||||
highlightCode = true
|
|
||||||
} = this.opts;
|
|
||||||
msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, {
|
|
||||||
start: {
|
|
||||||
line: loc.start.line,
|
|
||||||
column: loc.start.column + 1
|
|
||||||
}
|
|
||||||
}, {
|
|
||||||
highlightCode
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Error(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.default = File;
|
|
||||||
|
|
@ -1,89 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = generateCode;
|
|
||||||
|
|
||||||
function _convertSourceMap() {
|
|
||||||
const data = _interopRequireDefault(require("convert-source-map"));
|
|
||||||
|
|
||||||
_convertSourceMap = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _generator() {
|
|
||||||
const data = _interopRequireDefault(require("@babel/generator"));
|
|
||||||
|
|
||||||
_generator = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _mergeMap = _interopRequireDefault(require("./merge-map"));
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function generateCode(pluginPasses, file) {
|
|
||||||
const {
|
|
||||||
opts,
|
|
||||||
ast,
|
|
||||||
code,
|
|
||||||
inputMap
|
|
||||||
} = file;
|
|
||||||
const results = [];
|
|
||||||
|
|
||||||
for (const plugins of pluginPasses) {
|
|
||||||
for (const plugin of plugins) {
|
|
||||||
const {
|
|
||||||
generatorOverride
|
|
||||||
} = plugin;
|
|
||||||
|
|
||||||
if (generatorOverride) {
|
|
||||||
const result = generatorOverride(ast, opts.generatorOpts, code, _generator().default);
|
|
||||||
if (result !== undefined) results.push(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let result;
|
|
||||||
|
|
||||||
if (results.length === 0) {
|
|
||||||
result = (0, _generator().default)(ast, opts.generatorOpts, code);
|
|
||||||
} else if (results.length === 1) {
|
|
||||||
result = results[0];
|
|
||||||
|
|
||||||
if (typeof result.then === "function") {
|
|
||||||
throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw new Error("More than one plugin attempted to override codegen.");
|
|
||||||
}
|
|
||||||
|
|
||||||
let {
|
|
||||||
code: outputCode,
|
|
||||||
map: outputMap
|
|
||||||
} = result;
|
|
||||||
|
|
||||||
if (outputMap && inputMap) {
|
|
||||||
outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
|
|
||||||
outputCode += "\n" + _convertSourceMap().default.fromObject(outputMap).toComment();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts.sourceMaps === "inline") {
|
|
||||||
outputMap = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
outputCode,
|
|
||||||
outputMap
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,255 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = mergeSourceMap;
|
|
||||||
|
|
||||||
function _sourceMap() {
|
|
||||||
const data = _interopRequireDefault(require("source-map"));
|
|
||||||
|
|
||||||
_sourceMap = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function mergeSourceMap(inputMap, map) {
|
|
||||||
const input = buildMappingData(inputMap);
|
|
||||||
const output = buildMappingData(map);
|
|
||||||
const mergedGenerator = new (_sourceMap().default.SourceMapGenerator)();
|
|
||||||
|
|
||||||
for (const _ref of input.sources) {
|
|
||||||
const {
|
|
||||||
source
|
|
||||||
} = _ref;
|
|
||||||
|
|
||||||
if (typeof source.content === "string") {
|
|
||||||
mergedGenerator.setSourceContent(source.path, source.content);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (output.sources.length === 1) {
|
|
||||||
const defaultSource = output.sources[0];
|
|
||||||
const insertedMappings = new Map();
|
|
||||||
eachInputGeneratedRange(input, (generated, original, source) => {
|
|
||||||
eachOverlappingGeneratedOutputRange(defaultSource, generated, item => {
|
|
||||||
const key = makeMappingKey(item);
|
|
||||||
if (insertedMappings.has(key)) return;
|
|
||||||
insertedMappings.set(key, item);
|
|
||||||
mergedGenerator.addMapping({
|
|
||||||
source: source.path,
|
|
||||||
original: {
|
|
||||||
line: original.line,
|
|
||||||
column: original.columnStart
|
|
||||||
},
|
|
||||||
generated: {
|
|
||||||
line: item.line,
|
|
||||||
column: item.columnStart
|
|
||||||
},
|
|
||||||
name: original.name
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const item of insertedMappings.values()) {
|
|
||||||
if (item.columnEnd === Infinity) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const clearItem = {
|
|
||||||
line: item.line,
|
|
||||||
columnStart: item.columnEnd
|
|
||||||
};
|
|
||||||
const key = makeMappingKey(clearItem);
|
|
||||||
|
|
||||||
if (insertedMappings.has(key)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
mergedGenerator.addMapping({
|
|
||||||
generated: {
|
|
||||||
line: clearItem.line,
|
|
||||||
column: clearItem.columnStart
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = mergedGenerator.toJSON();
|
|
||||||
|
|
||||||
if (typeof input.sourceRoot === "string") {
|
|
||||||
result.sourceRoot = input.sourceRoot;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeMappingKey(item) {
|
|
||||||
return `${item.line}/${item.columnStart}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function eachOverlappingGeneratedOutputRange(outputFile, inputGeneratedRange, callback) {
|
|
||||||
const overlappingOriginal = filterApplicableOriginalRanges(outputFile, inputGeneratedRange);
|
|
||||||
|
|
||||||
for (const _ref2 of overlappingOriginal) {
|
|
||||||
const {
|
|
||||||
generated
|
|
||||||
} = _ref2;
|
|
||||||
|
|
||||||
for (const item of generated) {
|
|
||||||
callback(item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function filterApplicableOriginalRanges({
|
|
||||||
mappings
|
|
||||||
}, {
|
|
||||||
line,
|
|
||||||
columnStart,
|
|
||||||
columnEnd
|
|
||||||
}) {
|
|
||||||
return filterSortedArray(mappings, ({
|
|
||||||
original: outOriginal
|
|
||||||
}) => {
|
|
||||||
if (line > outOriginal.line) return -1;
|
|
||||||
if (line < outOriginal.line) return 1;
|
|
||||||
if (columnStart >= outOriginal.columnEnd) return -1;
|
|
||||||
if (columnEnd <= outOriginal.columnStart) return 1;
|
|
||||||
return 0;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function eachInputGeneratedRange(map, callback) {
|
|
||||||
for (const _ref3 of map.sources) {
|
|
||||||
const {
|
|
||||||
source,
|
|
||||||
mappings
|
|
||||||
} = _ref3;
|
|
||||||
|
|
||||||
for (const _ref4 of mappings) {
|
|
||||||
const {
|
|
||||||
original,
|
|
||||||
generated
|
|
||||||
} = _ref4;
|
|
||||||
|
|
||||||
for (const item of generated) {
|
|
||||||
callback(item, original, source);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildMappingData(map) {
|
|
||||||
const consumer = new (_sourceMap().default.SourceMapConsumer)(Object.assign({}, map, {
|
|
||||||
sourceRoot: null
|
|
||||||
}));
|
|
||||||
const sources = new Map();
|
|
||||||
const mappings = new Map();
|
|
||||||
let last = null;
|
|
||||||
consumer.computeColumnSpans();
|
|
||||||
consumer.eachMapping(m => {
|
|
||||||
if (m.originalLine === null) return;
|
|
||||||
let source = sources.get(m.source);
|
|
||||||
|
|
||||||
if (!source) {
|
|
||||||
source = {
|
|
||||||
path: m.source,
|
|
||||||
content: consumer.sourceContentFor(m.source, true)
|
|
||||||
};
|
|
||||||
sources.set(m.source, source);
|
|
||||||
}
|
|
||||||
|
|
||||||
let sourceData = mappings.get(source);
|
|
||||||
|
|
||||||
if (!sourceData) {
|
|
||||||
sourceData = {
|
|
||||||
source,
|
|
||||||
mappings: []
|
|
||||||
};
|
|
||||||
mappings.set(source, sourceData);
|
|
||||||
}
|
|
||||||
|
|
||||||
const obj = {
|
|
||||||
line: m.originalLine,
|
|
||||||
columnStart: m.originalColumn,
|
|
||||||
columnEnd: Infinity,
|
|
||||||
name: m.name
|
|
||||||
};
|
|
||||||
|
|
||||||
if (last && last.source === source && last.mapping.line === m.originalLine) {
|
|
||||||
last.mapping.columnEnd = m.originalColumn;
|
|
||||||
}
|
|
||||||
|
|
||||||
last = {
|
|
||||||
source,
|
|
||||||
mapping: obj
|
|
||||||
};
|
|
||||||
sourceData.mappings.push({
|
|
||||||
original: obj,
|
|
||||||
generated: consumer.allGeneratedPositionsFor({
|
|
||||||
source: m.source,
|
|
||||||
line: m.originalLine,
|
|
||||||
column: m.originalColumn
|
|
||||||
}).map(item => ({
|
|
||||||
line: item.line,
|
|
||||||
columnStart: item.column,
|
|
||||||
columnEnd: item.lastColumn + 1
|
|
||||||
}))
|
|
||||||
});
|
|
||||||
}, null, _sourceMap().default.SourceMapConsumer.ORIGINAL_ORDER);
|
|
||||||
return {
|
|
||||||
file: map.file,
|
|
||||||
sourceRoot: map.sourceRoot,
|
|
||||||
sources: Array.from(mappings.values())
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function findInsertionLocation(array, callback) {
|
|
||||||
let left = 0;
|
|
||||||
let right = array.length;
|
|
||||||
|
|
||||||
while (left < right) {
|
|
||||||
const mid = Math.floor((left + right) / 2);
|
|
||||||
const item = array[mid];
|
|
||||||
const result = callback(item);
|
|
||||||
|
|
||||||
if (result === 0) {
|
|
||||||
left = mid;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result >= 0) {
|
|
||||||
right = mid;
|
|
||||||
} else {
|
|
||||||
left = mid + 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let i = left;
|
|
||||||
|
|
||||||
if (i < array.length) {
|
|
||||||
while (i >= 0 && callback(array[i]) >= 0) {
|
|
||||||
i--;
|
|
||||||
}
|
|
||||||
|
|
||||||
return i + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
function filterSortedArray(array, callback) {
|
|
||||||
const start = findInsertionLocation(array, callback);
|
|
||||||
const results = [];
|
|
||||||
|
|
||||||
for (let i = start; i < array.length && callback(array[i]) === 0; i++) {
|
|
||||||
results.push(array[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return results;
|
|
||||||
}
|
|
||||||
|
|
@ -1,106 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.runAsync = runAsync;
|
|
||||||
exports.runSync = runSync;
|
|
||||||
|
|
||||||
function _traverse() {
|
|
||||||
const data = _interopRequireDefault(require("@babel/traverse"));
|
|
||||||
|
|
||||||
_traverse = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _pluginPass = _interopRequireDefault(require("./plugin-pass"));
|
|
||||||
|
|
||||||
var _blockHoistPlugin = _interopRequireDefault(require("./block-hoist-plugin"));
|
|
||||||
|
|
||||||
var _normalizeOpts = _interopRequireDefault(require("./normalize-opts"));
|
|
||||||
|
|
||||||
var _normalizeFile = _interopRequireDefault(require("./normalize-file"));
|
|
||||||
|
|
||||||
var _generate = _interopRequireDefault(require("./file/generate"));
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function runAsync(config, code, ast, callback) {
|
|
||||||
let result;
|
|
||||||
|
|
||||||
try {
|
|
||||||
result = runSync(config, code, ast);
|
|
||||||
} catch (err) {
|
|
||||||
return callback(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
return callback(null, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
function runSync(config, code, ast) {
|
|
||||||
const file = (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast);
|
|
||||||
transformFile(file, config.passes);
|
|
||||||
const opts = file.opts;
|
|
||||||
const {
|
|
||||||
outputCode,
|
|
||||||
outputMap
|
|
||||||
} = opts.code !== false ? (0, _generate.default)(config.passes, file) : {};
|
|
||||||
return {
|
|
||||||
metadata: file.metadata,
|
|
||||||
options: opts,
|
|
||||||
ast: opts.ast === true ? file.ast : null,
|
|
||||||
code: outputCode === undefined ? null : outputCode,
|
|
||||||
map: outputMap === undefined ? null : outputMap,
|
|
||||||
sourceType: file.ast.program.sourceType
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function transformFile(file, pluginPasses) {
|
|
||||||
for (const pluginPairs of pluginPasses) {
|
|
||||||
const passPairs = [];
|
|
||||||
const passes = [];
|
|
||||||
const visitors = [];
|
|
||||||
|
|
||||||
for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) {
|
|
||||||
const pass = new _pluginPass.default(file, plugin.key, plugin.options);
|
|
||||||
passPairs.push([plugin, pass]);
|
|
||||||
passes.push(pass);
|
|
||||||
visitors.push(plugin.visitor);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const [plugin, pass] of passPairs) {
|
|
||||||
const fn = plugin.pre;
|
|
||||||
|
|
||||||
if (fn) {
|
|
||||||
const result = fn.call(pass, file);
|
|
||||||
|
|
||||||
if (isThenable(result)) {
|
|
||||||
throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod);
|
|
||||||
|
|
||||||
(0, _traverse().default)(file.ast, visitor, file.scope);
|
|
||||||
|
|
||||||
for (const [plugin, pass] of passPairs) {
|
|
||||||
const fn = plugin.post;
|
|
||||||
|
|
||||||
if (fn) {
|
|
||||||
const result = fn.call(pass, file);
|
|
||||||
|
|
||||||
if (isThenable(result)) {
|
|
||||||
throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isThenable(val) {
|
|
||||||
return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
|
|
||||||
}
|
|
||||||
|
|
@ -1,211 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = normalizeFile;
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _debug() {
|
|
||||||
const data = _interopRequireDefault(require("debug"));
|
|
||||||
|
|
||||||
_debug = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _cloneDeep() {
|
|
||||||
const data = _interopRequireDefault(require("lodash/cloneDeep"));
|
|
||||||
|
|
||||||
_cloneDeep = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _convertSourceMap() {
|
|
||||||
const data = _interopRequireDefault(require("convert-source-map"));
|
|
||||||
|
|
||||||
_convertSourceMap = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _parser() {
|
|
||||||
const data = require("@babel/parser");
|
|
||||||
|
|
||||||
_parser = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _codeFrame() {
|
|
||||||
const data = require("@babel/code-frame");
|
|
||||||
|
|
||||||
_codeFrame = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _file = _interopRequireDefault(require("./file/file"));
|
|
||||||
|
|
||||||
var _missingPluginHelper = _interopRequireDefault(require("./util/missing-plugin-helper"));
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const debug = (0, _debug().default)("babel:transform:file");
|
|
||||||
|
|
||||||
function normalizeFile(pluginPasses, options, code, ast) {
|
|
||||||
code = `${code || ""}`;
|
|
||||||
let inputMap = null;
|
|
||||||
|
|
||||||
if (options.inputSourceMap !== false) {
|
|
||||||
if (typeof options.inputSourceMap === "object") {
|
|
||||||
inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!inputMap) {
|
|
||||||
try {
|
|
||||||
inputMap = _convertSourceMap().default.fromSource(code);
|
|
||||||
|
|
||||||
if (inputMap) {
|
|
||||||
code = _convertSourceMap().default.removeComments(code);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
debug("discarding unknown inline input sourcemap", err);
|
|
||||||
code = _convertSourceMap().default.removeComments(code);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!inputMap) {
|
|
||||||
if (typeof options.filename === "string") {
|
|
||||||
try {
|
|
||||||
inputMap = _convertSourceMap().default.fromMapFileSource(code, _path().default.dirname(options.filename));
|
|
||||||
|
|
||||||
if (inputMap) {
|
|
||||||
code = _convertSourceMap().default.removeMapFileComments(code);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
debug("discarding unknown file input sourcemap", err);
|
|
||||||
code = _convertSourceMap().default.removeMapFileComments(code);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
debug("discarding un-loadable file input sourcemap");
|
|
||||||
code = _convertSourceMap().default.removeMapFileComments(code);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ast) {
|
|
||||||
if (ast.type === "Program") {
|
|
||||||
ast = t().file(ast, [], []);
|
|
||||||
} else if (ast.type !== "File") {
|
|
||||||
throw new Error("AST root must be a Program or File node");
|
|
||||||
}
|
|
||||||
|
|
||||||
ast = (0, _cloneDeep().default)(ast);
|
|
||||||
} else {
|
|
||||||
ast = parser(pluginPasses, options, code);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new _file.default(options, {
|
|
||||||
code,
|
|
||||||
ast,
|
|
||||||
inputMap
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function parser(pluginPasses, {
|
|
||||||
parserOpts,
|
|
||||||
highlightCode = true,
|
|
||||||
filename = "unknown"
|
|
||||||
}, code) {
|
|
||||||
try {
|
|
||||||
const results = [];
|
|
||||||
|
|
||||||
for (const plugins of pluginPasses) {
|
|
||||||
for (const plugin of plugins) {
|
|
||||||
const {
|
|
||||||
parserOverride
|
|
||||||
} = plugin;
|
|
||||||
|
|
||||||
if (parserOverride) {
|
|
||||||
const ast = parserOverride(code, parserOpts, _parser().parse);
|
|
||||||
if (ast !== undefined) results.push(ast);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (results.length === 0) {
|
|
||||||
return (0, _parser().parse)(code, parserOpts);
|
|
||||||
} else if (results.length === 1) {
|
|
||||||
if (typeof results[0].then === "function") {
|
|
||||||
throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return results[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error("More than one plugin attempted to override parsing.");
|
|
||||||
} catch (err) {
|
|
||||||
if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") {
|
|
||||||
err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file.";
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
loc,
|
|
||||||
missingPlugin
|
|
||||||
} = err;
|
|
||||||
|
|
||||||
if (loc) {
|
|
||||||
const codeFrame = (0, _codeFrame().codeFrameColumns)(code, {
|
|
||||||
start: {
|
|
||||||
line: loc.line,
|
|
||||||
column: loc.column + 1
|
|
||||||
}
|
|
||||||
}, {
|
|
||||||
highlightCode
|
|
||||||
});
|
|
||||||
|
|
||||||
if (missingPlugin) {
|
|
||||||
err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame);
|
|
||||||
} else {
|
|
||||||
err.message = `${filename}: ${err.message}\n\n` + codeFrame;
|
|
||||||
}
|
|
||||||
|
|
||||||
err.code = "BABEL_PARSE_ERROR";
|
|
||||||
}
|
|
||||||
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = normalizeOptions;
|
|
||||||
|
|
||||||
function _path() {
|
|
||||||
const data = _interopRequireDefault(require("path"));
|
|
||||||
|
|
||||||
_path = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function normalizeOptions(config) {
|
|
||||||
const {
|
|
||||||
filename,
|
|
||||||
cwd,
|
|
||||||
filenameRelative = typeof filename === "string" ? _path().default.relative(cwd, filename) : "unknown",
|
|
||||||
sourceType = "module",
|
|
||||||
inputSourceMap,
|
|
||||||
sourceMaps = !!inputSourceMap,
|
|
||||||
moduleRoot,
|
|
||||||
sourceRoot = moduleRoot,
|
|
||||||
sourceFileName = _path().default.basename(filenameRelative),
|
|
||||||
comments = true,
|
|
||||||
compact = "auto"
|
|
||||||
} = config.options;
|
|
||||||
const opts = config.options;
|
|
||||||
const options = Object.assign({}, opts, {
|
|
||||||
parserOpts: Object.assign({
|
|
||||||
sourceType: _path().default.extname(filenameRelative) === ".mjs" ? "module" : sourceType,
|
|
||||||
sourceFileName: filename,
|
|
||||||
plugins: []
|
|
||||||
}, opts.parserOpts),
|
|
||||||
generatorOpts: Object.assign({
|
|
||||||
filename,
|
|
||||||
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
|
|
||||||
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
|
|
||||||
retainLines: opts.retainLines,
|
|
||||||
comments,
|
|
||||||
shouldPrintComment: opts.shouldPrintComment,
|
|
||||||
compact,
|
|
||||||
minified: opts.minified,
|
|
||||||
sourceMaps,
|
|
||||||
sourceRoot,
|
|
||||||
sourceFileName
|
|
||||||
}, opts.generatorOpts)
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const plugins of config.passes) {
|
|
||||||
for (const plugin of plugins) {
|
|
||||||
if (plugin.manipulateOptions) {
|
|
||||||
plugin.manipulateOptions(options, options.parserOpts);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return options;
|
|
||||||
}
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = void 0;
|
|
||||||
|
|
||||||
class PluginPass {
|
|
||||||
constructor(file, key, options) {
|
|
||||||
this._map = new Map();
|
|
||||||
this.key = key;
|
|
||||||
this.file = file;
|
|
||||||
this.opts = options || {};
|
|
||||||
this.cwd = file.opts.cwd;
|
|
||||||
this.filename = file.opts.filename;
|
|
||||||
}
|
|
||||||
|
|
||||||
set(key, val) {
|
|
||||||
this._map.set(key, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
get(key) {
|
|
||||||
return this._map.get(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
availableHelper(name, versionRange) {
|
|
||||||
return this.file.availableHelper(name, versionRange);
|
|
||||||
}
|
|
||||||
|
|
||||||
addHelper(name) {
|
|
||||||
return this.file.addHelper(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
addImport() {
|
|
||||||
return this.file.addImport();
|
|
||||||
}
|
|
||||||
|
|
||||||
getModuleName() {
|
|
||||||
return this.file.getModuleName();
|
|
||||||
}
|
|
||||||
|
|
||||||
buildCodeFrameError(node, msg, Error) {
|
|
||||||
return this.file.buildCodeFrameError(node, msg, Error);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.default = PluginPass;
|
|
||||||
|
|
@ -1,239 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = generateMissingPluginMessage;
|
|
||||||
const pluginNameMap = {
|
|
||||||
classProperties: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-class-properties",
|
|
||||||
url: "https://git.io/vb4yQ"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-class-properties",
|
|
||||||
url: "https://git.io/vb4SL"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
decorators: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-decorators",
|
|
||||||
url: "https://git.io/vb4y9"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-decorators",
|
|
||||||
url: "https://git.io/vb4ST"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
doExpressions: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-do-expressions",
|
|
||||||
url: "https://git.io/vb4yh"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-do-expressions",
|
|
||||||
url: "https://git.io/vb4S3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
dynamicImport: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-dynamic-import",
|
|
||||||
url: "https://git.io/vb4Sv"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
exportDefaultFrom: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-export-default-from",
|
|
||||||
url: "https://git.io/vb4SO"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-export-default-from",
|
|
||||||
url: "https://git.io/vb4yH"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
exportNamespaceFrom: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-export-namespace-from",
|
|
||||||
url: "https://git.io/vb4Sf"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-export-namespace-from",
|
|
||||||
url: "https://git.io/vb4SG"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
flow: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-flow",
|
|
||||||
url: "https://git.io/vb4yb"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-transform-flow-strip-types",
|
|
||||||
url: "https://git.io/vb49g"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
functionBind: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-function-bind",
|
|
||||||
url: "https://git.io/vb4y7"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-function-bind",
|
|
||||||
url: "https://git.io/vb4St"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
functionSent: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-function-sent",
|
|
||||||
url: "https://git.io/vb4yN"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-function-sent",
|
|
||||||
url: "https://git.io/vb4SZ"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
importMeta: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-import-meta",
|
|
||||||
url: "https://git.io/vbKK6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
jsx: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-jsx",
|
|
||||||
url: "https://git.io/vb4yA"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-transform-react-jsx",
|
|
||||||
url: "https://git.io/vb4yd"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
logicalAssignment: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-logical-assignment-operators",
|
|
||||||
url: "https://git.io/vAlBp"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-logical-assignment-operators",
|
|
||||||
url: "https://git.io/vAlRe"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
nullishCoalescingOperator: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-nullish-coalescing-operator",
|
|
||||||
url: "https://git.io/vb4yx"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-nullish-coalescing-operator",
|
|
||||||
url: "https://git.io/vb4Se"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
numericSeparator: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-numeric-separator",
|
|
||||||
url: "https://git.io/vb4Sq"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-numeric-separator",
|
|
||||||
url: "https://git.io/vb4yS"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
optionalChaining: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-optional-chaining",
|
|
||||||
url: "https://git.io/vb4Sc"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-optional-chaining",
|
|
||||||
url: "https://git.io/vb4Sk"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
pipelineOperator: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-pipeline-operator",
|
|
||||||
url: "https://git.io/vb4yj"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-pipeline-operator",
|
|
||||||
url: "https://git.io/vb4SU"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
throwExpressions: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-throw-expressions",
|
|
||||||
url: "https://git.io/vb4SJ"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-throw-expressions",
|
|
||||||
url: "https://git.io/vb4yF"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
typescript: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-typescript",
|
|
||||||
url: "https://git.io/vb4SC"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-transform-typescript",
|
|
||||||
url: "https://git.io/vb4Sm"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
asyncGenerators: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-async-generators",
|
|
||||||
url: "https://git.io/vb4SY"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-async-generator-functions",
|
|
||||||
url: "https://git.io/vb4yp"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
objectRestSpread: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-object-rest-spread",
|
|
||||||
url: "https://git.io/vb4y5"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-object-rest-spread",
|
|
||||||
url: "https://git.io/vb4Ss"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
optionalCatchBinding: {
|
|
||||||
syntax: {
|
|
||||||
name: "@babel/plugin-syntax-optional-catch-binding",
|
|
||||||
url: "https://git.io/vb4Sn"
|
|
||||||
},
|
|
||||||
transform: {
|
|
||||||
name: "@babel/plugin-proposal-optional-catch-binding",
|
|
||||||
url: "https://git.io/vb4SI"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getNameURLCombination = ({
|
|
||||||
name,
|
|
||||||
url
|
|
||||||
}) => `${name} (${url})`;
|
|
||||||
|
|
||||||
function generateMissingPluginMessage(missingPluginName, loc, codeFrame) {
|
|
||||||
let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame;
|
|
||||||
const pluginInfo = pluginNameMap[missingPluginName];
|
|
||||||
|
|
||||||
if (pluginInfo) {
|
|
||||||
const {
|
|
||||||
syntax: syntaxPlugin,
|
|
||||||
transform: transformPlugin
|
|
||||||
} = pluginInfo;
|
|
||||||
|
|
||||||
if (syntaxPlugin) {
|
|
||||||
if (transformPlugin) {
|
|
||||||
const transformPluginInfo = getNameURLCombination(transformPlugin);
|
|
||||||
helpMessage += `\n\nAdd ${transformPluginInfo} to the 'plugins' section of your Babel config ` + `to enable transformation.`;
|
|
||||||
} else {
|
|
||||||
const syntaxPluginInfo = getNameURLCombination(syntaxPlugin);
|
|
||||||
helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return helpMessage;
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
../semver/bin/semver
|
|
||||||
|
|
@ -1,395 +0,0 @@
|
||||||
|
|
||||||
3.1.0 / 2017-09-26
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Add `DEBUG_HIDE_DATE` env var (#486)
|
|
||||||
* Remove ReDoS regexp in %o formatter (#504)
|
|
||||||
* Remove "component" from package.json
|
|
||||||
* Remove `component.json`
|
|
||||||
* Ignore package-lock.json
|
|
||||||
* Examples: fix colors printout
|
|
||||||
* Fix: browser detection
|
|
||||||
* Fix: spelling mistake (#496, @EdwardBetts)
|
|
||||||
|
|
||||||
3.0.1 / 2017-08-24
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Disable colors in Edge and Internet Explorer (#489)
|
|
||||||
|
|
||||||
3.0.0 / 2017-08-08
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Breaking: Remove DEBUG_FD (#406)
|
|
||||||
* Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418)
|
|
||||||
* Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408)
|
|
||||||
* Addition: document `enabled` flag (#465)
|
|
||||||
* Addition: add 256 colors mode (#481)
|
|
||||||
* Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440)
|
|
||||||
* Update: component: update "ms" to v2.0.0
|
|
||||||
* Update: separate the Node and Browser tests in Travis-CI
|
|
||||||
* Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots
|
|
||||||
* Update: separate Node.js and web browser examples for organization
|
|
||||||
* Update: update "browserify" to v14.4.0
|
|
||||||
* Fix: fix Readme typo (#473)
|
|
||||||
|
|
||||||
2.6.9 / 2017-09-22
|
|
||||||
==================
|
|
||||||
|
|
||||||
* remove ReDoS regexp in %o formatter (#504)
|
|
||||||
|
|
||||||
2.6.8 / 2017-05-18
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Check for undefined on browser globals (#462, @marbemac)
|
|
||||||
|
|
||||||
2.6.7 / 2017-05-16
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom)
|
|
||||||
* Fix: Inline extend function in node implementation (#452, @dougwilson)
|
|
||||||
* Docs: Fix typo (#455, @msasad)
|
|
||||||
|
|
||||||
2.6.5 / 2017-04-27
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek)
|
|
||||||
* Misc: clean up browser reference checks (#447, @thebigredgeek)
|
|
||||||
* Misc: add npm-debug.log to .gitignore (@thebigredgeek)
|
|
||||||
|
|
||||||
|
|
||||||
2.6.4 / 2017-04-20
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo)
|
|
||||||
* Chore: ignore bower.json in npm installations. (#437, @joaovieira)
|
|
||||||
* Misc: update "ms" to v0.7.3 (@tootallnate)
|
|
||||||
|
|
||||||
2.6.3 / 2017-03-13
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts)
|
|
||||||
* Docs: Changelog fix (@thebigredgeek)
|
|
||||||
|
|
||||||
2.6.2 / 2017-03-10
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin)
|
|
||||||
* Docs: Add backers and sponsors from Open Collective (#422, @piamancini)
|
|
||||||
* Docs: Add Slackin invite badge (@tootallnate)
|
|
||||||
|
|
||||||
2.6.1 / 2017-02-10
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error
|
|
||||||
* Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0)
|
|
||||||
* Fix: IE8 "Expected identifier" error (#414, @vgoma)
|
|
||||||
* Fix: Namespaces would not disable once enabled (#409, @musikov)
|
|
||||||
|
|
||||||
2.6.0 / 2016-12-28
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: added better null pointer checks for browser useColors (@thebigredgeek)
|
|
||||||
* Improvement: removed explicit `window.debug` export (#404, @tootallnate)
|
|
||||||
* Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate)
|
|
||||||
|
|
||||||
2.5.2 / 2016-12-25
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: reference error on window within webworkers (#393, @KlausTrainer)
|
|
||||||
* Docs: fixed README typo (#391, @lurch)
|
|
||||||
* Docs: added notice about v3 api discussion (@thebigredgeek)
|
|
||||||
|
|
||||||
2.5.1 / 2016-12-20
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: babel-core compatibility
|
|
||||||
|
|
||||||
2.5.0 / 2016-12-20
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: wrong reference in bower file (@thebigredgeek)
|
|
||||||
* Fix: webworker compatibility (@thebigredgeek)
|
|
||||||
* Fix: output formatting issue (#388, @kribblo)
|
|
||||||
* Fix: babel-loader compatibility (#383, @escwald)
|
|
||||||
* Misc: removed built asset from repo and publications (@thebigredgeek)
|
|
||||||
* Misc: moved source files to /src (#378, @yamikuronue)
|
|
||||||
* Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue)
|
|
||||||
* Test: coveralls integration (#378, @yamikuronue)
|
|
||||||
* Docs: simplified language in the opening paragraph (#373, @yamikuronue)
|
|
||||||
|
|
||||||
2.4.5 / 2016-12-17
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: `navigator` undefined in Rhino (#376, @jochenberger)
|
|
||||||
* Fix: custom log function (#379, @hsiliev)
|
|
||||||
* Improvement: bit of cleanup + linting fixes (@thebigredgeek)
|
|
||||||
* Improvement: rm non-maintainted `dist/` dir (#375, @freewil)
|
|
||||||
* Docs: simplified language in the opening paragraph. (#373, @yamikuronue)
|
|
||||||
|
|
||||||
2.4.4 / 2016-12-14
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts)
|
|
||||||
|
|
||||||
2.4.3 / 2016-12-14
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: navigation.userAgent error for react native (#364, @escwald)
|
|
||||||
|
|
||||||
2.4.2 / 2016-12-14
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: browser colors (#367, @tootallnate)
|
|
||||||
* Misc: travis ci integration (@thebigredgeek)
|
|
||||||
* Misc: added linting and testing boilerplate with sanity check (@thebigredgeek)
|
|
||||||
|
|
||||||
2.4.1 / 2016-12-13
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: typo that broke the package (#356)
|
|
||||||
|
|
||||||
2.4.0 / 2016-12-13
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: bower.json references unbuilt src entry point (#342, @justmatt)
|
|
||||||
* Fix: revert "handle regex special characters" (@tootallnate)
|
|
||||||
* Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate)
|
|
||||||
* Feature: %O`(big O) pretty-prints objects (#322, @tootallnate)
|
|
||||||
* Improvement: allow colors in workers (#335, @botverse)
|
|
||||||
* Improvement: use same color for same namespace. (#338, @lchenay)
|
|
||||||
|
|
||||||
2.3.3 / 2016-11-09
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne)
|
|
||||||
* Fix: Returning `localStorage` saved values (#331, Levi Thomason)
|
|
||||||
* Improvement: Don't create an empty object when no `process` (Nathan Rajlich)
|
|
||||||
|
|
||||||
2.3.2 / 2016-11-09
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: be super-safe in index.js as well (@TooTallNate)
|
|
||||||
* Fix: should check whether process exists (Tom Newby)
|
|
||||||
|
|
||||||
2.3.1 / 2016-11-09
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Added electron compatibility (#324, @paulcbetts)
|
|
||||||
* Improvement: Added performance optimizations (@tootallnate)
|
|
||||||
* Readme: Corrected PowerShell environment variable example (#252, @gimre)
|
|
||||||
* Misc: Removed yarn lock file from source control (#321, @fengmk2)
|
|
||||||
|
|
||||||
2.3.0 / 2016-11-07
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Fix: Consistent placement of ms diff at end of output (#215, @gorangajic)
|
|
||||||
* Fix: Escaping of regex special characters in namespace strings (#250, @zacronos)
|
|
||||||
* Fix: Fixed bug causing crash on react-native (#282, @vkarpov15)
|
|
||||||
* Feature: Enabled ES6+ compatible import via default export (#212 @bucaran)
|
|
||||||
* Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom)
|
|
||||||
* Package: Update "ms" to 0.7.2 (#315, @DevSide)
|
|
||||||
* Package: removed superfluous version property from bower.json (#207 @kkirsche)
|
|
||||||
* Readme: fix USE_COLORS to DEBUG_COLORS
|
|
||||||
* Readme: Doc fixes for format string sugar (#269, @mlucool)
|
|
||||||
* Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0)
|
|
||||||
* Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable)
|
|
||||||
* Readme: better docs for browser support (#224, @matthewmueller)
|
|
||||||
* Tooling: Added yarn integration for development (#317, @thebigredgeek)
|
|
||||||
* Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek)
|
|
||||||
* Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman)
|
|
||||||
* Misc: Updated contributors (@thebigredgeek)
|
|
||||||
|
|
||||||
2.2.0 / 2015-05-09
|
|
||||||
==================
|
|
||||||
|
|
||||||
* package: update "ms" to v0.7.1 (#202, @dougwilson)
|
|
||||||
* README: add logging to file example (#193, @DanielOchoa)
|
|
||||||
* README: fixed a typo (#191, @amir-s)
|
|
||||||
* browser: expose `storage` (#190, @stephenmathieson)
|
|
||||||
* Makefile: add a `distclean` target (#189, @stephenmathieson)
|
|
||||||
|
|
||||||
2.1.3 / 2015-03-13
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Updated stdout/stderr example (#186)
|
|
||||||
* Updated example/stdout.js to match debug current behaviour
|
|
||||||
* Renamed example/stderr.js to stdout.js
|
|
||||||
* Update Readme.md (#184)
|
|
||||||
* replace high intensity foreground color for bold (#182, #183)
|
|
||||||
|
|
||||||
2.1.2 / 2015-03-01
|
|
||||||
==================
|
|
||||||
|
|
||||||
* dist: recompile
|
|
||||||
* update "ms" to v0.7.0
|
|
||||||
* package: update "browserify" to v9.0.3
|
|
||||||
* component: fix "ms.js" repo location
|
|
||||||
* changed bower package name
|
|
||||||
* updated documentation about using debug in a browser
|
|
||||||
* fix: security error on safari (#167, #168, @yields)
|
|
||||||
|
|
||||||
2.1.1 / 2014-12-29
|
|
||||||
==================
|
|
||||||
|
|
||||||
* browser: use `typeof` to check for `console` existence
|
|
||||||
* browser: check for `console.log` truthiness (fix IE 8/9)
|
|
||||||
* browser: add support for Chrome apps
|
|
||||||
* Readme: added Windows usage remarks
|
|
||||||
* Add `bower.json` to properly support bower install
|
|
||||||
|
|
||||||
2.1.0 / 2014-10-15
|
|
||||||
==================
|
|
||||||
|
|
||||||
* node: implement `DEBUG_FD` env variable support
|
|
||||||
* package: update "browserify" to v6.1.0
|
|
||||||
* package: add "license" field to package.json (#135, @panuhorsmalahti)
|
|
||||||
|
|
||||||
2.0.0 / 2014-09-01
|
|
||||||
==================
|
|
||||||
|
|
||||||
* package: update "browserify" to v5.11.0
|
|
||||||
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
|
|
||||||
|
|
||||||
1.0.4 / 2014-07-15
|
|
||||||
==================
|
|
||||||
|
|
||||||
* dist: recompile
|
|
||||||
* example: remove `console.info()` log usage
|
|
||||||
* example: add "Content-Type" UTF-8 header to browser example
|
|
||||||
* browser: place %c marker after the space character
|
|
||||||
* browser: reset the "content" color via `color: inherit`
|
|
||||||
* browser: add colors support for Firefox >= v31
|
|
||||||
* debug: prefer an instance `log()` function over the global one (#119)
|
|
||||||
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
|
|
||||||
|
|
||||||
1.0.3 / 2014-07-09
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Add support for multiple wildcards in namespaces (#122, @seegno)
|
|
||||||
* browser: fix lint
|
|
||||||
|
|
||||||
1.0.2 / 2014-06-10
|
|
||||||
==================
|
|
||||||
|
|
||||||
* browser: update color palette (#113, @gscottolson)
|
|
||||||
* common: make console logging function configurable (#108, @timoxley)
|
|
||||||
* node: fix %o colors on old node <= 0.8.x
|
|
||||||
* Makefile: find node path using shell/which (#109, @timoxley)
|
|
||||||
|
|
||||||
1.0.1 / 2014-06-06
|
|
||||||
==================
|
|
||||||
|
|
||||||
* browser: use `removeItem()` to clear localStorage
|
|
||||||
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
|
|
||||||
* package: add "contributors" section
|
|
||||||
* node: fix comment typo
|
|
||||||
* README: list authors
|
|
||||||
|
|
||||||
1.0.0 / 2014-06-04
|
|
||||||
==================
|
|
||||||
|
|
||||||
* make ms diff be global, not be scope
|
|
||||||
* debug: ignore empty strings in enable()
|
|
||||||
* node: make DEBUG_COLORS able to disable coloring
|
|
||||||
* *: export the `colors` array
|
|
||||||
* npmignore: don't publish the `dist` dir
|
|
||||||
* Makefile: refactor to use browserify
|
|
||||||
* package: add "browserify" as a dev dependency
|
|
||||||
* Readme: add Web Inspector Colors section
|
|
||||||
* node: reset terminal color for the debug content
|
|
||||||
* node: map "%o" to `util.inspect()`
|
|
||||||
* browser: map "%j" to `JSON.stringify()`
|
|
||||||
* debug: add custom "formatters"
|
|
||||||
* debug: use "ms" module for humanizing the diff
|
|
||||||
* Readme: add "bash" syntax highlighting
|
|
||||||
* browser: add Firebug color support
|
|
||||||
* browser: add colors for WebKit browsers
|
|
||||||
* node: apply log to `console`
|
|
||||||
* rewrite: abstract common logic for Node & browsers
|
|
||||||
* add .jshintrc file
|
|
||||||
|
|
||||||
0.8.1 / 2014-04-14
|
|
||||||
==================
|
|
||||||
|
|
||||||
* package: re-add the "component" section
|
|
||||||
|
|
||||||
0.8.0 / 2014-03-30
|
|
||||||
==================
|
|
||||||
|
|
||||||
* add `enable()` method for nodejs. Closes #27
|
|
||||||
* change from stderr to stdout
|
|
||||||
* remove unnecessary index.js file
|
|
||||||
|
|
||||||
0.7.4 / 2013-11-13
|
|
||||||
==================
|
|
||||||
|
|
||||||
* remove "browserify" key from package.json (fixes something in browserify)
|
|
||||||
|
|
||||||
0.7.3 / 2013-10-30
|
|
||||||
==================
|
|
||||||
|
|
||||||
* fix: catch localStorage security error when cookies are blocked (Chrome)
|
|
||||||
* add debug(err) support. Closes #46
|
|
||||||
* add .browser prop to package.json. Closes #42
|
|
||||||
|
|
||||||
0.7.2 / 2013-02-06
|
|
||||||
==================
|
|
||||||
|
|
||||||
* fix package.json
|
|
||||||
* fix: Mobile Safari (private mode) is broken with debug
|
|
||||||
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
|
|
||||||
|
|
||||||
0.7.1 / 2013-02-05
|
|
||||||
==================
|
|
||||||
|
|
||||||
* add repository URL to package.json
|
|
||||||
* add DEBUG_COLORED to force colored output
|
|
||||||
* add browserify support
|
|
||||||
* fix component. Closes #24
|
|
||||||
|
|
||||||
0.7.0 / 2012-05-04
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Added .component to package.json
|
|
||||||
* Added debug.component.js build
|
|
||||||
|
|
||||||
0.6.0 / 2012-03-16
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Added support for "-" prefix in DEBUG [Vinay Pulim]
|
|
||||||
* Added `.enabled` flag to the node version [TooTallNate]
|
|
||||||
|
|
||||||
0.5.0 / 2012-02-02
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Added: humanize diffs. Closes #8
|
|
||||||
* Added `debug.disable()` to the CS variant
|
|
||||||
* Removed padding. Closes #10
|
|
||||||
* Fixed: persist client-side variant again. Closes #9
|
|
||||||
|
|
||||||
0.4.0 / 2012-02-01
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Added browser variant support for older browsers [TooTallNate]
|
|
||||||
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
|
|
||||||
* Added padding to diff (moved it to the right)
|
|
||||||
|
|
||||||
0.3.0 / 2012-01-26
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Added millisecond diff when isatty, otherwise UTC string
|
|
||||||
|
|
||||||
0.2.0 / 2012-01-22
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Added wildcard support
|
|
||||||
|
|
||||||
0.1.0 / 2011-12-02
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Added: remove colors unless stderr isatty [TooTallNate]
|
|
||||||
|
|
||||||
0.0.1 / 2010-01-03
|
|
||||||
==================
|
|
||||||
|
|
||||||
* Initial release
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
(The MIT License)
|
|
||||||
|
|
||||||
Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
|
|
||||||
and associated documentation files (the 'Software'), to deal in the Software without restriction,
|
|
||||||
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
||||||
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
|
|
||||||
subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
|
||||||
portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
|
||||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
||||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
||||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
|
|
@ -1,455 +0,0 @@
|
||||||
# debug
|
|
||||||
[](https://travis-ci.org/visionmedia/debug) [](https://coveralls.io/github/visionmedia/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers)
|
|
||||||
[](#sponsors)
|
|
||||||
|
|
||||||
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
|
|
||||||
|
|
||||||
A tiny JavaScript debugging utility modelled after Node.js core's debugging
|
|
||||||
technique. Works in Node.js and web browsers.
|
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ npm install debug
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
|
|
||||||
|
|
||||||
Example [_app.js_](./examples/node/app.js):
|
|
||||||
|
|
||||||
```js
|
|
||||||
var debug = require('debug')('http')
|
|
||||||
, http = require('http')
|
|
||||||
, name = 'My App';
|
|
||||||
|
|
||||||
// fake app
|
|
||||||
|
|
||||||
debug('booting %o', name);
|
|
||||||
|
|
||||||
http.createServer(function(req, res){
|
|
||||||
debug(req.method + ' ' + req.url);
|
|
||||||
res.end('hello\n');
|
|
||||||
}).listen(3000, function(){
|
|
||||||
debug('listening');
|
|
||||||
});
|
|
||||||
|
|
||||||
// fake worker of some kind
|
|
||||||
|
|
||||||
require('./worker');
|
|
||||||
```
|
|
||||||
|
|
||||||
Example [_worker.js_](./examples/node/worker.js):
|
|
||||||
|
|
||||||
```js
|
|
||||||
var a = require('debug')('worker:a')
|
|
||||||
, b = require('debug')('worker:b');
|
|
||||||
|
|
||||||
function work() {
|
|
||||||
a('doing lots of uninteresting work');
|
|
||||||
setTimeout(work, Math.random() * 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
work();
|
|
||||||
|
|
||||||
function workb() {
|
|
||||||
b('doing some work');
|
|
||||||
setTimeout(workb, Math.random() * 2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
workb();
|
|
||||||
```
|
|
||||||
|
|
||||||
The `DEBUG` environment variable is then used to enable these based on space or
|
|
||||||
comma-delimited names.
|
|
||||||
|
|
||||||
Here are some examples:
|
|
||||||
|
|
||||||
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
|
|
||||||
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
|
|
||||||
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
|
|
||||||
|
|
||||||
#### Windows command prompt notes
|
|
||||||
|
|
||||||
##### CMD
|
|
||||||
|
|
||||||
On Windows the environment variable is set using the `set` command.
|
|
||||||
|
|
||||||
```cmd
|
|
||||||
set DEBUG=*,-not_this
|
|
||||||
```
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```cmd
|
|
||||||
set DEBUG=* & node app.js
|
|
||||||
```
|
|
||||||
|
|
||||||
##### PowerShell (VS Code default)
|
|
||||||
|
|
||||||
PowerShell uses different syntax to set environment variables.
|
|
||||||
|
|
||||||
```cmd
|
|
||||||
$env:DEBUG = "*,-not_this"
|
|
||||||
```
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```cmd
|
|
||||||
$env:DEBUG='app';node app.js
|
|
||||||
```
|
|
||||||
|
|
||||||
Then, run the program to be debugged as usual.
|
|
||||||
|
|
||||||
npm script example:
|
|
||||||
```js
|
|
||||||
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
|
|
||||||
```
|
|
||||||
|
|
||||||
## Namespace Colors
|
|
||||||
|
|
||||||
Every debug instance has a color generated for it based on its namespace name.
|
|
||||||
This helps when visually parsing the debug output to identify which debug instance
|
|
||||||
a debug line belongs to.
|
|
||||||
|
|
||||||
#### Node.js
|
|
||||||
|
|
||||||
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
|
|
||||||
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
|
|
||||||
otherwise debug will only use a small handful of basic colors.
|
|
||||||
|
|
||||||
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
|
|
||||||
|
|
||||||
#### Web Browser
|
|
||||||
|
|
||||||
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
|
|
||||||
option. These are WebKit web inspectors, Firefox ([since version
|
|
||||||
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
|
|
||||||
and the Firebug plugin for Firefox (any version).
|
|
||||||
|
|
||||||
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
|
|
||||||
|
|
||||||
|
|
||||||
## Millisecond diff
|
|
||||||
|
|
||||||
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
|
|
||||||
|
|
||||||
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
|
|
||||||
|
|
||||||
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
|
|
||||||
|
|
||||||
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
|
|
||||||
|
|
||||||
|
|
||||||
## Conventions
|
|
||||||
|
|
||||||
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
|
|
||||||
|
|
||||||
## Wildcards
|
|
||||||
|
|
||||||
The `*` character may be used as a wildcard. Suppose for example your library has
|
|
||||||
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
|
|
||||||
instead of listing all three with
|
|
||||||
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
|
|
||||||
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
|
|
||||||
|
|
||||||
You can also exclude specific debuggers by prefixing them with a "-" character.
|
|
||||||
For example, `DEBUG=*,-connect:*` would include all debuggers except those
|
|
||||||
starting with "connect:".
|
|
||||||
|
|
||||||
## Environment Variables
|
|
||||||
|
|
||||||
When running through Node.js, you can set a few environment variables that will
|
|
||||||
change the behavior of the debug logging:
|
|
||||||
|
|
||||||
| Name | Purpose |
|
|
||||||
|-----------|-------------------------------------------------|
|
|
||||||
| `DEBUG` | Enables/disables specific debugging namespaces. |
|
|
||||||
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
|
|
||||||
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
|
|
||||||
| `DEBUG_DEPTH` | Object inspection depth. |
|
|
||||||
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
|
|
||||||
|
|
||||||
|
|
||||||
__Note:__ The environment variables beginning with `DEBUG_` end up being
|
|
||||||
converted into an Options object that gets used with `%o`/`%O` formatters.
|
|
||||||
See the Node.js documentation for
|
|
||||||
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
|
|
||||||
for the complete list.
|
|
||||||
|
|
||||||
## Formatters
|
|
||||||
|
|
||||||
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
|
|
||||||
Below are the officially supported formatters:
|
|
||||||
|
|
||||||
| Formatter | Representation |
|
|
||||||
|-----------|----------------|
|
|
||||||
| `%O` | Pretty-print an Object on multiple lines. |
|
|
||||||
| `%o` | Pretty-print an Object all on a single line. |
|
|
||||||
| `%s` | String. |
|
|
||||||
| `%d` | Number (both integer and float). |
|
|
||||||
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
|
|
||||||
| `%%` | Single percent sign ('%'). This does not consume an argument. |
|
|
||||||
|
|
||||||
|
|
||||||
### Custom formatters
|
|
||||||
|
|
||||||
You can add custom formatters by extending the `debug.formatters` object.
|
|
||||||
For example, if you wanted to add support for rendering a Buffer as hex with
|
|
||||||
`%h`, you could do something like:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const createDebug = require('debug')
|
|
||||||
createDebug.formatters.h = (v) => {
|
|
||||||
return v.toString('hex')
|
|
||||||
}
|
|
||||||
|
|
||||||
// …elsewhere
|
|
||||||
const debug = createDebug('foo')
|
|
||||||
debug('this is hex: %h', new Buffer('hello world'))
|
|
||||||
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Browser Support
|
|
||||||
|
|
||||||
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
|
|
||||||
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
|
|
||||||
if you don't want to build it yourself.
|
|
||||||
|
|
||||||
Debug's enable state is currently persisted by `localStorage`.
|
|
||||||
Consider the situation shown below where you have `worker:a` and `worker:b`,
|
|
||||||
and wish to debug both. You can enable this using `localStorage.debug`:
|
|
||||||
|
|
||||||
```js
|
|
||||||
localStorage.debug = 'worker:*'
|
|
||||||
```
|
|
||||||
|
|
||||||
And then refresh the page.
|
|
||||||
|
|
||||||
```js
|
|
||||||
a = debug('worker:a');
|
|
||||||
b = debug('worker:b');
|
|
||||||
|
|
||||||
setInterval(function(){
|
|
||||||
a('doing some work');
|
|
||||||
}, 1000);
|
|
||||||
|
|
||||||
setInterval(function(){
|
|
||||||
b('doing some work');
|
|
||||||
}, 1200);
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Output streams
|
|
||||||
|
|
||||||
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
|
|
||||||
|
|
||||||
Example [_stdout.js_](./examples/node/stdout.js):
|
|
||||||
|
|
||||||
```js
|
|
||||||
var debug = require('debug');
|
|
||||||
var error = debug('app:error');
|
|
||||||
|
|
||||||
// by default stderr is used
|
|
||||||
error('goes to stderr!');
|
|
||||||
|
|
||||||
var log = debug('app:log');
|
|
||||||
// set this namespace to log via console.log
|
|
||||||
log.log = console.log.bind(console); // don't forget to bind to console!
|
|
||||||
log('goes to stdout');
|
|
||||||
error('still goes to stderr!');
|
|
||||||
|
|
||||||
// set all output to go via console.info
|
|
||||||
// overrides all per-namespace log settings
|
|
||||||
debug.log = console.info.bind(console);
|
|
||||||
error('now goes to stdout via console.info');
|
|
||||||
log('still goes to stdout, but via console.info now');
|
|
||||||
```
|
|
||||||
|
|
||||||
## Extend
|
|
||||||
You can simply extend debugger
|
|
||||||
```js
|
|
||||||
const log = require('debug')('auth');
|
|
||||||
|
|
||||||
//creates new debug instance with extended namespace
|
|
||||||
const logSign = log.extend('sign');
|
|
||||||
const logLogin = log.extend('login');
|
|
||||||
|
|
||||||
log('hello'); // auth hello
|
|
||||||
logSign('hello'); //auth:sign hello
|
|
||||||
logLogin('hello'); //auth:login hello
|
|
||||||
```
|
|
||||||
|
|
||||||
## Set dynamically
|
|
||||||
|
|
||||||
You can also enable debug dynamically by calling the `enable()` method :
|
|
||||||
|
|
||||||
```js
|
|
||||||
let debug = require('debug');
|
|
||||||
|
|
||||||
console.log(1, debug.enabled('test'));
|
|
||||||
|
|
||||||
debug.enable('test');
|
|
||||||
console.log(2, debug.enabled('test'));
|
|
||||||
|
|
||||||
debug.disable();
|
|
||||||
console.log(3, debug.enabled('test'));
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
print :
|
|
||||||
```
|
|
||||||
1 false
|
|
||||||
2 true
|
|
||||||
3 false
|
|
||||||
```
|
|
||||||
|
|
||||||
Usage :
|
|
||||||
`enable(namespaces)`
|
|
||||||
`namespaces` can include modes separated by a colon and wildcards.
|
|
||||||
|
|
||||||
Note that calling `enable()` completely overrides previously set DEBUG variable :
|
|
||||||
|
|
||||||
```
|
|
||||||
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
|
|
||||||
=> false
|
|
||||||
```
|
|
||||||
|
|
||||||
`disable()`
|
|
||||||
|
|
||||||
Will disable all namespaces. The functions returns the namespaces currently
|
|
||||||
enabled (and skipped). This can be useful if you want to disable debugging
|
|
||||||
temporarily without knowing what was enabled to begin with.
|
|
||||||
|
|
||||||
For example:
|
|
||||||
|
|
||||||
```js
|
|
||||||
let debug = require('debug');
|
|
||||||
debug.enable('foo:*,-foo:bar');
|
|
||||||
let namespaces = debug.disable();
|
|
||||||
debug.enable(namespaces);
|
|
||||||
```
|
|
||||||
|
|
||||||
Note: There is no guarantee that the string will be identical to the initial
|
|
||||||
enable string, but semantically they will be identical.
|
|
||||||
|
|
||||||
## Checking whether a debug target is enabled
|
|
||||||
|
|
||||||
After you've created a debug instance, you can determine whether or not it is
|
|
||||||
enabled by checking the `enabled` property:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
const debug = require('debug')('http');
|
|
||||||
|
|
||||||
if (debug.enabled) {
|
|
||||||
// do stuff...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also manually toggle this property to force the debug instance to be
|
|
||||||
enabled or disabled.
|
|
||||||
|
|
||||||
|
|
||||||
## Authors
|
|
||||||
|
|
||||||
- TJ Holowaychuk
|
|
||||||
- Nathan Rajlich
|
|
||||||
- Andrew Rhyne
|
|
||||||
|
|
||||||
## Backers
|
|
||||||
|
|
||||||
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
|
|
||||||
|
|
||||||
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
|
|
||||||
|
|
||||||
|
|
||||||
## Sponsors
|
|
||||||
|
|
||||||
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
|
|
||||||
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
|
|
||||||
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
(The MIT License)
|
|
||||||
|
|
||||||
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of this software and associated documentation files (the
|
|
||||||
'Software'), to deal in the Software without restriction, including
|
|
||||||
without limitation the rights to use, copy, modify, merge, publish,
|
|
||||||
distribute, sublicense, and/or sell copies of the Software, and to
|
|
||||||
permit persons to whom the Software is furnished to do so, subject to
|
|
||||||
the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be
|
|
||||||
included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
||||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
||||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
||||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
||||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
@ -1,912 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
|
|
||||||
|
|
||||||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
|
|
||||||
|
|
||||||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
|
|
||||||
|
|
||||||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
|
|
||||||
|
|
||||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
|
||||||
|
|
||||||
(function (f) {
|
|
||||||
if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === "object" && typeof module !== "undefined") {
|
|
||||||
module.exports = f();
|
|
||||||
} else if (typeof define === "function" && define.amd) {
|
|
||||||
define([], f);
|
|
||||||
} else {
|
|
||||||
var g;
|
|
||||||
|
|
||||||
if (typeof window !== "undefined") {
|
|
||||||
g = window;
|
|
||||||
} else if (typeof global !== "undefined") {
|
|
||||||
g = global;
|
|
||||||
} else if (typeof self !== "undefined") {
|
|
||||||
g = self;
|
|
||||||
} else {
|
|
||||||
g = this;
|
|
||||||
}
|
|
||||||
|
|
||||||
g.debug = f();
|
|
||||||
}
|
|
||||||
})(function () {
|
|
||||||
var define, module, exports;
|
|
||||||
return function () {
|
|
||||||
function r(e, n, t) {
|
|
||||||
function o(i, f) {
|
|
||||||
if (!n[i]) {
|
|
||||||
if (!e[i]) {
|
|
||||||
var c = "function" == typeof require && require;
|
|
||||||
if (!f && c) return c(i, !0);
|
|
||||||
if (u) return u(i, !0);
|
|
||||||
var a = new Error("Cannot find module '" + i + "'");
|
|
||||||
throw a.code = "MODULE_NOT_FOUND", a;
|
|
||||||
}
|
|
||||||
|
|
||||||
var p = n[i] = {
|
|
||||||
exports: {}
|
|
||||||
};
|
|
||||||
e[i][0].call(p.exports, function (r) {
|
|
||||||
var n = e[i][1][r];
|
|
||||||
return o(n || r);
|
|
||||||
}, p, p.exports, r, e, n, t);
|
|
||||||
}
|
|
||||||
|
|
||||||
return n[i].exports;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) {
|
|
||||||
o(t[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return o;
|
|
||||||
}
|
|
||||||
|
|
||||||
return r;
|
|
||||||
}()({
|
|
||||||
1: [function (require, module, exports) {
|
|
||||||
/**
|
|
||||||
* Helpers.
|
|
||||||
*/
|
|
||||||
var s = 1000;
|
|
||||||
var m = s * 60;
|
|
||||||
var h = m * 60;
|
|
||||||
var d = h * 24;
|
|
||||||
var w = d * 7;
|
|
||||||
var y = d * 365.25;
|
|
||||||
/**
|
|
||||||
* Parse or format the given `val`.
|
|
||||||
*
|
|
||||||
* Options:
|
|
||||||
*
|
|
||||||
* - `long` verbose formatting [false]
|
|
||||||
*
|
|
||||||
* @param {String|Number} val
|
|
||||||
* @param {Object} [options]
|
|
||||||
* @throws {Error} throw an error if val is not a non-empty string or a number
|
|
||||||
* @return {String|Number}
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
module.exports = function (val, options) {
|
|
||||||
options = options || {};
|
|
||||||
|
|
||||||
var type = _typeof(val);
|
|
||||||
|
|
||||||
if (type === 'string' && val.length > 0) {
|
|
||||||
return parse(val);
|
|
||||||
} else if (type === 'number' && isNaN(val) === false) {
|
|
||||||
return options.long ? fmtLong(val) : fmtShort(val);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
|
|
||||||
};
|
|
||||||
/**
|
|
||||||
* Parse the given `str` and return milliseconds.
|
|
||||||
*
|
|
||||||
* @param {String} str
|
|
||||||
* @return {Number}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function parse(str) {
|
|
||||||
str = String(str);
|
|
||||||
|
|
||||||
if (str.length > 100) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
|
|
||||||
|
|
||||||
if (!match) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var n = parseFloat(match[1]);
|
|
||||||
var type = (match[2] || 'ms').toLowerCase();
|
|
||||||
|
|
||||||
switch (type) {
|
|
||||||
case 'years':
|
|
||||||
case 'year':
|
|
||||||
case 'yrs':
|
|
||||||
case 'yr':
|
|
||||||
case 'y':
|
|
||||||
return n * y;
|
|
||||||
|
|
||||||
case 'weeks':
|
|
||||||
case 'week':
|
|
||||||
case 'w':
|
|
||||||
return n * w;
|
|
||||||
|
|
||||||
case 'days':
|
|
||||||
case 'day':
|
|
||||||
case 'd':
|
|
||||||
return n * d;
|
|
||||||
|
|
||||||
case 'hours':
|
|
||||||
case 'hour':
|
|
||||||
case 'hrs':
|
|
||||||
case 'hr':
|
|
||||||
case 'h':
|
|
||||||
return n * h;
|
|
||||||
|
|
||||||
case 'minutes':
|
|
||||||
case 'minute':
|
|
||||||
case 'mins':
|
|
||||||
case 'min':
|
|
||||||
case 'm':
|
|
||||||
return n * m;
|
|
||||||
|
|
||||||
case 'seconds':
|
|
||||||
case 'second':
|
|
||||||
case 'secs':
|
|
||||||
case 'sec':
|
|
||||||
case 's':
|
|
||||||
return n * s;
|
|
||||||
|
|
||||||
case 'milliseconds':
|
|
||||||
case 'millisecond':
|
|
||||||
case 'msecs':
|
|
||||||
case 'msec':
|
|
||||||
case 'ms':
|
|
||||||
return n;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Short format for `ms`.
|
|
||||||
*
|
|
||||||
* @param {Number} ms
|
|
||||||
* @return {String}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function fmtShort(ms) {
|
|
||||||
var msAbs = Math.abs(ms);
|
|
||||||
|
|
||||||
if (msAbs >= d) {
|
|
||||||
return Math.round(ms / d) + 'd';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msAbs >= h) {
|
|
||||||
return Math.round(ms / h) + 'h';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msAbs >= m) {
|
|
||||||
return Math.round(ms / m) + 'm';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msAbs >= s) {
|
|
||||||
return Math.round(ms / s) + 's';
|
|
||||||
}
|
|
||||||
|
|
||||||
return ms + 'ms';
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Long format for `ms`.
|
|
||||||
*
|
|
||||||
* @param {Number} ms
|
|
||||||
* @return {String}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function fmtLong(ms) {
|
|
||||||
var msAbs = Math.abs(ms);
|
|
||||||
|
|
||||||
if (msAbs >= d) {
|
|
||||||
return plural(ms, msAbs, d, 'day');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msAbs >= h) {
|
|
||||||
return plural(ms, msAbs, h, 'hour');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msAbs >= m) {
|
|
||||||
return plural(ms, msAbs, m, 'minute');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msAbs >= s) {
|
|
||||||
return plural(ms, msAbs, s, 'second');
|
|
||||||
}
|
|
||||||
|
|
||||||
return ms + ' ms';
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Pluralization helper.
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function plural(ms, msAbs, n, name) {
|
|
||||||
var isPlural = msAbs >= n * 1.5;
|
|
||||||
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
|
|
||||||
}
|
|
||||||
}, {}],
|
|
||||||
2: [function (require, module, exports) {
|
|
||||||
// shim for using process in browser
|
|
||||||
var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
|
|
||||||
// don't break things. But we need to wrap it in a try catch in case it is
|
|
||||||
// wrapped in strict mode code which doesn't define any globals. It's inside a
|
|
||||||
// function because try/catches deoptimize in certain engines.
|
|
||||||
|
|
||||||
var cachedSetTimeout;
|
|
||||||
var cachedClearTimeout;
|
|
||||||
|
|
||||||
function defaultSetTimout() {
|
|
||||||
throw new Error('setTimeout has not been defined');
|
|
||||||
}
|
|
||||||
|
|
||||||
function defaultClearTimeout() {
|
|
||||||
throw new Error('clearTimeout has not been defined');
|
|
||||||
}
|
|
||||||
|
|
||||||
(function () {
|
|
||||||
try {
|
|
||||||
if (typeof setTimeout === 'function') {
|
|
||||||
cachedSetTimeout = setTimeout;
|
|
||||||
} else {
|
|
||||||
cachedSetTimeout = defaultSetTimout;
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
cachedSetTimeout = defaultSetTimout;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (typeof clearTimeout === 'function') {
|
|
||||||
cachedClearTimeout = clearTimeout;
|
|
||||||
} else {
|
|
||||||
cachedClearTimeout = defaultClearTimeout;
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
cachedClearTimeout = defaultClearTimeout;
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
function runTimeout(fun) {
|
|
||||||
if (cachedSetTimeout === setTimeout) {
|
|
||||||
//normal enviroments in sane situations
|
|
||||||
return setTimeout(fun, 0);
|
|
||||||
} // if setTimeout wasn't available but was latter defined
|
|
||||||
|
|
||||||
|
|
||||||
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
|
|
||||||
cachedSetTimeout = setTimeout;
|
|
||||||
return setTimeout(fun, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// when when somebody has screwed with setTimeout but no I.E. maddness
|
|
||||||
return cachedSetTimeout(fun, 0);
|
|
||||||
} catch (e) {
|
|
||||||
try {
|
|
||||||
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
|
|
||||||
return cachedSetTimeout.call(null, fun, 0);
|
|
||||||
} catch (e) {
|
|
||||||
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
|
|
||||||
return cachedSetTimeout.call(this, fun, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function runClearTimeout(marker) {
|
|
||||||
if (cachedClearTimeout === clearTimeout) {
|
|
||||||
//normal enviroments in sane situations
|
|
||||||
return clearTimeout(marker);
|
|
||||||
} // if clearTimeout wasn't available but was latter defined
|
|
||||||
|
|
||||||
|
|
||||||
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
|
|
||||||
cachedClearTimeout = clearTimeout;
|
|
||||||
return clearTimeout(marker);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// when when somebody has screwed with setTimeout but no I.E. maddness
|
|
||||||
return cachedClearTimeout(marker);
|
|
||||||
} catch (e) {
|
|
||||||
try {
|
|
||||||
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
|
|
||||||
return cachedClearTimeout.call(null, marker);
|
|
||||||
} catch (e) {
|
|
||||||
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
|
|
||||||
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
|
|
||||||
return cachedClearTimeout.call(this, marker);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var queue = [];
|
|
||||||
var draining = false;
|
|
||||||
var currentQueue;
|
|
||||||
var queueIndex = -1;
|
|
||||||
|
|
||||||
function cleanUpNextTick() {
|
|
||||||
if (!draining || !currentQueue) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
draining = false;
|
|
||||||
|
|
||||||
if (currentQueue.length) {
|
|
||||||
queue = currentQueue.concat(queue);
|
|
||||||
} else {
|
|
||||||
queueIndex = -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (queue.length) {
|
|
||||||
drainQueue();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function drainQueue() {
|
|
||||||
if (draining) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var timeout = runTimeout(cleanUpNextTick);
|
|
||||||
draining = true;
|
|
||||||
var len = queue.length;
|
|
||||||
|
|
||||||
while (len) {
|
|
||||||
currentQueue = queue;
|
|
||||||
queue = [];
|
|
||||||
|
|
||||||
while (++queueIndex < len) {
|
|
||||||
if (currentQueue) {
|
|
||||||
currentQueue[queueIndex].run();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
queueIndex = -1;
|
|
||||||
len = queue.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
currentQueue = null;
|
|
||||||
draining = false;
|
|
||||||
runClearTimeout(timeout);
|
|
||||||
}
|
|
||||||
|
|
||||||
process.nextTick = function (fun) {
|
|
||||||
var args = new Array(arguments.length - 1);
|
|
||||||
|
|
||||||
if (arguments.length > 1) {
|
|
||||||
for (var i = 1; i < arguments.length; i++) {
|
|
||||||
args[i - 1] = arguments[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
queue.push(new Item(fun, args));
|
|
||||||
|
|
||||||
if (queue.length === 1 && !draining) {
|
|
||||||
runTimeout(drainQueue);
|
|
||||||
}
|
|
||||||
}; // v8 likes predictible objects
|
|
||||||
|
|
||||||
|
|
||||||
function Item(fun, array) {
|
|
||||||
this.fun = fun;
|
|
||||||
this.array = array;
|
|
||||||
}
|
|
||||||
|
|
||||||
Item.prototype.run = function () {
|
|
||||||
this.fun.apply(null, this.array);
|
|
||||||
};
|
|
||||||
|
|
||||||
process.title = 'browser';
|
|
||||||
process.browser = true;
|
|
||||||
process.env = {};
|
|
||||||
process.argv = [];
|
|
||||||
process.version = ''; // empty string to avoid regexp issues
|
|
||||||
|
|
||||||
process.versions = {};
|
|
||||||
|
|
||||||
function noop() {}
|
|
||||||
|
|
||||||
process.on = noop;
|
|
||||||
process.addListener = noop;
|
|
||||||
process.once = noop;
|
|
||||||
process.off = noop;
|
|
||||||
process.removeListener = noop;
|
|
||||||
process.removeAllListeners = noop;
|
|
||||||
process.emit = noop;
|
|
||||||
process.prependListener = noop;
|
|
||||||
process.prependOnceListener = noop;
|
|
||||||
|
|
||||||
process.listeners = function (name) {
|
|
||||||
return [];
|
|
||||||
};
|
|
||||||
|
|
||||||
process.binding = function (name) {
|
|
||||||
throw new Error('process.binding is not supported');
|
|
||||||
};
|
|
||||||
|
|
||||||
process.cwd = function () {
|
|
||||||
return '/';
|
|
||||||
};
|
|
||||||
|
|
||||||
process.chdir = function (dir) {
|
|
||||||
throw new Error('process.chdir is not supported');
|
|
||||||
};
|
|
||||||
|
|
||||||
process.umask = function () {
|
|
||||||
return 0;
|
|
||||||
};
|
|
||||||
}, {}],
|
|
||||||
3: [function (require, module, exports) {
|
|
||||||
/**
|
|
||||||
* This is the common logic for both the Node.js and web browser
|
|
||||||
* implementations of `debug()`.
|
|
||||||
*/
|
|
||||||
function setup(env) {
|
|
||||||
createDebug.debug = createDebug;
|
|
||||||
createDebug.default = createDebug;
|
|
||||||
createDebug.coerce = coerce;
|
|
||||||
createDebug.disable = disable;
|
|
||||||
createDebug.enable = enable;
|
|
||||||
createDebug.enabled = enabled;
|
|
||||||
createDebug.humanize = require('ms');
|
|
||||||
Object.keys(env).forEach(function (key) {
|
|
||||||
createDebug[key] = env[key];
|
|
||||||
});
|
|
||||||
/**
|
|
||||||
* Active `debug` instances.
|
|
||||||
*/
|
|
||||||
|
|
||||||
createDebug.instances = [];
|
|
||||||
/**
|
|
||||||
* The currently active debug mode names, and names to skip.
|
|
||||||
*/
|
|
||||||
|
|
||||||
createDebug.names = [];
|
|
||||||
createDebug.skips = [];
|
|
||||||
/**
|
|
||||||
* Map of special "%n" handling functions, for the debug "format" argument.
|
|
||||||
*
|
|
||||||
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
|
|
||||||
*/
|
|
||||||
|
|
||||||
createDebug.formatters = {};
|
|
||||||
/**
|
|
||||||
* Selects a color for a debug namespace
|
|
||||||
* @param {String} namespace The namespace string for the for the debug instance to be colored
|
|
||||||
* @return {Number|String} An ANSI color code for the given namespace
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
function selectColor(namespace) {
|
|
||||||
var hash = 0;
|
|
||||||
|
|
||||||
for (var i = 0; i < namespace.length; i++) {
|
|
||||||
hash = (hash << 5) - hash + namespace.charCodeAt(i);
|
|
||||||
hash |= 0; // Convert to 32bit integer
|
|
||||||
}
|
|
||||||
|
|
||||||
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
|
|
||||||
}
|
|
||||||
|
|
||||||
createDebug.selectColor = selectColor;
|
|
||||||
/**
|
|
||||||
* Create a debugger with the given `namespace`.
|
|
||||||
*
|
|
||||||
* @param {String} namespace
|
|
||||||
* @return {Function}
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
function createDebug(namespace) {
|
|
||||||
var prevTime;
|
|
||||||
|
|
||||||
function debug() {
|
|
||||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
||||||
args[_key] = arguments[_key];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Disabled?
|
|
||||||
if (!debug.enabled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var self = debug; // Set `diff` timestamp
|
|
||||||
|
|
||||||
var curr = Number(new Date());
|
|
||||||
var ms = curr - (prevTime || curr);
|
|
||||||
self.diff = ms;
|
|
||||||
self.prev = prevTime;
|
|
||||||
self.curr = curr;
|
|
||||||
prevTime = curr;
|
|
||||||
args[0] = createDebug.coerce(args[0]);
|
|
||||||
|
|
||||||
if (typeof args[0] !== 'string') {
|
|
||||||
// Anything else let's inspect with %O
|
|
||||||
args.unshift('%O');
|
|
||||||
} // Apply any `formatters` transformations
|
|
||||||
|
|
||||||
|
|
||||||
var index = 0;
|
|
||||||
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
|
|
||||||
// If we encounter an escaped % then don't increase the array index
|
|
||||||
if (match === '%%') {
|
|
||||||
return match;
|
|
||||||
}
|
|
||||||
|
|
||||||
index++;
|
|
||||||
var formatter = createDebug.formatters[format];
|
|
||||||
|
|
||||||
if (typeof formatter === 'function') {
|
|
||||||
var val = args[index];
|
|
||||||
match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
|
|
||||||
|
|
||||||
args.splice(index, 1);
|
|
||||||
index--;
|
|
||||||
}
|
|
||||||
|
|
||||||
return match;
|
|
||||||
}); // Apply env-specific formatting (colors, etc.)
|
|
||||||
|
|
||||||
createDebug.formatArgs.call(self, args);
|
|
||||||
var logFn = self.log || createDebug.log;
|
|
||||||
logFn.apply(self, args);
|
|
||||||
}
|
|
||||||
|
|
||||||
debug.namespace = namespace;
|
|
||||||
debug.enabled = createDebug.enabled(namespace);
|
|
||||||
debug.useColors = createDebug.useColors();
|
|
||||||
debug.color = selectColor(namespace);
|
|
||||||
debug.destroy = destroy;
|
|
||||||
debug.extend = extend; // Debug.formatArgs = formatArgs;
|
|
||||||
// debug.rawLog = rawLog;
|
|
||||||
// env-specific initialization logic for debug instances
|
|
||||||
|
|
||||||
if (typeof createDebug.init === 'function') {
|
|
||||||
createDebug.init(debug);
|
|
||||||
}
|
|
||||||
|
|
||||||
createDebug.instances.push(debug);
|
|
||||||
return debug;
|
|
||||||
}
|
|
||||||
|
|
||||||
function destroy() {
|
|
||||||
var index = createDebug.instances.indexOf(this);
|
|
||||||
|
|
||||||
if (index !== -1) {
|
|
||||||
createDebug.instances.splice(index, 1);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function extend(namespace, delimiter) {
|
|
||||||
var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
|
|
||||||
newDebug.log = this.log;
|
|
||||||
return newDebug;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Enables a debug mode by namespaces. This can include modes
|
|
||||||
* separated by a colon and wildcards.
|
|
||||||
*
|
|
||||||
* @param {String} namespaces
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function enable(namespaces) {
|
|
||||||
createDebug.save(namespaces);
|
|
||||||
createDebug.names = [];
|
|
||||||
createDebug.skips = [];
|
|
||||||
var i;
|
|
||||||
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
|
|
||||||
var len = split.length;
|
|
||||||
|
|
||||||
for (i = 0; i < len; i++) {
|
|
||||||
if (!split[i]) {
|
|
||||||
// ignore empty strings
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespaces = split[i].replace(/\*/g, '.*?');
|
|
||||||
|
|
||||||
if (namespaces[0] === '-') {
|
|
||||||
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
|
|
||||||
} else {
|
|
||||||
createDebug.names.push(new RegExp('^' + namespaces + '$'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (i = 0; i < createDebug.instances.length; i++) {
|
|
||||||
var instance = createDebug.instances[i];
|
|
||||||
instance.enabled = createDebug.enabled(instance.namespace);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Disable debug output.
|
|
||||||
*
|
|
||||||
* @return {String} namespaces
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function disable() {
|
|
||||||
var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) {
|
|
||||||
return '-' + namespace;
|
|
||||||
}))).join(',');
|
|
||||||
createDebug.enable('');
|
|
||||||
return namespaces;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Returns true if the given mode name is enabled, false otherwise.
|
|
||||||
*
|
|
||||||
* @param {String} name
|
|
||||||
* @return {Boolean}
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function enabled(name) {
|
|
||||||
if (name[name.length - 1] === '*') {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
var i;
|
|
||||||
var len;
|
|
||||||
|
|
||||||
for (i = 0, len = createDebug.skips.length; i < len; i++) {
|
|
||||||
if (createDebug.skips[i].test(name)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (i = 0, len = createDebug.names.length; i < len; i++) {
|
|
||||||
if (createDebug.names[i].test(name)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Convert regexp to namespace
|
|
||||||
*
|
|
||||||
* @param {RegExp} regxep
|
|
||||||
* @return {String} namespace
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function toNamespace(regexp) {
|
|
||||||
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Coerce `val`.
|
|
||||||
*
|
|
||||||
* @param {Mixed} val
|
|
||||||
* @return {Mixed}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function coerce(val) {
|
|
||||||
if (val instanceof Error) {
|
|
||||||
return val.stack || val.message;
|
|
||||||
}
|
|
||||||
|
|
||||||
return val;
|
|
||||||
}
|
|
||||||
|
|
||||||
createDebug.enable(createDebug.load());
|
|
||||||
return createDebug;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = setup;
|
|
||||||
}, {
|
|
||||||
"ms": 1
|
|
||||||
}],
|
|
||||||
4: [function (require, module, exports) {
|
|
||||||
(function (process) {
|
|
||||||
/* eslint-env browser */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This is the web browser implementation of `debug()`.
|
|
||||||
*/
|
|
||||||
exports.log = log;
|
|
||||||
exports.formatArgs = formatArgs;
|
|
||||||
exports.save = save;
|
|
||||||
exports.load = load;
|
|
||||||
exports.useColors = useColors;
|
|
||||||
exports.storage = localstorage();
|
|
||||||
/**
|
|
||||||
* Colors.
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
|
|
||||||
/**
|
|
||||||
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
|
|
||||||
* and the Firebug extension (any Firefox version) are known
|
|
||||||
* to support "%c" CSS customizations.
|
|
||||||
*
|
|
||||||
* TODO: add a `localStorage` variable to explicitly enable/disable colors
|
|
||||||
*/
|
|
||||||
// eslint-disable-next-line complexity
|
|
||||||
|
|
||||||
function useColors() {
|
|
||||||
// NB: In an Electron preload script, document will be defined but not fully
|
|
||||||
// initialized. Since we know we're in Chrome, we'll just detect this case
|
|
||||||
// explicitly
|
|
||||||
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
|
|
||||||
return true;
|
|
||||||
} // Internet Explorer and Edge do not support colors.
|
|
||||||
|
|
||||||
|
|
||||||
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
|
|
||||||
return false;
|
|
||||||
} // Is webkit? http://stackoverflow.com/a/16459606/376773
|
|
||||||
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
|
|
||||||
|
|
||||||
|
|
||||||
return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
|
|
||||||
typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
|
|
||||||
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
|
|
||||||
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
|
|
||||||
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Colorize log arguments if enabled.
|
|
||||||
*
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function formatArgs(args) {
|
|
||||||
args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
|
|
||||||
|
|
||||||
if (!this.useColors) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var c = 'color: ' + this.color;
|
|
||||||
args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
|
|
||||||
// arguments passed either before or after the %c, so we need to
|
|
||||||
// figure out the correct index to insert the CSS into
|
|
||||||
|
|
||||||
var index = 0;
|
|
||||||
var lastC = 0;
|
|
||||||
args[0].replace(/%[a-zA-Z%]/g, function (match) {
|
|
||||||
if (match === '%%') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
index++;
|
|
||||||
|
|
||||||
if (match === '%c') {
|
|
||||||
// We only are interested in the *last* %c
|
|
||||||
// (the user may have provided their own)
|
|
||||||
lastC = index;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
args.splice(lastC, 0, c);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Invokes `console.log()` when available.
|
|
||||||
* No-op when `console.log` is not a "function".
|
|
||||||
*
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function log() {
|
|
||||||
var _console;
|
|
||||||
|
|
||||||
// This hackery is required for IE8/9, where
|
|
||||||
// the `console.log` function doesn't have 'apply'
|
|
||||||
return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Save `namespaces`.
|
|
||||||
*
|
|
||||||
* @param {String} namespaces
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function save(namespaces) {
|
|
||||||
try {
|
|
||||||
if (namespaces) {
|
|
||||||
exports.storage.setItem('debug', namespaces);
|
|
||||||
} else {
|
|
||||||
exports.storage.removeItem('debug');
|
|
||||||
}
|
|
||||||
} catch (error) {// Swallow
|
|
||||||
// XXX (@Qix-) should we be logging these?
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Load `namespaces`.
|
|
||||||
*
|
|
||||||
* @return {String} returns the previously persisted debug modes
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function load() {
|
|
||||||
var r;
|
|
||||||
|
|
||||||
try {
|
|
||||||
r = exports.storage.getItem('debug');
|
|
||||||
} catch (error) {} // Swallow
|
|
||||||
// XXX (@Qix-) should we be logging these?
|
|
||||||
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
|
|
||||||
|
|
||||||
|
|
||||||
if (!r && typeof process !== 'undefined' && 'env' in process) {
|
|
||||||
r = process.env.DEBUG;
|
|
||||||
}
|
|
||||||
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Localstorage attempts to return the localstorage.
|
|
||||||
*
|
|
||||||
* This is necessary because safari throws
|
|
||||||
* when a user disables cookies/localstorage
|
|
||||||
* and you attempt to access it.
|
|
||||||
*
|
|
||||||
* @return {LocalStorage}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
function localstorage() {
|
|
||||||
try {
|
|
||||||
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
|
|
||||||
// The Browser also has localStorage in the global context.
|
|
||||||
return localStorage;
|
|
||||||
} catch (error) {// Swallow
|
|
||||||
// XXX (@Qix-) should we be logging these?
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = require('./common')(exports);
|
|
||||||
var formatters = module.exports.formatters;
|
|
||||||
/**
|
|
||||||
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
|
|
||||||
*/
|
|
||||||
|
|
||||||
formatters.j = function (v) {
|
|
||||||
try {
|
|
||||||
return JSON.stringify(v);
|
|
||||||
} catch (error) {
|
|
||||||
return '[UnexpectedJSONParseError]: ' + error.message;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}).call(this, require('_process'));
|
|
||||||
}, {
|
|
||||||
"./common": 3,
|
|
||||||
"_process": 2
|
|
||||||
}]
|
|
||||||
}, {}, [4])(4);
|
|
||||||
});
|
|
||||||
|
|
@ -1,106 +0,0 @@
|
||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"debug@4.1.1",
|
|
||||||
"/Users/eric/repos/actions/setup-node"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_development": true,
|
|
||||||
"_from": "debug@4.1.1",
|
|
||||||
"_id": "debug@4.1.1",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
|
|
||||||
"_location": "/@babel/core/debug",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "debug@4.1.1",
|
|
||||||
"name": "debug",
|
|
||||||
"escapedName": "debug",
|
|
||||||
"rawSpec": "4.1.1",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "4.1.1"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/@babel/core"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
|
|
||||||
"_spec": "4.1.1",
|
|
||||||
"_where": "/Users/eric/repos/actions/setup-node",
|
|
||||||
"author": {
|
|
||||||
"name": "TJ Holowaychuk",
|
|
||||||
"email": "tj@vision-media.ca"
|
|
||||||
},
|
|
||||||
"browser": "./src/browser.js",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/visionmedia/debug/issues"
|
|
||||||
},
|
|
||||||
"contributors": [
|
|
||||||
{
|
|
||||||
"name": "Nathan Rajlich",
|
|
||||||
"email": "nathan@tootallnate.net",
|
|
||||||
"url": "http://n8.io"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Andrew Rhyne",
|
|
||||||
"email": "rhyneandrew@gmail.com"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"dependencies": {
|
|
||||||
"ms": "^2.1.1"
|
|
||||||
},
|
|
||||||
"description": "small debugging utility",
|
|
||||||
"devDependencies": {
|
|
||||||
"@babel/cli": "^7.0.0",
|
|
||||||
"@babel/core": "^7.0.0",
|
|
||||||
"@babel/preset-env": "^7.0.0",
|
|
||||||
"browserify": "14.4.0",
|
|
||||||
"chai": "^3.5.0",
|
|
||||||
"concurrently": "^3.1.0",
|
|
||||||
"coveralls": "^3.0.2",
|
|
||||||
"istanbul": "^0.4.5",
|
|
||||||
"karma": "^3.0.0",
|
|
||||||
"karma-chai": "^0.1.0",
|
|
||||||
"karma-mocha": "^1.3.0",
|
|
||||||
"karma-phantomjs-launcher": "^1.0.2",
|
|
||||||
"mocha": "^5.2.0",
|
|
||||||
"mocha-lcov-reporter": "^1.2.0",
|
|
||||||
"rimraf": "^2.5.4",
|
|
||||||
"xo": "^0.23.0"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"src",
|
|
||||||
"dist/debug.js",
|
|
||||||
"LICENSE",
|
|
||||||
"README.md"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/visionmedia/debug#readme",
|
|
||||||
"keywords": [
|
|
||||||
"debug",
|
|
||||||
"log",
|
|
||||||
"debugger"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "./src/index.js",
|
|
||||||
"name": "debug",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git://github.com/visionmedia/debug.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"build": "npm run build:debug && npm run build:test",
|
|
||||||
"build:debug": "babel -o dist/debug.js dist/debug.es6.js > dist/debug.js",
|
|
||||||
"build:test": "babel -d dist test.js",
|
|
||||||
"clean": "rimraf dist coverage",
|
|
||||||
"lint": "xo",
|
|
||||||
"prebuild:debug": "mkdir -p dist && browserify --standalone debug -o dist/debug.es6.js .",
|
|
||||||
"pretest:browser": "npm run build",
|
|
||||||
"test": "npm run test:node && npm run test:browser",
|
|
||||||
"test:browser": "karma start --single-run",
|
|
||||||
"test:coverage": "cat ./coverage/lcov.info | coveralls",
|
|
||||||
"test:node": "istanbul cover _mocha -- test.js"
|
|
||||||
},
|
|
||||||
"unpkg": "./dist/debug.js",
|
|
||||||
"version": "4.1.1"
|
|
||||||
}
|
|
||||||
|
|
@ -1,264 +0,0 @@
|
||||||
/* eslint-env browser */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This is the web browser implementation of `debug()`.
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.log = log;
|
|
||||||
exports.formatArgs = formatArgs;
|
|
||||||
exports.save = save;
|
|
||||||
exports.load = load;
|
|
||||||
exports.useColors = useColors;
|
|
||||||
exports.storage = localstorage();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Colors.
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.colors = [
|
|
||||||
'#0000CC',
|
|
||||||
'#0000FF',
|
|
||||||
'#0033CC',
|
|
||||||
'#0033FF',
|
|
||||||
'#0066CC',
|
|
||||||
'#0066FF',
|
|
||||||
'#0099CC',
|
|
||||||
'#0099FF',
|
|
||||||
'#00CC00',
|
|
||||||
'#00CC33',
|
|
||||||
'#00CC66',
|
|
||||||
'#00CC99',
|
|
||||||
'#00CCCC',
|
|
||||||
'#00CCFF',
|
|
||||||
'#3300CC',
|
|
||||||
'#3300FF',
|
|
||||||
'#3333CC',
|
|
||||||
'#3333FF',
|
|
||||||
'#3366CC',
|
|
||||||
'#3366FF',
|
|
||||||
'#3399CC',
|
|
||||||
'#3399FF',
|
|
||||||
'#33CC00',
|
|
||||||
'#33CC33',
|
|
||||||
'#33CC66',
|
|
||||||
'#33CC99',
|
|
||||||
'#33CCCC',
|
|
||||||
'#33CCFF',
|
|
||||||
'#6600CC',
|
|
||||||
'#6600FF',
|
|
||||||
'#6633CC',
|
|
||||||
'#6633FF',
|
|
||||||
'#66CC00',
|
|
||||||
'#66CC33',
|
|
||||||
'#9900CC',
|
|
||||||
'#9900FF',
|
|
||||||
'#9933CC',
|
|
||||||
'#9933FF',
|
|
||||||
'#99CC00',
|
|
||||||
'#99CC33',
|
|
||||||
'#CC0000',
|
|
||||||
'#CC0033',
|
|
||||||
'#CC0066',
|
|
||||||
'#CC0099',
|
|
||||||
'#CC00CC',
|
|
||||||
'#CC00FF',
|
|
||||||
'#CC3300',
|
|
||||||
'#CC3333',
|
|
||||||
'#CC3366',
|
|
||||||
'#CC3399',
|
|
||||||
'#CC33CC',
|
|
||||||
'#CC33FF',
|
|
||||||
'#CC6600',
|
|
||||||
'#CC6633',
|
|
||||||
'#CC9900',
|
|
||||||
'#CC9933',
|
|
||||||
'#CCCC00',
|
|
||||||
'#CCCC33',
|
|
||||||
'#FF0000',
|
|
||||||
'#FF0033',
|
|
||||||
'#FF0066',
|
|
||||||
'#FF0099',
|
|
||||||
'#FF00CC',
|
|
||||||
'#FF00FF',
|
|
||||||
'#FF3300',
|
|
||||||
'#FF3333',
|
|
||||||
'#FF3366',
|
|
||||||
'#FF3399',
|
|
||||||
'#FF33CC',
|
|
||||||
'#FF33FF',
|
|
||||||
'#FF6600',
|
|
||||||
'#FF6633',
|
|
||||||
'#FF9900',
|
|
||||||
'#FF9933',
|
|
||||||
'#FFCC00',
|
|
||||||
'#FFCC33'
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
|
|
||||||
* and the Firebug extension (any Firefox version) are known
|
|
||||||
* to support "%c" CSS customizations.
|
|
||||||
*
|
|
||||||
* TODO: add a `localStorage` variable to explicitly enable/disable colors
|
|
||||||
*/
|
|
||||||
|
|
||||||
// eslint-disable-next-line complexity
|
|
||||||
function useColors() {
|
|
||||||
// NB: In an Electron preload script, document will be defined but not fully
|
|
||||||
// initialized. Since we know we're in Chrome, we'll just detect this case
|
|
||||||
// explicitly
|
|
||||||
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Internet Explorer and Edge do not support colors.
|
|
||||||
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Is webkit? http://stackoverflow.com/a/16459606/376773
|
|
||||||
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
|
|
||||||
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
|
|
||||||
// Is firebug? http://stackoverflow.com/a/398120/376773
|
|
||||||
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
|
|
||||||
// Is firefox >= v31?
|
|
||||||
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
|
|
||||||
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
|
|
||||||
// Double check webkit in userAgent just in case we are in a worker
|
|
||||||
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Colorize log arguments if enabled.
|
|
||||||
*
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
function formatArgs(args) {
|
|
||||||
args[0] = (this.useColors ? '%c' : '') +
|
|
||||||
this.namespace +
|
|
||||||
(this.useColors ? ' %c' : ' ') +
|
|
||||||
args[0] +
|
|
||||||
(this.useColors ? '%c ' : ' ') +
|
|
||||||
'+' + module.exports.humanize(this.diff);
|
|
||||||
|
|
||||||
if (!this.useColors) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const c = 'color: ' + this.color;
|
|
||||||
args.splice(1, 0, c, 'color: inherit');
|
|
||||||
|
|
||||||
// The final "%c" is somewhat tricky, because there could be other
|
|
||||||
// arguments passed either before or after the %c, so we need to
|
|
||||||
// figure out the correct index to insert the CSS into
|
|
||||||
let index = 0;
|
|
||||||
let lastC = 0;
|
|
||||||
args[0].replace(/%[a-zA-Z%]/g, match => {
|
|
||||||
if (match === '%%') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
index++;
|
|
||||||
if (match === '%c') {
|
|
||||||
// We only are interested in the *last* %c
|
|
||||||
// (the user may have provided their own)
|
|
||||||
lastC = index;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
args.splice(lastC, 0, c);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invokes `console.log()` when available.
|
|
||||||
* No-op when `console.log` is not a "function".
|
|
||||||
*
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
function log(...args) {
|
|
||||||
// This hackery is required for IE8/9, where
|
|
||||||
// the `console.log` function doesn't have 'apply'
|
|
||||||
return typeof console === 'object' &&
|
|
||||||
console.log &&
|
|
||||||
console.log(...args);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Save `namespaces`.
|
|
||||||
*
|
|
||||||
* @param {String} namespaces
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
function save(namespaces) {
|
|
||||||
try {
|
|
||||||
if (namespaces) {
|
|
||||||
exports.storage.setItem('debug', namespaces);
|
|
||||||
} else {
|
|
||||||
exports.storage.removeItem('debug');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// Swallow
|
|
||||||
// XXX (@Qix-) should we be logging these?
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load `namespaces`.
|
|
||||||
*
|
|
||||||
* @return {String} returns the previously persisted debug modes
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
function load() {
|
|
||||||
let r;
|
|
||||||
try {
|
|
||||||
r = exports.storage.getItem('debug');
|
|
||||||
} catch (error) {
|
|
||||||
// Swallow
|
|
||||||
// XXX (@Qix-) should we be logging these?
|
|
||||||
}
|
|
||||||
|
|
||||||
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
|
|
||||||
if (!r && typeof process !== 'undefined' && 'env' in process) {
|
|
||||||
r = process.env.DEBUG;
|
|
||||||
}
|
|
||||||
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Localstorage attempts to return the localstorage.
|
|
||||||
*
|
|
||||||
* This is necessary because safari throws
|
|
||||||
* when a user disables cookies/localstorage
|
|
||||||
* and you attempt to access it.
|
|
||||||
*
|
|
||||||
* @return {LocalStorage}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
function localstorage() {
|
|
||||||
try {
|
|
||||||
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
|
|
||||||
// The Browser also has localStorage in the global context.
|
|
||||||
return localStorage;
|
|
||||||
} catch (error) {
|
|
||||||
// Swallow
|
|
||||||
// XXX (@Qix-) should we be logging these?
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = require('./common')(exports);
|
|
||||||
|
|
||||||
const {formatters} = module.exports;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
|
|
||||||
*/
|
|
||||||
|
|
||||||
formatters.j = function (v) {
|
|
||||||
try {
|
|
||||||
return JSON.stringify(v);
|
|
||||||
} catch (error) {
|
|
||||||
return '[UnexpectedJSONParseError]: ' + error.message;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
@ -1,266 +0,0 @@
|
||||||
|
|
||||||
/**
|
|
||||||
* This is the common logic for both the Node.js and web browser
|
|
||||||
* implementations of `debug()`.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function setup(env) {
|
|
||||||
createDebug.debug = createDebug;
|
|
||||||
createDebug.default = createDebug;
|
|
||||||
createDebug.coerce = coerce;
|
|
||||||
createDebug.disable = disable;
|
|
||||||
createDebug.enable = enable;
|
|
||||||
createDebug.enabled = enabled;
|
|
||||||
createDebug.humanize = require('ms');
|
|
||||||
|
|
||||||
Object.keys(env).forEach(key => {
|
|
||||||
createDebug[key] = env[key];
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Active `debug` instances.
|
|
||||||
*/
|
|
||||||
createDebug.instances = [];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The currently active debug mode names, and names to skip.
|
|
||||||
*/
|
|
||||||
|
|
||||||
createDebug.names = [];
|
|
||||||
createDebug.skips = [];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Map of special "%n" handling functions, for the debug "format" argument.
|
|
||||||
*
|
|
||||||
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
|
|
||||||
*/
|
|
||||||
createDebug.formatters = {};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Selects a color for a debug namespace
|
|
||||||
* @param {String} namespace The namespace string for the for the debug instance to be colored
|
|
||||||
* @return {Number|String} An ANSI color code for the given namespace
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
function selectColor(namespace) {
|
|
||||||
let hash = 0;
|
|
||||||
|
|
||||||
for (let i = 0; i < namespace.length; i++) {
|
|
||||||
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
|
|
||||||
hash |= 0; // Convert to 32bit integer
|
|
||||||
}
|
|
||||||
|
|
||||||
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
|
|
||||||
}
|
|
||||||
createDebug.selectColor = selectColor;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a debugger with the given `namespace`.
|
|
||||||
*
|
|
||||||
* @param {String} namespace
|
|
||||||
* @return {Function}
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
function createDebug(namespace) {
|
|
||||||
let prevTime;
|
|
||||||
|
|
||||||
function debug(...args) {
|
|
||||||
// Disabled?
|
|
||||||
if (!debug.enabled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const self = debug;
|
|
||||||
|
|
||||||
// Set `diff` timestamp
|
|
||||||
const curr = Number(new Date());
|
|
||||||
const ms = curr - (prevTime || curr);
|
|
||||||
self.diff = ms;
|
|
||||||
self.prev = prevTime;
|
|
||||||
self.curr = curr;
|
|
||||||
prevTime = curr;
|
|
||||||
|
|
||||||
args[0] = createDebug.coerce(args[0]);
|
|
||||||
|
|
||||||
if (typeof args[0] !== 'string') {
|
|
||||||
// Anything else let's inspect with %O
|
|
||||||
args.unshift('%O');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Apply any `formatters` transformations
|
|
||||||
let index = 0;
|
|
||||||
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
|
|
||||||
// If we encounter an escaped % then don't increase the array index
|
|
||||||
if (match === '%%') {
|
|
||||||
return match;
|
|
||||||
}
|
|
||||||
index++;
|
|
||||||
const formatter = createDebug.formatters[format];
|
|
||||||
if (typeof formatter === 'function') {
|
|
||||||
const val = args[index];
|
|
||||||
match = formatter.call(self, val);
|
|
||||||
|
|
||||||
// Now we need to remove `args[index]` since it's inlined in the `format`
|
|
||||||
args.splice(index, 1);
|
|
||||||
index--;
|
|
||||||
}
|
|
||||||
return match;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Apply env-specific formatting (colors, etc.)
|
|
||||||
createDebug.formatArgs.call(self, args);
|
|
||||||
|
|
||||||
const logFn = self.log || createDebug.log;
|
|
||||||
logFn.apply(self, args);
|
|
||||||
}
|
|
||||||
|
|
||||||
debug.namespace = namespace;
|
|
||||||
debug.enabled = createDebug.enabled(namespace);
|
|
||||||
debug.useColors = createDebug.useColors();
|
|
||||||
debug.color = selectColor(namespace);
|
|
||||||
debug.destroy = destroy;
|
|
||||||
debug.extend = extend;
|
|
||||||
// Debug.formatArgs = formatArgs;
|
|
||||||
// debug.rawLog = rawLog;
|
|
||||||
|
|
||||||
// env-specific initialization logic for debug instances
|
|
||||||
if (typeof createDebug.init === 'function') {
|
|
||||||
createDebug.init(debug);
|
|
||||||
}
|
|
||||||
|
|
||||||
createDebug.instances.push(debug);
|
|
||||||
|
|
||||||
return debug;
|
|
||||||
}
|
|
||||||
|
|
||||||
function destroy() {
|
|
||||||
const index = createDebug.instances.indexOf(this);
|
|
||||||
if (index !== -1) {
|
|
||||||
createDebug.instances.splice(index, 1);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function extend(namespace, delimiter) {
|
|
||||||
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
|
|
||||||
newDebug.log = this.log;
|
|
||||||
return newDebug;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enables a debug mode by namespaces. This can include modes
|
|
||||||
* separated by a colon and wildcards.
|
|
||||||
*
|
|
||||||
* @param {String} namespaces
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
function enable(namespaces) {
|
|
||||||
createDebug.save(namespaces);
|
|
||||||
|
|
||||||
createDebug.names = [];
|
|
||||||
createDebug.skips = [];
|
|
||||||
|
|
||||||
let i;
|
|
||||||
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
|
|
||||||
const len = split.length;
|
|
||||||
|
|
||||||
for (i = 0; i < len; i++) {
|
|
||||||
if (!split[i]) {
|
|
||||||
// ignore empty strings
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespaces = split[i].replace(/\*/g, '.*?');
|
|
||||||
|
|
||||||
if (namespaces[0] === '-') {
|
|
||||||
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
|
|
||||||
} else {
|
|
||||||
createDebug.names.push(new RegExp('^' + namespaces + '$'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (i = 0; i < createDebug.instances.length; i++) {
|
|
||||||
const instance = createDebug.instances[i];
|
|
||||||
instance.enabled = createDebug.enabled(instance.namespace);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disable debug output.
|
|
||||||
*
|
|
||||||
* @return {String} namespaces
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
function disable() {
|
|
||||||
const namespaces = [
|
|
||||||
...createDebug.names.map(toNamespace),
|
|
||||||
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
|
|
||||||
].join(',');
|
|
||||||
createDebug.enable('');
|
|
||||||
return namespaces;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if the given mode name is enabled, false otherwise.
|
|
||||||
*
|
|
||||||
* @param {String} name
|
|
||||||
* @return {Boolean}
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
function enabled(name) {
|
|
||||||
if (name[name.length - 1] === '*') {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
let i;
|
|
||||||
let len;
|
|
||||||
|
|
||||||
for (i = 0, len = createDebug.skips.length; i < len; i++) {
|
|
||||||
if (createDebug.skips[i].test(name)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (i = 0, len = createDebug.names.length; i < len; i++) {
|
|
||||||
if (createDebug.names[i].test(name)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert regexp to namespace
|
|
||||||
*
|
|
||||||
* @param {RegExp} regxep
|
|
||||||
* @return {String} namespace
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
function toNamespace(regexp) {
|
|
||||||
return regexp.toString()
|
|
||||||
.substring(2, regexp.toString().length - 2)
|
|
||||||
.replace(/\.\*\?$/, '*');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Coerce `val`.
|
|
||||||
*
|
|
||||||
* @param {Mixed} val
|
|
||||||
* @return {Mixed}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
function coerce(val) {
|
|
||||||
if (val instanceof Error) {
|
|
||||||
return val.stack || val.message;
|
|
||||||
}
|
|
||||||
return val;
|
|
||||||
}
|
|
||||||
|
|
||||||
createDebug.enable(createDebug.load());
|
|
||||||
|
|
||||||
return createDebug;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = setup;
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
/**
|
|
||||||
* Detect Electron renderer / nwjs process, which is node, but we should
|
|
||||||
* treat as a browser.
|
|
||||||
*/
|
|
||||||
|
|
||||||
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
|
|
||||||
module.exports = require('./browser.js');
|
|
||||||
} else {
|
|
||||||
module.exports = require('./node.js');
|
|
||||||
}
|
|
||||||
|
|
@ -1,257 +0,0 @@
|
||||||
/**
|
|
||||||
* Module dependencies.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const tty = require('tty');
|
|
||||||
const util = require('util');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This is the Node.js implementation of `debug()`.
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.init = init;
|
|
||||||
exports.log = log;
|
|
||||||
exports.formatArgs = formatArgs;
|
|
||||||
exports.save = save;
|
|
||||||
exports.load = load;
|
|
||||||
exports.useColors = useColors;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Colors.
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.colors = [6, 2, 3, 4, 5, 1];
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
|
|
||||||
// eslint-disable-next-line import/no-extraneous-dependencies
|
|
||||||
const supportsColor = require('supports-color');
|
|
||||||
|
|
||||||
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
|
|
||||||
exports.colors = [
|
|
||||||
20,
|
|
||||||
21,
|
|
||||||
26,
|
|
||||||
27,
|
|
||||||
32,
|
|
||||||
33,
|
|
||||||
38,
|
|
||||||
39,
|
|
||||||
40,
|
|
||||||
41,
|
|
||||||
42,
|
|
||||||
43,
|
|
||||||
44,
|
|
||||||
45,
|
|
||||||
56,
|
|
||||||
57,
|
|
||||||
62,
|
|
||||||
63,
|
|
||||||
68,
|
|
||||||
69,
|
|
||||||
74,
|
|
||||||
75,
|
|
||||||
76,
|
|
||||||
77,
|
|
||||||
78,
|
|
||||||
79,
|
|
||||||
80,
|
|
||||||
81,
|
|
||||||
92,
|
|
||||||
93,
|
|
||||||
98,
|
|
||||||
99,
|
|
||||||
112,
|
|
||||||
113,
|
|
||||||
128,
|
|
||||||
129,
|
|
||||||
134,
|
|
||||||
135,
|
|
||||||
148,
|
|
||||||
149,
|
|
||||||
160,
|
|
||||||
161,
|
|
||||||
162,
|
|
||||||
163,
|
|
||||||
164,
|
|
||||||
165,
|
|
||||||
166,
|
|
||||||
167,
|
|
||||||
168,
|
|
||||||
169,
|
|
||||||
170,
|
|
||||||
171,
|
|
||||||
172,
|
|
||||||
173,
|
|
||||||
178,
|
|
||||||
179,
|
|
||||||
184,
|
|
||||||
185,
|
|
||||||
196,
|
|
||||||
197,
|
|
||||||
198,
|
|
||||||
199,
|
|
||||||
200,
|
|
||||||
201,
|
|
||||||
202,
|
|
||||||
203,
|
|
||||||
204,
|
|
||||||
205,
|
|
||||||
206,
|
|
||||||
207,
|
|
||||||
208,
|
|
||||||
209,
|
|
||||||
214,
|
|
||||||
215,
|
|
||||||
220,
|
|
||||||
221
|
|
||||||
];
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build up the default `inspectOpts` object from the environment variables.
|
|
||||||
*
|
|
||||||
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.inspectOpts = Object.keys(process.env).filter(key => {
|
|
||||||
return /^debug_/i.test(key);
|
|
||||||
}).reduce((obj, key) => {
|
|
||||||
// Camel-case
|
|
||||||
const prop = key
|
|
||||||
.substring(6)
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/_([a-z])/g, (_, k) => {
|
|
||||||
return k.toUpperCase();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Coerce string value into JS value
|
|
||||||
let val = process.env[key];
|
|
||||||
if (/^(yes|on|true|enabled)$/i.test(val)) {
|
|
||||||
val = true;
|
|
||||||
} else if (/^(no|off|false|disabled)$/i.test(val)) {
|
|
||||||
val = false;
|
|
||||||
} else if (val === 'null') {
|
|
||||||
val = null;
|
|
||||||
} else {
|
|
||||||
val = Number(val);
|
|
||||||
}
|
|
||||||
|
|
||||||
obj[prop] = val;
|
|
||||||
return obj;
|
|
||||||
}, {});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Is stdout a TTY? Colored output is enabled when `true`.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function useColors() {
|
|
||||||
return 'colors' in exports.inspectOpts ?
|
|
||||||
Boolean(exports.inspectOpts.colors) :
|
|
||||||
tty.isatty(process.stderr.fd);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds ANSI color escape codes if enabled.
|
|
||||||
*
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
function formatArgs(args) {
|
|
||||||
const {namespace: name, useColors} = this;
|
|
||||||
|
|
||||||
if (useColors) {
|
|
||||||
const c = this.color;
|
|
||||||
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
|
|
||||||
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
|
|
||||||
|
|
||||||
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
|
|
||||||
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
|
|
||||||
} else {
|
|
||||||
args[0] = getDate() + name + ' ' + args[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getDate() {
|
|
||||||
if (exports.inspectOpts.hideDate) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
return new Date().toISOString() + ' ';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invokes `util.format()` with the specified arguments and writes to stderr.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function log(...args) {
|
|
||||||
return process.stderr.write(util.format(...args) + '\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Save `namespaces`.
|
|
||||||
*
|
|
||||||
* @param {String} namespaces
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
function save(namespaces) {
|
|
||||||
if (namespaces) {
|
|
||||||
process.env.DEBUG = namespaces;
|
|
||||||
} else {
|
|
||||||
// If you set a process.env field to null or undefined, it gets cast to the
|
|
||||||
// string 'null' or 'undefined'. Just delete instead.
|
|
||||||
delete process.env.DEBUG;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load `namespaces`.
|
|
||||||
*
|
|
||||||
* @return {String} returns the previously persisted debug modes
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
function load() {
|
|
||||||
return process.env.DEBUG;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Init logic for `debug` instances.
|
|
||||||
*
|
|
||||||
* Create a new `inspectOpts` object in case `useColors` is set
|
|
||||||
* differently for a particular `debug` instance.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function init(debug) {
|
|
||||||
debug.inspectOpts = {};
|
|
||||||
|
|
||||||
const keys = Object.keys(exports.inspectOpts);
|
|
||||||
for (let i = 0; i < keys.length; i++) {
|
|
||||||
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = require('./common')(exports);
|
|
||||||
|
|
||||||
const {formatters} = module.exports;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Map %o to `util.inspect()`, all on a single line.
|
|
||||||
*/
|
|
||||||
|
|
||||||
formatters.o = function (v) {
|
|
||||||
this.inspectOpts.colors = this.useColors;
|
|
||||||
return util.inspect(v, this.inspectOpts)
|
|
||||||
.replace(/\s*\n\s*/g, ' ');
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Map %O to `util.inspect()`, allowing multiple lines if needed.
|
|
||||||
*/
|
|
||||||
|
|
||||||
formatters.O = function (v) {
|
|
||||||
this.inspectOpts.colors = this.useColors;
|
|
||||||
return util.inspect(v, this.inspectOpts);
|
|
||||||
};
|
|
||||||
|
|
@ -1,162 +0,0 @@
|
||||||
/**
|
|
||||||
* Helpers.
|
|
||||||
*/
|
|
||||||
|
|
||||||
var s = 1000;
|
|
||||||
var m = s * 60;
|
|
||||||
var h = m * 60;
|
|
||||||
var d = h * 24;
|
|
||||||
var w = d * 7;
|
|
||||||
var y = d * 365.25;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse or format the given `val`.
|
|
||||||
*
|
|
||||||
* Options:
|
|
||||||
*
|
|
||||||
* - `long` verbose formatting [false]
|
|
||||||
*
|
|
||||||
* @param {String|Number} val
|
|
||||||
* @param {Object} [options]
|
|
||||||
* @throws {Error} throw an error if val is not a non-empty string or a number
|
|
||||||
* @return {String|Number}
|
|
||||||
* @api public
|
|
||||||
*/
|
|
||||||
|
|
||||||
module.exports = function(val, options) {
|
|
||||||
options = options || {};
|
|
||||||
var type = typeof val;
|
|
||||||
if (type === 'string' && val.length > 0) {
|
|
||||||
return parse(val);
|
|
||||||
} else if (type === 'number' && isFinite(val)) {
|
|
||||||
return options.long ? fmtLong(val) : fmtShort(val);
|
|
||||||
}
|
|
||||||
throw new Error(
|
|
||||||
'val is not a non-empty string or a valid number. val=' +
|
|
||||||
JSON.stringify(val)
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse the given `str` and return milliseconds.
|
|
||||||
*
|
|
||||||
* @param {String} str
|
|
||||||
* @return {Number}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
function parse(str) {
|
|
||||||
str = String(str);
|
|
||||||
if (str.length > 100) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
|
|
||||||
str
|
|
||||||
);
|
|
||||||
if (!match) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var n = parseFloat(match[1]);
|
|
||||||
var type = (match[2] || 'ms').toLowerCase();
|
|
||||||
switch (type) {
|
|
||||||
case 'years':
|
|
||||||
case 'year':
|
|
||||||
case 'yrs':
|
|
||||||
case 'yr':
|
|
||||||
case 'y':
|
|
||||||
return n * y;
|
|
||||||
case 'weeks':
|
|
||||||
case 'week':
|
|
||||||
case 'w':
|
|
||||||
return n * w;
|
|
||||||
case 'days':
|
|
||||||
case 'day':
|
|
||||||
case 'd':
|
|
||||||
return n * d;
|
|
||||||
case 'hours':
|
|
||||||
case 'hour':
|
|
||||||
case 'hrs':
|
|
||||||
case 'hr':
|
|
||||||
case 'h':
|
|
||||||
return n * h;
|
|
||||||
case 'minutes':
|
|
||||||
case 'minute':
|
|
||||||
case 'mins':
|
|
||||||
case 'min':
|
|
||||||
case 'm':
|
|
||||||
return n * m;
|
|
||||||
case 'seconds':
|
|
||||||
case 'second':
|
|
||||||
case 'secs':
|
|
||||||
case 'sec':
|
|
||||||
case 's':
|
|
||||||
return n * s;
|
|
||||||
case 'milliseconds':
|
|
||||||
case 'millisecond':
|
|
||||||
case 'msecs':
|
|
||||||
case 'msec':
|
|
||||||
case 'ms':
|
|
||||||
return n;
|
|
||||||
default:
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Short format for `ms`.
|
|
||||||
*
|
|
||||||
* @param {Number} ms
|
|
||||||
* @return {String}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
function fmtShort(ms) {
|
|
||||||
var msAbs = Math.abs(ms);
|
|
||||||
if (msAbs >= d) {
|
|
||||||
return Math.round(ms / d) + 'd';
|
|
||||||
}
|
|
||||||
if (msAbs >= h) {
|
|
||||||
return Math.round(ms / h) + 'h';
|
|
||||||
}
|
|
||||||
if (msAbs >= m) {
|
|
||||||
return Math.round(ms / m) + 'm';
|
|
||||||
}
|
|
||||||
if (msAbs >= s) {
|
|
||||||
return Math.round(ms / s) + 's';
|
|
||||||
}
|
|
||||||
return ms + 'ms';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Long format for `ms`.
|
|
||||||
*
|
|
||||||
* @param {Number} ms
|
|
||||||
* @return {String}
|
|
||||||
* @api private
|
|
||||||
*/
|
|
||||||
|
|
||||||
function fmtLong(ms) {
|
|
||||||
var msAbs = Math.abs(ms);
|
|
||||||
if (msAbs >= d) {
|
|
||||||
return plural(ms, msAbs, d, 'day');
|
|
||||||
}
|
|
||||||
if (msAbs >= h) {
|
|
||||||
return plural(ms, msAbs, h, 'hour');
|
|
||||||
}
|
|
||||||
if (msAbs >= m) {
|
|
||||||
return plural(ms, msAbs, m, 'minute');
|
|
||||||
}
|
|
||||||
if (msAbs >= s) {
|
|
||||||
return plural(ms, msAbs, s, 'second');
|
|
||||||
}
|
|
||||||
return ms + ' ms';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pluralization helper.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function plural(ms, msAbs, n, name) {
|
|
||||||
var isPlural = msAbs >= n * 1.5;
|
|
||||||
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
|
|
||||||
}
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
The MIT License (MIT)
|
|
||||||
|
|
||||||
Copyright (c) 2016 Zeit, Inc.
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
|
|
@ -1,73 +0,0 @@
|
||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"ms@2.1.2",
|
|
||||||
"/Users/eric/repos/actions/setup-node"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_development": true,
|
|
||||||
"_from": "ms@2.1.2",
|
|
||||||
"_id": "ms@2.1.2",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
|
|
||||||
"_location": "/@babel/core/ms",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "ms@2.1.2",
|
|
||||||
"name": "ms",
|
|
||||||
"escapedName": "ms",
|
|
||||||
"rawSpec": "2.1.2",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "2.1.2"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/@babel/core/debug"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
|
|
||||||
"_spec": "2.1.2",
|
|
||||||
"_where": "/Users/eric/repos/actions/setup-node",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/zeit/ms/issues"
|
|
||||||
},
|
|
||||||
"description": "Tiny millisecond conversion utility",
|
|
||||||
"devDependencies": {
|
|
||||||
"eslint": "4.12.1",
|
|
||||||
"expect.js": "0.3.1",
|
|
||||||
"husky": "0.14.3",
|
|
||||||
"lint-staged": "5.0.0",
|
|
||||||
"mocha": "4.0.1"
|
|
||||||
},
|
|
||||||
"eslintConfig": {
|
|
||||||
"extends": "eslint:recommended",
|
|
||||||
"env": {
|
|
||||||
"node": true,
|
|
||||||
"es6": true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"index.js"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/zeit/ms#readme",
|
|
||||||
"license": "MIT",
|
|
||||||
"lint-staged": {
|
|
||||||
"*.js": [
|
|
||||||
"npm run lint",
|
|
||||||
"prettier --single-quote --write",
|
|
||||||
"git add"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"main": "./index",
|
|
||||||
"name": "ms",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/zeit/ms.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"lint": "eslint lib/* bin/*",
|
|
||||||
"precommit": "lint-staged",
|
|
||||||
"test": "mocha tests.js"
|
|
||||||
},
|
|
||||||
"version": "2.1.2"
|
|
||||||
}
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
# ms
|
|
||||||
|
|
||||||
[](https://travis-ci.org/zeit/ms)
|
|
||||||
[](https://spectrum.chat/zeit)
|
|
||||||
|
|
||||||
Use this package to easily convert various time formats to milliseconds.
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
```js
|
|
||||||
ms('2 days') // 172800000
|
|
||||||
ms('1d') // 86400000
|
|
||||||
ms('10h') // 36000000
|
|
||||||
ms('2.5 hrs') // 9000000
|
|
||||||
ms('2h') // 7200000
|
|
||||||
ms('1m') // 60000
|
|
||||||
ms('5s') // 5000
|
|
||||||
ms('1y') // 31557600000
|
|
||||||
ms('100') // 100
|
|
||||||
ms('-3 days') // -259200000
|
|
||||||
ms('-1h') // -3600000
|
|
||||||
ms('-200') // -200
|
|
||||||
```
|
|
||||||
|
|
||||||
### Convert from Milliseconds
|
|
||||||
|
|
||||||
```js
|
|
||||||
ms(60000) // "1m"
|
|
||||||
ms(2 * 60000) // "2m"
|
|
||||||
ms(-3 * 60000) // "-3m"
|
|
||||||
ms(ms('10 hours')) // "10h"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Time Format Written-Out
|
|
||||||
|
|
||||||
```js
|
|
||||||
ms(60000, { long: true }) // "1 minute"
|
|
||||||
ms(2 * 60000, { long: true }) // "2 minutes"
|
|
||||||
ms(-3 * 60000, { long: true }) // "-3 minutes"
|
|
||||||
ms(ms('10 hours'), { long: true }) // "10 hours"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- Works both in [Node.js](https://nodejs.org) and in the browser
|
|
||||||
- If a number is supplied to `ms`, a string with a unit is returned
|
|
||||||
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
|
|
||||||
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
|
|
||||||
|
|
||||||
## Related Packages
|
|
||||||
|
|
||||||
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
|
|
||||||
|
|
||||||
## Caught a Bug?
|
|
||||||
|
|
||||||
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
|
|
||||||
2. Link the package to the global module directory: `npm link`
|
|
||||||
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
|
|
||||||
|
|
||||||
As always, you can run the tests using: `npm test`
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
# changes log
|
|
||||||
|
|
||||||
## 5.7
|
|
||||||
|
|
||||||
* Add `minVersion` method
|
|
||||||
|
|
||||||
## 5.6
|
|
||||||
|
|
||||||
* Move boolean `loose` param to an options object, with
|
|
||||||
backwards-compatibility protection.
|
|
||||||
* Add ability to opt out of special prerelease version handling with
|
|
||||||
the `includePrerelease` option flag.
|
|
||||||
|
|
||||||
## 5.5
|
|
||||||
|
|
||||||
* Add version coercion capabilities
|
|
||||||
|
|
||||||
## 5.4
|
|
||||||
|
|
||||||
* Add intersection checking
|
|
||||||
|
|
||||||
## 5.3
|
|
||||||
|
|
||||||
* Add `minSatisfying` method
|
|
||||||
|
|
||||||
## 5.2
|
|
||||||
|
|
||||||
* Add `prerelease(v)` that returns prerelease components
|
|
||||||
|
|
||||||
## 5.1
|
|
||||||
|
|
||||||
* Add Backus-Naur for ranges
|
|
||||||
* Remove excessively cute inspection methods
|
|
||||||
|
|
||||||
## 5.0
|
|
||||||
|
|
||||||
* Remove AMD/Browserified build artifacts
|
|
||||||
* Fix ltr and gtr when using the `*` range
|
|
||||||
* Fix for range `*` with a prerelease identifier
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
The ISC License
|
|
||||||
|
|
||||||
Copyright (c) Isaac Z. Schlueter and Contributors
|
|
||||||
|
|
||||||
Permission to use, copy, modify, and/or distribute this software for any
|
|
||||||
purpose with or without fee is hereby granted, provided that the above
|
|
||||||
copyright notice and this permission notice appear in all copies.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
||||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
||||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
||||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
||||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
||||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
|
||||||
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
||||||
|
|
@ -1,411 +0,0 @@
|
||||||
semver(1) -- The semantic versioner for npm
|
|
||||||
===========================================
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install --save semver
|
|
||||||
````
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
As a node module:
|
|
||||||
|
|
||||||
```js
|
|
||||||
const semver = require('semver')
|
|
||||||
|
|
||||||
semver.valid('1.2.3') // '1.2.3'
|
|
||||||
semver.valid('a.b.c') // null
|
|
||||||
semver.clean(' =v1.2.3 ') // '1.2.3'
|
|
||||||
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
|
|
||||||
semver.gt('1.2.3', '9.8.7') // false
|
|
||||||
semver.lt('1.2.3', '9.8.7') // true
|
|
||||||
semver.minVersion('>=1.0.0') // '1.0.0'
|
|
||||||
semver.valid(semver.coerce('v2')) // '2.0.0'
|
|
||||||
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
|
|
||||||
```
|
|
||||||
|
|
||||||
As a command-line utility:
|
|
||||||
|
|
||||||
```
|
|
||||||
$ semver -h
|
|
||||||
|
|
||||||
A JavaScript implementation of the https://semver.org/ specification
|
|
||||||
Copyright Isaac Z. Schlueter
|
|
||||||
|
|
||||||
Usage: semver [options] <version> [<version> [...]]
|
|
||||||
Prints valid versions sorted by SemVer precedence
|
|
||||||
|
|
||||||
Options:
|
|
||||||
-r --range <range>
|
|
||||||
Print versions that match the specified range.
|
|
||||||
|
|
||||||
-i --increment [<level>]
|
|
||||||
Increment a version by the specified level. Level can
|
|
||||||
be one of: major, minor, patch, premajor, preminor,
|
|
||||||
prepatch, or prerelease. Default level is 'patch'.
|
|
||||||
Only one version may be specified.
|
|
||||||
|
|
||||||
--preid <identifier>
|
|
||||||
Identifier to be used to prefix premajor, preminor,
|
|
||||||
prepatch or prerelease version increments.
|
|
||||||
|
|
||||||
-l --loose
|
|
||||||
Interpret versions and ranges loosely
|
|
||||||
|
|
||||||
-p --include-prerelease
|
|
||||||
Always include prerelease versions in range matching
|
|
||||||
|
|
||||||
-c --coerce
|
|
||||||
Coerce a string into SemVer if possible
|
|
||||||
(does not imply --loose)
|
|
||||||
|
|
||||||
Program exits successfully if any valid version satisfies
|
|
||||||
all supplied ranges, and prints all satisfying versions.
|
|
||||||
|
|
||||||
If no satisfying versions are found, then exits failure.
|
|
||||||
|
|
||||||
Versions are printed in ascending order, so supplying
|
|
||||||
multiple versions to the utility will just sort them.
|
|
||||||
```
|
|
||||||
|
|
||||||
## Versions
|
|
||||||
|
|
||||||
A "version" is described by the `v2.0.0` specification found at
|
|
||||||
<https://semver.org/>.
|
|
||||||
|
|
||||||
A leading `"="` or `"v"` character is stripped off and ignored.
|
|
||||||
|
|
||||||
## Ranges
|
|
||||||
|
|
||||||
A `version range` is a set of `comparators` which specify versions
|
|
||||||
that satisfy the range.
|
|
||||||
|
|
||||||
A `comparator` is composed of an `operator` and a `version`. The set
|
|
||||||
of primitive `operators` is:
|
|
||||||
|
|
||||||
* `<` Less than
|
|
||||||
* `<=` Less than or equal to
|
|
||||||
* `>` Greater than
|
|
||||||
* `>=` Greater than or equal to
|
|
||||||
* `=` Equal. If no operator is specified, then equality is assumed,
|
|
||||||
so this operator is optional, but MAY be included.
|
|
||||||
|
|
||||||
For example, the comparator `>=1.2.7` would match the versions
|
|
||||||
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
|
|
||||||
or `1.1.0`.
|
|
||||||
|
|
||||||
Comparators can be joined by whitespace to form a `comparator set`,
|
|
||||||
which is satisfied by the **intersection** of all of the comparators
|
|
||||||
it includes.
|
|
||||||
|
|
||||||
A range is composed of one or more comparator sets, joined by `||`. A
|
|
||||||
version matches a range if and only if every comparator in at least
|
|
||||||
one of the `||`-separated comparator sets is satisfied by the version.
|
|
||||||
|
|
||||||
For example, the range `>=1.2.7 <1.3.0` would match the versions
|
|
||||||
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
|
|
||||||
or `1.1.0`.
|
|
||||||
|
|
||||||
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
|
|
||||||
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
|
|
||||||
|
|
||||||
### Prerelease Tags
|
|
||||||
|
|
||||||
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
|
|
||||||
it will only be allowed to satisfy comparator sets if at least one
|
|
||||||
comparator with the same `[major, minor, patch]` tuple also has a
|
|
||||||
prerelease tag.
|
|
||||||
|
|
||||||
For example, the range `>1.2.3-alpha.3` would be allowed to match the
|
|
||||||
version `1.2.3-alpha.7`, but it would *not* be satisfied by
|
|
||||||
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
|
|
||||||
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
|
|
||||||
range only accepts prerelease tags on the `1.2.3` version. The
|
|
||||||
version `3.4.5` *would* satisfy the range, because it does not have a
|
|
||||||
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
|
|
||||||
|
|
||||||
The purpose for this behavior is twofold. First, prerelease versions
|
|
||||||
frequently are updated very quickly, and contain many breaking changes
|
|
||||||
that are (by the author's design) not yet fit for public consumption.
|
|
||||||
Therefore, by default, they are excluded from range matching
|
|
||||||
semantics.
|
|
||||||
|
|
||||||
Second, a user who has opted into using a prerelease version has
|
|
||||||
clearly indicated the intent to use *that specific* set of
|
|
||||||
alpha/beta/rc versions. By including a prerelease tag in the range,
|
|
||||||
the user is indicating that they are aware of the risk. However, it
|
|
||||||
is still not appropriate to assume that they have opted into taking a
|
|
||||||
similar risk on the *next* set of prerelease versions.
|
|
||||||
|
|
||||||
Note that this behavior can be suppressed (treating all prerelease
|
|
||||||
versions as if they were normal versions, for the purpose of range
|
|
||||||
matching) by setting the `includePrerelease` flag on the options
|
|
||||||
object to any
|
|
||||||
[functions](https://github.com/npm/node-semver#functions) that do
|
|
||||||
range matching.
|
|
||||||
|
|
||||||
#### Prerelease Identifiers
|
|
||||||
|
|
||||||
The method `.inc` takes an additional `identifier` string argument that
|
|
||||||
will append the value of the string as a prerelease identifier:
|
|
||||||
|
|
||||||
```javascript
|
|
||||||
semver.inc('1.2.3', 'prerelease', 'beta')
|
|
||||||
// '1.2.4-beta.0'
|
|
||||||
```
|
|
||||||
|
|
||||||
command-line example:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ semver 1.2.3 -i prerelease --preid beta
|
|
||||||
1.2.4-beta.0
|
|
||||||
```
|
|
||||||
|
|
||||||
Which then can be used to increment further:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
$ semver 1.2.4-beta.0 -i prerelease
|
|
||||||
1.2.4-beta.1
|
|
||||||
```
|
|
||||||
|
|
||||||
### Advanced Range Syntax
|
|
||||||
|
|
||||||
Advanced range syntax desugars to primitive comparators in
|
|
||||||
deterministic ways.
|
|
||||||
|
|
||||||
Advanced ranges may be combined in the same way as primitive
|
|
||||||
comparators using white space or `||`.
|
|
||||||
|
|
||||||
#### Hyphen Ranges `X.Y.Z - A.B.C`
|
|
||||||
|
|
||||||
Specifies an inclusive set.
|
|
||||||
|
|
||||||
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
|
|
||||||
|
|
||||||
If a partial version is provided as the first version in the inclusive
|
|
||||||
range, then the missing pieces are replaced with zeroes.
|
|
||||||
|
|
||||||
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
|
|
||||||
|
|
||||||
If a partial version is provided as the second version in the
|
|
||||||
inclusive range, then all versions that start with the supplied parts
|
|
||||||
of the tuple are accepted, but nothing that would be greater than the
|
|
||||||
provided tuple parts.
|
|
||||||
|
|
||||||
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0`
|
|
||||||
* `1.2.3 - 2` := `>=1.2.3 <3.0.0`
|
|
||||||
|
|
||||||
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
|
|
||||||
|
|
||||||
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
|
|
||||||
numeric values in the `[major, minor, patch]` tuple.
|
|
||||||
|
|
||||||
* `*` := `>=0.0.0` (Any version satisfies)
|
|
||||||
* `1.x` := `>=1.0.0 <2.0.0` (Matching major version)
|
|
||||||
* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions)
|
|
||||||
|
|
||||||
A partial version range is treated as an X-Range, so the special
|
|
||||||
character is in fact optional.
|
|
||||||
|
|
||||||
* `""` (empty string) := `*` := `>=0.0.0`
|
|
||||||
* `1` := `1.x.x` := `>=1.0.0 <2.0.0`
|
|
||||||
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0`
|
|
||||||
|
|
||||||
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
|
|
||||||
|
|
||||||
Allows patch-level changes if a minor version is specified on the
|
|
||||||
comparator. Allows minor-level changes if not.
|
|
||||||
|
|
||||||
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0`
|
|
||||||
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`)
|
|
||||||
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`)
|
|
||||||
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0`
|
|
||||||
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`)
|
|
||||||
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`)
|
|
||||||
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in
|
|
||||||
the `1.2.3` version will be allowed, if they are greater than or
|
|
||||||
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
|
|
||||||
`1.2.4-beta.2` would not, because it is a prerelease of a
|
|
||||||
different `[major, minor, patch]` tuple.
|
|
||||||
|
|
||||||
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
|
|
||||||
|
|
||||||
Allows changes that do not modify the left-most non-zero digit in the
|
|
||||||
`[major, minor, patch]` tuple. In other words, this allows patch and
|
|
||||||
minor updates for versions `1.0.0` and above, patch updates for
|
|
||||||
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
|
|
||||||
|
|
||||||
Many authors treat a `0.x` version as if the `x` were the major
|
|
||||||
"breaking-change" indicator.
|
|
||||||
|
|
||||||
Caret ranges are ideal when an author may make breaking changes
|
|
||||||
between `0.2.4` and `0.3.0` releases, which is a common practice.
|
|
||||||
However, it presumes that there will *not* be breaking changes between
|
|
||||||
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
|
|
||||||
additive (but non-breaking), according to commonly observed practices.
|
|
||||||
|
|
||||||
* `^1.2.3` := `>=1.2.3 <2.0.0`
|
|
||||||
* `^0.2.3` := `>=0.2.3 <0.3.0`
|
|
||||||
* `^0.0.3` := `>=0.0.3 <0.0.4`
|
|
||||||
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in
|
|
||||||
the `1.2.3` version will be allowed, if they are greater than or
|
|
||||||
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
|
|
||||||
`1.2.4-beta.2` would not, because it is a prerelease of a
|
|
||||||
different `[major, minor, patch]` tuple.
|
|
||||||
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the
|
|
||||||
`0.0.3` version *only* will be allowed, if they are greater than or
|
|
||||||
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
|
|
||||||
|
|
||||||
When parsing caret ranges, a missing `patch` value desugars to the
|
|
||||||
number `0`, but will allow flexibility within that value, even if the
|
|
||||||
major and minor versions are both `0`.
|
|
||||||
|
|
||||||
* `^1.2.x` := `>=1.2.0 <2.0.0`
|
|
||||||
* `^0.0.x` := `>=0.0.0 <0.1.0`
|
|
||||||
* `^0.0` := `>=0.0.0 <0.1.0`
|
|
||||||
|
|
||||||
A missing `minor` and `patch` values will desugar to zero, but also
|
|
||||||
allow flexibility within those values, even if the major version is
|
|
||||||
zero.
|
|
||||||
|
|
||||||
* `^1.x` := `>=1.0.0 <2.0.0`
|
|
||||||
* `^0.x` := `>=0.0.0 <1.0.0`
|
|
||||||
|
|
||||||
### Range Grammar
|
|
||||||
|
|
||||||
Putting all this together, here is a Backus-Naur grammar for ranges,
|
|
||||||
for the benefit of parser authors:
|
|
||||||
|
|
||||||
```bnf
|
|
||||||
range-set ::= range ( logical-or range ) *
|
|
||||||
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
|
|
||||||
range ::= hyphen | simple ( ' ' simple ) * | ''
|
|
||||||
hyphen ::= partial ' - ' partial
|
|
||||||
simple ::= primitive | partial | tilde | caret
|
|
||||||
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
|
|
||||||
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
|
|
||||||
xr ::= 'x' | 'X' | '*' | nr
|
|
||||||
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
|
|
||||||
tilde ::= '~' partial
|
|
||||||
caret ::= '^' partial
|
|
||||||
qualifier ::= ( '-' pre )? ( '+' build )?
|
|
||||||
pre ::= parts
|
|
||||||
build ::= parts
|
|
||||||
parts ::= part ( '.' part ) *
|
|
||||||
part ::= nr | [-0-9A-Za-z]+
|
|
||||||
```
|
|
||||||
|
|
||||||
## Functions
|
|
||||||
|
|
||||||
All methods and classes take a final `options` object argument. All
|
|
||||||
options in this object are `false` by default. The options supported
|
|
||||||
are:
|
|
||||||
|
|
||||||
- `loose` Be more forgiving about not-quite-valid semver strings.
|
|
||||||
(Any resulting output will always be 100% strict compliant, of
|
|
||||||
course.) For backwards compatibility reasons, if the `options`
|
|
||||||
argument is a boolean value instead of an object, it is interpreted
|
|
||||||
to be the `loose` param.
|
|
||||||
- `includePrerelease` Set to suppress the [default
|
|
||||||
behavior](https://github.com/npm/node-semver#prerelease-tags) of
|
|
||||||
excluding prerelease tagged versions from ranges unless they are
|
|
||||||
explicitly opted into.
|
|
||||||
|
|
||||||
Strict-mode Comparators and Ranges will be strict about the SemVer
|
|
||||||
strings that they parse.
|
|
||||||
|
|
||||||
* `valid(v)`: Return the parsed version, or null if it's not valid.
|
|
||||||
* `inc(v, release)`: Return the version incremented by the release
|
|
||||||
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
|
|
||||||
`prepatch`, or `prerelease`), or null if it's not valid
|
|
||||||
* `premajor` in one call will bump the version up to the next major
|
|
||||||
version and down to a prerelease of that major version.
|
|
||||||
`preminor`, and `prepatch` work the same way.
|
|
||||||
* If called from a non-prerelease version, the `prerelease` will work the
|
|
||||||
same as `prepatch`. It increments the patch version, then makes a
|
|
||||||
prerelease. If the input version is already a prerelease it simply
|
|
||||||
increments it.
|
|
||||||
* `prerelease(v)`: Returns an array of prerelease components, or null
|
|
||||||
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
|
|
||||||
* `major(v)`: Return the major version number.
|
|
||||||
* `minor(v)`: Return the minor version number.
|
|
||||||
* `patch(v)`: Return the patch version number.
|
|
||||||
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
|
|
||||||
or comparators intersect.
|
|
||||||
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
|
|
||||||
a `SemVer` object or `null`.
|
|
||||||
|
|
||||||
### Comparison
|
|
||||||
|
|
||||||
* `gt(v1, v2)`: `v1 > v2`
|
|
||||||
* `gte(v1, v2)`: `v1 >= v2`
|
|
||||||
* `lt(v1, v2)`: `v1 < v2`
|
|
||||||
* `lte(v1, v2)`: `v1 <= v2`
|
|
||||||
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
|
|
||||||
even if they're not the exact same string. You already know how to
|
|
||||||
compare strings.
|
|
||||||
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
|
|
||||||
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
|
|
||||||
the corresponding function above. `"==="` and `"!=="` do simple
|
|
||||||
string comparison, but are included for completeness. Throws if an
|
|
||||||
invalid comparison string is provided.
|
|
||||||
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
|
|
||||||
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
|
|
||||||
* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions
|
|
||||||
in descending order when passed to `Array.sort()`.
|
|
||||||
* `diff(v1, v2)`: Returns difference between two versions by the release type
|
|
||||||
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
|
|
||||||
or null if the versions are the same.
|
|
||||||
|
|
||||||
### Comparators
|
|
||||||
|
|
||||||
* `intersects(comparator)`: Return true if the comparators intersect
|
|
||||||
|
|
||||||
### Ranges
|
|
||||||
|
|
||||||
* `validRange(range)`: Return the valid range or null if it's not valid
|
|
||||||
* `satisfies(version, range)`: Return true if the version satisfies the
|
|
||||||
range.
|
|
||||||
* `maxSatisfying(versions, range)`: Return the highest version in the list
|
|
||||||
that satisfies the range, or `null` if none of them do.
|
|
||||||
* `minSatisfying(versions, range)`: Return the lowest version in the list
|
|
||||||
that satisfies the range, or `null` if none of them do.
|
|
||||||
* `minVersion(range)`: Return the lowest version that can possibly match
|
|
||||||
the given range.
|
|
||||||
* `gtr(version, range)`: Return `true` if version is greater than all the
|
|
||||||
versions possible in the range.
|
|
||||||
* `ltr(version, range)`: Return `true` if version is less than all the
|
|
||||||
versions possible in the range.
|
|
||||||
* `outside(version, range, hilo)`: Return true if the version is outside
|
|
||||||
the bounds of the range in either the high or low direction. The
|
|
||||||
`hilo` argument must be either the string `'>'` or `'<'`. (This is
|
|
||||||
the function called by `gtr` and `ltr`.)
|
|
||||||
* `intersects(range)`: Return true if any of the ranges comparators intersect
|
|
||||||
|
|
||||||
Note that, since ranges may be non-contiguous, a version might not be
|
|
||||||
greater than a range, less than a range, *or* satisfy a range! For
|
|
||||||
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
|
|
||||||
until `2.0.0`, so the version `1.2.10` would not be greater than the
|
|
||||||
range (because `2.0.1` satisfies, which is higher), nor less than the
|
|
||||||
range (since `1.2.8` satisfies, which is lower), and it also does not
|
|
||||||
satisfy the range.
|
|
||||||
|
|
||||||
If you want to know if a version satisfies or does not satisfy a
|
|
||||||
range, use the `satisfies(version, range)` function.
|
|
||||||
|
|
||||||
### Coercion
|
|
||||||
|
|
||||||
* `coerce(version)`: Coerces a string to semver if possible
|
|
||||||
|
|
||||||
This aims to provide a very forgiving translation of a non-semver
|
|
||||||
string to semver. It looks for the first digit in a string, and
|
|
||||||
consumes all remaining characters which satisfy at least a partial semver
|
|
||||||
(e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters).
|
|
||||||
Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`).
|
|
||||||
All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`).
|
|
||||||
Only text which lacks digits will fail coercion (`version one` is not valid).
|
|
||||||
The maximum length for any semver component considered for coercion is 16 characters;
|
|
||||||
longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`).
|
|
||||||
The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`;
|
|
||||||
higher value components are invalid (`9999999999999999.4.7.4` is likely invalid).
|
|
||||||
|
|
@ -1,160 +0,0 @@
|
||||||
#!/usr/bin/env node
|
|
||||||
// Standalone semver comparison program.
|
|
||||||
// Exits successfully and prints matching version(s) if
|
|
||||||
// any supplied version is valid and passes all tests.
|
|
||||||
|
|
||||||
var argv = process.argv.slice(2)
|
|
||||||
|
|
||||||
var versions = []
|
|
||||||
|
|
||||||
var range = []
|
|
||||||
|
|
||||||
var inc = null
|
|
||||||
|
|
||||||
var version = require('../package.json').version
|
|
||||||
|
|
||||||
var loose = false
|
|
||||||
|
|
||||||
var includePrerelease = false
|
|
||||||
|
|
||||||
var coerce = false
|
|
||||||
|
|
||||||
var identifier
|
|
||||||
|
|
||||||
var semver = require('../semver')
|
|
||||||
|
|
||||||
var reverse = false
|
|
||||||
|
|
||||||
var options = {}
|
|
||||||
|
|
||||||
main()
|
|
||||||
|
|
||||||
function main () {
|
|
||||||
if (!argv.length) return help()
|
|
||||||
while (argv.length) {
|
|
||||||
var a = argv.shift()
|
|
||||||
var indexOfEqualSign = a.indexOf('=')
|
|
||||||
if (indexOfEqualSign !== -1) {
|
|
||||||
a = a.slice(0, indexOfEqualSign)
|
|
||||||
argv.unshift(a.slice(indexOfEqualSign + 1))
|
|
||||||
}
|
|
||||||
switch (a) {
|
|
||||||
case '-rv': case '-rev': case '--rev': case '--reverse':
|
|
||||||
reverse = true
|
|
||||||
break
|
|
||||||
case '-l': case '--loose':
|
|
||||||
loose = true
|
|
||||||
break
|
|
||||||
case '-p': case '--include-prerelease':
|
|
||||||
includePrerelease = true
|
|
||||||
break
|
|
||||||
case '-v': case '--version':
|
|
||||||
versions.push(argv.shift())
|
|
||||||
break
|
|
||||||
case '-i': case '--inc': case '--increment':
|
|
||||||
switch (argv[0]) {
|
|
||||||
case 'major': case 'minor': case 'patch': case 'prerelease':
|
|
||||||
case 'premajor': case 'preminor': case 'prepatch':
|
|
||||||
inc = argv.shift()
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
inc = 'patch'
|
|
||||||
break
|
|
||||||
}
|
|
||||||
break
|
|
||||||
case '--preid':
|
|
||||||
identifier = argv.shift()
|
|
||||||
break
|
|
||||||
case '-r': case '--range':
|
|
||||||
range.push(argv.shift())
|
|
||||||
break
|
|
||||||
case '-c': case '--coerce':
|
|
||||||
coerce = true
|
|
||||||
break
|
|
||||||
case '-h': case '--help': case '-?':
|
|
||||||
return help()
|
|
||||||
default:
|
|
||||||
versions.push(a)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var options = { loose: loose, includePrerelease: includePrerelease }
|
|
||||||
|
|
||||||
versions = versions.map(function (v) {
|
|
||||||
return coerce ? (semver.coerce(v) || { version: v }).version : v
|
|
||||||
}).filter(function (v) {
|
|
||||||
return semver.valid(v)
|
|
||||||
})
|
|
||||||
if (!versions.length) return fail()
|
|
||||||
if (inc && (versions.length !== 1 || range.length)) { return failInc() }
|
|
||||||
|
|
||||||
for (var i = 0, l = range.length; i < l; i++) {
|
|
||||||
versions = versions.filter(function (v) {
|
|
||||||
return semver.satisfies(v, range[i], options)
|
|
||||||
})
|
|
||||||
if (!versions.length) return fail()
|
|
||||||
}
|
|
||||||
return success(versions)
|
|
||||||
}
|
|
||||||
|
|
||||||
function failInc () {
|
|
||||||
console.error('--inc can only be used on a single version with no range')
|
|
||||||
fail()
|
|
||||||
}
|
|
||||||
|
|
||||||
function fail () { process.exit(1) }
|
|
||||||
|
|
||||||
function success () {
|
|
||||||
var compare = reverse ? 'rcompare' : 'compare'
|
|
||||||
versions.sort(function (a, b) {
|
|
||||||
return semver[compare](a, b, options)
|
|
||||||
}).map(function (v) {
|
|
||||||
return semver.clean(v, options)
|
|
||||||
}).map(function (v) {
|
|
||||||
return inc ? semver.inc(v, inc, options, identifier) : v
|
|
||||||
}).forEach(function (v, i, _) { console.log(v) })
|
|
||||||
}
|
|
||||||
|
|
||||||
function help () {
|
|
||||||
console.log(['SemVer ' + version,
|
|
||||||
'',
|
|
||||||
'A JavaScript implementation of the https://semver.org/ specification',
|
|
||||||
'Copyright Isaac Z. Schlueter',
|
|
||||||
'',
|
|
||||||
'Usage: semver [options] <version> [<version> [...]]',
|
|
||||||
'Prints valid versions sorted by SemVer precedence',
|
|
||||||
'',
|
|
||||||
'Options:',
|
|
||||||
'-r --range <range>',
|
|
||||||
' Print versions that match the specified range.',
|
|
||||||
'',
|
|
||||||
'-i --increment [<level>]',
|
|
||||||
' Increment a version by the specified level. Level can',
|
|
||||||
' be one of: major, minor, patch, premajor, preminor,',
|
|
||||||
" prepatch, or prerelease. Default level is 'patch'.",
|
|
||||||
' Only one version may be specified.',
|
|
||||||
'',
|
|
||||||
'--preid <identifier>',
|
|
||||||
' Identifier to be used to prefix premajor, preminor,',
|
|
||||||
' prepatch or prerelease version increments.',
|
|
||||||
'',
|
|
||||||
'-l --loose',
|
|
||||||
' Interpret versions and ranges loosely',
|
|
||||||
'',
|
|
||||||
'-p --include-prerelease',
|
|
||||||
' Always include prerelease versions in range matching',
|
|
||||||
'',
|
|
||||||
'-c --coerce',
|
|
||||||
' Coerce a string into SemVer if possible',
|
|
||||||
' (does not imply --loose)',
|
|
||||||
'',
|
|
||||||
'Program exits successfully if any valid version satisfies',
|
|
||||||
'all supplied ranges, and prints all satisfying versions.',
|
|
||||||
'',
|
|
||||||
'If no satisfying versions are found, then exits failure.',
|
|
||||||
'',
|
|
||||||
'Versions are printed in ascending order, so supplying',
|
|
||||||
'multiple versions to the utility will just sort them.'
|
|
||||||
].join('\n'))
|
|
||||||
}
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"semver@5.7.0",
|
|
||||||
"/Users/eric/repos/actions/setup-node"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_development": true,
|
|
||||||
"_from": "semver@5.7.0",
|
|
||||||
"_id": "semver@5.7.0",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==",
|
|
||||||
"_location": "/@babel/core/semver",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "semver@5.7.0",
|
|
||||||
"name": "semver",
|
|
||||||
"escapedName": "semver",
|
|
||||||
"rawSpec": "5.7.0",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "5.7.0"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/@babel/core"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz",
|
|
||||||
"_spec": "5.7.0",
|
|
||||||
"_where": "/Users/eric/repos/actions/setup-node",
|
|
||||||
"bin": {
|
|
||||||
"semver": "./bin/semver"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/npm/node-semver/issues"
|
|
||||||
},
|
|
||||||
"description": "The semantic version parser used by npm.",
|
|
||||||
"devDependencies": {
|
|
||||||
"tap": "^13.0.0-rc.18"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"bin",
|
|
||||||
"range.bnf",
|
|
||||||
"semver.js"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/npm/node-semver#readme",
|
|
||||||
"license": "ISC",
|
|
||||||
"main": "semver.js",
|
|
||||||
"name": "semver",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/npm/node-semver.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"postpublish": "git push origin --all; git push origin --tags",
|
|
||||||
"postversion": "npm publish",
|
|
||||||
"preversion": "npm test",
|
|
||||||
"test": "tap"
|
|
||||||
},
|
|
||||||
"tap": {
|
|
||||||
"check-coverage": true
|
|
||||||
},
|
|
||||||
"version": "5.7.0"
|
|
||||||
}
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
range-set ::= range ( logical-or range ) *
|
|
||||||
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
|
|
||||||
range ::= hyphen | simple ( ' ' simple ) * | ''
|
|
||||||
hyphen ::= partial ' - ' partial
|
|
||||||
simple ::= primitive | partial | tilde | caret
|
|
||||||
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
|
|
||||||
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
|
|
||||||
xr ::= 'x' | 'X' | '*' | nr
|
|
||||||
nr ::= '0' | [1-9] ( [0-9] ) *
|
|
||||||
tilde ::= '~' partial
|
|
||||||
caret ::= '^' partial
|
|
||||||
qualifier ::= ( '-' pre )? ( '+' build )?
|
|
||||||
pre ::= parts
|
|
||||||
build ::= parts
|
|
||||||
parts ::= part ( '.' part ) *
|
|
||||||
part ::= nr | [-0-9A-Za-z]+
|
|
||||||
|
|
@ -1,1483 +0,0 @@
|
||||||
exports = module.exports = SemVer
|
|
||||||
|
|
||||||
var debug
|
|
||||||
/* istanbul ignore next */
|
|
||||||
if (typeof process === 'object' &&
|
|
||||||
process.env &&
|
|
||||||
process.env.NODE_DEBUG &&
|
|
||||||
/\bsemver\b/i.test(process.env.NODE_DEBUG)) {
|
|
||||||
debug = function () {
|
|
||||||
var args = Array.prototype.slice.call(arguments, 0)
|
|
||||||
args.unshift('SEMVER')
|
|
||||||
console.log.apply(console, args)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
debug = function () {}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Note: this is the semver.org version of the spec that it implements
|
|
||||||
// Not necessarily the package version of this code.
|
|
||||||
exports.SEMVER_SPEC_VERSION = '2.0.0'
|
|
||||||
|
|
||||||
var MAX_LENGTH = 256
|
|
||||||
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
|
|
||||||
/* istanbul ignore next */ 9007199254740991
|
|
||||||
|
|
||||||
// Max safe segment length for coercion.
|
|
||||||
var MAX_SAFE_COMPONENT_LENGTH = 16
|
|
||||||
|
|
||||||
// The actual regexps go on exports.re
|
|
||||||
var re = exports.re = []
|
|
||||||
var src = exports.src = []
|
|
||||||
var R = 0
|
|
||||||
|
|
||||||
// The following Regular Expressions can be used for tokenizing,
|
|
||||||
// validating, and parsing SemVer version strings.
|
|
||||||
|
|
||||||
// ## Numeric Identifier
|
|
||||||
// A single `0`, or a non-zero digit followed by zero or more digits.
|
|
||||||
|
|
||||||
var NUMERICIDENTIFIER = R++
|
|
||||||
src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'
|
|
||||||
var NUMERICIDENTIFIERLOOSE = R++
|
|
||||||
src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'
|
|
||||||
|
|
||||||
// ## Non-numeric Identifier
|
|
||||||
// Zero or more digits, followed by a letter or hyphen, and then zero or
|
|
||||||
// more letters, digits, or hyphens.
|
|
||||||
|
|
||||||
var NONNUMERICIDENTIFIER = R++
|
|
||||||
src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'
|
|
||||||
|
|
||||||
// ## Main Version
|
|
||||||
// Three dot-separated numeric identifiers.
|
|
||||||
|
|
||||||
var MAINVERSION = R++
|
|
||||||
src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' +
|
|
||||||
'(' + src[NUMERICIDENTIFIER] + ')\\.' +
|
|
||||||
'(' + src[NUMERICIDENTIFIER] + ')'
|
|
||||||
|
|
||||||
var MAINVERSIONLOOSE = R++
|
|
||||||
src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
|
|
||||||
'(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
|
|
||||||
'(' + src[NUMERICIDENTIFIERLOOSE] + ')'
|
|
||||||
|
|
||||||
// ## Pre-release Version Identifier
|
|
||||||
// A numeric identifier, or a non-numeric identifier.
|
|
||||||
|
|
||||||
var PRERELEASEIDENTIFIER = R++
|
|
||||||
src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +
|
|
||||||
'|' + src[NONNUMERICIDENTIFIER] + ')'
|
|
||||||
|
|
||||||
var PRERELEASEIDENTIFIERLOOSE = R++
|
|
||||||
src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +
|
|
||||||
'|' + src[NONNUMERICIDENTIFIER] + ')'
|
|
||||||
|
|
||||||
// ## Pre-release Version
|
|
||||||
// Hyphen, followed by one or more dot-separated pre-release version
|
|
||||||
// identifiers.
|
|
||||||
|
|
||||||
var PRERELEASE = R++
|
|
||||||
src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +
|
|
||||||
'(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'
|
|
||||||
|
|
||||||
var PRERELEASELOOSE = R++
|
|
||||||
src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +
|
|
||||||
'(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'
|
|
||||||
|
|
||||||
// ## Build Metadata Identifier
|
|
||||||
// Any combination of digits, letters, or hyphens.
|
|
||||||
|
|
||||||
var BUILDIDENTIFIER = R++
|
|
||||||
src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'
|
|
||||||
|
|
||||||
// ## Build Metadata
|
|
||||||
// Plus sign, followed by one or more period-separated build metadata
|
|
||||||
// identifiers.
|
|
||||||
|
|
||||||
var BUILD = R++
|
|
||||||
src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] +
|
|
||||||
'(?:\\.' + src[BUILDIDENTIFIER] + ')*))'
|
|
||||||
|
|
||||||
// ## Full Version String
|
|
||||||
// A main version, followed optionally by a pre-release version and
|
|
||||||
// build metadata.
|
|
||||||
|
|
||||||
// Note that the only major, minor, patch, and pre-release sections of
|
|
||||||
// the version string are capturing groups. The build metadata is not a
|
|
||||||
// capturing group, because it should not ever be used in version
|
|
||||||
// comparison.
|
|
||||||
|
|
||||||
var FULL = R++
|
|
||||||
var FULLPLAIN = 'v?' + src[MAINVERSION] +
|
|
||||||
src[PRERELEASE] + '?' +
|
|
||||||
src[BUILD] + '?'
|
|
||||||
|
|
||||||
src[FULL] = '^' + FULLPLAIN + '$'
|
|
||||||
|
|
||||||
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
|
|
||||||
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
|
|
||||||
// common in the npm registry.
|
|
||||||
var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] +
|
|
||||||
src[PRERELEASELOOSE] + '?' +
|
|
||||||
src[BUILD] + '?'
|
|
||||||
|
|
||||||
var LOOSE = R++
|
|
||||||
src[LOOSE] = '^' + LOOSEPLAIN + '$'
|
|
||||||
|
|
||||||
var GTLT = R++
|
|
||||||
src[GTLT] = '((?:<|>)?=?)'
|
|
||||||
|
|
||||||
// Something like "2.*" or "1.2.x".
|
|
||||||
// Note that "x.x" is a valid xRange identifer, meaning "any version"
|
|
||||||
// Only the first item is strictly required.
|
|
||||||
var XRANGEIDENTIFIERLOOSE = R++
|
|
||||||
src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'
|
|
||||||
var XRANGEIDENTIFIER = R++
|
|
||||||
src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'
|
|
||||||
|
|
||||||
var XRANGEPLAIN = R++
|
|
||||||
src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' +
|
|
||||||
'(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
|
|
||||||
'(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
|
|
||||||
'(?:' + src[PRERELEASE] + ')?' +
|
|
||||||
src[BUILD] + '?' +
|
|
||||||
')?)?'
|
|
||||||
|
|
||||||
var XRANGEPLAINLOOSE = R++
|
|
||||||
src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
|
|
||||||
'(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
|
|
||||||
'(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
|
|
||||||
'(?:' + src[PRERELEASELOOSE] + ')?' +
|
|
||||||
src[BUILD] + '?' +
|
|
||||||
')?)?'
|
|
||||||
|
|
||||||
var XRANGE = R++
|
|
||||||
src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'
|
|
||||||
var XRANGELOOSE = R++
|
|
||||||
src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'
|
|
||||||
|
|
||||||
// Coercion.
|
|
||||||
// Extract anything that could conceivably be a part of a valid semver
|
|
||||||
var COERCE = R++
|
|
||||||
src[COERCE] = '(?:^|[^\\d])' +
|
|
||||||
'(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
|
|
||||||
'(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
|
|
||||||
'(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
|
|
||||||
'(?:$|[^\\d])'
|
|
||||||
|
|
||||||
// Tilde ranges.
|
|
||||||
// Meaning is "reasonably at or greater than"
|
|
||||||
var LONETILDE = R++
|
|
||||||
src[LONETILDE] = '(?:~>?)'
|
|
||||||
|
|
||||||
var TILDETRIM = R++
|
|
||||||
src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'
|
|
||||||
re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g')
|
|
||||||
var tildeTrimReplace = '$1~'
|
|
||||||
|
|
||||||
var TILDE = R++
|
|
||||||
src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'
|
|
||||||
var TILDELOOSE = R++
|
|
||||||
src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'
|
|
||||||
|
|
||||||
// Caret ranges.
|
|
||||||
// Meaning is "at least and backwards compatible with"
|
|
||||||
var LONECARET = R++
|
|
||||||
src[LONECARET] = '(?:\\^)'
|
|
||||||
|
|
||||||
var CARETTRIM = R++
|
|
||||||
src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'
|
|
||||||
re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g')
|
|
||||||
var caretTrimReplace = '$1^'
|
|
||||||
|
|
||||||
var CARET = R++
|
|
||||||
src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'
|
|
||||||
var CARETLOOSE = R++
|
|
||||||
src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'
|
|
||||||
|
|
||||||
// A simple gt/lt/eq thing, or just "" to indicate "any version"
|
|
||||||
var COMPARATORLOOSE = R++
|
|
||||||
src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'
|
|
||||||
var COMPARATOR = R++
|
|
||||||
src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'
|
|
||||||
|
|
||||||
// An expression to strip any whitespace between the gtlt and the thing
|
|
||||||
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
|
|
||||||
var COMPARATORTRIM = R++
|
|
||||||
src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] +
|
|
||||||
'\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'
|
|
||||||
|
|
||||||
// this one has to use the /g flag
|
|
||||||
re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g')
|
|
||||||
var comparatorTrimReplace = '$1$2$3'
|
|
||||||
|
|
||||||
// Something like `1.2.3 - 1.2.4`
|
|
||||||
// Note that these all use the loose form, because they'll be
|
|
||||||
// checked against either the strict or loose comparator form
|
|
||||||
// later.
|
|
||||||
var HYPHENRANGE = R++
|
|
||||||
src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' +
|
|
||||||
'\\s+-\\s+' +
|
|
||||||
'(' + src[XRANGEPLAIN] + ')' +
|
|
||||||
'\\s*$'
|
|
||||||
|
|
||||||
var HYPHENRANGELOOSE = R++
|
|
||||||
src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' +
|
|
||||||
'\\s+-\\s+' +
|
|
||||||
'(' + src[XRANGEPLAINLOOSE] + ')' +
|
|
||||||
'\\s*$'
|
|
||||||
|
|
||||||
// Star ranges basically just allow anything at all.
|
|
||||||
var STAR = R++
|
|
||||||
src[STAR] = '(<|>)?=?\\s*\\*'
|
|
||||||
|
|
||||||
// Compile to actual regexp objects.
|
|
||||||
// All are flag-free, unless they were created above with a flag.
|
|
||||||
for (var i = 0; i < R; i++) {
|
|
||||||
debug(i, src[i])
|
|
||||||
if (!re[i]) {
|
|
||||||
re[i] = new RegExp(src[i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.parse = parse
|
|
||||||
function parse (version, options) {
|
|
||||||
if (!options || typeof options !== 'object') {
|
|
||||||
options = {
|
|
||||||
loose: !!options,
|
|
||||||
includePrerelease: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (version instanceof SemVer) {
|
|
||||||
return version
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof version !== 'string') {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (version.length > MAX_LENGTH) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
var r = options.loose ? re[LOOSE] : re[FULL]
|
|
||||||
if (!r.test(version)) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return new SemVer(version, options)
|
|
||||||
} catch (er) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.valid = valid
|
|
||||||
function valid (version, options) {
|
|
||||||
var v = parse(version, options)
|
|
||||||
return v ? v.version : null
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.clean = clean
|
|
||||||
function clean (version, options) {
|
|
||||||
var s = parse(version.trim().replace(/^[=v]+/, ''), options)
|
|
||||||
return s ? s.version : null
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.SemVer = SemVer
|
|
||||||
|
|
||||||
function SemVer (version, options) {
|
|
||||||
if (!options || typeof options !== 'object') {
|
|
||||||
options = {
|
|
||||||
loose: !!options,
|
|
||||||
includePrerelease: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (version instanceof SemVer) {
|
|
||||||
if (version.loose === options.loose) {
|
|
||||||
return version
|
|
||||||
} else {
|
|
||||||
version = version.version
|
|
||||||
}
|
|
||||||
} else if (typeof version !== 'string') {
|
|
||||||
throw new TypeError('Invalid Version: ' + version)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (version.length > MAX_LENGTH) {
|
|
||||||
throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!(this instanceof SemVer)) {
|
|
||||||
return new SemVer(version, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
debug('SemVer', version, options)
|
|
||||||
this.options = options
|
|
||||||
this.loose = !!options.loose
|
|
||||||
|
|
||||||
var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL])
|
|
||||||
|
|
||||||
if (!m) {
|
|
||||||
throw new TypeError('Invalid Version: ' + version)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.raw = version
|
|
||||||
|
|
||||||
// these are actually numbers
|
|
||||||
this.major = +m[1]
|
|
||||||
this.minor = +m[2]
|
|
||||||
this.patch = +m[3]
|
|
||||||
|
|
||||||
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
|
|
||||||
throw new TypeError('Invalid major version')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
|
|
||||||
throw new TypeError('Invalid minor version')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
|
|
||||||
throw new TypeError('Invalid patch version')
|
|
||||||
}
|
|
||||||
|
|
||||||
// numberify any prerelease numeric ids
|
|
||||||
if (!m[4]) {
|
|
||||||
this.prerelease = []
|
|
||||||
} else {
|
|
||||||
this.prerelease = m[4].split('.').map(function (id) {
|
|
||||||
if (/^[0-9]+$/.test(id)) {
|
|
||||||
var num = +id
|
|
||||||
if (num >= 0 && num < MAX_SAFE_INTEGER) {
|
|
||||||
return num
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return id
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
this.build = m[5] ? m[5].split('.') : []
|
|
||||||
this.format()
|
|
||||||
}
|
|
||||||
|
|
||||||
SemVer.prototype.format = function () {
|
|
||||||
this.version = this.major + '.' + this.minor + '.' + this.patch
|
|
||||||
if (this.prerelease.length) {
|
|
||||||
this.version += '-' + this.prerelease.join('.')
|
|
||||||
}
|
|
||||||
return this.version
|
|
||||||
}
|
|
||||||
|
|
||||||
SemVer.prototype.toString = function () {
|
|
||||||
return this.version
|
|
||||||
}
|
|
||||||
|
|
||||||
SemVer.prototype.compare = function (other) {
|
|
||||||
debug('SemVer.compare', this.version, this.options, other)
|
|
||||||
if (!(other instanceof SemVer)) {
|
|
||||||
other = new SemVer(other, this.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.compareMain(other) || this.comparePre(other)
|
|
||||||
}
|
|
||||||
|
|
||||||
SemVer.prototype.compareMain = function (other) {
|
|
||||||
if (!(other instanceof SemVer)) {
|
|
||||||
other = new SemVer(other, this.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return compareIdentifiers(this.major, other.major) ||
|
|
||||||
compareIdentifiers(this.minor, other.minor) ||
|
|
||||||
compareIdentifiers(this.patch, other.patch)
|
|
||||||
}
|
|
||||||
|
|
||||||
SemVer.prototype.comparePre = function (other) {
|
|
||||||
if (!(other instanceof SemVer)) {
|
|
||||||
other = new SemVer(other, this.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NOT having a prerelease is > having one
|
|
||||||
if (this.prerelease.length && !other.prerelease.length) {
|
|
||||||
return -1
|
|
||||||
} else if (!this.prerelease.length && other.prerelease.length) {
|
|
||||||
return 1
|
|
||||||
} else if (!this.prerelease.length && !other.prerelease.length) {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
var i = 0
|
|
||||||
do {
|
|
||||||
var a = this.prerelease[i]
|
|
||||||
var b = other.prerelease[i]
|
|
||||||
debug('prerelease compare', i, a, b)
|
|
||||||
if (a === undefined && b === undefined) {
|
|
||||||
return 0
|
|
||||||
} else if (b === undefined) {
|
|
||||||
return 1
|
|
||||||
} else if (a === undefined) {
|
|
||||||
return -1
|
|
||||||
} else if (a === b) {
|
|
||||||
continue
|
|
||||||
} else {
|
|
||||||
return compareIdentifiers(a, b)
|
|
||||||
}
|
|
||||||
} while (++i)
|
|
||||||
}
|
|
||||||
|
|
||||||
// preminor will bump the version up to the next minor release, and immediately
|
|
||||||
// down to pre-release. premajor and prepatch work the same way.
|
|
||||||
SemVer.prototype.inc = function (release, identifier) {
|
|
||||||
switch (release) {
|
|
||||||
case 'premajor':
|
|
||||||
this.prerelease.length = 0
|
|
||||||
this.patch = 0
|
|
||||||
this.minor = 0
|
|
||||||
this.major++
|
|
||||||
this.inc('pre', identifier)
|
|
||||||
break
|
|
||||||
case 'preminor':
|
|
||||||
this.prerelease.length = 0
|
|
||||||
this.patch = 0
|
|
||||||
this.minor++
|
|
||||||
this.inc('pre', identifier)
|
|
||||||
break
|
|
||||||
case 'prepatch':
|
|
||||||
// If this is already a prerelease, it will bump to the next version
|
|
||||||
// drop any prereleases that might already exist, since they are not
|
|
||||||
// relevant at this point.
|
|
||||||
this.prerelease.length = 0
|
|
||||||
this.inc('patch', identifier)
|
|
||||||
this.inc('pre', identifier)
|
|
||||||
break
|
|
||||||
// If the input is a non-prerelease version, this acts the same as
|
|
||||||
// prepatch.
|
|
||||||
case 'prerelease':
|
|
||||||
if (this.prerelease.length === 0) {
|
|
||||||
this.inc('patch', identifier)
|
|
||||||
}
|
|
||||||
this.inc('pre', identifier)
|
|
||||||
break
|
|
||||||
|
|
||||||
case 'major':
|
|
||||||
// If this is a pre-major version, bump up to the same major version.
|
|
||||||
// Otherwise increment major.
|
|
||||||
// 1.0.0-5 bumps to 1.0.0
|
|
||||||
// 1.1.0 bumps to 2.0.0
|
|
||||||
if (this.minor !== 0 ||
|
|
||||||
this.patch !== 0 ||
|
|
||||||
this.prerelease.length === 0) {
|
|
||||||
this.major++
|
|
||||||
}
|
|
||||||
this.minor = 0
|
|
||||||
this.patch = 0
|
|
||||||
this.prerelease = []
|
|
||||||
break
|
|
||||||
case 'minor':
|
|
||||||
// If this is a pre-minor version, bump up to the same minor version.
|
|
||||||
// Otherwise increment minor.
|
|
||||||
// 1.2.0-5 bumps to 1.2.0
|
|
||||||
// 1.2.1 bumps to 1.3.0
|
|
||||||
if (this.patch !== 0 || this.prerelease.length === 0) {
|
|
||||||
this.minor++
|
|
||||||
}
|
|
||||||
this.patch = 0
|
|
||||||
this.prerelease = []
|
|
||||||
break
|
|
||||||
case 'patch':
|
|
||||||
// If this is not a pre-release version, it will increment the patch.
|
|
||||||
// If it is a pre-release it will bump up to the same patch version.
|
|
||||||
// 1.2.0-5 patches to 1.2.0
|
|
||||||
// 1.2.0 patches to 1.2.1
|
|
||||||
if (this.prerelease.length === 0) {
|
|
||||||
this.patch++
|
|
||||||
}
|
|
||||||
this.prerelease = []
|
|
||||||
break
|
|
||||||
// This probably shouldn't be used publicly.
|
|
||||||
// 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
|
|
||||||
case 'pre':
|
|
||||||
if (this.prerelease.length === 0) {
|
|
||||||
this.prerelease = [0]
|
|
||||||
} else {
|
|
||||||
var i = this.prerelease.length
|
|
||||||
while (--i >= 0) {
|
|
||||||
if (typeof this.prerelease[i] === 'number') {
|
|
||||||
this.prerelease[i]++
|
|
||||||
i = -2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (i === -1) {
|
|
||||||
// didn't increment anything
|
|
||||||
this.prerelease.push(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (identifier) {
|
|
||||||
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
|
|
||||||
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
|
|
||||||
if (this.prerelease[0] === identifier) {
|
|
||||||
if (isNaN(this.prerelease[1])) {
|
|
||||||
this.prerelease = [identifier, 0]
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this.prerelease = [identifier, 0]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new Error('invalid increment argument: ' + release)
|
|
||||||
}
|
|
||||||
this.format()
|
|
||||||
this.raw = this.version
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.inc = inc
|
|
||||||
function inc (version, release, loose, identifier) {
|
|
||||||
if (typeof (loose) === 'string') {
|
|
||||||
identifier = loose
|
|
||||||
loose = undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
return new SemVer(version, loose).inc(release, identifier).version
|
|
||||||
} catch (er) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.diff = diff
|
|
||||||
function diff (version1, version2) {
|
|
||||||
if (eq(version1, version2)) {
|
|
||||||
return null
|
|
||||||
} else {
|
|
||||||
var v1 = parse(version1)
|
|
||||||
var v2 = parse(version2)
|
|
||||||
var prefix = ''
|
|
||||||
if (v1.prerelease.length || v2.prerelease.length) {
|
|
||||||
prefix = 'pre'
|
|
||||||
var defaultResult = 'prerelease'
|
|
||||||
}
|
|
||||||
for (var key in v1) {
|
|
||||||
if (key === 'major' || key === 'minor' || key === 'patch') {
|
|
||||||
if (v1[key] !== v2[key]) {
|
|
||||||
return prefix + key
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return defaultResult // may be undefined
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.compareIdentifiers = compareIdentifiers
|
|
||||||
|
|
||||||
var numeric = /^[0-9]+$/
|
|
||||||
function compareIdentifiers (a, b) {
|
|
||||||
var anum = numeric.test(a)
|
|
||||||
var bnum = numeric.test(b)
|
|
||||||
|
|
||||||
if (anum && bnum) {
|
|
||||||
a = +a
|
|
||||||
b = +b
|
|
||||||
}
|
|
||||||
|
|
||||||
return a === b ? 0
|
|
||||||
: (anum && !bnum) ? -1
|
|
||||||
: (bnum && !anum) ? 1
|
|
||||||
: a < b ? -1
|
|
||||||
: 1
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.rcompareIdentifiers = rcompareIdentifiers
|
|
||||||
function rcompareIdentifiers (a, b) {
|
|
||||||
return compareIdentifiers(b, a)
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.major = major
|
|
||||||
function major (a, loose) {
|
|
||||||
return new SemVer(a, loose).major
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.minor = minor
|
|
||||||
function minor (a, loose) {
|
|
||||||
return new SemVer(a, loose).minor
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.patch = patch
|
|
||||||
function patch (a, loose) {
|
|
||||||
return new SemVer(a, loose).patch
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.compare = compare
|
|
||||||
function compare (a, b, loose) {
|
|
||||||
return new SemVer(a, loose).compare(new SemVer(b, loose))
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.compareLoose = compareLoose
|
|
||||||
function compareLoose (a, b) {
|
|
||||||
return compare(a, b, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.rcompare = rcompare
|
|
||||||
function rcompare (a, b, loose) {
|
|
||||||
return compare(b, a, loose)
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.sort = sort
|
|
||||||
function sort (list, loose) {
|
|
||||||
return list.sort(function (a, b) {
|
|
||||||
return exports.compare(a, b, loose)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.rsort = rsort
|
|
||||||
function rsort (list, loose) {
|
|
||||||
return list.sort(function (a, b) {
|
|
||||||
return exports.rcompare(a, b, loose)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.gt = gt
|
|
||||||
function gt (a, b, loose) {
|
|
||||||
return compare(a, b, loose) > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.lt = lt
|
|
||||||
function lt (a, b, loose) {
|
|
||||||
return compare(a, b, loose) < 0
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.eq = eq
|
|
||||||
function eq (a, b, loose) {
|
|
||||||
return compare(a, b, loose) === 0
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.neq = neq
|
|
||||||
function neq (a, b, loose) {
|
|
||||||
return compare(a, b, loose) !== 0
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.gte = gte
|
|
||||||
function gte (a, b, loose) {
|
|
||||||
return compare(a, b, loose) >= 0
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.lte = lte
|
|
||||||
function lte (a, b, loose) {
|
|
||||||
return compare(a, b, loose) <= 0
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.cmp = cmp
|
|
||||||
function cmp (a, op, b, loose) {
|
|
||||||
switch (op) {
|
|
||||||
case '===':
|
|
||||||
if (typeof a === 'object')
|
|
||||||
a = a.version
|
|
||||||
if (typeof b === 'object')
|
|
||||||
b = b.version
|
|
||||||
return a === b
|
|
||||||
|
|
||||||
case '!==':
|
|
||||||
if (typeof a === 'object')
|
|
||||||
a = a.version
|
|
||||||
if (typeof b === 'object')
|
|
||||||
b = b.version
|
|
||||||
return a !== b
|
|
||||||
|
|
||||||
case '':
|
|
||||||
case '=':
|
|
||||||
case '==':
|
|
||||||
return eq(a, b, loose)
|
|
||||||
|
|
||||||
case '!=':
|
|
||||||
return neq(a, b, loose)
|
|
||||||
|
|
||||||
case '>':
|
|
||||||
return gt(a, b, loose)
|
|
||||||
|
|
||||||
case '>=':
|
|
||||||
return gte(a, b, loose)
|
|
||||||
|
|
||||||
case '<':
|
|
||||||
return lt(a, b, loose)
|
|
||||||
|
|
||||||
case '<=':
|
|
||||||
return lte(a, b, loose)
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new TypeError('Invalid operator: ' + op)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.Comparator = Comparator
|
|
||||||
function Comparator (comp, options) {
|
|
||||||
if (!options || typeof options !== 'object') {
|
|
||||||
options = {
|
|
||||||
loose: !!options,
|
|
||||||
includePrerelease: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (comp instanceof Comparator) {
|
|
||||||
if (comp.loose === !!options.loose) {
|
|
||||||
return comp
|
|
||||||
} else {
|
|
||||||
comp = comp.value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!(this instanceof Comparator)) {
|
|
||||||
return new Comparator(comp, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
debug('comparator', comp, options)
|
|
||||||
this.options = options
|
|
||||||
this.loose = !!options.loose
|
|
||||||
this.parse(comp)
|
|
||||||
|
|
||||||
if (this.semver === ANY) {
|
|
||||||
this.value = ''
|
|
||||||
} else {
|
|
||||||
this.value = this.operator + this.semver.version
|
|
||||||
}
|
|
||||||
|
|
||||||
debug('comp', this)
|
|
||||||
}
|
|
||||||
|
|
||||||
var ANY = {}
|
|
||||||
Comparator.prototype.parse = function (comp) {
|
|
||||||
var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]
|
|
||||||
var m = comp.match(r)
|
|
||||||
|
|
||||||
if (!m) {
|
|
||||||
throw new TypeError('Invalid comparator: ' + comp)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.operator = m[1]
|
|
||||||
if (this.operator === '=') {
|
|
||||||
this.operator = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
// if it literally is just '>' or '' then allow anything.
|
|
||||||
if (!m[2]) {
|
|
||||||
this.semver = ANY
|
|
||||||
} else {
|
|
||||||
this.semver = new SemVer(m[2], this.options.loose)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Comparator.prototype.toString = function () {
|
|
||||||
return this.value
|
|
||||||
}
|
|
||||||
|
|
||||||
Comparator.prototype.test = function (version) {
|
|
||||||
debug('Comparator.test', version, this.options.loose)
|
|
||||||
|
|
||||||
if (this.semver === ANY) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof version === 'string') {
|
|
||||||
version = new SemVer(version, this.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
return cmp(version, this.operator, this.semver, this.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
Comparator.prototype.intersects = function (comp, options) {
|
|
||||||
if (!(comp instanceof Comparator)) {
|
|
||||||
throw new TypeError('a Comparator is required')
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!options || typeof options !== 'object') {
|
|
||||||
options = {
|
|
||||||
loose: !!options,
|
|
||||||
includePrerelease: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var rangeTmp
|
|
||||||
|
|
||||||
if (this.operator === '') {
|
|
||||||
rangeTmp = new Range(comp.value, options)
|
|
||||||
return satisfies(this.value, rangeTmp, options)
|
|
||||||
} else if (comp.operator === '') {
|
|
||||||
rangeTmp = new Range(this.value, options)
|
|
||||||
return satisfies(comp.semver, rangeTmp, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
var sameDirectionIncreasing =
|
|
||||||
(this.operator === '>=' || this.operator === '>') &&
|
|
||||||
(comp.operator === '>=' || comp.operator === '>')
|
|
||||||
var sameDirectionDecreasing =
|
|
||||||
(this.operator === '<=' || this.operator === '<') &&
|
|
||||||
(comp.operator === '<=' || comp.operator === '<')
|
|
||||||
var sameSemVer = this.semver.version === comp.semver.version
|
|
||||||
var differentDirectionsInclusive =
|
|
||||||
(this.operator === '>=' || this.operator === '<=') &&
|
|
||||||
(comp.operator === '>=' || comp.operator === '<=')
|
|
||||||
var oppositeDirectionsLessThan =
|
|
||||||
cmp(this.semver, '<', comp.semver, options) &&
|
|
||||||
((this.operator === '>=' || this.operator === '>') &&
|
|
||||||
(comp.operator === '<=' || comp.operator === '<'))
|
|
||||||
var oppositeDirectionsGreaterThan =
|
|
||||||
cmp(this.semver, '>', comp.semver, options) &&
|
|
||||||
((this.operator === '<=' || this.operator === '<') &&
|
|
||||||
(comp.operator === '>=' || comp.operator === '>'))
|
|
||||||
|
|
||||||
return sameDirectionIncreasing || sameDirectionDecreasing ||
|
|
||||||
(sameSemVer && differentDirectionsInclusive) ||
|
|
||||||
oppositeDirectionsLessThan || oppositeDirectionsGreaterThan
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.Range = Range
|
|
||||||
function Range (range, options) {
|
|
||||||
if (!options || typeof options !== 'object') {
|
|
||||||
options = {
|
|
||||||
loose: !!options,
|
|
||||||
includePrerelease: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (range instanceof Range) {
|
|
||||||
if (range.loose === !!options.loose &&
|
|
||||||
range.includePrerelease === !!options.includePrerelease) {
|
|
||||||
return range
|
|
||||||
} else {
|
|
||||||
return new Range(range.raw, options)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (range instanceof Comparator) {
|
|
||||||
return new Range(range.value, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!(this instanceof Range)) {
|
|
||||||
return new Range(range, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.options = options
|
|
||||||
this.loose = !!options.loose
|
|
||||||
this.includePrerelease = !!options.includePrerelease
|
|
||||||
|
|
||||||
// First, split based on boolean or ||
|
|
||||||
this.raw = range
|
|
||||||
this.set = range.split(/\s*\|\|\s*/).map(function (range) {
|
|
||||||
return this.parseRange(range.trim())
|
|
||||||
}, this).filter(function (c) {
|
|
||||||
// throw out any that are not relevant for whatever reason
|
|
||||||
return c.length
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!this.set.length) {
|
|
||||||
throw new TypeError('Invalid SemVer Range: ' + range)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.format()
|
|
||||||
}
|
|
||||||
|
|
||||||
Range.prototype.format = function () {
|
|
||||||
this.range = this.set.map(function (comps) {
|
|
||||||
return comps.join(' ').trim()
|
|
||||||
}).join('||').trim()
|
|
||||||
return this.range
|
|
||||||
}
|
|
||||||
|
|
||||||
Range.prototype.toString = function () {
|
|
||||||
return this.range
|
|
||||||
}
|
|
||||||
|
|
||||||
Range.prototype.parseRange = function (range) {
|
|
||||||
var loose = this.options.loose
|
|
||||||
range = range.trim()
|
|
||||||
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
|
|
||||||
var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]
|
|
||||||
range = range.replace(hr, hyphenReplace)
|
|
||||||
debug('hyphen replace', range)
|
|
||||||
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
|
|
||||||
range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace)
|
|
||||||
debug('comparator trim', range, re[COMPARATORTRIM])
|
|
||||||
|
|
||||||
// `~ 1.2.3` => `~1.2.3`
|
|
||||||
range = range.replace(re[TILDETRIM], tildeTrimReplace)
|
|
||||||
|
|
||||||
// `^ 1.2.3` => `^1.2.3`
|
|
||||||
range = range.replace(re[CARETTRIM], caretTrimReplace)
|
|
||||||
|
|
||||||
// normalize spaces
|
|
||||||
range = range.split(/\s+/).join(' ')
|
|
||||||
|
|
||||||
// At this point, the range is completely trimmed and
|
|
||||||
// ready to be split into comparators.
|
|
||||||
|
|
||||||
var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]
|
|
||||||
var set = range.split(' ').map(function (comp) {
|
|
||||||
return parseComparator(comp, this.options)
|
|
||||||
}, this).join(' ').split(/\s+/)
|
|
||||||
if (this.options.loose) {
|
|
||||||
// in loose mode, throw out any that are not valid comparators
|
|
||||||
set = set.filter(function (comp) {
|
|
||||||
return !!comp.match(compRe)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
set = set.map(function (comp) {
|
|
||||||
return new Comparator(comp, this.options)
|
|
||||||
}, this)
|
|
||||||
|
|
||||||
return set
|
|
||||||
}
|
|
||||||
|
|
||||||
Range.prototype.intersects = function (range, options) {
|
|
||||||
if (!(range instanceof Range)) {
|
|
||||||
throw new TypeError('a Range is required')
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.set.some(function (thisComparators) {
|
|
||||||
return thisComparators.every(function (thisComparator) {
|
|
||||||
return range.set.some(function (rangeComparators) {
|
|
||||||
return rangeComparators.every(function (rangeComparator) {
|
|
||||||
return thisComparator.intersects(rangeComparator, options)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mostly just for testing and legacy API reasons
|
|
||||||
exports.toComparators = toComparators
|
|
||||||
function toComparators (range, options) {
|
|
||||||
return new Range(range, options).set.map(function (comp) {
|
|
||||||
return comp.map(function (c) {
|
|
||||||
return c.value
|
|
||||||
}).join(' ').trim().split(' ')
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// comprised of xranges, tildes, stars, and gtlt's at this point.
|
|
||||||
// already replaced the hyphen ranges
|
|
||||||
// turn into a set of JUST comparators.
|
|
||||||
function parseComparator (comp, options) {
|
|
||||||
debug('comp', comp, options)
|
|
||||||
comp = replaceCarets(comp, options)
|
|
||||||
debug('caret', comp)
|
|
||||||
comp = replaceTildes(comp, options)
|
|
||||||
debug('tildes', comp)
|
|
||||||
comp = replaceXRanges(comp, options)
|
|
||||||
debug('xrange', comp)
|
|
||||||
comp = replaceStars(comp, options)
|
|
||||||
debug('stars', comp)
|
|
||||||
return comp
|
|
||||||
}
|
|
||||||
|
|
||||||
function isX (id) {
|
|
||||||
return !id || id.toLowerCase() === 'x' || id === '*'
|
|
||||||
}
|
|
||||||
|
|
||||||
// ~, ~> --> * (any, kinda silly)
|
|
||||||
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
|
|
||||||
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
|
|
||||||
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
|
|
||||||
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
|
|
||||||
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
|
|
||||||
function replaceTildes (comp, options) {
|
|
||||||
return comp.trim().split(/\s+/).map(function (comp) {
|
|
||||||
return replaceTilde(comp, options)
|
|
||||||
}).join(' ')
|
|
||||||
}
|
|
||||||
|
|
||||||
function replaceTilde (comp, options) {
|
|
||||||
var r = options.loose ? re[TILDELOOSE] : re[TILDE]
|
|
||||||
return comp.replace(r, function (_, M, m, p, pr) {
|
|
||||||
debug('tilde', comp, _, M, m, p, pr)
|
|
||||||
var ret
|
|
||||||
|
|
||||||
if (isX(M)) {
|
|
||||||
ret = ''
|
|
||||||
} else if (isX(m)) {
|
|
||||||
ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'
|
|
||||||
} else if (isX(p)) {
|
|
||||||
// ~1.2 == >=1.2.0 <1.3.0
|
|
||||||
ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'
|
|
||||||
} else if (pr) {
|
|
||||||
debug('replaceTilde pr', pr)
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
|
|
||||||
' <' + M + '.' + (+m + 1) + '.0'
|
|
||||||
} else {
|
|
||||||
// ~1.2.3 == >=1.2.3 <1.3.0
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p +
|
|
||||||
' <' + M + '.' + (+m + 1) + '.0'
|
|
||||||
}
|
|
||||||
|
|
||||||
debug('tilde return', ret)
|
|
||||||
return ret
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ^ --> * (any, kinda silly)
|
|
||||||
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
|
|
||||||
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
|
|
||||||
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
|
|
||||||
// ^1.2.3 --> >=1.2.3 <2.0.0
|
|
||||||
// ^1.2.0 --> >=1.2.0 <2.0.0
|
|
||||||
function replaceCarets (comp, options) {
|
|
||||||
return comp.trim().split(/\s+/).map(function (comp) {
|
|
||||||
return replaceCaret(comp, options)
|
|
||||||
}).join(' ')
|
|
||||||
}
|
|
||||||
|
|
||||||
function replaceCaret (comp, options) {
|
|
||||||
debug('caret', comp, options)
|
|
||||||
var r = options.loose ? re[CARETLOOSE] : re[CARET]
|
|
||||||
return comp.replace(r, function (_, M, m, p, pr) {
|
|
||||||
debug('caret', comp, _, M, m, p, pr)
|
|
||||||
var ret
|
|
||||||
|
|
||||||
if (isX(M)) {
|
|
||||||
ret = ''
|
|
||||||
} else if (isX(m)) {
|
|
||||||
ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'
|
|
||||||
} else if (isX(p)) {
|
|
||||||
if (M === '0') {
|
|
||||||
ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'
|
|
||||||
} else {
|
|
||||||
ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'
|
|
||||||
}
|
|
||||||
} else if (pr) {
|
|
||||||
debug('replaceCaret pr', pr)
|
|
||||||
if (M === '0') {
|
|
||||||
if (m === '0') {
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
|
|
||||||
' <' + M + '.' + m + '.' + (+p + 1)
|
|
||||||
} else {
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
|
|
||||||
' <' + M + '.' + (+m + 1) + '.0'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
|
|
||||||
' <' + (+M + 1) + '.0.0'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
debug('no pr')
|
|
||||||
if (M === '0') {
|
|
||||||
if (m === '0') {
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p +
|
|
||||||
' <' + M + '.' + m + '.' + (+p + 1)
|
|
||||||
} else {
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p +
|
|
||||||
' <' + M + '.' + (+m + 1) + '.0'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ret = '>=' + M + '.' + m + '.' + p +
|
|
||||||
' <' + (+M + 1) + '.0.0'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
debug('caret return', ret)
|
|
||||||
return ret
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function replaceXRanges (comp, options) {
|
|
||||||
debug('replaceXRanges', comp, options)
|
|
||||||
return comp.split(/\s+/).map(function (comp) {
|
|
||||||
return replaceXRange(comp, options)
|
|
||||||
}).join(' ')
|
|
||||||
}
|
|
||||||
|
|
||||||
function replaceXRange (comp, options) {
|
|
||||||
comp = comp.trim()
|
|
||||||
var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]
|
|
||||||
return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
|
|
||||||
debug('xRange', comp, ret, gtlt, M, m, p, pr)
|
|
||||||
var xM = isX(M)
|
|
||||||
var xm = xM || isX(m)
|
|
||||||
var xp = xm || isX(p)
|
|
||||||
var anyX = xp
|
|
||||||
|
|
||||||
if (gtlt === '=' && anyX) {
|
|
||||||
gtlt = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
if (xM) {
|
|
||||||
if (gtlt === '>' || gtlt === '<') {
|
|
||||||
// nothing is allowed
|
|
||||||
ret = '<0.0.0'
|
|
||||||
} else {
|
|
||||||
// nothing is forbidden
|
|
||||||
ret = '*'
|
|
||||||
}
|
|
||||||
} else if (gtlt && anyX) {
|
|
||||||
// we know patch is an x, because we have any x at all.
|
|
||||||
// replace X with 0
|
|
||||||
if (xm) {
|
|
||||||
m = 0
|
|
||||||
}
|
|
||||||
p = 0
|
|
||||||
|
|
||||||
if (gtlt === '>') {
|
|
||||||
// >1 => >=2.0.0
|
|
||||||
// >1.2 => >=1.3.0
|
|
||||||
// >1.2.3 => >= 1.2.4
|
|
||||||
gtlt = '>='
|
|
||||||
if (xm) {
|
|
||||||
M = +M + 1
|
|
||||||
m = 0
|
|
||||||
p = 0
|
|
||||||
} else {
|
|
||||||
m = +m + 1
|
|
||||||
p = 0
|
|
||||||
}
|
|
||||||
} else if (gtlt === '<=') {
|
|
||||||
// <=0.7.x is actually <0.8.0, since any 0.7.x should
|
|
||||||
// pass. Similarly, <=7.x is actually <8.0.0, etc.
|
|
||||||
gtlt = '<'
|
|
||||||
if (xm) {
|
|
||||||
M = +M + 1
|
|
||||||
} else {
|
|
||||||
m = +m + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ret = gtlt + M + '.' + m + '.' + p
|
|
||||||
} else if (xm) {
|
|
||||||
ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'
|
|
||||||
} else if (xp) {
|
|
||||||
ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'
|
|
||||||
}
|
|
||||||
|
|
||||||
debug('xRange return', ret)
|
|
||||||
|
|
||||||
return ret
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Because * is AND-ed with everything else in the comparator,
|
|
||||||
// and '' means "any version", just remove the *s entirely.
|
|
||||||
function replaceStars (comp, options) {
|
|
||||||
debug('replaceStars', comp, options)
|
|
||||||
// Looseness is ignored here. star is always as loose as it gets!
|
|
||||||
return comp.trim().replace(re[STAR], '')
|
|
||||||
}
|
|
||||||
|
|
||||||
// This function is passed to string.replace(re[HYPHENRANGE])
|
|
||||||
// M, m, patch, prerelease, build
|
|
||||||
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
|
|
||||||
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
|
|
||||||
// 1.2 - 3.4 => >=1.2.0 <3.5.0
|
|
||||||
function hyphenReplace ($0,
|
|
||||||
from, fM, fm, fp, fpr, fb,
|
|
||||||
to, tM, tm, tp, tpr, tb) {
|
|
||||||
if (isX(fM)) {
|
|
||||||
from = ''
|
|
||||||
} else if (isX(fm)) {
|
|
||||||
from = '>=' + fM + '.0.0'
|
|
||||||
} else if (isX(fp)) {
|
|
||||||
from = '>=' + fM + '.' + fm + '.0'
|
|
||||||
} else {
|
|
||||||
from = '>=' + from
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isX(tM)) {
|
|
||||||
to = ''
|
|
||||||
} else if (isX(tm)) {
|
|
||||||
to = '<' + (+tM + 1) + '.0.0'
|
|
||||||
} else if (isX(tp)) {
|
|
||||||
to = '<' + tM + '.' + (+tm + 1) + '.0'
|
|
||||||
} else if (tpr) {
|
|
||||||
to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr
|
|
||||||
} else {
|
|
||||||
to = '<=' + to
|
|
||||||
}
|
|
||||||
|
|
||||||
return (from + ' ' + to).trim()
|
|
||||||
}
|
|
||||||
|
|
||||||
// if ANY of the sets match ALL of its comparators, then pass
|
|
||||||
Range.prototype.test = function (version) {
|
|
||||||
if (!version) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof version === 'string') {
|
|
||||||
version = new SemVer(version, this.options)
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var i = 0; i < this.set.length; i++) {
|
|
||||||
if (testSet(this.set[i], version, this.options)) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
function testSet (set, version, options) {
|
|
||||||
for (var i = 0; i < set.length; i++) {
|
|
||||||
if (!set[i].test(version)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (version.prerelease.length && !options.includePrerelease) {
|
|
||||||
// Find the set of versions that are allowed to have prereleases
|
|
||||||
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
|
|
||||||
// That should allow `1.2.3-pr.2` to pass.
|
|
||||||
// However, `1.2.4-alpha.notready` should NOT be allowed,
|
|
||||||
// even though it's within the range set by the comparators.
|
|
||||||
for (i = 0; i < set.length; i++) {
|
|
||||||
debug(set[i].semver)
|
|
||||||
if (set[i].semver === ANY) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (set[i].semver.prerelease.length > 0) {
|
|
||||||
var allowed = set[i].semver
|
|
||||||
if (allowed.major === version.major &&
|
|
||||||
allowed.minor === version.minor &&
|
|
||||||
allowed.patch === version.patch) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Version has a -pre, but it's not one of the ones we like.
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.satisfies = satisfies
|
|
||||||
function satisfies (version, range, options) {
|
|
||||||
try {
|
|
||||||
range = new Range(range, options)
|
|
||||||
} catch (er) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return range.test(version)
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.maxSatisfying = maxSatisfying
|
|
||||||
function maxSatisfying (versions, range, options) {
|
|
||||||
var max = null
|
|
||||||
var maxSV = null
|
|
||||||
try {
|
|
||||||
var rangeObj = new Range(range, options)
|
|
||||||
} catch (er) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
versions.forEach(function (v) {
|
|
||||||
if (rangeObj.test(v)) {
|
|
||||||
// satisfies(v, range, options)
|
|
||||||
if (!max || maxSV.compare(v) === -1) {
|
|
||||||
// compare(max, v, true)
|
|
||||||
max = v
|
|
||||||
maxSV = new SemVer(max, options)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.minSatisfying = minSatisfying
|
|
||||||
function minSatisfying (versions, range, options) {
|
|
||||||
var min = null
|
|
||||||
var minSV = null
|
|
||||||
try {
|
|
||||||
var rangeObj = new Range(range, options)
|
|
||||||
} catch (er) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
versions.forEach(function (v) {
|
|
||||||
if (rangeObj.test(v)) {
|
|
||||||
// satisfies(v, range, options)
|
|
||||||
if (!min || minSV.compare(v) === 1) {
|
|
||||||
// compare(min, v, true)
|
|
||||||
min = v
|
|
||||||
minSV = new SemVer(min, options)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return min
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.minVersion = minVersion
|
|
||||||
function minVersion (range, loose) {
|
|
||||||
range = new Range(range, loose)
|
|
||||||
|
|
||||||
var minver = new SemVer('0.0.0')
|
|
||||||
if (range.test(minver)) {
|
|
||||||
return minver
|
|
||||||
}
|
|
||||||
|
|
||||||
minver = new SemVer('0.0.0-0')
|
|
||||||
if (range.test(minver)) {
|
|
||||||
return minver
|
|
||||||
}
|
|
||||||
|
|
||||||
minver = null
|
|
||||||
for (var i = 0; i < range.set.length; ++i) {
|
|
||||||
var comparators = range.set[i]
|
|
||||||
|
|
||||||
comparators.forEach(function (comparator) {
|
|
||||||
// Clone to avoid manipulating the comparator's semver object.
|
|
||||||
var compver = new SemVer(comparator.semver.version)
|
|
||||||
switch (comparator.operator) {
|
|
||||||
case '>':
|
|
||||||
if (compver.prerelease.length === 0) {
|
|
||||||
compver.patch++
|
|
||||||
} else {
|
|
||||||
compver.prerelease.push(0)
|
|
||||||
}
|
|
||||||
compver.raw = compver.format()
|
|
||||||
/* fallthrough */
|
|
||||||
case '':
|
|
||||||
case '>=':
|
|
||||||
if (!minver || gt(minver, compver)) {
|
|
||||||
minver = compver
|
|
||||||
}
|
|
||||||
break
|
|
||||||
case '<':
|
|
||||||
case '<=':
|
|
||||||
/* Ignore maximum versions */
|
|
||||||
break
|
|
||||||
/* istanbul ignore next */
|
|
||||||
default:
|
|
||||||
throw new Error('Unexpected operation: ' + comparator.operator)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (minver && range.test(minver)) {
|
|
||||||
return minver
|
|
||||||
}
|
|
||||||
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.validRange = validRange
|
|
||||||
function validRange (range, options) {
|
|
||||||
try {
|
|
||||||
// Return '*' instead of '' so that truthiness works.
|
|
||||||
// This will throw if it's invalid anyway
|
|
||||||
return new Range(range, options).range || '*'
|
|
||||||
} catch (er) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine if version is less than all the versions possible in the range
|
|
||||||
exports.ltr = ltr
|
|
||||||
function ltr (version, range, options) {
|
|
||||||
return outside(version, range, '<', options)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine if version is greater than all the versions possible in the range.
|
|
||||||
exports.gtr = gtr
|
|
||||||
function gtr (version, range, options) {
|
|
||||||
return outside(version, range, '>', options)
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.outside = outside
|
|
||||||
function outside (version, range, hilo, options) {
|
|
||||||
version = new SemVer(version, options)
|
|
||||||
range = new Range(range, options)
|
|
||||||
|
|
||||||
var gtfn, ltefn, ltfn, comp, ecomp
|
|
||||||
switch (hilo) {
|
|
||||||
case '>':
|
|
||||||
gtfn = gt
|
|
||||||
ltefn = lte
|
|
||||||
ltfn = lt
|
|
||||||
comp = '>'
|
|
||||||
ecomp = '>='
|
|
||||||
break
|
|
||||||
case '<':
|
|
||||||
gtfn = lt
|
|
||||||
ltefn = gte
|
|
||||||
ltfn = gt
|
|
||||||
comp = '<'
|
|
||||||
ecomp = '<='
|
|
||||||
break
|
|
||||||
default:
|
|
||||||
throw new TypeError('Must provide a hilo val of "<" or ">"')
|
|
||||||
}
|
|
||||||
|
|
||||||
// If it satisifes the range it is not outside
|
|
||||||
if (satisfies(version, range, options)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// From now on, variable terms are as if we're in "gtr" mode.
|
|
||||||
// but note that everything is flipped for the "ltr" function.
|
|
||||||
|
|
||||||
for (var i = 0; i < range.set.length; ++i) {
|
|
||||||
var comparators = range.set[i]
|
|
||||||
|
|
||||||
var high = null
|
|
||||||
var low = null
|
|
||||||
|
|
||||||
comparators.forEach(function (comparator) {
|
|
||||||
if (comparator.semver === ANY) {
|
|
||||||
comparator = new Comparator('>=0.0.0')
|
|
||||||
}
|
|
||||||
high = high || comparator
|
|
||||||
low = low || comparator
|
|
||||||
if (gtfn(comparator.semver, high.semver, options)) {
|
|
||||||
high = comparator
|
|
||||||
} else if (ltfn(comparator.semver, low.semver, options)) {
|
|
||||||
low = comparator
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// If the edge version comparator has a operator then our version
|
|
||||||
// isn't outside it
|
|
||||||
if (high.operator === comp || high.operator === ecomp) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the lowest version comparator has an operator and our version
|
|
||||||
// is less than it then it isn't higher than the range
|
|
||||||
if ((!low.operator || low.operator === comp) &&
|
|
||||||
ltefn(version, low.semver)) {
|
|
||||||
return false
|
|
||||||
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.prerelease = prerelease
|
|
||||||
function prerelease (version, options) {
|
|
||||||
var parsed = parse(version, options)
|
|
||||||
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.intersects = intersects
|
|
||||||
function intersects (r1, r2, options) {
|
|
||||||
r1 = new Range(r1, options)
|
|
||||||
r2 = new Range(r2, options)
|
|
||||||
return r1.intersects(r2)
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.coerce = coerce
|
|
||||||
function coerce (version) {
|
|
||||||
if (version instanceof SemVer) {
|
|
||||||
return version
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof version !== 'string') {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
var match = version.match(re[COERCE])
|
|
||||||
|
|
||||||
if (match == null) {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
return parse(match[1] +
|
|
||||||
'.' + (match[2] || '0') +
|
|
||||||
'.' + (match[3] || '0'))
|
|
||||||
}
|
|
||||||
|
|
@ -1,301 +0,0 @@
|
||||||
# Change Log
|
|
||||||
|
|
||||||
## 0.5.6
|
|
||||||
|
|
||||||
* Fix for regression when people were using numbers as names in source maps. See
|
|
||||||
#236.
|
|
||||||
|
|
||||||
## 0.5.5
|
|
||||||
|
|
||||||
* Fix "regression" of unsupported, implementation behavior that half the world
|
|
||||||
happens to have come to depend on. See #235.
|
|
||||||
|
|
||||||
* Fix regression involving function hoisting in SpiderMonkey. See #233.
|
|
||||||
|
|
||||||
## 0.5.4
|
|
||||||
|
|
||||||
* Large performance improvements to source-map serialization. See #228 and #229.
|
|
||||||
|
|
||||||
## 0.5.3
|
|
||||||
|
|
||||||
* Do not include unnecessary distribution files. See
|
|
||||||
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
|
|
||||||
|
|
||||||
## 0.5.2
|
|
||||||
|
|
||||||
* Include browser distributions of the library in package.json's `files`. See
|
|
||||||
issue #212.
|
|
||||||
|
|
||||||
## 0.5.1
|
|
||||||
|
|
||||||
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
|
|
||||||
ff05274becc9e6e1295ed60f3ea090d31d843379.
|
|
||||||
|
|
||||||
## 0.5.0
|
|
||||||
|
|
||||||
* Node 0.8 is no longer supported.
|
|
||||||
|
|
||||||
* Use webpack instead of dryice for bundling.
|
|
||||||
|
|
||||||
* Big speedups serializing source maps. See pull request #203.
|
|
||||||
|
|
||||||
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
|
|
||||||
explicitly start with the source root. See issue #199.
|
|
||||||
|
|
||||||
## 0.4.4
|
|
||||||
|
|
||||||
* Fix an issue where using a `SourceMapGenerator` after having created a
|
|
||||||
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
|
|
||||||
issue #191.
|
|
||||||
|
|
||||||
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
|
|
||||||
different mappings as duplicates of each other and avoid generating them. See
|
|
||||||
issue #192.
|
|
||||||
|
|
||||||
## 0.4.3
|
|
||||||
|
|
||||||
* A very large number of performance improvements, particularly when parsing
|
|
||||||
source maps. Collectively about 75% of time shaved off of the source map
|
|
||||||
parsing benchmark!
|
|
||||||
|
|
||||||
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
|
|
||||||
searching in the presence of a column option. See issue #177.
|
|
||||||
|
|
||||||
* Fix a bug with joining a source and its source root when the source is above
|
|
||||||
the root. See issue #182.
|
|
||||||
|
|
||||||
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
|
|
||||||
determine when all sources' contents are inlined into the source map. See
|
|
||||||
issue #190.
|
|
||||||
|
|
||||||
## 0.4.2
|
|
||||||
|
|
||||||
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
|
|
||||||
dependent projects. Issue #169.
|
|
||||||
|
|
||||||
* Add an optional `column` argument to
|
|
||||||
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
|
|
||||||
with no mappings. Issues #172 and #173.
|
|
||||||
|
|
||||||
## 0.4.1
|
|
||||||
|
|
||||||
* Fix accidentally defining a global variable. #170.
|
|
||||||
|
|
||||||
## 0.4.0
|
|
||||||
|
|
||||||
* The default direction for fuzzy searching was changed back to its original
|
|
||||||
direction. See #164.
|
|
||||||
|
|
||||||
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
|
|
||||||
the fuzzy searching direction. See #167.
|
|
||||||
|
|
||||||
* About an 8% speed up in parsing source maps. See #159.
|
|
||||||
|
|
||||||
* Added a benchmark for parsing and generating source maps.
|
|
||||||
|
|
||||||
## 0.3.0
|
|
||||||
|
|
||||||
* Change the default direction that searching for positions fuzzes when there is
|
|
||||||
not an exact match. See #154.
|
|
||||||
|
|
||||||
* Support for environments using json2.js for JSON serialization. See #156.
|
|
||||||
|
|
||||||
## 0.2.0
|
|
||||||
|
|
||||||
* Support for consuming "indexed" source maps which do not have any remote
|
|
||||||
sections. See pull request #127. This introduces a minor backwards
|
|
||||||
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
|
|
||||||
methods.
|
|
||||||
|
|
||||||
## 0.1.43
|
|
||||||
|
|
||||||
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
|
|
||||||
#148 for some discussion and issues #150, #151, and #152 for implementations.
|
|
||||||
|
|
||||||
## 0.1.42
|
|
||||||
|
|
||||||
* Fix an issue where `SourceNode`s from different versions of the source-map
|
|
||||||
library couldn't be used in conjunction with each other. See issue #142.
|
|
||||||
|
|
||||||
## 0.1.41
|
|
||||||
|
|
||||||
* Fix a bug with getting the source content of relative sources with a "./"
|
|
||||||
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
|
|
||||||
|
|
||||||
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
|
|
||||||
column span of each mapping.
|
|
||||||
|
|
||||||
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
|
|
||||||
all generated positions associated with a given original source and line.
|
|
||||||
|
|
||||||
## 0.1.40
|
|
||||||
|
|
||||||
* Performance improvements for parsing source maps in SourceMapConsumer.
|
|
||||||
|
|
||||||
## 0.1.39
|
|
||||||
|
|
||||||
* Fix a bug where setting a source's contents to null before any source content
|
|
||||||
had been set before threw a TypeError. See issue #131.
|
|
||||||
|
|
||||||
## 0.1.38
|
|
||||||
|
|
||||||
* Fix a bug where finding relative paths from an empty path were creating
|
|
||||||
absolute paths. See issue #129.
|
|
||||||
|
|
||||||
## 0.1.37
|
|
||||||
|
|
||||||
* Fix a bug where if the source root was an empty string, relative source paths
|
|
||||||
would turn into absolute source paths. Issue #124.
|
|
||||||
|
|
||||||
## 0.1.36
|
|
||||||
|
|
||||||
* Allow the `names` mapping property to be an empty string. Issue #121.
|
|
||||||
|
|
||||||
## 0.1.35
|
|
||||||
|
|
||||||
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
|
|
||||||
to specify a path that relative sources in the second parameter should be
|
|
||||||
relative to. Issue #105.
|
|
||||||
|
|
||||||
* If no file property is given to a `SourceMapGenerator`, then the resulting
|
|
||||||
source map will no longer have a `null` file property. The property will
|
|
||||||
simply not exist. Issue #104.
|
|
||||||
|
|
||||||
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
|
|
||||||
Issue #116.
|
|
||||||
|
|
||||||
## 0.1.34
|
|
||||||
|
|
||||||
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
|
|
||||||
|
|
||||||
* Fix bug involving source contents and the
|
|
||||||
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
|
|
||||||
|
|
||||||
## 0.1.33
|
|
||||||
|
|
||||||
* Fix some edge cases surrounding path joining and URL resolution.
|
|
||||||
|
|
||||||
* Add a third parameter for relative path to
|
|
||||||
`SourceMapGenerator.prototype.applySourceMap`.
|
|
||||||
|
|
||||||
* Fix issues with mappings and EOLs.
|
|
||||||
|
|
||||||
## 0.1.32
|
|
||||||
|
|
||||||
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
|
|
||||||
(issue 92).
|
|
||||||
|
|
||||||
* Fixed test runner to actually report number of failed tests as its process
|
|
||||||
exit code.
|
|
||||||
|
|
||||||
* Fixed a typo when reporting bad mappings (issue 87).
|
|
||||||
|
|
||||||
## 0.1.31
|
|
||||||
|
|
||||||
* Delay parsing the mappings in SourceMapConsumer until queried for a source
|
|
||||||
location.
|
|
||||||
|
|
||||||
* Support Sass source maps (which at the time of writing deviate from the spec
|
|
||||||
in small ways) in SourceMapConsumer.
|
|
||||||
|
|
||||||
## 0.1.30
|
|
||||||
|
|
||||||
* Do not join source root with a source, when the source is a data URI.
|
|
||||||
|
|
||||||
* Extend the test runner to allow running single specific test files at a time.
|
|
||||||
|
|
||||||
* Performance improvements in `SourceNode.prototype.walk` and
|
|
||||||
`SourceMapConsumer.prototype.eachMapping`.
|
|
||||||
|
|
||||||
* Source map browser builds will now work inside Workers.
|
|
||||||
|
|
||||||
* Better error messages when attempting to add an invalid mapping to a
|
|
||||||
`SourceMapGenerator`.
|
|
||||||
|
|
||||||
## 0.1.29
|
|
||||||
|
|
||||||
* Allow duplicate entries in the `names` and `sources` arrays of source maps
|
|
||||||
(usually from TypeScript) we are parsing. Fixes github issue 72.
|
|
||||||
|
|
||||||
## 0.1.28
|
|
||||||
|
|
||||||
* Skip duplicate mappings when creating source maps from SourceNode; github
|
|
||||||
issue 75.
|
|
||||||
|
|
||||||
## 0.1.27
|
|
||||||
|
|
||||||
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
|
|
||||||
we don't use it anyway.
|
|
||||||
|
|
||||||
## 0.1.26
|
|
||||||
|
|
||||||
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
|
|
||||||
|
|
||||||
## 0.1.25
|
|
||||||
|
|
||||||
* Make compatible with browserify
|
|
||||||
|
|
||||||
## 0.1.24
|
|
||||||
|
|
||||||
* Fix issue with absolute paths and `file://` URIs. See
|
|
||||||
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
|
|
||||||
|
|
||||||
## 0.1.23
|
|
||||||
|
|
||||||
* Fix issue with absolute paths and sourcesContent, github issue 64.
|
|
||||||
|
|
||||||
## 0.1.22
|
|
||||||
|
|
||||||
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
|
|
||||||
|
|
||||||
## 0.1.21
|
|
||||||
|
|
||||||
* Fixed handling of sources that start with a slash so that they are relative to
|
|
||||||
the source root's host.
|
|
||||||
|
|
||||||
## 0.1.20
|
|
||||||
|
|
||||||
* Fixed github issue #43: absolute URLs aren't joined with the source root
|
|
||||||
anymore.
|
|
||||||
|
|
||||||
## 0.1.19
|
|
||||||
|
|
||||||
* Using Travis CI to run tests.
|
|
||||||
|
|
||||||
## 0.1.18
|
|
||||||
|
|
||||||
* Fixed a bug in the handling of sourceRoot.
|
|
||||||
|
|
||||||
## 0.1.17
|
|
||||||
|
|
||||||
* Added SourceNode.fromStringWithSourceMap.
|
|
||||||
|
|
||||||
## 0.1.16
|
|
||||||
|
|
||||||
* Added missing documentation.
|
|
||||||
|
|
||||||
* Fixed the generating of empty mappings in SourceNode.
|
|
||||||
|
|
||||||
## 0.1.15
|
|
||||||
|
|
||||||
* Added SourceMapGenerator.applySourceMap.
|
|
||||||
|
|
||||||
## 0.1.14
|
|
||||||
|
|
||||||
* The sourceRoot is now handled consistently.
|
|
||||||
|
|
||||||
## 0.1.13
|
|
||||||
|
|
||||||
* Added SourceMapGenerator.fromSourceMap.
|
|
||||||
|
|
||||||
## 0.1.12
|
|
||||||
|
|
||||||
* SourceNode now generates empty mappings too.
|
|
||||||
|
|
||||||
## 0.1.11
|
|
||||||
|
|
||||||
* Added name support to SourceNode.
|
|
||||||
|
|
||||||
## 0.1.10
|
|
||||||
|
|
||||||
* Added sourcesContent support to the customer and generator.
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
|
|
||||||
Copyright (c) 2009-2011, Mozilla Foundation and contributors
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
* Redistributions of source code must retain the above copyright notice, this
|
|
||||||
list of conditions and the following disclaimer.
|
|
||||||
|
|
||||||
* Redistributions in binary form must reproduce the above copyright notice,
|
|
||||||
this list of conditions and the following disclaimer in the documentation
|
|
||||||
and/or other materials provided with the distribution.
|
|
||||||
|
|
||||||
* Neither the names of the Mozilla Foundation nor the names of project
|
|
||||||
contributors may be used to endorse or promote products derived from this
|
|
||||||
software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
||||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
||||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
||||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
||||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
||||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
||||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
||||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
||||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
@ -1,729 +0,0 @@
|
||||||
# Source Map
|
|
||||||
|
|
||||||
[](https://travis-ci.org/mozilla/source-map)
|
|
||||||
|
|
||||||
[](https://www.npmjs.com/package/source-map)
|
|
||||||
|
|
||||||
This is a library to generate and consume the source map format
|
|
||||||
[described here][format].
|
|
||||||
|
|
||||||
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
|
|
||||||
|
|
||||||
## Use with Node
|
|
||||||
|
|
||||||
$ npm install source-map
|
|
||||||
|
|
||||||
## Use on the Web
|
|
||||||
|
|
||||||
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
<!-- `npm run toc` to regenerate the Table of Contents -->
|
|
||||||
|
|
||||||
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
|
|
||||||
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
|
|
||||||
## Table of Contents
|
|
||||||
|
|
||||||
- [Examples](#examples)
|
|
||||||
- [Consuming a source map](#consuming-a-source-map)
|
|
||||||
- [Generating a source map](#generating-a-source-map)
|
|
||||||
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
|
|
||||||
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
|
|
||||||
- [API](#api)
|
|
||||||
- [SourceMapConsumer](#sourcemapconsumer)
|
|
||||||
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
|
|
||||||
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
|
|
||||||
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
|
|
||||||
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
|
|
||||||
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
|
|
||||||
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
|
|
||||||
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
|
|
||||||
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
|
|
||||||
- [SourceMapGenerator](#sourcemapgenerator)
|
|
||||||
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
|
|
||||||
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
|
|
||||||
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
|
|
||||||
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
|
|
||||||
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
|
|
||||||
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
|
|
||||||
- [SourceNode](#sourcenode)
|
|
||||||
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
|
|
||||||
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
|
|
||||||
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
|
|
||||||
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
|
|
||||||
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
|
|
||||||
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
|
|
||||||
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
|
|
||||||
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
|
|
||||||
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
|
|
||||||
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
|
|
||||||
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
|
|
||||||
|
|
||||||
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
### Consuming a source map
|
|
||||||
|
|
||||||
```js
|
|
||||||
var rawSourceMap = {
|
|
||||||
version: 3,
|
|
||||||
file: 'min.js',
|
|
||||||
names: ['bar', 'baz', 'n'],
|
|
||||||
sources: ['one.js', 'two.js'],
|
|
||||||
sourceRoot: 'http://example.com/www/js/',
|
|
||||||
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
|
|
||||||
};
|
|
||||||
|
|
||||||
var smc = new SourceMapConsumer(rawSourceMap);
|
|
||||||
|
|
||||||
console.log(smc.sources);
|
|
||||||
// [ 'http://example.com/www/js/one.js',
|
|
||||||
// 'http://example.com/www/js/two.js' ]
|
|
||||||
|
|
||||||
console.log(smc.originalPositionFor({
|
|
||||||
line: 2,
|
|
||||||
column: 28
|
|
||||||
}));
|
|
||||||
// { source: 'http://example.com/www/js/two.js',
|
|
||||||
// line: 2,
|
|
||||||
// column: 10,
|
|
||||||
// name: 'n' }
|
|
||||||
|
|
||||||
console.log(smc.generatedPositionFor({
|
|
||||||
source: 'http://example.com/www/js/two.js',
|
|
||||||
line: 2,
|
|
||||||
column: 10
|
|
||||||
}));
|
|
||||||
// { line: 2, column: 28 }
|
|
||||||
|
|
||||||
smc.eachMapping(function (m) {
|
|
||||||
// ...
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Generating a source map
|
|
||||||
|
|
||||||
In depth guide:
|
|
||||||
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
|
|
||||||
|
|
||||||
#### With SourceNode (high level API)
|
|
||||||
|
|
||||||
```js
|
|
||||||
function compile(ast) {
|
|
||||||
switch (ast.type) {
|
|
||||||
case 'BinaryExpression':
|
|
||||||
return new SourceNode(
|
|
||||||
ast.location.line,
|
|
||||||
ast.location.column,
|
|
||||||
ast.location.source,
|
|
||||||
[compile(ast.left), " + ", compile(ast.right)]
|
|
||||||
);
|
|
||||||
case 'Literal':
|
|
||||||
return new SourceNode(
|
|
||||||
ast.location.line,
|
|
||||||
ast.location.column,
|
|
||||||
ast.location.source,
|
|
||||||
String(ast.value)
|
|
||||||
);
|
|
||||||
// ...
|
|
||||||
default:
|
|
||||||
throw new Error("Bad AST");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var ast = parse("40 + 2", "add.js");
|
|
||||||
console.log(compile(ast).toStringWithSourceMap({
|
|
||||||
file: 'add.js'
|
|
||||||
}));
|
|
||||||
// { code: '40 + 2',
|
|
||||||
// map: [object SourceMapGenerator] }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### With SourceMapGenerator (low level API)
|
|
||||||
|
|
||||||
```js
|
|
||||||
var map = new SourceMapGenerator({
|
|
||||||
file: "source-mapped.js"
|
|
||||||
});
|
|
||||||
|
|
||||||
map.addMapping({
|
|
||||||
generated: {
|
|
||||||
line: 10,
|
|
||||||
column: 35
|
|
||||||
},
|
|
||||||
source: "foo.js",
|
|
||||||
original: {
|
|
||||||
line: 33,
|
|
||||||
column: 2
|
|
||||||
},
|
|
||||||
name: "christopher"
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(map.toString());
|
|
||||||
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
|
|
||||||
```
|
|
||||||
|
|
||||||
## API
|
|
||||||
|
|
||||||
Get a reference to the module:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// Node.js
|
|
||||||
var sourceMap = require('source-map');
|
|
||||||
|
|
||||||
// Browser builds
|
|
||||||
var sourceMap = window.sourceMap;
|
|
||||||
|
|
||||||
// Inside Firefox
|
|
||||||
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
|
|
||||||
```
|
|
||||||
|
|
||||||
### SourceMapConsumer
|
|
||||||
|
|
||||||
A SourceMapConsumer instance represents a parsed source map which we can query
|
|
||||||
for information about the original file positions by giving it a file position
|
|
||||||
in the generated source.
|
|
||||||
|
|
||||||
#### new SourceMapConsumer(rawSourceMap)
|
|
||||||
|
|
||||||
The only parameter is the raw source map (either as a string which can be
|
|
||||||
`JSON.parse`'d, or an object). According to the spec, source maps have the
|
|
||||||
following attributes:
|
|
||||||
|
|
||||||
* `version`: Which version of the source map spec this map is following.
|
|
||||||
|
|
||||||
* `sources`: An array of URLs to the original source files.
|
|
||||||
|
|
||||||
* `names`: An array of identifiers which can be referenced by individual
|
|
||||||
mappings.
|
|
||||||
|
|
||||||
* `sourceRoot`: Optional. The URL root from which all sources are relative.
|
|
||||||
|
|
||||||
* `sourcesContent`: Optional. An array of contents of the original source files.
|
|
||||||
|
|
||||||
* `mappings`: A string of base64 VLQs which contain the actual mappings.
|
|
||||||
|
|
||||||
* `file`: Optional. The generated filename this source map is associated with.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.computeColumnSpans()
|
|
||||||
|
|
||||||
Compute the last column for each generated mapping. The last column is
|
|
||||||
inclusive.
|
|
||||||
|
|
||||||
```js
|
|
||||||
// Before:
|
|
||||||
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
|
|
||||||
// [ { line: 2,
|
|
||||||
// column: 1 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 10 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 20 } ]
|
|
||||||
|
|
||||||
consumer.computeColumnSpans();
|
|
||||||
|
|
||||||
// After:
|
|
||||||
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
|
|
||||||
// [ { line: 2,
|
|
||||||
// column: 1,
|
|
||||||
// lastColumn: 9 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 10,
|
|
||||||
// lastColumn: 19 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 20,
|
|
||||||
// lastColumn: Infinity } ]
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
|
|
||||||
|
|
||||||
Returns the original source, line, and column information for the generated
|
|
||||||
source's line and column positions provided. The only argument is an object with
|
|
||||||
the following properties:
|
|
||||||
|
|
||||||
* `line`: The line number in the generated source.
|
|
||||||
|
|
||||||
* `column`: The column number in the generated source.
|
|
||||||
|
|
||||||
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
|
|
||||||
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
|
|
||||||
element that is smaller than or greater than the one we are searching for,
|
|
||||||
respectively, if the exact element cannot be found. Defaults to
|
|
||||||
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
|
|
||||||
|
|
||||||
and an object is returned with the following properties:
|
|
||||||
|
|
||||||
* `source`: The original source file, or null if this information is not
|
|
||||||
available.
|
|
||||||
|
|
||||||
* `line`: The line number in the original source, or null if this information is
|
|
||||||
not available.
|
|
||||||
|
|
||||||
* `column`: The column number in the original source, or null if this
|
|
||||||
information is not available.
|
|
||||||
|
|
||||||
* `name`: The original identifier, or null if this information is not available.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.originalPositionFor({ line: 2, column: 10 })
|
|
||||||
// { source: 'foo.coffee',
|
|
||||||
// line: 2,
|
|
||||||
// column: 2,
|
|
||||||
// name: null }
|
|
||||||
|
|
||||||
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
|
|
||||||
// { source: null,
|
|
||||||
// line: null,
|
|
||||||
// column: null,
|
|
||||||
// name: null }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
|
|
||||||
|
|
||||||
Returns the generated line and column information for the original source,
|
|
||||||
line, and column positions provided. The only argument is an object with
|
|
||||||
the following properties:
|
|
||||||
|
|
||||||
* `source`: The filename of the original source.
|
|
||||||
|
|
||||||
* `line`: The line number in the original source.
|
|
||||||
|
|
||||||
* `column`: The column number in the original source.
|
|
||||||
|
|
||||||
and an object is returned with the following properties:
|
|
||||||
|
|
||||||
* `line`: The line number in the generated source, or null.
|
|
||||||
|
|
||||||
* `column`: The column number in the generated source, or null.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
|
|
||||||
// { line: 1,
|
|
||||||
// column: 56 }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
|
|
||||||
|
|
||||||
Returns all generated line and column information for the original source, line,
|
|
||||||
and column provided. If no column is provided, returns all mappings
|
|
||||||
corresponding to a either the line we are searching for or the next closest line
|
|
||||||
that has any mappings. Otherwise, returns all mappings corresponding to the
|
|
||||||
given line and either the column we are searching for or the next closest column
|
|
||||||
that has any offsets.
|
|
||||||
|
|
||||||
The only argument is an object with the following properties:
|
|
||||||
|
|
||||||
* `source`: The filename of the original source.
|
|
||||||
|
|
||||||
* `line`: The line number in the original source.
|
|
||||||
|
|
||||||
* `column`: Optional. The column number in the original source.
|
|
||||||
|
|
||||||
and an array of objects is returned, each with the following properties:
|
|
||||||
|
|
||||||
* `line`: The line number in the generated source, or null.
|
|
||||||
|
|
||||||
* `column`: The column number in the generated source, or null.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
|
|
||||||
// [ { line: 2,
|
|
||||||
// column: 1 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 10 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 20 } ]
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
|
|
||||||
|
|
||||||
Return true if we have the embedded source content for every source listed in
|
|
||||||
the source map, false otherwise.
|
|
||||||
|
|
||||||
In other words, if this method returns `true`, then
|
|
||||||
`consumer.sourceContentFor(s)` will succeed for every source `s` in
|
|
||||||
`consumer.sources`.
|
|
||||||
|
|
||||||
```js
|
|
||||||
// ...
|
|
||||||
if (consumer.hasContentsOfAllSources()) {
|
|
||||||
consumerReadyCallback(consumer);
|
|
||||||
} else {
|
|
||||||
fetchSources(consumer, consumerReadyCallback);
|
|
||||||
}
|
|
||||||
// ...
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
|
|
||||||
|
|
||||||
Returns the original source content for the source provided. The only
|
|
||||||
argument is the URL of the original source file.
|
|
||||||
|
|
||||||
If the source content for the given source is not found, then an error is
|
|
||||||
thrown. Optionally, pass `true` as the second param to have `null` returned
|
|
||||||
instead.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.sources
|
|
||||||
// [ "my-cool-lib.clj" ]
|
|
||||||
|
|
||||||
consumer.sourceContentFor("my-cool-lib.clj")
|
|
||||||
// "..."
|
|
||||||
|
|
||||||
consumer.sourceContentFor("this is not in the source map");
|
|
||||||
// Error: "this is not in the source map" is not in the source map
|
|
||||||
|
|
||||||
consumer.sourceContentFor("this is not in the source map", true);
|
|
||||||
// null
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
|
|
||||||
|
|
||||||
Iterate over each mapping between an original source/line/column and a
|
|
||||||
generated line/column in this source map.
|
|
||||||
|
|
||||||
* `callback`: The function that is called with each mapping. Mappings have the
|
|
||||||
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
|
|
||||||
name }`
|
|
||||||
|
|
||||||
* `context`: Optional. If specified, this object will be the value of `this`
|
|
||||||
every time that `callback` is called.
|
|
||||||
|
|
||||||
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
|
|
||||||
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
|
|
||||||
the mappings sorted by the generated file's line/column order or the
|
|
||||||
original's source/line/column order, respectively. Defaults to
|
|
||||||
`SourceMapConsumer.GENERATED_ORDER`.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.eachMapping(function (m) { console.log(m); })
|
|
||||||
// ...
|
|
||||||
// { source: 'illmatic.js',
|
|
||||||
// generatedLine: 1,
|
|
||||||
// generatedColumn: 0,
|
|
||||||
// originalLine: 1,
|
|
||||||
// originalColumn: 0,
|
|
||||||
// name: null }
|
|
||||||
// { source: 'illmatic.js',
|
|
||||||
// generatedLine: 2,
|
|
||||||
// generatedColumn: 0,
|
|
||||||
// originalLine: 2,
|
|
||||||
// originalColumn: 0,
|
|
||||||
// name: null }
|
|
||||||
// ...
|
|
||||||
```
|
|
||||||
### SourceMapGenerator
|
|
||||||
|
|
||||||
An instance of the SourceMapGenerator represents a source map which is being
|
|
||||||
built incrementally.
|
|
||||||
|
|
||||||
#### new SourceMapGenerator([startOfSourceMap])
|
|
||||||
|
|
||||||
You may pass an object with the following properties:
|
|
||||||
|
|
||||||
* `file`: The filename of the generated source that this source map is
|
|
||||||
associated with.
|
|
||||||
|
|
||||||
* `sourceRoot`: A root for all relative URLs in this source map.
|
|
||||||
|
|
||||||
* `skipValidation`: Optional. When `true`, disables validation of mappings as
|
|
||||||
they are added. This can improve performance but should be used with
|
|
||||||
discretion, as a last resort. Even then, one should avoid using this flag when
|
|
||||||
running tests, if possible.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var generator = new sourceMap.SourceMapGenerator({
|
|
||||||
file: "my-generated-javascript-file.js",
|
|
||||||
sourceRoot: "http://example.com/app/js/"
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
|
|
||||||
|
|
||||||
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
|
|
||||||
|
|
||||||
* `sourceMapConsumer` The SourceMap.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.addMapping(mapping)
|
|
||||||
|
|
||||||
Add a single mapping from original source line and column to the generated
|
|
||||||
source's line and column for this source map being created. The mapping object
|
|
||||||
should have the following properties:
|
|
||||||
|
|
||||||
* `generated`: An object with the generated line and column positions.
|
|
||||||
|
|
||||||
* `original`: An object with the original line and column positions.
|
|
||||||
|
|
||||||
* `source`: The original source file (relative to the sourceRoot).
|
|
||||||
|
|
||||||
* `name`: An optional original token name for this mapping.
|
|
||||||
|
|
||||||
```js
|
|
||||||
generator.addMapping({
|
|
||||||
source: "module-one.scm",
|
|
||||||
original: { line: 128, column: 0 },
|
|
||||||
generated: { line: 3, column: 456 }
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
|
|
||||||
|
|
||||||
Set the source content for an original source file.
|
|
||||||
|
|
||||||
* `sourceFile` the URL of the original source file.
|
|
||||||
|
|
||||||
* `sourceContent` the content of the source file.
|
|
||||||
|
|
||||||
```js
|
|
||||||
generator.setSourceContent("module-one.scm",
|
|
||||||
fs.readFileSync("path/to/module-one.scm"))
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
|
|
||||||
|
|
||||||
Applies a SourceMap for a source file to the SourceMap.
|
|
||||||
Each mapping to the supplied source file is rewritten using the
|
|
||||||
supplied SourceMap. Note: The resolution for the resulting mappings
|
|
||||||
is the minimum of this map and the supplied map.
|
|
||||||
|
|
||||||
* `sourceMapConsumer`: The SourceMap to be applied.
|
|
||||||
|
|
||||||
* `sourceFile`: Optional. The filename of the source file.
|
|
||||||
If omitted, sourceMapConsumer.file will be used, if it exists.
|
|
||||||
Otherwise an error will be thrown.
|
|
||||||
|
|
||||||
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
|
|
||||||
to be applied. If relative, it is relative to the SourceMap.
|
|
||||||
|
|
||||||
This parameter is needed when the two SourceMaps aren't in the same
|
|
||||||
directory, and the SourceMap to be applied contains relative source
|
|
||||||
paths. If so, those relative source paths need to be rewritten
|
|
||||||
relative to the SourceMap.
|
|
||||||
|
|
||||||
If omitted, it is assumed that both SourceMaps are in the same directory,
|
|
||||||
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.toString()
|
|
||||||
|
|
||||||
Renders the source map being generated to a string.
|
|
||||||
|
|
||||||
```js
|
|
||||||
generator.toString()
|
|
||||||
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
|
|
||||||
```
|
|
||||||
|
|
||||||
### SourceNode
|
|
||||||
|
|
||||||
SourceNodes provide a way to abstract over interpolating and/or concatenating
|
|
||||||
snippets of generated JavaScript source code, while maintaining the line and
|
|
||||||
column information associated between those snippets and the original source
|
|
||||||
code. This is useful as the final intermediate representation a compiler might
|
|
||||||
use before outputting the generated JS and source map.
|
|
||||||
|
|
||||||
#### new SourceNode([line, column, source[, chunk[, name]]])
|
|
||||||
|
|
||||||
* `line`: The original line number associated with this source node, or null if
|
|
||||||
it isn't associated with an original line.
|
|
||||||
|
|
||||||
* `column`: The original column number associated with this source node, or null
|
|
||||||
if it isn't associated with an original column.
|
|
||||||
|
|
||||||
* `source`: The original source's filename; null if no filename is provided.
|
|
||||||
|
|
||||||
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
|
|
||||||
below.
|
|
||||||
|
|
||||||
* `name`: Optional. The original identifier.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.cpp", [
|
|
||||||
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
|
|
||||||
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
|
|
||||||
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
|
|
||||||
]);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
|
|
||||||
|
|
||||||
Creates a SourceNode from generated code and a SourceMapConsumer.
|
|
||||||
|
|
||||||
* `code`: The generated code
|
|
||||||
|
|
||||||
* `sourceMapConsumer` The SourceMap for the generated code
|
|
||||||
|
|
||||||
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
|
|
||||||
should be relative to.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
|
|
||||||
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
|
|
||||||
consumer);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.add(chunk)
|
|
||||||
|
|
||||||
Add a chunk of generated JS to this source node.
|
|
||||||
|
|
||||||
* `chunk`: A string snippet of generated JS code, another instance of
|
|
||||||
`SourceNode`, or an array where each member is one of those things.
|
|
||||||
|
|
||||||
```js
|
|
||||||
node.add(" + ");
|
|
||||||
node.add(otherNode);
|
|
||||||
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.prepend(chunk)
|
|
||||||
|
|
||||||
Prepend a chunk of generated JS to this source node.
|
|
||||||
|
|
||||||
* `chunk`: A string snippet of generated JS code, another instance of
|
|
||||||
`SourceNode`, or an array where each member is one of those things.
|
|
||||||
|
|
||||||
```js
|
|
||||||
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
|
|
||||||
|
|
||||||
Set the source content for a source file. This will be added to the
|
|
||||||
`SourceMap` in the `sourcesContent` field.
|
|
||||||
|
|
||||||
* `sourceFile`: The filename of the source file
|
|
||||||
|
|
||||||
* `sourceContent`: The content of the source file
|
|
||||||
|
|
||||||
```js
|
|
||||||
node.setSourceContent("module-one.scm",
|
|
||||||
fs.readFileSync("path/to/module-one.scm"))
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.walk(fn)
|
|
||||||
|
|
||||||
Walk over the tree of JS snippets in this node and its children. The walking
|
|
||||||
function is called once for each snippet of JS and is passed that snippet and
|
|
||||||
the its original associated source's line/column location.
|
|
||||||
|
|
||||||
* `fn`: The traversal function.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.js", [
|
|
||||||
new SourceNode(3, 4, "b.js", "uno"),
|
|
||||||
"dos",
|
|
||||||
[
|
|
||||||
"tres",
|
|
||||||
new SourceNode(5, 6, "c.js", "quatro")
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
|
|
||||||
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
|
|
||||||
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
|
|
||||||
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
|
|
||||||
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.walkSourceContents(fn)
|
|
||||||
|
|
||||||
Walk over the tree of SourceNodes. The walking function is called for each
|
|
||||||
source file content and is passed the filename and source content.
|
|
||||||
|
|
||||||
* `fn`: The traversal function.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var a = new SourceNode(1, 2, "a.js", "generated from a");
|
|
||||||
a.setSourceContent("a.js", "original a");
|
|
||||||
var b = new SourceNode(1, 2, "b.js", "generated from b");
|
|
||||||
b.setSourceContent("b.js", "original b");
|
|
||||||
var c = new SourceNode(1, 2, "c.js", "generated from c");
|
|
||||||
c.setSourceContent("c.js", "original c");
|
|
||||||
|
|
||||||
var node = new SourceNode(null, null, null, [a, b, c]);
|
|
||||||
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
|
|
||||||
// WALK: a.js : original a
|
|
||||||
// WALK: b.js : original b
|
|
||||||
// WALK: c.js : original c
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.join(sep)
|
|
||||||
|
|
||||||
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
|
|
||||||
between each of this source node's children.
|
|
||||||
|
|
||||||
* `sep`: The separator.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
|
|
||||||
var operand = new SourceNode(3, 4, "a.rs", "=");
|
|
||||||
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
|
|
||||||
|
|
||||||
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
|
|
||||||
var joinedNode = node.join(" ");
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.replaceRight(pattern, replacement)
|
|
||||||
|
|
||||||
Call `String.prototype.replace` on the very right-most source snippet. Useful
|
|
||||||
for trimming white space from the end of a source node, etc.
|
|
||||||
|
|
||||||
* `pattern`: The pattern to replace.
|
|
||||||
|
|
||||||
* `replacement`: The thing to replace the pattern with.
|
|
||||||
|
|
||||||
```js
|
|
||||||
// Trim trailing white space.
|
|
||||||
node.replaceRight(/\s*$/, "");
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.toString()
|
|
||||||
|
|
||||||
Return the string representation of this source node. Walks over the tree and
|
|
||||||
concatenates all the various snippets together to one string.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.js", [
|
|
||||||
new SourceNode(3, 4, "b.js", "uno"),
|
|
||||||
"dos",
|
|
||||||
[
|
|
||||||
"tres",
|
|
||||||
new SourceNode(5, 6, "c.js", "quatro")
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
node.toString()
|
|
||||||
// 'unodostresquatro'
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
|
|
||||||
|
|
||||||
Returns the string representation of this tree of source nodes, plus a
|
|
||||||
SourceMapGenerator which contains all the mappings between the generated and
|
|
||||||
original sources.
|
|
||||||
|
|
||||||
The arguments are the same as those to `new SourceMapGenerator`.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.js", [
|
|
||||||
new SourceNode(3, 4, "b.js", "uno"),
|
|
||||||
"dos",
|
|
||||||
[
|
|
||||||
"tres",
|
|
||||||
new SourceNode(5, 6, "c.js", "quatro")
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
node.toStringWithSourceMap({ file: "my-output-file.js" })
|
|
||||||
// { code: 'unodostresquatro',
|
|
||||||
// map: [object SourceMapGenerator] }
|
|
||||||
```
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,121 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
var util = require('./util');
|
|
||||||
var has = Object.prototype.hasOwnProperty;
|
|
||||||
var hasNativeMap = typeof Map !== "undefined";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A data structure which is a combination of an array and a set. Adding a new
|
|
||||||
* member is O(1), testing for membership is O(1), and finding the index of an
|
|
||||||
* element is O(1). Removing elements from the set is not supported. Only
|
|
||||||
* strings are supported for membership.
|
|
||||||
*/
|
|
||||||
function ArraySet() {
|
|
||||||
this._array = [];
|
|
||||||
this._set = hasNativeMap ? new Map() : Object.create(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Static method for creating ArraySet instances from an existing array.
|
|
||||||
*/
|
|
||||||
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
|
|
||||||
var set = new ArraySet();
|
|
||||||
for (var i = 0, len = aArray.length; i < len; i++) {
|
|
||||||
set.add(aArray[i], aAllowDuplicates);
|
|
||||||
}
|
|
||||||
return set;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return how many unique items are in this ArraySet. If duplicates have been
|
|
||||||
* added, than those do not count towards the size.
|
|
||||||
*
|
|
||||||
* @returns Number
|
|
||||||
*/
|
|
||||||
ArraySet.prototype.size = function ArraySet_size() {
|
|
||||||
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add the given string to this set.
|
|
||||||
*
|
|
||||||
* @param String aStr
|
|
||||||
*/
|
|
||||||
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
|
|
||||||
var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
|
|
||||||
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
|
|
||||||
var idx = this._array.length;
|
|
||||||
if (!isDuplicate || aAllowDuplicates) {
|
|
||||||
this._array.push(aStr);
|
|
||||||
}
|
|
||||||
if (!isDuplicate) {
|
|
||||||
if (hasNativeMap) {
|
|
||||||
this._set.set(aStr, idx);
|
|
||||||
} else {
|
|
||||||
this._set[sStr] = idx;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Is the given string a member of this set?
|
|
||||||
*
|
|
||||||
* @param String aStr
|
|
||||||
*/
|
|
||||||
ArraySet.prototype.has = function ArraySet_has(aStr) {
|
|
||||||
if (hasNativeMap) {
|
|
||||||
return this._set.has(aStr);
|
|
||||||
} else {
|
|
||||||
var sStr = util.toSetString(aStr);
|
|
||||||
return has.call(this._set, sStr);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What is the index of the given string in the array?
|
|
||||||
*
|
|
||||||
* @param String aStr
|
|
||||||
*/
|
|
||||||
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
|
|
||||||
if (hasNativeMap) {
|
|
||||||
var idx = this._set.get(aStr);
|
|
||||||
if (idx >= 0) {
|
|
||||||
return idx;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var sStr = util.toSetString(aStr);
|
|
||||||
if (has.call(this._set, sStr)) {
|
|
||||||
return this._set[sStr];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('"' + aStr + '" is not in the set.');
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What is the element at the given index?
|
|
||||||
*
|
|
||||||
* @param Number aIdx
|
|
||||||
*/
|
|
||||||
ArraySet.prototype.at = function ArraySet_at(aIdx) {
|
|
||||||
if (aIdx >= 0 && aIdx < this._array.length) {
|
|
||||||
return this._array[aIdx];
|
|
||||||
}
|
|
||||||
throw new Error('No element indexed by ' + aIdx);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the array representation of this set (which has the proper indices
|
|
||||||
* indicated by indexOf). Note that this is a copy of the internal array used
|
|
||||||
* for storing the members so that no one can mess with internal state.
|
|
||||||
*/
|
|
||||||
ArraySet.prototype.toArray = function ArraySet_toArray() {
|
|
||||||
return this._array.slice();
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.ArraySet = ArraySet;
|
|
||||||
|
|
@ -1,140 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*
|
|
||||||
* Based on the Base 64 VLQ implementation in Closure Compiler:
|
|
||||||
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
|
|
||||||
*
|
|
||||||
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
|
|
||||||
* Redistribution and use in source and binary forms, with or without
|
|
||||||
* modification, are permitted provided that the following conditions are
|
|
||||||
* met:
|
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright
|
|
||||||
* notice, this list of conditions and the following disclaimer.
|
|
||||||
* * Redistributions in binary form must reproduce the above
|
|
||||||
* copyright notice, this list of conditions and the following
|
|
||||||
* disclaimer in the documentation and/or other materials provided
|
|
||||||
* with the distribution.
|
|
||||||
* * Neither the name of Google Inc. nor the names of its
|
|
||||||
* contributors may be used to endorse or promote products derived
|
|
||||||
* from this software without specific prior written permission.
|
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
*/
|
|
||||||
|
|
||||||
var base64 = require('./base64');
|
|
||||||
|
|
||||||
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
|
|
||||||
// length quantities we use in the source map spec, the first bit is the sign,
|
|
||||||
// the next four bits are the actual value, and the 6th bit is the
|
|
||||||
// continuation bit. The continuation bit tells us whether there are more
|
|
||||||
// digits in this value following this digit.
|
|
||||||
//
|
|
||||||
// Continuation
|
|
||||||
// | Sign
|
|
||||||
// | |
|
|
||||||
// V V
|
|
||||||
// 101011
|
|
||||||
|
|
||||||
var VLQ_BASE_SHIFT = 5;
|
|
||||||
|
|
||||||
// binary: 100000
|
|
||||||
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
|
|
||||||
|
|
||||||
// binary: 011111
|
|
||||||
var VLQ_BASE_MASK = VLQ_BASE - 1;
|
|
||||||
|
|
||||||
// binary: 100000
|
|
||||||
var VLQ_CONTINUATION_BIT = VLQ_BASE;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts from a two-complement value to a value where the sign bit is
|
|
||||||
* placed in the least significant bit. For example, as decimals:
|
|
||||||
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
|
|
||||||
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
|
|
||||||
*/
|
|
||||||
function toVLQSigned(aValue) {
|
|
||||||
return aValue < 0
|
|
||||||
? ((-aValue) << 1) + 1
|
|
||||||
: (aValue << 1) + 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts to a two-complement value from a value where the sign bit is
|
|
||||||
* placed in the least significant bit. For example, as decimals:
|
|
||||||
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
|
|
||||||
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
|
|
||||||
*/
|
|
||||||
function fromVLQSigned(aValue) {
|
|
||||||
var isNegative = (aValue & 1) === 1;
|
|
||||||
var shifted = aValue >> 1;
|
|
||||||
return isNegative
|
|
||||||
? -shifted
|
|
||||||
: shifted;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the base 64 VLQ encoded value.
|
|
||||||
*/
|
|
||||||
exports.encode = function base64VLQ_encode(aValue) {
|
|
||||||
var encoded = "";
|
|
||||||
var digit;
|
|
||||||
|
|
||||||
var vlq = toVLQSigned(aValue);
|
|
||||||
|
|
||||||
do {
|
|
||||||
digit = vlq & VLQ_BASE_MASK;
|
|
||||||
vlq >>>= VLQ_BASE_SHIFT;
|
|
||||||
if (vlq > 0) {
|
|
||||||
// There are still more digits in this value, so we must make sure the
|
|
||||||
// continuation bit is marked.
|
|
||||||
digit |= VLQ_CONTINUATION_BIT;
|
|
||||||
}
|
|
||||||
encoded += base64.encode(digit);
|
|
||||||
} while (vlq > 0);
|
|
||||||
|
|
||||||
return encoded;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decodes the next base 64 VLQ value from the given string and returns the
|
|
||||||
* value and the rest of the string via the out parameter.
|
|
||||||
*/
|
|
||||||
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
|
|
||||||
var strLen = aStr.length;
|
|
||||||
var result = 0;
|
|
||||||
var shift = 0;
|
|
||||||
var continuation, digit;
|
|
||||||
|
|
||||||
do {
|
|
||||||
if (aIndex >= strLen) {
|
|
||||||
throw new Error("Expected more digits in base 64 VLQ value.");
|
|
||||||
}
|
|
||||||
|
|
||||||
digit = base64.decode(aStr.charCodeAt(aIndex++));
|
|
||||||
if (digit === -1) {
|
|
||||||
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
continuation = !!(digit & VLQ_CONTINUATION_BIT);
|
|
||||||
digit &= VLQ_BASE_MASK;
|
|
||||||
result = result + (digit << shift);
|
|
||||||
shift += VLQ_BASE_SHIFT;
|
|
||||||
} while (continuation);
|
|
||||||
|
|
||||||
aOutParam.value = fromVLQSigned(result);
|
|
||||||
aOutParam.rest = aIndex;
|
|
||||||
};
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
|
|
||||||
*/
|
|
||||||
exports.encode = function (number) {
|
|
||||||
if (0 <= number && number < intToCharMap.length) {
|
|
||||||
return intToCharMap[number];
|
|
||||||
}
|
|
||||||
throw new TypeError("Must be between 0 and 63: " + number);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decode a single base 64 character code digit to an integer. Returns -1 on
|
|
||||||
* failure.
|
|
||||||
*/
|
|
||||||
exports.decode = function (charCode) {
|
|
||||||
var bigA = 65; // 'A'
|
|
||||||
var bigZ = 90; // 'Z'
|
|
||||||
|
|
||||||
var littleA = 97; // 'a'
|
|
||||||
var littleZ = 122; // 'z'
|
|
||||||
|
|
||||||
var zero = 48; // '0'
|
|
||||||
var nine = 57; // '9'
|
|
||||||
|
|
||||||
var plus = 43; // '+'
|
|
||||||
var slash = 47; // '/'
|
|
||||||
|
|
||||||
var littleOffset = 26;
|
|
||||||
var numberOffset = 52;
|
|
||||||
|
|
||||||
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
|
||||||
if (bigA <= charCode && charCode <= bigZ) {
|
|
||||||
return (charCode - bigA);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 26 - 51: abcdefghijklmnopqrstuvwxyz
|
|
||||||
if (littleA <= charCode && charCode <= littleZ) {
|
|
||||||
return (charCode - littleA + littleOffset);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 52 - 61: 0123456789
|
|
||||||
if (zero <= charCode && charCode <= nine) {
|
|
||||||
return (charCode - zero + numberOffset);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 62: +
|
|
||||||
if (charCode == plus) {
|
|
||||||
return 62;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 63: /
|
|
||||||
if (charCode == slash) {
|
|
||||||
return 63;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invalid base64 digit.
|
|
||||||
return -1;
|
|
||||||
};
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
exports.GREATEST_LOWER_BOUND = 1;
|
|
||||||
exports.LEAST_UPPER_BOUND = 2;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Recursive implementation of binary search.
|
|
||||||
*
|
|
||||||
* @param aLow Indices here and lower do not contain the needle.
|
|
||||||
* @param aHigh Indices here and higher do not contain the needle.
|
|
||||||
* @param aNeedle The element being searched for.
|
|
||||||
* @param aHaystack The non-empty array being searched.
|
|
||||||
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
|
|
||||||
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
|
|
||||||
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
|
|
||||||
* closest element that is smaller than or greater than the one we are
|
|
||||||
* searching for, respectively, if the exact element cannot be found.
|
|
||||||
*/
|
|
||||||
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
|
|
||||||
// This function terminates when one of the following is true:
|
|
||||||
//
|
|
||||||
// 1. We find the exact element we are looking for.
|
|
||||||
//
|
|
||||||
// 2. We did not find the exact element, but we can return the index of
|
|
||||||
// the next-closest element.
|
|
||||||
//
|
|
||||||
// 3. We did not find the exact element, and there is no next-closest
|
|
||||||
// element than the one we are searching for, so we return -1.
|
|
||||||
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
|
|
||||||
var cmp = aCompare(aNeedle, aHaystack[mid], true);
|
|
||||||
if (cmp === 0) {
|
|
||||||
// Found the element we are looking for.
|
|
||||||
return mid;
|
|
||||||
}
|
|
||||||
else if (cmp > 0) {
|
|
||||||
// Our needle is greater than aHaystack[mid].
|
|
||||||
if (aHigh - mid > 1) {
|
|
||||||
// The element is in the upper half.
|
|
||||||
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The exact needle element was not found in this haystack. Determine if
|
|
||||||
// we are in termination case (3) or (2) and return the appropriate thing.
|
|
||||||
if (aBias == exports.LEAST_UPPER_BOUND) {
|
|
||||||
return aHigh < aHaystack.length ? aHigh : -1;
|
|
||||||
} else {
|
|
||||||
return mid;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// Our needle is less than aHaystack[mid].
|
|
||||||
if (mid - aLow > 1) {
|
|
||||||
// The element is in the lower half.
|
|
||||||
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
|
|
||||||
}
|
|
||||||
|
|
||||||
// we are in termination case (3) or (2) and return the appropriate thing.
|
|
||||||
if (aBias == exports.LEAST_UPPER_BOUND) {
|
|
||||||
return mid;
|
|
||||||
} else {
|
|
||||||
return aLow < 0 ? -1 : aLow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This is an implementation of binary search which will always try and return
|
|
||||||
* the index of the closest element if there is no exact hit. This is because
|
|
||||||
* mappings between original and generated line/col pairs are single points,
|
|
||||||
* and there is an implicit region between each of them, so a miss just means
|
|
||||||
* that you aren't on the very start of a region.
|
|
||||||
*
|
|
||||||
* @param aNeedle The element you are looking for.
|
|
||||||
* @param aHaystack The array that is being searched.
|
|
||||||
* @param aCompare A function which takes the needle and an element in the
|
|
||||||
* array and returns -1, 0, or 1 depending on whether the needle is less
|
|
||||||
* than, equal to, or greater than the element, respectively.
|
|
||||||
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
|
|
||||||
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
|
|
||||||
* closest element that is smaller than or greater than the one we are
|
|
||||||
* searching for, respectively, if the exact element cannot be found.
|
|
||||||
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
|
|
||||||
*/
|
|
||||||
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
|
|
||||||
if (aHaystack.length === 0) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
|
|
||||||
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
|
|
||||||
if (index < 0) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// We have found either the exact element, or the next-closest element than
|
|
||||||
// the one we are searching for. However, there may be more than one such
|
|
||||||
// element. Make sure we always return the smallest of these.
|
|
||||||
while (index - 1 >= 0) {
|
|
||||||
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
--index;
|
|
||||||
}
|
|
||||||
|
|
||||||
return index;
|
|
||||||
};
|
|
||||||
|
|
@ -1,79 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2014 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
var util = require('./util');
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether mappingB is after mappingA with respect to generated
|
|
||||||
* position.
|
|
||||||
*/
|
|
||||||
function generatedPositionAfter(mappingA, mappingB) {
|
|
||||||
// Optimized for most common case
|
|
||||||
var lineA = mappingA.generatedLine;
|
|
||||||
var lineB = mappingB.generatedLine;
|
|
||||||
var columnA = mappingA.generatedColumn;
|
|
||||||
var columnB = mappingB.generatedColumn;
|
|
||||||
return lineB > lineA || lineB == lineA && columnB >= columnA ||
|
|
||||||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A data structure to provide a sorted view of accumulated mappings in a
|
|
||||||
* performance conscious manner. It trades a neglibable overhead in general
|
|
||||||
* case for a large speedup in case of mappings being added in order.
|
|
||||||
*/
|
|
||||||
function MappingList() {
|
|
||||||
this._array = [];
|
|
||||||
this._sorted = true;
|
|
||||||
// Serves as infimum
|
|
||||||
this._last = {generatedLine: -1, generatedColumn: 0};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Iterate through internal items. This method takes the same arguments that
|
|
||||||
* `Array.prototype.forEach` takes.
|
|
||||||
*
|
|
||||||
* NOTE: The order of the mappings is NOT guaranteed.
|
|
||||||
*/
|
|
||||||
MappingList.prototype.unsortedForEach =
|
|
||||||
function MappingList_forEach(aCallback, aThisArg) {
|
|
||||||
this._array.forEach(aCallback, aThisArg);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add the given source mapping.
|
|
||||||
*
|
|
||||||
* @param Object aMapping
|
|
||||||
*/
|
|
||||||
MappingList.prototype.add = function MappingList_add(aMapping) {
|
|
||||||
if (generatedPositionAfter(this._last, aMapping)) {
|
|
||||||
this._last = aMapping;
|
|
||||||
this._array.push(aMapping);
|
|
||||||
} else {
|
|
||||||
this._sorted = false;
|
|
||||||
this._array.push(aMapping);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the flat, sorted array of mappings. The mappings are sorted by
|
|
||||||
* generated position.
|
|
||||||
*
|
|
||||||
* WARNING: This method returns internal data without copying, for
|
|
||||||
* performance. The return value must NOT be mutated, and should be treated as
|
|
||||||
* an immutable borrow. If you want to take ownership, you must make your own
|
|
||||||
* copy.
|
|
||||||
*/
|
|
||||||
MappingList.prototype.toArray = function MappingList_toArray() {
|
|
||||||
if (!this._sorted) {
|
|
||||||
this._array.sort(util.compareByGeneratedPositionsInflated);
|
|
||||||
this._sorted = true;
|
|
||||||
}
|
|
||||||
return this._array;
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.MappingList = MappingList;
|
|
||||||
|
|
@ -1,114 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
// It turns out that some (most?) JavaScript engines don't self-host
|
|
||||||
// `Array.prototype.sort`. This makes sense because C++ will likely remain
|
|
||||||
// faster than JS when doing raw CPU-intensive sorting. However, when using a
|
|
||||||
// custom comparator function, calling back and forth between the VM's C++ and
|
|
||||||
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
|
|
||||||
// worse generated code for the comparator function than would be optimal. In
|
|
||||||
// fact, when sorting with a comparator, these costs outweigh the benefits of
|
|
||||||
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
|
|
||||||
// a ~3500ms mean speed-up in `bench/bench.html`.
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Swap the elements indexed by `x` and `y` in the array `ary`.
|
|
||||||
*
|
|
||||||
* @param {Array} ary
|
|
||||||
* The array.
|
|
||||||
* @param {Number} x
|
|
||||||
* The index of the first item.
|
|
||||||
* @param {Number} y
|
|
||||||
* The index of the second item.
|
|
||||||
*/
|
|
||||||
function swap(ary, x, y) {
|
|
||||||
var temp = ary[x];
|
|
||||||
ary[x] = ary[y];
|
|
||||||
ary[y] = temp;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a random integer within the range `low .. high` inclusive.
|
|
||||||
*
|
|
||||||
* @param {Number} low
|
|
||||||
* The lower bound on the range.
|
|
||||||
* @param {Number} high
|
|
||||||
* The upper bound on the range.
|
|
||||||
*/
|
|
||||||
function randomIntInRange(low, high) {
|
|
||||||
return Math.round(low + (Math.random() * (high - low)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The Quick Sort algorithm.
|
|
||||||
*
|
|
||||||
* @param {Array} ary
|
|
||||||
* An array to sort.
|
|
||||||
* @param {function} comparator
|
|
||||||
* Function to use to compare two items.
|
|
||||||
* @param {Number} p
|
|
||||||
* Start index of the array
|
|
||||||
* @param {Number} r
|
|
||||||
* End index of the array
|
|
||||||
*/
|
|
||||||
function doQuickSort(ary, comparator, p, r) {
|
|
||||||
// If our lower bound is less than our upper bound, we (1) partition the
|
|
||||||
// array into two pieces and (2) recurse on each half. If it is not, this is
|
|
||||||
// the empty array and our base case.
|
|
||||||
|
|
||||||
if (p < r) {
|
|
||||||
// (1) Partitioning.
|
|
||||||
//
|
|
||||||
// The partitioning chooses a pivot between `p` and `r` and moves all
|
|
||||||
// elements that are less than or equal to the pivot to the before it, and
|
|
||||||
// all the elements that are greater than it after it. The effect is that
|
|
||||||
// once partition is done, the pivot is in the exact place it will be when
|
|
||||||
// the array is put in sorted order, and it will not need to be moved
|
|
||||||
// again. This runs in O(n) time.
|
|
||||||
|
|
||||||
// Always choose a random pivot so that an input array which is reverse
|
|
||||||
// sorted does not cause O(n^2) running time.
|
|
||||||
var pivotIndex = randomIntInRange(p, r);
|
|
||||||
var i = p - 1;
|
|
||||||
|
|
||||||
swap(ary, pivotIndex, r);
|
|
||||||
var pivot = ary[r];
|
|
||||||
|
|
||||||
// Immediately after `j` is incremented in this loop, the following hold
|
|
||||||
// true:
|
|
||||||
//
|
|
||||||
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
|
|
||||||
//
|
|
||||||
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
|
|
||||||
for (var j = p; j < r; j++) {
|
|
||||||
if (comparator(ary[j], pivot) <= 0) {
|
|
||||||
i += 1;
|
|
||||||
swap(ary, i, j);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
swap(ary, i + 1, j);
|
|
||||||
var q = i + 1;
|
|
||||||
|
|
||||||
// (2) Recurse on each half.
|
|
||||||
|
|
||||||
doQuickSort(ary, comparator, p, q - 1);
|
|
||||||
doQuickSort(ary, comparator, q + 1, r);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sort the given array in-place with the given comparator function.
|
|
||||||
*
|
|
||||||
* @param {Array} ary
|
|
||||||
* An array to sort.
|
|
||||||
* @param {function} comparator
|
|
||||||
* Function to use to compare two items.
|
|
||||||
*/
|
|
||||||
exports.quickSort = function (ary, comparator) {
|
|
||||||
doQuickSort(ary, comparator, 0, ary.length - 1);
|
|
||||||
};
|
|
||||||
|
|
@ -1,1082 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
var util = require('./util');
|
|
||||||
var binarySearch = require('./binary-search');
|
|
||||||
var ArraySet = require('./array-set').ArraySet;
|
|
||||||
var base64VLQ = require('./base64-vlq');
|
|
||||||
var quickSort = require('./quick-sort').quickSort;
|
|
||||||
|
|
||||||
function SourceMapConsumer(aSourceMap) {
|
|
||||||
var sourceMap = aSourceMap;
|
|
||||||
if (typeof aSourceMap === 'string') {
|
|
||||||
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
|
|
||||||
}
|
|
||||||
|
|
||||||
return sourceMap.sections != null
|
|
||||||
? new IndexedSourceMapConsumer(sourceMap)
|
|
||||||
: new BasicSourceMapConsumer(sourceMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
SourceMapConsumer.fromSourceMap = function(aSourceMap) {
|
|
||||||
return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The version of the source mapping spec that we are consuming.
|
|
||||||
*/
|
|
||||||
SourceMapConsumer.prototype._version = 3;
|
|
||||||
|
|
||||||
// `__generatedMappings` and `__originalMappings` are arrays that hold the
|
|
||||||
// parsed mapping coordinates from the source map's "mappings" attribute. They
|
|
||||||
// are lazily instantiated, accessed via the `_generatedMappings` and
|
|
||||||
// `_originalMappings` getters respectively, and we only parse the mappings
|
|
||||||
// and create these arrays once queried for a source location. We jump through
|
|
||||||
// these hoops because there can be many thousands of mappings, and parsing
|
|
||||||
// them is expensive, so we only want to do it if we must.
|
|
||||||
//
|
|
||||||
// Each object in the arrays is of the form:
|
|
||||||
//
|
|
||||||
// {
|
|
||||||
// generatedLine: The line number in the generated code,
|
|
||||||
// generatedColumn: The column number in the generated code,
|
|
||||||
// source: The path to the original source file that generated this
|
|
||||||
// chunk of code,
|
|
||||||
// originalLine: The line number in the original source that
|
|
||||||
// corresponds to this chunk of generated code,
|
|
||||||
// originalColumn: The column number in the original source that
|
|
||||||
// corresponds to this chunk of generated code,
|
|
||||||
// name: The name of the original symbol which generated this chunk of
|
|
||||||
// code.
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// All properties except for `generatedLine` and `generatedColumn` can be
|
|
||||||
// `null`.
|
|
||||||
//
|
|
||||||
// `_generatedMappings` is ordered by the generated positions.
|
|
||||||
//
|
|
||||||
// `_originalMappings` is ordered by the original positions.
|
|
||||||
|
|
||||||
SourceMapConsumer.prototype.__generatedMappings = null;
|
|
||||||
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
|
|
||||||
get: function () {
|
|
||||||
if (!this.__generatedMappings) {
|
|
||||||
this._parseMappings(this._mappings, this.sourceRoot);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.__generatedMappings;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
SourceMapConsumer.prototype.__originalMappings = null;
|
|
||||||
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
|
|
||||||
get: function () {
|
|
||||||
if (!this.__originalMappings) {
|
|
||||||
this._parseMappings(this._mappings, this.sourceRoot);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.__originalMappings;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
SourceMapConsumer.prototype._charIsMappingSeparator =
|
|
||||||
function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
|
|
||||||
var c = aStr.charAt(index);
|
|
||||||
return c === ";" || c === ",";
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse the mappings in a string in to a data structure which we can easily
|
|
||||||
* query (the ordered arrays in the `this.__generatedMappings` and
|
|
||||||
* `this.__originalMappings` properties).
|
|
||||||
*/
|
|
||||||
SourceMapConsumer.prototype._parseMappings =
|
|
||||||
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
|
|
||||||
throw new Error("Subclasses must implement _parseMappings");
|
|
||||||
};
|
|
||||||
|
|
||||||
SourceMapConsumer.GENERATED_ORDER = 1;
|
|
||||||
SourceMapConsumer.ORIGINAL_ORDER = 2;
|
|
||||||
|
|
||||||
SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
|
|
||||||
SourceMapConsumer.LEAST_UPPER_BOUND = 2;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Iterate over each mapping between an original source/line/column and a
|
|
||||||
* generated line/column in this source map.
|
|
||||||
*
|
|
||||||
* @param Function aCallback
|
|
||||||
* The function that is called with each mapping.
|
|
||||||
* @param Object aContext
|
|
||||||
* Optional. If specified, this object will be the value of `this` every
|
|
||||||
* time that `aCallback` is called.
|
|
||||||
* @param aOrder
|
|
||||||
* Either `SourceMapConsumer.GENERATED_ORDER` or
|
|
||||||
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
|
|
||||||
* iterate over the mappings sorted by the generated file's line/column
|
|
||||||
* order or the original's source/line/column order, respectively. Defaults to
|
|
||||||
* `SourceMapConsumer.GENERATED_ORDER`.
|
|
||||||
*/
|
|
||||||
SourceMapConsumer.prototype.eachMapping =
|
|
||||||
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
|
|
||||||
var context = aContext || null;
|
|
||||||
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
|
|
||||||
|
|
||||||
var mappings;
|
|
||||||
switch (order) {
|
|
||||||
case SourceMapConsumer.GENERATED_ORDER:
|
|
||||||
mappings = this._generatedMappings;
|
|
||||||
break;
|
|
||||||
case SourceMapConsumer.ORIGINAL_ORDER:
|
|
||||||
mappings = this._originalMappings;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw new Error("Unknown order of iteration.");
|
|
||||||
}
|
|
||||||
|
|
||||||
var sourceRoot = this.sourceRoot;
|
|
||||||
mappings.map(function (mapping) {
|
|
||||||
var source = mapping.source === null ? null : this._sources.at(mapping.source);
|
|
||||||
if (source != null && sourceRoot != null) {
|
|
||||||
source = util.join(sourceRoot, source);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
source: source,
|
|
||||||
generatedLine: mapping.generatedLine,
|
|
||||||
generatedColumn: mapping.generatedColumn,
|
|
||||||
originalLine: mapping.originalLine,
|
|
||||||
originalColumn: mapping.originalColumn,
|
|
||||||
name: mapping.name === null ? null : this._names.at(mapping.name)
|
|
||||||
};
|
|
||||||
}, this).forEach(aCallback, context);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns all generated line and column information for the original source,
|
|
||||||
* line, and column provided. If no column is provided, returns all mappings
|
|
||||||
* corresponding to a either the line we are searching for or the next
|
|
||||||
* closest line that has any mappings. Otherwise, returns all mappings
|
|
||||||
* corresponding to the given line and either the column we are searching for
|
|
||||||
* or the next closest column that has any offsets.
|
|
||||||
*
|
|
||||||
* The only argument is an object with the following properties:
|
|
||||||
*
|
|
||||||
* - source: The filename of the original source.
|
|
||||||
* - line: The line number in the original source.
|
|
||||||
* - column: Optional. the column number in the original source.
|
|
||||||
*
|
|
||||||
* and an array of objects is returned, each with the following properties:
|
|
||||||
*
|
|
||||||
* - line: The line number in the generated source, or null.
|
|
||||||
* - column: The column number in the generated source, or null.
|
|
||||||
*/
|
|
||||||
SourceMapConsumer.prototype.allGeneratedPositionsFor =
|
|
||||||
function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
|
|
||||||
var line = util.getArg(aArgs, 'line');
|
|
||||||
|
|
||||||
// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
|
|
||||||
// returns the index of the closest mapping less than the needle. By
|
|
||||||
// setting needle.originalColumn to 0, we thus find the last mapping for
|
|
||||||
// the given line, provided such a mapping exists.
|
|
||||||
var needle = {
|
|
||||||
source: util.getArg(aArgs, 'source'),
|
|
||||||
originalLine: line,
|
|
||||||
originalColumn: util.getArg(aArgs, 'column', 0)
|
|
||||||
};
|
|
||||||
|
|
||||||
if (this.sourceRoot != null) {
|
|
||||||
needle.source = util.relative(this.sourceRoot, needle.source);
|
|
||||||
}
|
|
||||||
if (!this._sources.has(needle.source)) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
needle.source = this._sources.indexOf(needle.source);
|
|
||||||
|
|
||||||
var mappings = [];
|
|
||||||
|
|
||||||
var index = this._findMapping(needle,
|
|
||||||
this._originalMappings,
|
|
||||||
"originalLine",
|
|
||||||
"originalColumn",
|
|
||||||
util.compareByOriginalPositions,
|
|
||||||
binarySearch.LEAST_UPPER_BOUND);
|
|
||||||
if (index >= 0) {
|
|
||||||
var mapping = this._originalMappings[index];
|
|
||||||
|
|
||||||
if (aArgs.column === undefined) {
|
|
||||||
var originalLine = mapping.originalLine;
|
|
||||||
|
|
||||||
// Iterate until either we run out of mappings, or we run into
|
|
||||||
// a mapping for a different line than the one we found. Since
|
|
||||||
// mappings are sorted, this is guaranteed to find all mappings for
|
|
||||||
// the line we found.
|
|
||||||
while (mapping && mapping.originalLine === originalLine) {
|
|
||||||
mappings.push({
|
|
||||||
line: util.getArg(mapping, 'generatedLine', null),
|
|
||||||
column: util.getArg(mapping, 'generatedColumn', null),
|
|
||||||
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
|
|
||||||
});
|
|
||||||
|
|
||||||
mapping = this._originalMappings[++index];
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var originalColumn = mapping.originalColumn;
|
|
||||||
|
|
||||||
// Iterate until either we run out of mappings, or we run into
|
|
||||||
// a mapping for a different line than the one we were searching for.
|
|
||||||
// Since mappings are sorted, this is guaranteed to find all mappings for
|
|
||||||
// the line we are searching for.
|
|
||||||
while (mapping &&
|
|
||||||
mapping.originalLine === line &&
|
|
||||||
mapping.originalColumn == originalColumn) {
|
|
||||||
mappings.push({
|
|
||||||
line: util.getArg(mapping, 'generatedLine', null),
|
|
||||||
column: util.getArg(mapping, 'generatedColumn', null),
|
|
||||||
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
|
|
||||||
});
|
|
||||||
|
|
||||||
mapping = this._originalMappings[++index];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return mappings;
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.SourceMapConsumer = SourceMapConsumer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A BasicSourceMapConsumer instance represents a parsed source map which we can
|
|
||||||
* query for information about the original file positions by giving it a file
|
|
||||||
* position in the generated source.
|
|
||||||
*
|
|
||||||
* The only parameter is the raw source map (either as a JSON string, or
|
|
||||||
* already parsed to an object). According to the spec, source maps have the
|
|
||||||
* following attributes:
|
|
||||||
*
|
|
||||||
* - version: Which version of the source map spec this map is following.
|
|
||||||
* - sources: An array of URLs to the original source files.
|
|
||||||
* - names: An array of identifiers which can be referrenced by individual mappings.
|
|
||||||
* - sourceRoot: Optional. The URL root from which all sources are relative.
|
|
||||||
* - sourcesContent: Optional. An array of contents of the original source files.
|
|
||||||
* - mappings: A string of base64 VLQs which contain the actual mappings.
|
|
||||||
* - file: Optional. The generated file this source map is associated with.
|
|
||||||
*
|
|
||||||
* Here is an example source map, taken from the source map spec[0]:
|
|
||||||
*
|
|
||||||
* {
|
|
||||||
* version : 3,
|
|
||||||
* file: "out.js",
|
|
||||||
* sourceRoot : "",
|
|
||||||
* sources: ["foo.js", "bar.js"],
|
|
||||||
* names: ["src", "maps", "are", "fun"],
|
|
||||||
* mappings: "AA,AB;;ABCDE;"
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
|
|
||||||
*/
|
|
||||||
function BasicSourceMapConsumer(aSourceMap) {
|
|
||||||
var sourceMap = aSourceMap;
|
|
||||||
if (typeof aSourceMap === 'string') {
|
|
||||||
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
|
|
||||||
}
|
|
||||||
|
|
||||||
var version = util.getArg(sourceMap, 'version');
|
|
||||||
var sources = util.getArg(sourceMap, 'sources');
|
|
||||||
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
|
|
||||||
// requires the array) to play nice here.
|
|
||||||
var names = util.getArg(sourceMap, 'names', []);
|
|
||||||
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
|
|
||||||
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
|
|
||||||
var mappings = util.getArg(sourceMap, 'mappings');
|
|
||||||
var file = util.getArg(sourceMap, 'file', null);
|
|
||||||
|
|
||||||
// Once again, Sass deviates from the spec and supplies the version as a
|
|
||||||
// string rather than a number, so we use loose equality checking here.
|
|
||||||
if (version != this._version) {
|
|
||||||
throw new Error('Unsupported version: ' + version);
|
|
||||||
}
|
|
||||||
|
|
||||||
sources = sources
|
|
||||||
.map(String)
|
|
||||||
// Some source maps produce relative source paths like "./foo.js" instead of
|
|
||||||
// "foo.js". Normalize these first so that future comparisons will succeed.
|
|
||||||
// See bugzil.la/1090768.
|
|
||||||
.map(util.normalize)
|
|
||||||
// Always ensure that absolute sources are internally stored relative to
|
|
||||||
// the source root, if the source root is absolute. Not doing this would
|
|
||||||
// be particularly problematic when the source root is a prefix of the
|
|
||||||
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
|
|
||||||
.map(function (source) {
|
|
||||||
return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
|
|
||||||
? util.relative(sourceRoot, source)
|
|
||||||
: source;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Pass `true` below to allow duplicate names and sources. While source maps
|
|
||||||
// are intended to be compressed and deduplicated, the TypeScript compiler
|
|
||||||
// sometimes generates source maps with duplicates in them. See Github issue
|
|
||||||
// #72 and bugzil.la/889492.
|
|
||||||
this._names = ArraySet.fromArray(names.map(String), true);
|
|
||||||
this._sources = ArraySet.fromArray(sources, true);
|
|
||||||
|
|
||||||
this.sourceRoot = sourceRoot;
|
|
||||||
this.sourcesContent = sourcesContent;
|
|
||||||
this._mappings = mappings;
|
|
||||||
this.file = file;
|
|
||||||
}
|
|
||||||
|
|
||||||
BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
|
|
||||||
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
|
|
||||||
*
|
|
||||||
* @param SourceMapGenerator aSourceMap
|
|
||||||
* The source map that will be consumed.
|
|
||||||
* @returns BasicSourceMapConsumer
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.fromSourceMap =
|
|
||||||
function SourceMapConsumer_fromSourceMap(aSourceMap) {
|
|
||||||
var smc = Object.create(BasicSourceMapConsumer.prototype);
|
|
||||||
|
|
||||||
var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
|
|
||||||
var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
|
|
||||||
smc.sourceRoot = aSourceMap._sourceRoot;
|
|
||||||
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
|
|
||||||
smc.sourceRoot);
|
|
||||||
smc.file = aSourceMap._file;
|
|
||||||
|
|
||||||
// Because we are modifying the entries (by converting string sources and
|
|
||||||
// names to indices into the sources and names ArraySets), we have to make
|
|
||||||
// a copy of the entry or else bad things happen. Shared mutable state
|
|
||||||
// strikes again! See github issue #191.
|
|
||||||
|
|
||||||
var generatedMappings = aSourceMap._mappings.toArray().slice();
|
|
||||||
var destGeneratedMappings = smc.__generatedMappings = [];
|
|
||||||
var destOriginalMappings = smc.__originalMappings = [];
|
|
||||||
|
|
||||||
for (var i = 0, length = generatedMappings.length; i < length; i++) {
|
|
||||||
var srcMapping = generatedMappings[i];
|
|
||||||
var destMapping = new Mapping;
|
|
||||||
destMapping.generatedLine = srcMapping.generatedLine;
|
|
||||||
destMapping.generatedColumn = srcMapping.generatedColumn;
|
|
||||||
|
|
||||||
if (srcMapping.source) {
|
|
||||||
destMapping.source = sources.indexOf(srcMapping.source);
|
|
||||||
destMapping.originalLine = srcMapping.originalLine;
|
|
||||||
destMapping.originalColumn = srcMapping.originalColumn;
|
|
||||||
|
|
||||||
if (srcMapping.name) {
|
|
||||||
destMapping.name = names.indexOf(srcMapping.name);
|
|
||||||
}
|
|
||||||
|
|
||||||
destOriginalMappings.push(destMapping);
|
|
||||||
}
|
|
||||||
|
|
||||||
destGeneratedMappings.push(destMapping);
|
|
||||||
}
|
|
||||||
|
|
||||||
quickSort(smc.__originalMappings, util.compareByOriginalPositions);
|
|
||||||
|
|
||||||
return smc;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The version of the source mapping spec that we are consuming.
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype._version = 3;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The list of original sources.
|
|
||||||
*/
|
|
||||||
Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
|
|
||||||
get: function () {
|
|
||||||
return this._sources.toArray().map(function (s) {
|
|
||||||
return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
|
|
||||||
}, this);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Provide the JIT with a nice shape / hidden class.
|
|
||||||
*/
|
|
||||||
function Mapping() {
|
|
||||||
this.generatedLine = 0;
|
|
||||||
this.generatedColumn = 0;
|
|
||||||
this.source = null;
|
|
||||||
this.originalLine = null;
|
|
||||||
this.originalColumn = null;
|
|
||||||
this.name = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse the mappings in a string in to a data structure which we can easily
|
|
||||||
* query (the ordered arrays in the `this.__generatedMappings` and
|
|
||||||
* `this.__originalMappings` properties).
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype._parseMappings =
|
|
||||||
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
|
|
||||||
var generatedLine = 1;
|
|
||||||
var previousGeneratedColumn = 0;
|
|
||||||
var previousOriginalLine = 0;
|
|
||||||
var previousOriginalColumn = 0;
|
|
||||||
var previousSource = 0;
|
|
||||||
var previousName = 0;
|
|
||||||
var length = aStr.length;
|
|
||||||
var index = 0;
|
|
||||||
var cachedSegments = {};
|
|
||||||
var temp = {};
|
|
||||||
var originalMappings = [];
|
|
||||||
var generatedMappings = [];
|
|
||||||
var mapping, str, segment, end, value;
|
|
||||||
|
|
||||||
while (index < length) {
|
|
||||||
if (aStr.charAt(index) === ';') {
|
|
||||||
generatedLine++;
|
|
||||||
index++;
|
|
||||||
previousGeneratedColumn = 0;
|
|
||||||
}
|
|
||||||
else if (aStr.charAt(index) === ',') {
|
|
||||||
index++;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
mapping = new Mapping();
|
|
||||||
mapping.generatedLine = generatedLine;
|
|
||||||
|
|
||||||
// Because each offset is encoded relative to the previous one,
|
|
||||||
// many segments often have the same encoding. We can exploit this
|
|
||||||
// fact by caching the parsed variable length fields of each segment,
|
|
||||||
// allowing us to avoid a second parse if we encounter the same
|
|
||||||
// segment again.
|
|
||||||
for (end = index; end < length; end++) {
|
|
||||||
if (this._charIsMappingSeparator(aStr, end)) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
str = aStr.slice(index, end);
|
|
||||||
|
|
||||||
segment = cachedSegments[str];
|
|
||||||
if (segment) {
|
|
||||||
index += str.length;
|
|
||||||
} else {
|
|
||||||
segment = [];
|
|
||||||
while (index < end) {
|
|
||||||
base64VLQ.decode(aStr, index, temp);
|
|
||||||
value = temp.value;
|
|
||||||
index = temp.rest;
|
|
||||||
segment.push(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (segment.length === 2) {
|
|
||||||
throw new Error('Found a source, but no line and column');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (segment.length === 3) {
|
|
||||||
throw new Error('Found a source and line, but no column');
|
|
||||||
}
|
|
||||||
|
|
||||||
cachedSegments[str] = segment;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generated column.
|
|
||||||
mapping.generatedColumn = previousGeneratedColumn + segment[0];
|
|
||||||
previousGeneratedColumn = mapping.generatedColumn;
|
|
||||||
|
|
||||||
if (segment.length > 1) {
|
|
||||||
// Original source.
|
|
||||||
mapping.source = previousSource + segment[1];
|
|
||||||
previousSource += segment[1];
|
|
||||||
|
|
||||||
// Original line.
|
|
||||||
mapping.originalLine = previousOriginalLine + segment[2];
|
|
||||||
previousOriginalLine = mapping.originalLine;
|
|
||||||
// Lines are stored 0-based
|
|
||||||
mapping.originalLine += 1;
|
|
||||||
|
|
||||||
// Original column.
|
|
||||||
mapping.originalColumn = previousOriginalColumn + segment[3];
|
|
||||||
previousOriginalColumn = mapping.originalColumn;
|
|
||||||
|
|
||||||
if (segment.length > 4) {
|
|
||||||
// Original name.
|
|
||||||
mapping.name = previousName + segment[4];
|
|
||||||
previousName += segment[4];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
generatedMappings.push(mapping);
|
|
||||||
if (typeof mapping.originalLine === 'number') {
|
|
||||||
originalMappings.push(mapping);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
|
|
||||||
this.__generatedMappings = generatedMappings;
|
|
||||||
|
|
||||||
quickSort(originalMappings, util.compareByOriginalPositions);
|
|
||||||
this.__originalMappings = originalMappings;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Find the mapping that best matches the hypothetical "needle" mapping that
|
|
||||||
* we are searching for in the given "haystack" of mappings.
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype._findMapping =
|
|
||||||
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
|
|
||||||
aColumnName, aComparator, aBias) {
|
|
||||||
// To return the position we are searching for, we must first find the
|
|
||||||
// mapping for the given position and then return the opposite position it
|
|
||||||
// points to. Because the mappings are sorted, we can use binary search to
|
|
||||||
// find the best mapping.
|
|
||||||
|
|
||||||
if (aNeedle[aLineName] <= 0) {
|
|
||||||
throw new TypeError('Line must be greater than or equal to 1, got '
|
|
||||||
+ aNeedle[aLineName]);
|
|
||||||
}
|
|
||||||
if (aNeedle[aColumnName] < 0) {
|
|
||||||
throw new TypeError('Column must be greater than or equal to 0, got '
|
|
||||||
+ aNeedle[aColumnName]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Compute the last column for each generated mapping. The last column is
|
|
||||||
* inclusive.
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype.computeColumnSpans =
|
|
||||||
function SourceMapConsumer_computeColumnSpans() {
|
|
||||||
for (var index = 0; index < this._generatedMappings.length; ++index) {
|
|
||||||
var mapping = this._generatedMappings[index];
|
|
||||||
|
|
||||||
// Mappings do not contain a field for the last generated columnt. We
|
|
||||||
// can come up with an optimistic estimate, however, by assuming that
|
|
||||||
// mappings are contiguous (i.e. given two consecutive mappings, the
|
|
||||||
// first mapping ends where the second one starts).
|
|
||||||
if (index + 1 < this._generatedMappings.length) {
|
|
||||||
var nextMapping = this._generatedMappings[index + 1];
|
|
||||||
|
|
||||||
if (mapping.generatedLine === nextMapping.generatedLine) {
|
|
||||||
mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The last mapping for each line spans the entire line.
|
|
||||||
mapping.lastGeneratedColumn = Infinity;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the original source, line, and column information for the generated
|
|
||||||
* source's line and column positions provided. The only argument is an object
|
|
||||||
* with the following properties:
|
|
||||||
*
|
|
||||||
* - line: The line number in the generated source.
|
|
||||||
* - column: The column number in the generated source.
|
|
||||||
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
|
|
||||||
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
|
|
||||||
* closest element that is smaller than or greater than the one we are
|
|
||||||
* searching for, respectively, if the exact element cannot be found.
|
|
||||||
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
|
|
||||||
*
|
|
||||||
* and an object is returned with the following properties:
|
|
||||||
*
|
|
||||||
* - source: The original source file, or null.
|
|
||||||
* - line: The line number in the original source, or null.
|
|
||||||
* - column: The column number in the original source, or null.
|
|
||||||
* - name: The original identifier, or null.
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype.originalPositionFor =
|
|
||||||
function SourceMapConsumer_originalPositionFor(aArgs) {
|
|
||||||
var needle = {
|
|
||||||
generatedLine: util.getArg(aArgs, 'line'),
|
|
||||||
generatedColumn: util.getArg(aArgs, 'column')
|
|
||||||
};
|
|
||||||
|
|
||||||
var index = this._findMapping(
|
|
||||||
needle,
|
|
||||||
this._generatedMappings,
|
|
||||||
"generatedLine",
|
|
||||||
"generatedColumn",
|
|
||||||
util.compareByGeneratedPositionsDeflated,
|
|
||||||
util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (index >= 0) {
|
|
||||||
var mapping = this._generatedMappings[index];
|
|
||||||
|
|
||||||
if (mapping.generatedLine === needle.generatedLine) {
|
|
||||||
var source = util.getArg(mapping, 'source', null);
|
|
||||||
if (source !== null) {
|
|
||||||
source = this._sources.at(source);
|
|
||||||
if (this.sourceRoot != null) {
|
|
||||||
source = util.join(this.sourceRoot, source);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var name = util.getArg(mapping, 'name', null);
|
|
||||||
if (name !== null) {
|
|
||||||
name = this._names.at(name);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
source: source,
|
|
||||||
line: util.getArg(mapping, 'originalLine', null),
|
|
||||||
column: util.getArg(mapping, 'originalColumn', null),
|
|
||||||
name: name
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
source: null,
|
|
||||||
line: null,
|
|
||||||
column: null,
|
|
||||||
name: null
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return true if we have the source content for every source in the source
|
|
||||||
* map, false otherwise.
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
|
|
||||||
function BasicSourceMapConsumer_hasContentsOfAllSources() {
|
|
||||||
if (!this.sourcesContent) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return this.sourcesContent.length >= this._sources.size() &&
|
|
||||||
!this.sourcesContent.some(function (sc) { return sc == null; });
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the original source content. The only argument is the url of the
|
|
||||||
* original source file. Returns null if no original source content is
|
|
||||||
* available.
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype.sourceContentFor =
|
|
||||||
function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
|
|
||||||
if (!this.sourcesContent) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.sourceRoot != null) {
|
|
||||||
aSource = util.relative(this.sourceRoot, aSource);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._sources.has(aSource)) {
|
|
||||||
return this.sourcesContent[this._sources.indexOf(aSource)];
|
|
||||||
}
|
|
||||||
|
|
||||||
var url;
|
|
||||||
if (this.sourceRoot != null
|
|
||||||
&& (url = util.urlParse(this.sourceRoot))) {
|
|
||||||
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
|
|
||||||
// many users. We can help them out when they expect file:// URIs to
|
|
||||||
// behave like it would if they were running a local HTTP server. See
|
|
||||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
|
|
||||||
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
|
|
||||||
if (url.scheme == "file"
|
|
||||||
&& this._sources.has(fileUriAbsPath)) {
|
|
||||||
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((!url.path || url.path == "/")
|
|
||||||
&& this._sources.has("/" + aSource)) {
|
|
||||||
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// This function is used recursively from
|
|
||||||
// IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
|
|
||||||
// don't want to throw if we can't find the source - we just want to
|
|
||||||
// return null, so we provide a flag to exit gracefully.
|
|
||||||
if (nullOnMissing) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new Error('"' + aSource + '" is not in the SourceMap.');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the generated line and column information for the original source,
|
|
||||||
* line, and column positions provided. The only argument is an object with
|
|
||||||
* the following properties:
|
|
||||||
*
|
|
||||||
* - source: The filename of the original source.
|
|
||||||
* - line: The line number in the original source.
|
|
||||||
* - column: The column number in the original source.
|
|
||||||
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
|
|
||||||
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
|
|
||||||
* closest element that is smaller than or greater than the one we are
|
|
||||||
* searching for, respectively, if the exact element cannot be found.
|
|
||||||
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
|
|
||||||
*
|
|
||||||
* and an object is returned with the following properties:
|
|
||||||
*
|
|
||||||
* - line: The line number in the generated source, or null.
|
|
||||||
* - column: The column number in the generated source, or null.
|
|
||||||
*/
|
|
||||||
BasicSourceMapConsumer.prototype.generatedPositionFor =
|
|
||||||
function SourceMapConsumer_generatedPositionFor(aArgs) {
|
|
||||||
var source = util.getArg(aArgs, 'source');
|
|
||||||
if (this.sourceRoot != null) {
|
|
||||||
source = util.relative(this.sourceRoot, source);
|
|
||||||
}
|
|
||||||
if (!this._sources.has(source)) {
|
|
||||||
return {
|
|
||||||
line: null,
|
|
||||||
column: null,
|
|
||||||
lastColumn: null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
source = this._sources.indexOf(source);
|
|
||||||
|
|
||||||
var needle = {
|
|
||||||
source: source,
|
|
||||||
originalLine: util.getArg(aArgs, 'line'),
|
|
||||||
originalColumn: util.getArg(aArgs, 'column')
|
|
||||||
};
|
|
||||||
|
|
||||||
var index = this._findMapping(
|
|
||||||
needle,
|
|
||||||
this._originalMappings,
|
|
||||||
"originalLine",
|
|
||||||
"originalColumn",
|
|
||||||
util.compareByOriginalPositions,
|
|
||||||
util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (index >= 0) {
|
|
||||||
var mapping = this._originalMappings[index];
|
|
||||||
|
|
||||||
if (mapping.source === needle.source) {
|
|
||||||
return {
|
|
||||||
line: util.getArg(mapping, 'generatedLine', null),
|
|
||||||
column: util.getArg(mapping, 'generatedColumn', null),
|
|
||||||
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
line: null,
|
|
||||||
column: null,
|
|
||||||
lastColumn: null
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An IndexedSourceMapConsumer instance represents a parsed source map which
|
|
||||||
* we can query for information. It differs from BasicSourceMapConsumer in
|
|
||||||
* that it takes "indexed" source maps (i.e. ones with a "sections" field) as
|
|
||||||
* input.
|
|
||||||
*
|
|
||||||
* The only parameter is a raw source map (either as a JSON string, or already
|
|
||||||
* parsed to an object). According to the spec for indexed source maps, they
|
|
||||||
* have the following attributes:
|
|
||||||
*
|
|
||||||
* - version: Which version of the source map spec this map is following.
|
|
||||||
* - file: Optional. The generated file this source map is associated with.
|
|
||||||
* - sections: A list of section definitions.
|
|
||||||
*
|
|
||||||
* Each value under the "sections" field has two fields:
|
|
||||||
* - offset: The offset into the original specified at which this section
|
|
||||||
* begins to apply, defined as an object with a "line" and "column"
|
|
||||||
* field.
|
|
||||||
* - map: A source map definition. This source map could also be indexed,
|
|
||||||
* but doesn't have to be.
|
|
||||||
*
|
|
||||||
* Instead of the "map" field, it's also possible to have a "url" field
|
|
||||||
* specifying a URL to retrieve a source map from, but that's currently
|
|
||||||
* unsupported.
|
|
||||||
*
|
|
||||||
* Here's an example source map, taken from the source map spec[0], but
|
|
||||||
* modified to omit a section which uses the "url" field.
|
|
||||||
*
|
|
||||||
* {
|
|
||||||
* version : 3,
|
|
||||||
* file: "app.js",
|
|
||||||
* sections: [{
|
|
||||||
* offset: {line:100, column:10},
|
|
||||||
* map: {
|
|
||||||
* version : 3,
|
|
||||||
* file: "section.js",
|
|
||||||
* sources: ["foo.js", "bar.js"],
|
|
||||||
* names: ["src", "maps", "are", "fun"],
|
|
||||||
* mappings: "AAAA,E;;ABCDE;"
|
|
||||||
* }
|
|
||||||
* }],
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
|
|
||||||
*/
|
|
||||||
function IndexedSourceMapConsumer(aSourceMap) {
|
|
||||||
var sourceMap = aSourceMap;
|
|
||||||
if (typeof aSourceMap === 'string') {
|
|
||||||
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
|
|
||||||
}
|
|
||||||
|
|
||||||
var version = util.getArg(sourceMap, 'version');
|
|
||||||
var sections = util.getArg(sourceMap, 'sections');
|
|
||||||
|
|
||||||
if (version != this._version) {
|
|
||||||
throw new Error('Unsupported version: ' + version);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._sources = new ArraySet();
|
|
||||||
this._names = new ArraySet();
|
|
||||||
|
|
||||||
var lastOffset = {
|
|
||||||
line: -1,
|
|
||||||
column: 0
|
|
||||||
};
|
|
||||||
this._sections = sections.map(function (s) {
|
|
||||||
if (s.url) {
|
|
||||||
// The url field will require support for asynchronicity.
|
|
||||||
// See https://github.com/mozilla/source-map/issues/16
|
|
||||||
throw new Error('Support for url field in sections not implemented.');
|
|
||||||
}
|
|
||||||
var offset = util.getArg(s, 'offset');
|
|
||||||
var offsetLine = util.getArg(offset, 'line');
|
|
||||||
var offsetColumn = util.getArg(offset, 'column');
|
|
||||||
|
|
||||||
if (offsetLine < lastOffset.line ||
|
|
||||||
(offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
|
|
||||||
throw new Error('Section offsets must be ordered and non-overlapping.');
|
|
||||||
}
|
|
||||||
lastOffset = offset;
|
|
||||||
|
|
||||||
return {
|
|
||||||
generatedOffset: {
|
|
||||||
// The offset fields are 0-based, but we use 1-based indices when
|
|
||||||
// encoding/decoding from VLQ.
|
|
||||||
generatedLine: offsetLine + 1,
|
|
||||||
generatedColumn: offsetColumn + 1
|
|
||||||
},
|
|
||||||
consumer: new SourceMapConsumer(util.getArg(s, 'map'))
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
|
|
||||||
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The version of the source mapping spec that we are consuming.
|
|
||||||
*/
|
|
||||||
IndexedSourceMapConsumer.prototype._version = 3;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The list of original sources.
|
|
||||||
*/
|
|
||||||
Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
|
|
||||||
get: function () {
|
|
||||||
var sources = [];
|
|
||||||
for (var i = 0; i < this._sections.length; i++) {
|
|
||||||
for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
|
|
||||||
sources.push(this._sections[i].consumer.sources[j]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return sources;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the original source, line, and column information for the generated
|
|
||||||
* source's line and column positions provided. The only argument is an object
|
|
||||||
* with the following properties:
|
|
||||||
*
|
|
||||||
* - line: The line number in the generated source.
|
|
||||||
* - column: The column number in the generated source.
|
|
||||||
*
|
|
||||||
* and an object is returned with the following properties:
|
|
||||||
*
|
|
||||||
* - source: The original source file, or null.
|
|
||||||
* - line: The line number in the original source, or null.
|
|
||||||
* - column: The column number in the original source, or null.
|
|
||||||
* - name: The original identifier, or null.
|
|
||||||
*/
|
|
||||||
IndexedSourceMapConsumer.prototype.originalPositionFor =
|
|
||||||
function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
|
|
||||||
var needle = {
|
|
||||||
generatedLine: util.getArg(aArgs, 'line'),
|
|
||||||
generatedColumn: util.getArg(aArgs, 'column')
|
|
||||||
};
|
|
||||||
|
|
||||||
// Find the section containing the generated position we're trying to map
|
|
||||||
// to an original position.
|
|
||||||
var sectionIndex = binarySearch.search(needle, this._sections,
|
|
||||||
function(needle, section) {
|
|
||||||
var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
|
|
||||||
if (cmp) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (needle.generatedColumn -
|
|
||||||
section.generatedOffset.generatedColumn);
|
|
||||||
});
|
|
||||||
var section = this._sections[sectionIndex];
|
|
||||||
|
|
||||||
if (!section) {
|
|
||||||
return {
|
|
||||||
source: null,
|
|
||||||
line: null,
|
|
||||||
column: null,
|
|
||||||
name: null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return section.consumer.originalPositionFor({
|
|
||||||
line: needle.generatedLine -
|
|
||||||
(section.generatedOffset.generatedLine - 1),
|
|
||||||
column: needle.generatedColumn -
|
|
||||||
(section.generatedOffset.generatedLine === needle.generatedLine
|
|
||||||
? section.generatedOffset.generatedColumn - 1
|
|
||||||
: 0),
|
|
||||||
bias: aArgs.bias
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return true if we have the source content for every source in the source
|
|
||||||
* map, false otherwise.
|
|
||||||
*/
|
|
||||||
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
|
|
||||||
function IndexedSourceMapConsumer_hasContentsOfAllSources() {
|
|
||||||
return this._sections.every(function (s) {
|
|
||||||
return s.consumer.hasContentsOfAllSources();
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the original source content. The only argument is the url of the
|
|
||||||
* original source file. Returns null if no original source content is
|
|
||||||
* available.
|
|
||||||
*/
|
|
||||||
IndexedSourceMapConsumer.prototype.sourceContentFor =
|
|
||||||
function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
|
|
||||||
for (var i = 0; i < this._sections.length; i++) {
|
|
||||||
var section = this._sections[i];
|
|
||||||
|
|
||||||
var content = section.consumer.sourceContentFor(aSource, true);
|
|
||||||
if (content) {
|
|
||||||
return content;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (nullOnMissing) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new Error('"' + aSource + '" is not in the SourceMap.');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the generated line and column information for the original source,
|
|
||||||
* line, and column positions provided. The only argument is an object with
|
|
||||||
* the following properties:
|
|
||||||
*
|
|
||||||
* - source: The filename of the original source.
|
|
||||||
* - line: The line number in the original source.
|
|
||||||
* - column: The column number in the original source.
|
|
||||||
*
|
|
||||||
* and an object is returned with the following properties:
|
|
||||||
*
|
|
||||||
* - line: The line number in the generated source, or null.
|
|
||||||
* - column: The column number in the generated source, or null.
|
|
||||||
*/
|
|
||||||
IndexedSourceMapConsumer.prototype.generatedPositionFor =
|
|
||||||
function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
|
|
||||||
for (var i = 0; i < this._sections.length; i++) {
|
|
||||||
var section = this._sections[i];
|
|
||||||
|
|
||||||
// Only consider this section if the requested source is in the list of
|
|
||||||
// sources of the consumer.
|
|
||||||
if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
var generatedPosition = section.consumer.generatedPositionFor(aArgs);
|
|
||||||
if (generatedPosition) {
|
|
||||||
var ret = {
|
|
||||||
line: generatedPosition.line +
|
|
||||||
(section.generatedOffset.generatedLine - 1),
|
|
||||||
column: generatedPosition.column +
|
|
||||||
(section.generatedOffset.generatedLine === generatedPosition.line
|
|
||||||
? section.generatedOffset.generatedColumn - 1
|
|
||||||
: 0)
|
|
||||||
};
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
line: null,
|
|
||||||
column: null
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse the mappings in a string in to a data structure which we can easily
|
|
||||||
* query (the ordered arrays in the `this.__generatedMappings` and
|
|
||||||
* `this.__originalMappings` properties).
|
|
||||||
*/
|
|
||||||
IndexedSourceMapConsumer.prototype._parseMappings =
|
|
||||||
function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
|
|
||||||
this.__generatedMappings = [];
|
|
||||||
this.__originalMappings = [];
|
|
||||||
for (var i = 0; i < this._sections.length; i++) {
|
|
||||||
var section = this._sections[i];
|
|
||||||
var sectionMappings = section.consumer._generatedMappings;
|
|
||||||
for (var j = 0; j < sectionMappings.length; j++) {
|
|
||||||
var mapping = sectionMappings[j];
|
|
||||||
|
|
||||||
var source = section.consumer._sources.at(mapping.source);
|
|
||||||
if (section.consumer.sourceRoot !== null) {
|
|
||||||
source = util.join(section.consumer.sourceRoot, source);
|
|
||||||
}
|
|
||||||
this._sources.add(source);
|
|
||||||
source = this._sources.indexOf(source);
|
|
||||||
|
|
||||||
var name = section.consumer._names.at(mapping.name);
|
|
||||||
this._names.add(name);
|
|
||||||
name = this._names.indexOf(name);
|
|
||||||
|
|
||||||
// The mappings coming from the consumer for the section have
|
|
||||||
// generated positions relative to the start of the section, so we
|
|
||||||
// need to offset them to be relative to the start of the concatenated
|
|
||||||
// generated file.
|
|
||||||
var adjustedMapping = {
|
|
||||||
source: source,
|
|
||||||
generatedLine: mapping.generatedLine +
|
|
||||||
(section.generatedOffset.generatedLine - 1),
|
|
||||||
generatedColumn: mapping.generatedColumn +
|
|
||||||
(section.generatedOffset.generatedLine === mapping.generatedLine
|
|
||||||
? section.generatedOffset.generatedColumn - 1
|
|
||||||
: 0),
|
|
||||||
originalLine: mapping.originalLine,
|
|
||||||
originalColumn: mapping.originalColumn,
|
|
||||||
name: name
|
|
||||||
};
|
|
||||||
|
|
||||||
this.__generatedMappings.push(adjustedMapping);
|
|
||||||
if (typeof adjustedMapping.originalLine === 'number') {
|
|
||||||
this.__originalMappings.push(adjustedMapping);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
|
|
||||||
quickSort(this.__originalMappings, util.compareByOriginalPositions);
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
|
|
||||||
|
|
@ -1,416 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
var base64VLQ = require('./base64-vlq');
|
|
||||||
var util = require('./util');
|
|
||||||
var ArraySet = require('./array-set').ArraySet;
|
|
||||||
var MappingList = require('./mapping-list').MappingList;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An instance of the SourceMapGenerator represents a source map which is
|
|
||||||
* being built incrementally. You may pass an object with the following
|
|
||||||
* properties:
|
|
||||||
*
|
|
||||||
* - file: The filename of the generated source.
|
|
||||||
* - sourceRoot: A root for all relative URLs in this source map.
|
|
||||||
*/
|
|
||||||
function SourceMapGenerator(aArgs) {
|
|
||||||
if (!aArgs) {
|
|
||||||
aArgs = {};
|
|
||||||
}
|
|
||||||
this._file = util.getArg(aArgs, 'file', null);
|
|
||||||
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
|
|
||||||
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
|
|
||||||
this._sources = new ArraySet();
|
|
||||||
this._names = new ArraySet();
|
|
||||||
this._mappings = new MappingList();
|
|
||||||
this._sourcesContents = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
SourceMapGenerator.prototype._version = 3;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new SourceMapGenerator based on a SourceMapConsumer
|
|
||||||
*
|
|
||||||
* @param aSourceMapConsumer The SourceMap.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.fromSourceMap =
|
|
||||||
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
|
|
||||||
var sourceRoot = aSourceMapConsumer.sourceRoot;
|
|
||||||
var generator = new SourceMapGenerator({
|
|
||||||
file: aSourceMapConsumer.file,
|
|
||||||
sourceRoot: sourceRoot
|
|
||||||
});
|
|
||||||
aSourceMapConsumer.eachMapping(function (mapping) {
|
|
||||||
var newMapping = {
|
|
||||||
generated: {
|
|
||||||
line: mapping.generatedLine,
|
|
||||||
column: mapping.generatedColumn
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (mapping.source != null) {
|
|
||||||
newMapping.source = mapping.source;
|
|
||||||
if (sourceRoot != null) {
|
|
||||||
newMapping.source = util.relative(sourceRoot, newMapping.source);
|
|
||||||
}
|
|
||||||
|
|
||||||
newMapping.original = {
|
|
||||||
line: mapping.originalLine,
|
|
||||||
column: mapping.originalColumn
|
|
||||||
};
|
|
||||||
|
|
||||||
if (mapping.name != null) {
|
|
||||||
newMapping.name = mapping.name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
generator.addMapping(newMapping);
|
|
||||||
});
|
|
||||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
|
||||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
|
||||||
if (content != null) {
|
|
||||||
generator.setSourceContent(sourceFile, content);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return generator;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a single mapping from original source line and column to the generated
|
|
||||||
* source's line and column for this source map being created. The mapping
|
|
||||||
* object should have the following properties:
|
|
||||||
*
|
|
||||||
* - generated: An object with the generated line and column positions.
|
|
||||||
* - original: An object with the original line and column positions.
|
|
||||||
* - source: The original source file (relative to the sourceRoot).
|
|
||||||
* - name: An optional original token name for this mapping.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.prototype.addMapping =
|
|
||||||
function SourceMapGenerator_addMapping(aArgs) {
|
|
||||||
var generated = util.getArg(aArgs, 'generated');
|
|
||||||
var original = util.getArg(aArgs, 'original', null);
|
|
||||||
var source = util.getArg(aArgs, 'source', null);
|
|
||||||
var name = util.getArg(aArgs, 'name', null);
|
|
||||||
|
|
||||||
if (!this._skipValidation) {
|
|
||||||
this._validateMapping(generated, original, source, name);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (source != null) {
|
|
||||||
source = String(source);
|
|
||||||
if (!this._sources.has(source)) {
|
|
||||||
this._sources.add(source);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (name != null) {
|
|
||||||
name = String(name);
|
|
||||||
if (!this._names.has(name)) {
|
|
||||||
this._names.add(name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this._mappings.add({
|
|
||||||
generatedLine: generated.line,
|
|
||||||
generatedColumn: generated.column,
|
|
||||||
originalLine: original != null && original.line,
|
|
||||||
originalColumn: original != null && original.column,
|
|
||||||
source: source,
|
|
||||||
name: name
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set the source content for a source file.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.prototype.setSourceContent =
|
|
||||||
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
|
|
||||||
var source = aSourceFile;
|
|
||||||
if (this._sourceRoot != null) {
|
|
||||||
source = util.relative(this._sourceRoot, source);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aSourceContent != null) {
|
|
||||||
// Add the source content to the _sourcesContents map.
|
|
||||||
// Create a new _sourcesContents map if the property is null.
|
|
||||||
if (!this._sourcesContents) {
|
|
||||||
this._sourcesContents = Object.create(null);
|
|
||||||
}
|
|
||||||
this._sourcesContents[util.toSetString(source)] = aSourceContent;
|
|
||||||
} else if (this._sourcesContents) {
|
|
||||||
// Remove the source file from the _sourcesContents map.
|
|
||||||
// If the _sourcesContents map is empty, set the property to null.
|
|
||||||
delete this._sourcesContents[util.toSetString(source)];
|
|
||||||
if (Object.keys(this._sourcesContents).length === 0) {
|
|
||||||
this._sourcesContents = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Applies the mappings of a sub-source-map for a specific source file to the
|
|
||||||
* source map being generated. Each mapping to the supplied source file is
|
|
||||||
* rewritten using the supplied source map. Note: The resolution for the
|
|
||||||
* resulting mappings is the minimium of this map and the supplied map.
|
|
||||||
*
|
|
||||||
* @param aSourceMapConsumer The source map to be applied.
|
|
||||||
* @param aSourceFile Optional. The filename of the source file.
|
|
||||||
* If omitted, SourceMapConsumer's file property will be used.
|
|
||||||
* @param aSourceMapPath Optional. The dirname of the path to the source map
|
|
||||||
* to be applied. If relative, it is relative to the SourceMapConsumer.
|
|
||||||
* This parameter is needed when the two source maps aren't in the same
|
|
||||||
* directory, and the source map to be applied contains relative source
|
|
||||||
* paths. If so, those relative source paths need to be rewritten
|
|
||||||
* relative to the SourceMapGenerator.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.prototype.applySourceMap =
|
|
||||||
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
|
|
||||||
var sourceFile = aSourceFile;
|
|
||||||
// If aSourceFile is omitted, we will use the file property of the SourceMap
|
|
||||||
if (aSourceFile == null) {
|
|
||||||
if (aSourceMapConsumer.file == null) {
|
|
||||||
throw new Error(
|
|
||||||
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
|
|
||||||
'or the source map\'s "file" property. Both were omitted.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
sourceFile = aSourceMapConsumer.file;
|
|
||||||
}
|
|
||||||
var sourceRoot = this._sourceRoot;
|
|
||||||
// Make "sourceFile" relative if an absolute Url is passed.
|
|
||||||
if (sourceRoot != null) {
|
|
||||||
sourceFile = util.relative(sourceRoot, sourceFile);
|
|
||||||
}
|
|
||||||
// Applying the SourceMap can add and remove items from the sources and
|
|
||||||
// the names array.
|
|
||||||
var newSources = new ArraySet();
|
|
||||||
var newNames = new ArraySet();
|
|
||||||
|
|
||||||
// Find mappings for the "sourceFile"
|
|
||||||
this._mappings.unsortedForEach(function (mapping) {
|
|
||||||
if (mapping.source === sourceFile && mapping.originalLine != null) {
|
|
||||||
// Check if it can be mapped by the source map, then update the mapping.
|
|
||||||
var original = aSourceMapConsumer.originalPositionFor({
|
|
||||||
line: mapping.originalLine,
|
|
||||||
column: mapping.originalColumn
|
|
||||||
});
|
|
||||||
if (original.source != null) {
|
|
||||||
// Copy mapping
|
|
||||||
mapping.source = original.source;
|
|
||||||
if (aSourceMapPath != null) {
|
|
||||||
mapping.source = util.join(aSourceMapPath, mapping.source)
|
|
||||||
}
|
|
||||||
if (sourceRoot != null) {
|
|
||||||
mapping.source = util.relative(sourceRoot, mapping.source);
|
|
||||||
}
|
|
||||||
mapping.originalLine = original.line;
|
|
||||||
mapping.originalColumn = original.column;
|
|
||||||
if (original.name != null) {
|
|
||||||
mapping.name = original.name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var source = mapping.source;
|
|
||||||
if (source != null && !newSources.has(source)) {
|
|
||||||
newSources.add(source);
|
|
||||||
}
|
|
||||||
|
|
||||||
var name = mapping.name;
|
|
||||||
if (name != null && !newNames.has(name)) {
|
|
||||||
newNames.add(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
}, this);
|
|
||||||
this._sources = newSources;
|
|
||||||
this._names = newNames;
|
|
||||||
|
|
||||||
// Copy sourcesContents of applied map.
|
|
||||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
|
||||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
|
||||||
if (content != null) {
|
|
||||||
if (aSourceMapPath != null) {
|
|
||||||
sourceFile = util.join(aSourceMapPath, sourceFile);
|
|
||||||
}
|
|
||||||
if (sourceRoot != null) {
|
|
||||||
sourceFile = util.relative(sourceRoot, sourceFile);
|
|
||||||
}
|
|
||||||
this.setSourceContent(sourceFile, content);
|
|
||||||
}
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A mapping can have one of the three levels of data:
|
|
||||||
*
|
|
||||||
* 1. Just the generated position.
|
|
||||||
* 2. The Generated position, original position, and original source.
|
|
||||||
* 3. Generated and original position, original source, as well as a name
|
|
||||||
* token.
|
|
||||||
*
|
|
||||||
* To maintain consistency, we validate that any new mapping being added falls
|
|
||||||
* in to one of these categories.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.prototype._validateMapping =
|
|
||||||
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
|
|
||||||
aName) {
|
|
||||||
// When aOriginal is truthy but has empty values for .line and .column,
|
|
||||||
// it is most likely a programmer error. In this case we throw a very
|
|
||||||
// specific error message to try to guide them the right way.
|
|
||||||
// For example: https://github.com/Polymer/polymer-bundler/pull/519
|
|
||||||
if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
|
|
||||||
throw new Error(
|
|
||||||
'original.line and original.column are not numbers -- you probably meant to omit ' +
|
|
||||||
'the original mapping entirely and only map the generated position. If so, pass ' +
|
|
||||||
'null for the original mapping instead of an object with empty or null values.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
|
||||||
&& aGenerated.line > 0 && aGenerated.column >= 0
|
|
||||||
&& !aOriginal && !aSource && !aName) {
|
|
||||||
// Case 1.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
|
|
||||||
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
|
|
||||||
&& aGenerated.line > 0 && aGenerated.column >= 0
|
|
||||||
&& aOriginal.line > 0 && aOriginal.column >= 0
|
|
||||||
&& aSource) {
|
|
||||||
// Cases 2 and 3.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new Error('Invalid mapping: ' + JSON.stringify({
|
|
||||||
generated: aGenerated,
|
|
||||||
source: aSource,
|
|
||||||
original: aOriginal,
|
|
||||||
name: aName
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Serialize the accumulated mappings in to the stream of base 64 VLQs
|
|
||||||
* specified by the source map format.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.prototype._serializeMappings =
|
|
||||||
function SourceMapGenerator_serializeMappings() {
|
|
||||||
var previousGeneratedColumn = 0;
|
|
||||||
var previousGeneratedLine = 1;
|
|
||||||
var previousOriginalColumn = 0;
|
|
||||||
var previousOriginalLine = 0;
|
|
||||||
var previousName = 0;
|
|
||||||
var previousSource = 0;
|
|
||||||
var result = '';
|
|
||||||
var next;
|
|
||||||
var mapping;
|
|
||||||
var nameIdx;
|
|
||||||
var sourceIdx;
|
|
||||||
|
|
||||||
var mappings = this._mappings.toArray();
|
|
||||||
for (var i = 0, len = mappings.length; i < len; i++) {
|
|
||||||
mapping = mappings[i];
|
|
||||||
next = ''
|
|
||||||
|
|
||||||
if (mapping.generatedLine !== previousGeneratedLine) {
|
|
||||||
previousGeneratedColumn = 0;
|
|
||||||
while (mapping.generatedLine !== previousGeneratedLine) {
|
|
||||||
next += ';';
|
|
||||||
previousGeneratedLine++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (i > 0) {
|
|
||||||
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
next += ',';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
next += base64VLQ.encode(mapping.generatedColumn
|
|
||||||
- previousGeneratedColumn);
|
|
||||||
previousGeneratedColumn = mapping.generatedColumn;
|
|
||||||
|
|
||||||
if (mapping.source != null) {
|
|
||||||
sourceIdx = this._sources.indexOf(mapping.source);
|
|
||||||
next += base64VLQ.encode(sourceIdx - previousSource);
|
|
||||||
previousSource = sourceIdx;
|
|
||||||
|
|
||||||
// lines are stored 0-based in SourceMap spec version 3
|
|
||||||
next += base64VLQ.encode(mapping.originalLine - 1
|
|
||||||
- previousOriginalLine);
|
|
||||||
previousOriginalLine = mapping.originalLine - 1;
|
|
||||||
|
|
||||||
next += base64VLQ.encode(mapping.originalColumn
|
|
||||||
- previousOriginalColumn);
|
|
||||||
previousOriginalColumn = mapping.originalColumn;
|
|
||||||
|
|
||||||
if (mapping.name != null) {
|
|
||||||
nameIdx = this._names.indexOf(mapping.name);
|
|
||||||
next += base64VLQ.encode(nameIdx - previousName);
|
|
||||||
previousName = nameIdx;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
result += next;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
|
|
||||||
SourceMapGenerator.prototype._generateSourcesContent =
|
|
||||||
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
|
|
||||||
return aSources.map(function (source) {
|
|
||||||
if (!this._sourcesContents) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (aSourceRoot != null) {
|
|
||||||
source = util.relative(aSourceRoot, source);
|
|
||||||
}
|
|
||||||
var key = util.toSetString(source);
|
|
||||||
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
|
|
||||||
? this._sourcesContents[key]
|
|
||||||
: null;
|
|
||||||
}, this);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Externalize the source map.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.prototype.toJSON =
|
|
||||||
function SourceMapGenerator_toJSON() {
|
|
||||||
var map = {
|
|
||||||
version: this._version,
|
|
||||||
sources: this._sources.toArray(),
|
|
||||||
names: this._names.toArray(),
|
|
||||||
mappings: this._serializeMappings()
|
|
||||||
};
|
|
||||||
if (this._file != null) {
|
|
||||||
map.file = this._file;
|
|
||||||
}
|
|
||||||
if (this._sourceRoot != null) {
|
|
||||||
map.sourceRoot = this._sourceRoot;
|
|
||||||
}
|
|
||||||
if (this._sourcesContents) {
|
|
||||||
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
|
|
||||||
}
|
|
||||||
|
|
||||||
return map;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Render the source map being generated to a string.
|
|
||||||
*/
|
|
||||||
SourceMapGenerator.prototype.toString =
|
|
||||||
function SourceMapGenerator_toString() {
|
|
||||||
return JSON.stringify(this.toJSON());
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.SourceMapGenerator = SourceMapGenerator;
|
|
||||||
|
|
@ -1,413 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
|
|
||||||
var util = require('./util');
|
|
||||||
|
|
||||||
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
|
|
||||||
// operating systems these days (capturing the result).
|
|
||||||
var REGEX_NEWLINE = /(\r?\n)/;
|
|
||||||
|
|
||||||
// Newline character code for charCodeAt() comparisons
|
|
||||||
var NEWLINE_CODE = 10;
|
|
||||||
|
|
||||||
// Private symbol for identifying `SourceNode`s when multiple versions of
|
|
||||||
// the source-map library are loaded. This MUST NOT CHANGE across
|
|
||||||
// versions!
|
|
||||||
var isSourceNode = "$$$isSourceNode$$$";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SourceNodes provide a way to abstract over interpolating/concatenating
|
|
||||||
* snippets of generated JavaScript source code while maintaining the line and
|
|
||||||
* column information associated with the original source code.
|
|
||||||
*
|
|
||||||
* @param aLine The original line number.
|
|
||||||
* @param aColumn The original column number.
|
|
||||||
* @param aSource The original source's filename.
|
|
||||||
* @param aChunks Optional. An array of strings which are snippets of
|
|
||||||
* generated JS, or other SourceNodes.
|
|
||||||
* @param aName The original identifier.
|
|
||||||
*/
|
|
||||||
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
|
|
||||||
this.children = [];
|
|
||||||
this.sourceContents = {};
|
|
||||||
this.line = aLine == null ? null : aLine;
|
|
||||||
this.column = aColumn == null ? null : aColumn;
|
|
||||||
this.source = aSource == null ? null : aSource;
|
|
||||||
this.name = aName == null ? null : aName;
|
|
||||||
this[isSourceNode] = true;
|
|
||||||
if (aChunks != null) this.add(aChunks);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a SourceNode from generated code and a SourceMapConsumer.
|
|
||||||
*
|
|
||||||
* @param aGeneratedCode The generated code
|
|
||||||
* @param aSourceMapConsumer The SourceMap for the generated code
|
|
||||||
* @param aRelativePath Optional. The path that relative sources in the
|
|
||||||
* SourceMapConsumer should be relative to.
|
|
||||||
*/
|
|
||||||
SourceNode.fromStringWithSourceMap =
|
|
||||||
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
|
|
||||||
// The SourceNode we want to fill with the generated code
|
|
||||||
// and the SourceMap
|
|
||||||
var node = new SourceNode();
|
|
||||||
|
|
||||||
// All even indices of this array are one line of the generated code,
|
|
||||||
// while all odd indices are the newlines between two adjacent lines
|
|
||||||
// (since `REGEX_NEWLINE` captures its match).
|
|
||||||
// Processed fragments are accessed by calling `shiftNextLine`.
|
|
||||||
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
|
|
||||||
var remainingLinesIndex = 0;
|
|
||||||
var shiftNextLine = function() {
|
|
||||||
var lineContents = getNextLine();
|
|
||||||
// The last line of a file might not have a newline.
|
|
||||||
var newLine = getNextLine() || "";
|
|
||||||
return lineContents + newLine;
|
|
||||||
|
|
||||||
function getNextLine() {
|
|
||||||
return remainingLinesIndex < remainingLines.length ?
|
|
||||||
remainingLines[remainingLinesIndex++] : undefined;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// We need to remember the position of "remainingLines"
|
|
||||||
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
|
|
||||||
|
|
||||||
// The generate SourceNodes we need a code range.
|
|
||||||
// To extract it current and last mapping is used.
|
|
||||||
// Here we store the last mapping.
|
|
||||||
var lastMapping = null;
|
|
||||||
|
|
||||||
aSourceMapConsumer.eachMapping(function (mapping) {
|
|
||||||
if (lastMapping !== null) {
|
|
||||||
// We add the code from "lastMapping" to "mapping":
|
|
||||||
// First check if there is a new line in between.
|
|
||||||
if (lastGeneratedLine < mapping.generatedLine) {
|
|
||||||
// Associate first line with "lastMapping"
|
|
||||||
addMappingWithCode(lastMapping, shiftNextLine());
|
|
||||||
lastGeneratedLine++;
|
|
||||||
lastGeneratedColumn = 0;
|
|
||||||
// The remaining code is added without mapping
|
|
||||||
} else {
|
|
||||||
// There is no new line in between.
|
|
||||||
// Associate the code between "lastGeneratedColumn" and
|
|
||||||
// "mapping.generatedColumn" with "lastMapping"
|
|
||||||
var nextLine = remainingLines[remainingLinesIndex];
|
|
||||||
var code = nextLine.substr(0, mapping.generatedColumn -
|
|
||||||
lastGeneratedColumn);
|
|
||||||
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
|
|
||||||
lastGeneratedColumn);
|
|
||||||
lastGeneratedColumn = mapping.generatedColumn;
|
|
||||||
addMappingWithCode(lastMapping, code);
|
|
||||||
// No more remaining code, continue
|
|
||||||
lastMapping = mapping;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// We add the generated code until the first mapping
|
|
||||||
// to the SourceNode without any mapping.
|
|
||||||
// Each line is added as separate string.
|
|
||||||
while (lastGeneratedLine < mapping.generatedLine) {
|
|
||||||
node.add(shiftNextLine());
|
|
||||||
lastGeneratedLine++;
|
|
||||||
}
|
|
||||||
if (lastGeneratedColumn < mapping.generatedColumn) {
|
|
||||||
var nextLine = remainingLines[remainingLinesIndex];
|
|
||||||
node.add(nextLine.substr(0, mapping.generatedColumn));
|
|
||||||
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
|
|
||||||
lastGeneratedColumn = mapping.generatedColumn;
|
|
||||||
}
|
|
||||||
lastMapping = mapping;
|
|
||||||
}, this);
|
|
||||||
// We have processed all mappings.
|
|
||||||
if (remainingLinesIndex < remainingLines.length) {
|
|
||||||
if (lastMapping) {
|
|
||||||
// Associate the remaining code in the current line with "lastMapping"
|
|
||||||
addMappingWithCode(lastMapping, shiftNextLine());
|
|
||||||
}
|
|
||||||
// and add the remaining lines without any mapping
|
|
||||||
node.add(remainingLines.splice(remainingLinesIndex).join(""));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copy sourcesContent into SourceNode
|
|
||||||
aSourceMapConsumer.sources.forEach(function (sourceFile) {
|
|
||||||
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
|
||||||
if (content != null) {
|
|
||||||
if (aRelativePath != null) {
|
|
||||||
sourceFile = util.join(aRelativePath, sourceFile);
|
|
||||||
}
|
|
||||||
node.setSourceContent(sourceFile, content);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return node;
|
|
||||||
|
|
||||||
function addMappingWithCode(mapping, code) {
|
|
||||||
if (mapping === null || mapping.source === undefined) {
|
|
||||||
node.add(code);
|
|
||||||
} else {
|
|
||||||
var source = aRelativePath
|
|
||||||
? util.join(aRelativePath, mapping.source)
|
|
||||||
: mapping.source;
|
|
||||||
node.add(new SourceNode(mapping.originalLine,
|
|
||||||
mapping.originalColumn,
|
|
||||||
source,
|
|
||||||
code,
|
|
||||||
mapping.name));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a chunk of generated JS to this source node.
|
|
||||||
*
|
|
||||||
* @param aChunk A string snippet of generated JS code, another instance of
|
|
||||||
* SourceNode, or an array where each member is one of those things.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.add = function SourceNode_add(aChunk) {
|
|
||||||
if (Array.isArray(aChunk)) {
|
|
||||||
aChunk.forEach(function (chunk) {
|
|
||||||
this.add(chunk);
|
|
||||||
}, this);
|
|
||||||
}
|
|
||||||
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
|
|
||||||
if (aChunk) {
|
|
||||||
this.children.push(aChunk);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new TypeError(
|
|
||||||
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a chunk of generated JS to the beginning of this source node.
|
|
||||||
*
|
|
||||||
* @param aChunk A string snippet of generated JS code, another instance of
|
|
||||||
* SourceNode, or an array where each member is one of those things.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
|
|
||||||
if (Array.isArray(aChunk)) {
|
|
||||||
for (var i = aChunk.length-1; i >= 0; i--) {
|
|
||||||
this.prepend(aChunk[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
|
|
||||||
this.children.unshift(aChunk);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new TypeError(
|
|
||||||
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Walk over the tree of JS snippets in this node and its children. The
|
|
||||||
* walking function is called once for each snippet of JS and is passed that
|
|
||||||
* snippet and the its original associated source's line/column location.
|
|
||||||
*
|
|
||||||
* @param aFn The traversal function.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
|
|
||||||
var chunk;
|
|
||||||
for (var i = 0, len = this.children.length; i < len; i++) {
|
|
||||||
chunk = this.children[i];
|
|
||||||
if (chunk[isSourceNode]) {
|
|
||||||
chunk.walk(aFn);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (chunk !== '') {
|
|
||||||
aFn(chunk, { source: this.source,
|
|
||||||
line: this.line,
|
|
||||||
column: this.column,
|
|
||||||
name: this.name });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
|
|
||||||
* each of `this.children`.
|
|
||||||
*
|
|
||||||
* @param aSep The separator.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.join = function SourceNode_join(aSep) {
|
|
||||||
var newChildren;
|
|
||||||
var i;
|
|
||||||
var len = this.children.length;
|
|
||||||
if (len > 0) {
|
|
||||||
newChildren = [];
|
|
||||||
for (i = 0; i < len-1; i++) {
|
|
||||||
newChildren.push(this.children[i]);
|
|
||||||
newChildren.push(aSep);
|
|
||||||
}
|
|
||||||
newChildren.push(this.children[i]);
|
|
||||||
this.children = newChildren;
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Call String.prototype.replace on the very right-most source snippet. Useful
|
|
||||||
* for trimming whitespace from the end of a source node, etc.
|
|
||||||
*
|
|
||||||
* @param aPattern The pattern to replace.
|
|
||||||
* @param aReplacement The thing to replace the pattern with.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
|
|
||||||
var lastChild = this.children[this.children.length - 1];
|
|
||||||
if (lastChild[isSourceNode]) {
|
|
||||||
lastChild.replaceRight(aPattern, aReplacement);
|
|
||||||
}
|
|
||||||
else if (typeof lastChild === 'string') {
|
|
||||||
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
this.children.push(''.replace(aPattern, aReplacement));
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set the source content for a source file. This will be added to the SourceMapGenerator
|
|
||||||
* in the sourcesContent field.
|
|
||||||
*
|
|
||||||
* @param aSourceFile The filename of the source file
|
|
||||||
* @param aSourceContent The content of the source file
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.setSourceContent =
|
|
||||||
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
|
|
||||||
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Walk over the tree of SourceNodes. The walking function is called for each
|
|
||||||
* source file content and is passed the filename and source content.
|
|
||||||
*
|
|
||||||
* @param aFn The traversal function.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.walkSourceContents =
|
|
||||||
function SourceNode_walkSourceContents(aFn) {
|
|
||||||
for (var i = 0, len = this.children.length; i < len; i++) {
|
|
||||||
if (this.children[i][isSourceNode]) {
|
|
||||||
this.children[i].walkSourceContents(aFn);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var sources = Object.keys(this.sourceContents);
|
|
||||||
for (var i = 0, len = sources.length; i < len; i++) {
|
|
||||||
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return the string representation of this source node. Walks over the tree
|
|
||||||
* and concatenates all the various snippets together to one string.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.toString = function SourceNode_toString() {
|
|
||||||
var str = "";
|
|
||||||
this.walk(function (chunk) {
|
|
||||||
str += chunk;
|
|
||||||
});
|
|
||||||
return str;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the string representation of this source node along with a source
|
|
||||||
* map.
|
|
||||||
*/
|
|
||||||
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
|
|
||||||
var generated = {
|
|
||||||
code: "",
|
|
||||||
line: 1,
|
|
||||||
column: 0
|
|
||||||
};
|
|
||||||
var map = new SourceMapGenerator(aArgs);
|
|
||||||
var sourceMappingActive = false;
|
|
||||||
var lastOriginalSource = null;
|
|
||||||
var lastOriginalLine = null;
|
|
||||||
var lastOriginalColumn = null;
|
|
||||||
var lastOriginalName = null;
|
|
||||||
this.walk(function (chunk, original) {
|
|
||||||
generated.code += chunk;
|
|
||||||
if (original.source !== null
|
|
||||||
&& original.line !== null
|
|
||||||
&& original.column !== null) {
|
|
||||||
if(lastOriginalSource !== original.source
|
|
||||||
|| lastOriginalLine !== original.line
|
|
||||||
|| lastOriginalColumn !== original.column
|
|
||||||
|| lastOriginalName !== original.name) {
|
|
||||||
map.addMapping({
|
|
||||||
source: original.source,
|
|
||||||
original: {
|
|
||||||
line: original.line,
|
|
||||||
column: original.column
|
|
||||||
},
|
|
||||||
generated: {
|
|
||||||
line: generated.line,
|
|
||||||
column: generated.column
|
|
||||||
},
|
|
||||||
name: original.name
|
|
||||||
});
|
|
||||||
}
|
|
||||||
lastOriginalSource = original.source;
|
|
||||||
lastOriginalLine = original.line;
|
|
||||||
lastOriginalColumn = original.column;
|
|
||||||
lastOriginalName = original.name;
|
|
||||||
sourceMappingActive = true;
|
|
||||||
} else if (sourceMappingActive) {
|
|
||||||
map.addMapping({
|
|
||||||
generated: {
|
|
||||||
line: generated.line,
|
|
||||||
column: generated.column
|
|
||||||
}
|
|
||||||
});
|
|
||||||
lastOriginalSource = null;
|
|
||||||
sourceMappingActive = false;
|
|
||||||
}
|
|
||||||
for (var idx = 0, length = chunk.length; idx < length; idx++) {
|
|
||||||
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
|
|
||||||
generated.line++;
|
|
||||||
generated.column = 0;
|
|
||||||
// Mappings end at eol
|
|
||||||
if (idx + 1 === length) {
|
|
||||||
lastOriginalSource = null;
|
|
||||||
sourceMappingActive = false;
|
|
||||||
} else if (sourceMappingActive) {
|
|
||||||
map.addMapping({
|
|
||||||
source: original.source,
|
|
||||||
original: {
|
|
||||||
line: original.line,
|
|
||||||
column: original.column
|
|
||||||
},
|
|
||||||
generated: {
|
|
||||||
line: generated.line,
|
|
||||||
column: generated.column
|
|
||||||
},
|
|
||||||
name: original.name
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
generated.column++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
this.walkSourceContents(function (sourceFile, sourceContent) {
|
|
||||||
map.setSourceContent(sourceFile, sourceContent);
|
|
||||||
});
|
|
||||||
|
|
||||||
return { code: generated.code, map: map };
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.SourceNode = SourceNode;
|
|
||||||
|
|
@ -1,417 +0,0 @@
|
||||||
/* -*- Mode: js; js-indent-level: 2; -*- */
|
|
||||||
/*
|
|
||||||
* Copyright 2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This is a helper function for getting values from parameter/options
|
|
||||||
* objects.
|
|
||||||
*
|
|
||||||
* @param args The object we are extracting values from
|
|
||||||
* @param name The name of the property we are getting.
|
|
||||||
* @param defaultValue An optional value to return if the property is missing
|
|
||||||
* from the object. If this is not specified and the property is missing, an
|
|
||||||
* error will be thrown.
|
|
||||||
*/
|
|
||||||
function getArg(aArgs, aName, aDefaultValue) {
|
|
||||||
if (aName in aArgs) {
|
|
||||||
return aArgs[aName];
|
|
||||||
} else if (arguments.length === 3) {
|
|
||||||
return aDefaultValue;
|
|
||||||
} else {
|
|
||||||
throw new Error('"' + aName + '" is a required argument.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exports.getArg = getArg;
|
|
||||||
|
|
||||||
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
|
|
||||||
var dataUrlRegexp = /^data:.+\,.+$/;
|
|
||||||
|
|
||||||
function urlParse(aUrl) {
|
|
||||||
var match = aUrl.match(urlRegexp);
|
|
||||||
if (!match) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
scheme: match[1],
|
|
||||||
auth: match[2],
|
|
||||||
host: match[3],
|
|
||||||
port: match[4],
|
|
||||||
path: match[5]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
exports.urlParse = urlParse;
|
|
||||||
|
|
||||||
function urlGenerate(aParsedUrl) {
|
|
||||||
var url = '';
|
|
||||||
if (aParsedUrl.scheme) {
|
|
||||||
url += aParsedUrl.scheme + ':';
|
|
||||||
}
|
|
||||||
url += '//';
|
|
||||||
if (aParsedUrl.auth) {
|
|
||||||
url += aParsedUrl.auth + '@';
|
|
||||||
}
|
|
||||||
if (aParsedUrl.host) {
|
|
||||||
url += aParsedUrl.host;
|
|
||||||
}
|
|
||||||
if (aParsedUrl.port) {
|
|
||||||
url += ":" + aParsedUrl.port
|
|
||||||
}
|
|
||||||
if (aParsedUrl.path) {
|
|
||||||
url += aParsedUrl.path;
|
|
||||||
}
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
exports.urlGenerate = urlGenerate;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Normalizes a path, or the path portion of a URL:
|
|
||||||
*
|
|
||||||
* - Replaces consecutive slashes with one slash.
|
|
||||||
* - Removes unnecessary '.' parts.
|
|
||||||
* - Removes unnecessary '<dir>/..' parts.
|
|
||||||
*
|
|
||||||
* Based on code in the Node.js 'path' core module.
|
|
||||||
*
|
|
||||||
* @param aPath The path or url to normalize.
|
|
||||||
*/
|
|
||||||
function normalize(aPath) {
|
|
||||||
var path = aPath;
|
|
||||||
var url = urlParse(aPath);
|
|
||||||
if (url) {
|
|
||||||
if (!url.path) {
|
|
||||||
return aPath;
|
|
||||||
}
|
|
||||||
path = url.path;
|
|
||||||
}
|
|
||||||
var isAbsolute = exports.isAbsolute(path);
|
|
||||||
|
|
||||||
var parts = path.split(/\/+/);
|
|
||||||
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
|
|
||||||
part = parts[i];
|
|
||||||
if (part === '.') {
|
|
||||||
parts.splice(i, 1);
|
|
||||||
} else if (part === '..') {
|
|
||||||
up++;
|
|
||||||
} else if (up > 0) {
|
|
||||||
if (part === '') {
|
|
||||||
// The first part is blank if the path is absolute. Trying to go
|
|
||||||
// above the root is a no-op. Therefore we can remove all '..' parts
|
|
||||||
// directly after the root.
|
|
||||||
parts.splice(i + 1, up);
|
|
||||||
up = 0;
|
|
||||||
} else {
|
|
||||||
parts.splice(i, 2);
|
|
||||||
up--;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
path = parts.join('/');
|
|
||||||
|
|
||||||
if (path === '') {
|
|
||||||
path = isAbsolute ? '/' : '.';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url) {
|
|
||||||
url.path = path;
|
|
||||||
return urlGenerate(url);
|
|
||||||
}
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
exports.normalize = normalize;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Joins two paths/URLs.
|
|
||||||
*
|
|
||||||
* @param aRoot The root path or URL.
|
|
||||||
* @param aPath The path or URL to be joined with the root.
|
|
||||||
*
|
|
||||||
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
|
|
||||||
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
|
|
||||||
* first.
|
|
||||||
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
|
|
||||||
* is updated with the result and aRoot is returned. Otherwise the result
|
|
||||||
* is returned.
|
|
||||||
* - If aPath is absolute, the result is aPath.
|
|
||||||
* - Otherwise the two paths are joined with a slash.
|
|
||||||
* - Joining for example 'http://' and 'www.example.com' is also supported.
|
|
||||||
*/
|
|
||||||
function join(aRoot, aPath) {
|
|
||||||
if (aRoot === "") {
|
|
||||||
aRoot = ".";
|
|
||||||
}
|
|
||||||
if (aPath === "") {
|
|
||||||
aPath = ".";
|
|
||||||
}
|
|
||||||
var aPathUrl = urlParse(aPath);
|
|
||||||
var aRootUrl = urlParse(aRoot);
|
|
||||||
if (aRootUrl) {
|
|
||||||
aRoot = aRootUrl.path || '/';
|
|
||||||
}
|
|
||||||
|
|
||||||
// `join(foo, '//www.example.org')`
|
|
||||||
if (aPathUrl && !aPathUrl.scheme) {
|
|
||||||
if (aRootUrl) {
|
|
||||||
aPathUrl.scheme = aRootUrl.scheme;
|
|
||||||
}
|
|
||||||
return urlGenerate(aPathUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aPathUrl || aPath.match(dataUrlRegexp)) {
|
|
||||||
return aPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// `join('http://', 'www.example.com')`
|
|
||||||
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
|
|
||||||
aRootUrl.host = aPath;
|
|
||||||
return urlGenerate(aRootUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
var joined = aPath.charAt(0) === '/'
|
|
||||||
? aPath
|
|
||||||
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
|
|
||||||
|
|
||||||
if (aRootUrl) {
|
|
||||||
aRootUrl.path = joined;
|
|
||||||
return urlGenerate(aRootUrl);
|
|
||||||
}
|
|
||||||
return joined;
|
|
||||||
}
|
|
||||||
exports.join = join;
|
|
||||||
|
|
||||||
exports.isAbsolute = function (aPath) {
|
|
||||||
return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Make a path relative to a URL or another path.
|
|
||||||
*
|
|
||||||
* @param aRoot The root path or URL.
|
|
||||||
* @param aPath The path or URL to be made relative to aRoot.
|
|
||||||
*/
|
|
||||||
function relative(aRoot, aPath) {
|
|
||||||
if (aRoot === "") {
|
|
||||||
aRoot = ".";
|
|
||||||
}
|
|
||||||
|
|
||||||
aRoot = aRoot.replace(/\/$/, '');
|
|
||||||
|
|
||||||
// It is possible for the path to be above the root. In this case, simply
|
|
||||||
// checking whether the root is a prefix of the path won't work. Instead, we
|
|
||||||
// need to remove components from the root one by one, until either we find
|
|
||||||
// a prefix that fits, or we run out of components to remove.
|
|
||||||
var level = 0;
|
|
||||||
while (aPath.indexOf(aRoot + '/') !== 0) {
|
|
||||||
var index = aRoot.lastIndexOf("/");
|
|
||||||
if (index < 0) {
|
|
||||||
return aPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the only part of the root that is left is the scheme (i.e. http://,
|
|
||||||
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
|
|
||||||
// have exhausted all components, so the path is not relative to the root.
|
|
||||||
aRoot = aRoot.slice(0, index);
|
|
||||||
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
|
|
||||||
return aPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
++level;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make sure we add a "../" for each component we removed from the root.
|
|
||||||
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
|
|
||||||
}
|
|
||||||
exports.relative = relative;
|
|
||||||
|
|
||||||
var supportsNullProto = (function () {
|
|
||||||
var obj = Object.create(null);
|
|
||||||
return !('__proto__' in obj);
|
|
||||||
}());
|
|
||||||
|
|
||||||
function identity (s) {
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Because behavior goes wacky when you set `__proto__` on objects, we
|
|
||||||
* have to prefix all the strings in our set with an arbitrary character.
|
|
||||||
*
|
|
||||||
* See https://github.com/mozilla/source-map/pull/31 and
|
|
||||||
* https://github.com/mozilla/source-map/issues/30
|
|
||||||
*
|
|
||||||
* @param String aStr
|
|
||||||
*/
|
|
||||||
function toSetString(aStr) {
|
|
||||||
if (isProtoString(aStr)) {
|
|
||||||
return '$' + aStr;
|
|
||||||
}
|
|
||||||
|
|
||||||
return aStr;
|
|
||||||
}
|
|
||||||
exports.toSetString = supportsNullProto ? identity : toSetString;
|
|
||||||
|
|
||||||
function fromSetString(aStr) {
|
|
||||||
if (isProtoString(aStr)) {
|
|
||||||
return aStr.slice(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
return aStr;
|
|
||||||
}
|
|
||||||
exports.fromSetString = supportsNullProto ? identity : fromSetString;
|
|
||||||
|
|
||||||
function isProtoString(s) {
|
|
||||||
if (!s) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var length = s.length;
|
|
||||||
|
|
||||||
if (length < 9 /* "__proto__".length */) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
|
|
||||||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
|
|
||||||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
|
|
||||||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
|
|
||||||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
|
|
||||||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
|
|
||||||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
|
|
||||||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
|
|
||||||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var i = length - 10; i >= 0; i--) {
|
|
||||||
if (s.charCodeAt(i) !== 36 /* '$' */) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Comparator between two mappings where the original positions are compared.
|
|
||||||
*
|
|
||||||
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
|
|
||||||
* mappings with the same original source/line/column, but different generated
|
|
||||||
* line and column the same. Useful when searching for a mapping with a
|
|
||||||
* stubbed out mapping.
|
|
||||||
*/
|
|
||||||
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
|
|
||||||
var cmp = mappingA.source - mappingB.source;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.originalLine - mappingB.originalLine;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.originalColumn - mappingB.originalColumn;
|
|
||||||
if (cmp !== 0 || onlyCompareOriginal) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.generatedLine - mappingB.generatedLine;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mappingA.name - mappingB.name;
|
|
||||||
}
|
|
||||||
exports.compareByOriginalPositions = compareByOriginalPositions;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Comparator between two mappings with deflated source and name indices where
|
|
||||||
* the generated positions are compared.
|
|
||||||
*
|
|
||||||
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
|
|
||||||
* mappings with the same generated line and column, but different
|
|
||||||
* source/name/original line and column the same. Useful when searching for a
|
|
||||||
* mapping with a stubbed out mapping.
|
|
||||||
*/
|
|
||||||
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
|
|
||||||
var cmp = mappingA.generatedLine - mappingB.generatedLine;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
|
||||||
if (cmp !== 0 || onlyCompareGenerated) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.source - mappingB.source;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.originalLine - mappingB.originalLine;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.originalColumn - mappingB.originalColumn;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mappingA.name - mappingB.name;
|
|
||||||
}
|
|
||||||
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
|
|
||||||
|
|
||||||
function strcmp(aStr1, aStr2) {
|
|
||||||
if (aStr1 === aStr2) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aStr1 > aStr2) {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Comparator between two mappings with inflated source and name strings where
|
|
||||||
* the generated positions are compared.
|
|
||||||
*/
|
|
||||||
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
|
|
||||||
var cmp = mappingA.generatedLine - mappingB.generatedLine;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = strcmp(mappingA.source, mappingB.source);
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.originalLine - mappingB.originalLine;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
cmp = mappingA.originalColumn - mappingB.originalColumn;
|
|
||||||
if (cmp !== 0) {
|
|
||||||
return cmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
return strcmp(mappingA.name, mappingB.name);
|
|
||||||
}
|
|
||||||
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
|
|
||||||
|
|
@ -1,215 +0,0 @@
|
||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"source-map@0.5.7",
|
|
||||||
"/Users/eric/repos/actions/setup-node"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_development": true,
|
|
||||||
"_from": "source-map@0.5.7",
|
|
||||||
"_id": "source-map@0.5.7",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=",
|
|
||||||
"_location": "/@babel/core/source-map",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "source-map@0.5.7",
|
|
||||||
"name": "source-map",
|
|
||||||
"escapedName": "source-map",
|
|
||||||
"rawSpec": "0.5.7",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "0.5.7"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/@babel/core"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",
|
|
||||||
"_spec": "0.5.7",
|
|
||||||
"_where": "/Users/eric/repos/actions/setup-node",
|
|
||||||
"author": {
|
|
||||||
"name": "Nick Fitzgerald",
|
|
||||||
"email": "nfitzgerald@mozilla.com"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/mozilla/source-map/issues"
|
|
||||||
},
|
|
||||||
"contributors": [
|
|
||||||
{
|
|
||||||
"name": "Tobias Koppers",
|
|
||||||
"email": "tobias.koppers@googlemail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Duncan Beevers",
|
|
||||||
"email": "duncan@dweebd.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Stephen Crane",
|
|
||||||
"email": "scrane@mozilla.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Ryan Seddon",
|
|
||||||
"email": "seddon.ryan@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Miles Elam",
|
|
||||||
"email": "miles.elam@deem.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Mihai Bazon",
|
|
||||||
"email": "mihai.bazon@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Michael Ficarra",
|
|
||||||
"email": "github.public.email@michael.ficarra.me"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Todd Wolfson",
|
|
||||||
"email": "todd@twolfson.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Alexander Solovyov",
|
|
||||||
"email": "alexander@solovyov.net"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Felix Gnass",
|
|
||||||
"email": "fgnass@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Conrad Irwin",
|
|
||||||
"email": "conrad.irwin@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "usrbincc",
|
|
||||||
"email": "usrbincc@yahoo.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "David Glasser",
|
|
||||||
"email": "glasser@davidglasser.net"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Chase Douglas",
|
|
||||||
"email": "chase@newrelic.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Evan Wallace",
|
|
||||||
"email": "evan.exe@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Heather Arthur",
|
|
||||||
"email": "fayearthur@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Hugh Kennedy",
|
|
||||||
"email": "hughskennedy@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "David Glasser",
|
|
||||||
"email": "glasser@davidglasser.net"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Simon Lydell",
|
|
||||||
"email": "simon.lydell@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Jmeas Smith",
|
|
||||||
"email": "jellyes2@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Michael Z Goddard",
|
|
||||||
"email": "mzgoddard@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "azu",
|
|
||||||
"email": "azu@users.noreply.github.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "John Gozde",
|
|
||||||
"email": "john@gozde.ca"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Adam Kirkton",
|
|
||||||
"email": "akirkton@truefitinnovation.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Chris Montgomery",
|
|
||||||
"email": "christopher.montgomery@dowjones.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "J. Ryan Stinnett",
|
|
||||||
"email": "jryans@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Jack Herrington",
|
|
||||||
"email": "jherrington@walmartlabs.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Chris Truter",
|
|
||||||
"email": "jeffpalentine@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Daniel Espeset",
|
|
||||||
"email": "daniel@danielespeset.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Jamie Wong",
|
|
||||||
"email": "jamie.lf.wong@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Eddy Bruël",
|
|
||||||
"email": "ejpbruel@mozilla.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Hawken Rives",
|
|
||||||
"email": "hawkrives@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Gilad Peleg",
|
|
||||||
"email": "giladp007@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "djchie",
|
|
||||||
"email": "djchie.dev@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Gary Ye",
|
|
||||||
"email": "garysye@gmail.com"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Nicolas Lalevée",
|
|
||||||
"email": "nicolas.lalevee@hibnet.org"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "Generates and consumes source maps",
|
|
||||||
"devDependencies": {
|
|
||||||
"doctoc": "^0.15.0",
|
|
||||||
"webpack": "^1.12.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=0.10.0"
|
|
||||||
},
|
|
||||||
"files": [
|
|
||||||
"source-map.js",
|
|
||||||
"lib/",
|
|
||||||
"dist/source-map.debug.js",
|
|
||||||
"dist/source-map.js",
|
|
||||||
"dist/source-map.min.js",
|
|
||||||
"dist/source-map.min.js.map"
|
|
||||||
],
|
|
||||||
"homepage": "https://github.com/mozilla/source-map",
|
|
||||||
"license": "BSD-3-Clause",
|
|
||||||
"main": "./source-map.js",
|
|
||||||
"name": "source-map",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+ssh://git@github.com/mozilla/source-map.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"build": "webpack --color",
|
|
||||||
"test": "npm run build && node test/run-tests.js",
|
|
||||||
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
|
|
||||||
},
|
|
||||||
"typings": "source-map",
|
|
||||||
"version": "0.5.7"
|
|
||||||
}
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
/*
|
|
||||||
* Copyright 2009-2011 Mozilla Foundation and contributors
|
|
||||||
* Licensed under the New BSD license. See LICENSE.txt or:
|
|
||||||
* http://opensource.org/licenses/BSD-3-Clause
|
|
||||||
*/
|
|
||||||
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
|
|
||||||
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
|
|
||||||
exports.SourceNode = require('./lib/source-node').SourceNode;
|
|
||||||
|
|
@ -1,93 +0,0 @@
|
||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"@babel/core@7.4.5",
|
|
||||||
"/Users/eric/repos/actions/setup-node"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_development": true,
|
|
||||||
"_from": "@babel/core@7.4.5",
|
|
||||||
"_id": "@babel/core@7.4.5",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==",
|
|
||||||
"_location": "/@babel/core",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "@babel/core@7.4.5",
|
|
||||||
"name": "@babel/core",
|
|
||||||
"escapedName": "@babel%2fcore",
|
|
||||||
"scope": "@babel",
|
|
||||||
"rawSpec": "7.4.5",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "7.4.5"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/@jest/transform",
|
|
||||||
"/jest-config"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz",
|
|
||||||
"_spec": "7.4.5",
|
|
||||||
"_where": "/Users/eric/repos/actions/setup-node",
|
|
||||||
"author": {
|
|
||||||
"name": "Sebastian McKenzie",
|
|
||||||
"email": "sebmck@gmail.com"
|
|
||||||
},
|
|
||||||
"browser": {
|
|
||||||
"./lib/config/files/index.js": "./lib/config/files/index-browser.js",
|
|
||||||
"./lib/transform-file.js": "./lib/transform-file-browser.js"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@babel/code-frame": "^7.0.0",
|
|
||||||
"@babel/generator": "^7.4.4",
|
|
||||||
"@babel/helpers": "^7.4.4",
|
|
||||||
"@babel/parser": "^7.4.5",
|
|
||||||
"@babel/template": "^7.4.4",
|
|
||||||
"@babel/traverse": "^7.4.5",
|
|
||||||
"@babel/types": "^7.4.4",
|
|
||||||
"convert-source-map": "^1.1.0",
|
|
||||||
"debug": "^4.1.0",
|
|
||||||
"json5": "^2.1.0",
|
|
||||||
"lodash": "^4.17.11",
|
|
||||||
"resolve": "^1.3.2",
|
|
||||||
"semver": "^5.4.1",
|
|
||||||
"source-map": "^0.5.0"
|
|
||||||
},
|
|
||||||
"description": "Babel compiler core.",
|
|
||||||
"devDependencies": {
|
|
||||||
"@babel/helper-transform-fixture-test-runner": "^7.4.4",
|
|
||||||
"@babel/register": "^7.4.4"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=6.9.0"
|
|
||||||
},
|
|
||||||
"gitHead": "33ab4f166117e2380de3955a0842985f578b01b8",
|
|
||||||
"homepage": "https://babeljs.io/",
|
|
||||||
"keywords": [
|
|
||||||
"6to5",
|
|
||||||
"babel",
|
|
||||||
"classes",
|
|
||||||
"const",
|
|
||||||
"es6",
|
|
||||||
"harmony",
|
|
||||||
"let",
|
|
||||||
"modules",
|
|
||||||
"transpile",
|
|
||||||
"transpiler",
|
|
||||||
"var",
|
|
||||||
"babel-core",
|
|
||||||
"compiler"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "lib/index.js",
|
|
||||||
"name": "@babel/core",
|
|
||||||
"publishConfig": {
|
|
||||||
"access": "public"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/babel/babel/tree/master/packages/babel-core"
|
|
||||||
},
|
|
||||||
"version": "7.4.5"
|
|
||||||
}
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2014-present Sebastian McKenzie and other contributors
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining
|
|
||||||
a copy of this software and associated documentation files (the
|
|
||||||
"Software"), to deal in the Software without restriction, including
|
|
||||||
without limitation the rights to use, copy, modify, merge, publish,
|
|
||||||
distribute, sublicense, and/or sell copies of the Software, and to
|
|
||||||
permit persons to whom the Software is furnished to do so, subject to
|
|
||||||
the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be
|
|
||||||
included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
||||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
||||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
||||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
||||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
# @babel/generator
|
|
||||||
|
|
||||||
> Turns an AST into code.
|
|
||||||
|
|
||||||
See our website [@babel/generator](https://babeljs.io/docs/en/next/babel-generator.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20generator%22+is%3Aopen) associated with this package.
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
Using npm:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm install --save-dev @babel/generator
|
|
||||||
```
|
|
||||||
|
|
||||||
or using yarn:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
yarn add @babel/generator --dev
|
|
||||||
```
|
|
||||||
|
|
@ -1,257 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = void 0;
|
|
||||||
|
|
||||||
function _trimRight() {
|
|
||||||
const data = _interopRequireDefault(require("trim-right"));
|
|
||||||
|
|
||||||
_trimRight = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const SPACES_RE = /^[ \t]+$/;
|
|
||||||
|
|
||||||
class Buffer {
|
|
||||||
constructor(map) {
|
|
||||||
this._map = null;
|
|
||||||
this._buf = [];
|
|
||||||
this._last = "";
|
|
||||||
this._queue = [];
|
|
||||||
this._position = {
|
|
||||||
line: 1,
|
|
||||||
column: 0
|
|
||||||
};
|
|
||||||
this._sourcePosition = {
|
|
||||||
identifierName: null,
|
|
||||||
line: null,
|
|
||||||
column: null,
|
|
||||||
filename: null
|
|
||||||
};
|
|
||||||
this._disallowedPop = null;
|
|
||||||
this._map = map;
|
|
||||||
}
|
|
||||||
|
|
||||||
get() {
|
|
||||||
this._flush();
|
|
||||||
|
|
||||||
const map = this._map;
|
|
||||||
const result = {
|
|
||||||
code: (0, _trimRight().default)(this._buf.join("")),
|
|
||||||
map: null,
|
|
||||||
rawMappings: map && map.getRawMappings()
|
|
||||||
};
|
|
||||||
|
|
||||||
if (map) {
|
|
||||||
Object.defineProperty(result, "map", {
|
|
||||||
configurable: true,
|
|
||||||
enumerable: true,
|
|
||||||
|
|
||||||
get() {
|
|
||||||
return this.map = map.get();
|
|
||||||
},
|
|
||||||
|
|
||||||
set(value) {
|
|
||||||
Object.defineProperty(this, "map", {
|
|
||||||
value,
|
|
||||||
writable: true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
append(str) {
|
|
||||||
this._flush();
|
|
||||||
|
|
||||||
const {
|
|
||||||
line,
|
|
||||||
column,
|
|
||||||
filename,
|
|
||||||
identifierName,
|
|
||||||
force
|
|
||||||
} = this._sourcePosition;
|
|
||||||
|
|
||||||
this._append(str, line, column, identifierName, filename, force);
|
|
||||||
}
|
|
||||||
|
|
||||||
queue(str) {
|
|
||||||
if (str === "\n") {
|
|
||||||
while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) {
|
|
||||||
this._queue.shift();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
line,
|
|
||||||
column,
|
|
||||||
filename,
|
|
||||||
identifierName,
|
|
||||||
force
|
|
||||||
} = this._sourcePosition;
|
|
||||||
|
|
||||||
this._queue.unshift([str, line, column, identifierName, filename, force]);
|
|
||||||
}
|
|
||||||
|
|
||||||
_flush() {
|
|
||||||
let item;
|
|
||||||
|
|
||||||
while (item = this._queue.pop()) this._append(...item);
|
|
||||||
}
|
|
||||||
|
|
||||||
_append(str, line, column, identifierName, filename, force) {
|
|
||||||
if (this._map && str[0] !== "\n") {
|
|
||||||
this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename, force);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._buf.push(str);
|
|
||||||
|
|
||||||
this._last = str[str.length - 1];
|
|
||||||
|
|
||||||
for (let i = 0; i < str.length; i++) {
|
|
||||||
if (str[i] === "\n") {
|
|
||||||
this._position.line++;
|
|
||||||
this._position.column = 0;
|
|
||||||
} else {
|
|
||||||
this._position.column++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
removeTrailingNewline() {
|
|
||||||
if (this._queue.length > 0 && this._queue[0][0] === "\n") {
|
|
||||||
this._queue.shift();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
removeLastSemicolon() {
|
|
||||||
if (this._queue.length > 0 && this._queue[0][0] === ";") {
|
|
||||||
this._queue.shift();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
endsWith(suffix) {
|
|
||||||
if (suffix.length === 1) {
|
|
||||||
let last;
|
|
||||||
|
|
||||||
if (this._queue.length > 0) {
|
|
||||||
const str = this._queue[0][0];
|
|
||||||
last = str[str.length - 1];
|
|
||||||
} else {
|
|
||||||
last = this._last;
|
|
||||||
}
|
|
||||||
|
|
||||||
return last === suffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
const end = this._last + this._queue.reduce((acc, item) => item[0] + acc, "");
|
|
||||||
|
|
||||||
if (suffix.length <= end.length) {
|
|
||||||
return end.slice(-suffix.length) === suffix;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
hasContent() {
|
|
||||||
return this._queue.length > 0 || !!this._last;
|
|
||||||
}
|
|
||||||
|
|
||||||
exactSource(loc, cb) {
|
|
||||||
this.source("start", loc, true);
|
|
||||||
cb();
|
|
||||||
this.source("end", loc);
|
|
||||||
|
|
||||||
this._disallowPop("start", loc);
|
|
||||||
}
|
|
||||||
|
|
||||||
source(prop, loc, force) {
|
|
||||||
if (prop && !loc) return;
|
|
||||||
|
|
||||||
this._normalizePosition(prop, loc, this._sourcePosition, force);
|
|
||||||
}
|
|
||||||
|
|
||||||
withSource(prop, loc, cb) {
|
|
||||||
if (!this._map) return cb();
|
|
||||||
const originalLine = this._sourcePosition.line;
|
|
||||||
const originalColumn = this._sourcePosition.column;
|
|
||||||
const originalFilename = this._sourcePosition.filename;
|
|
||||||
const originalIdentifierName = this._sourcePosition.identifierName;
|
|
||||||
this.source(prop, loc);
|
|
||||||
cb();
|
|
||||||
|
|
||||||
if ((!this._sourcePosition.force || this._sourcePosition.line !== originalLine || this._sourcePosition.column !== originalColumn || this._sourcePosition.filename !== originalFilename) && (!this._disallowedPop || this._disallowedPop.line !== originalLine || this._disallowedPop.column !== originalColumn || this._disallowedPop.filename !== originalFilename)) {
|
|
||||||
this._sourcePosition.line = originalLine;
|
|
||||||
this._sourcePosition.column = originalColumn;
|
|
||||||
this._sourcePosition.filename = originalFilename;
|
|
||||||
this._sourcePosition.identifierName = originalIdentifierName;
|
|
||||||
this._sourcePosition.force = false;
|
|
||||||
this._disallowedPop = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_disallowPop(prop, loc) {
|
|
||||||
if (prop && !loc) return;
|
|
||||||
this._disallowedPop = this._normalizePosition(prop, loc);
|
|
||||||
}
|
|
||||||
|
|
||||||
_normalizePosition(prop, loc, targetObj, force) {
|
|
||||||
const pos = loc ? loc[prop] : null;
|
|
||||||
|
|
||||||
if (targetObj === undefined) {
|
|
||||||
targetObj = {
|
|
||||||
identifierName: null,
|
|
||||||
line: null,
|
|
||||||
column: null,
|
|
||||||
filename: null,
|
|
||||||
force: false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const origLine = targetObj.line;
|
|
||||||
const origColumn = targetObj.column;
|
|
||||||
const origFilename = targetObj.filename;
|
|
||||||
targetObj.identifierName = prop === "start" && loc && loc.identifierName || null;
|
|
||||||
targetObj.line = pos ? pos.line : null;
|
|
||||||
targetObj.column = pos ? pos.column : null;
|
|
||||||
targetObj.filename = loc && loc.filename || null;
|
|
||||||
|
|
||||||
if (force || targetObj.line !== origLine || targetObj.column !== origColumn || targetObj.filename !== origFilename) {
|
|
||||||
targetObj.force = force;
|
|
||||||
}
|
|
||||||
|
|
||||||
return targetObj;
|
|
||||||
}
|
|
||||||
|
|
||||||
getCurrentColumn() {
|
|
||||||
const extra = this._queue.reduce((acc, item) => item[0] + acc, "");
|
|
||||||
|
|
||||||
const lastIndex = extra.lastIndexOf("\n");
|
|
||||||
return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex;
|
|
||||||
}
|
|
||||||
|
|
||||||
getCurrentLine() {
|
|
||||||
const extra = this._queue.reduce((acc, item) => item[0] + acc, "");
|
|
||||||
|
|
||||||
let count = 0;
|
|
||||||
|
|
||||||
for (let i = 0; i < extra.length; i++) {
|
|
||||||
if (extra[i] === "\n") count++;
|
|
||||||
}
|
|
||||||
|
|
||||||
return this._position.line + count;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.default = Buffer;
|
|
||||||
|
|
@ -1,97 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.File = File;
|
|
||||||
exports.Program = Program;
|
|
||||||
exports.BlockStatement = BlockStatement;
|
|
||||||
exports.Noop = Noop;
|
|
||||||
exports.Directive = Directive;
|
|
||||||
exports.DirectiveLiteral = DirectiveLiteral;
|
|
||||||
exports.InterpreterDirective = InterpreterDirective;
|
|
||||||
exports.Placeholder = Placeholder;
|
|
||||||
|
|
||||||
function File(node) {
|
|
||||||
if (node.program) {
|
|
||||||
this.print(node.program.interpreter, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.program, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Program(node) {
|
|
||||||
this.printInnerComments(node, false);
|
|
||||||
this.printSequence(node.directives, node);
|
|
||||||
if (node.directives && node.directives.length) this.newline();
|
|
||||||
this.printSequence(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function BlockStatement(node) {
|
|
||||||
this.token("{");
|
|
||||||
this.printInnerComments(node);
|
|
||||||
const hasDirectives = node.directives && node.directives.length;
|
|
||||||
|
|
||||||
if (node.body.length || hasDirectives) {
|
|
||||||
this.newline();
|
|
||||||
this.printSequence(node.directives, node, {
|
|
||||||
indent: true
|
|
||||||
});
|
|
||||||
if (hasDirectives) this.newline();
|
|
||||||
this.printSequence(node.body, node, {
|
|
||||||
indent: true
|
|
||||||
});
|
|
||||||
this.removeTrailingNewline();
|
|
||||||
this.source("end", node.loc);
|
|
||||||
if (!this.endsWith("\n")) this.newline();
|
|
||||||
this.rightBrace();
|
|
||||||
} else {
|
|
||||||
this.source("end", node.loc);
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Noop() {}
|
|
||||||
|
|
||||||
function Directive(node) {
|
|
||||||
this.print(node.value, node);
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/;
|
|
||||||
const unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/;
|
|
||||||
|
|
||||||
function DirectiveLiteral(node) {
|
|
||||||
const raw = this.getPossibleRaw(node);
|
|
||||||
|
|
||||||
if (raw != null) {
|
|
||||||
this.token(raw);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
value
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (!unescapedDoubleQuoteRE.test(value)) {
|
|
||||||
this.token(`"${value}"`);
|
|
||||||
} else if (!unescapedSingleQuoteRE.test(value)) {
|
|
||||||
this.token(`'${value}'`);
|
|
||||||
} else {
|
|
||||||
throw new Error("Malformed AST: it is not possible to print a directive containing" + " both unescaped single and double quotes.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function InterpreterDirective(node) {
|
|
||||||
this.token(`#!${node.value}\n`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Placeholder(node) {
|
|
||||||
this.token("%%");
|
|
||||||
this.print(node.name);
|
|
||||||
this.token("%%");
|
|
||||||
|
|
||||||
if (node.expectedNode === "Statement") {
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,190 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration;
|
|
||||||
exports.ClassBody = ClassBody;
|
|
||||||
exports.ClassProperty = ClassProperty;
|
|
||||||
exports.ClassPrivateProperty = ClassPrivateProperty;
|
|
||||||
exports.ClassMethod = ClassMethod;
|
|
||||||
exports.ClassPrivateMethod = ClassPrivateMethod;
|
|
||||||
exports._classMethodHead = _classMethodHead;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function ClassDeclaration(node, parent) {
|
|
||||||
if (!this.format.decoratorsBeforeExport || !t().isExportDefaultDeclaration(parent) && !t().isExportNamedDeclaration(parent)) {
|
|
||||||
this.printJoin(node.decorators, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.declare) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.abstract) {
|
|
||||||
this.word("abstract");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("class");
|
|
||||||
|
|
||||||
if (node.id) {
|
|
||||||
this.space();
|
|
||||||
this.print(node.id, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
|
|
||||||
if (node.superClass) {
|
|
||||||
this.space();
|
|
||||||
this.word("extends");
|
|
||||||
this.space();
|
|
||||||
this.print(node.superClass, node);
|
|
||||||
this.print(node.superTypeParameters, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.implements) {
|
|
||||||
this.space();
|
|
||||||
this.word("implements");
|
|
||||||
this.space();
|
|
||||||
this.printList(node.implements, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ClassBody(node) {
|
|
||||||
this.token("{");
|
|
||||||
this.printInnerComments(node);
|
|
||||||
|
|
||||||
if (node.body.length === 0) {
|
|
||||||
this.token("}");
|
|
||||||
} else {
|
|
||||||
this.newline();
|
|
||||||
this.indent();
|
|
||||||
this.printSequence(node.body, node);
|
|
||||||
this.dedent();
|
|
||||||
if (!this.endsWith("\n")) this.newline();
|
|
||||||
this.rightBrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ClassProperty(node) {
|
|
||||||
this.printJoin(node.decorators, node);
|
|
||||||
|
|
||||||
if (node.accessibility) {
|
|
||||||
this.word(node.accessibility);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.static) {
|
|
||||||
this.word("static");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.abstract) {
|
|
||||||
this.word("abstract");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.readonly) {
|
|
||||||
this.word("readonly");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.computed) {
|
|
||||||
this.token("[");
|
|
||||||
this.print(node.key, node);
|
|
||||||
this.token("]");
|
|
||||||
} else {
|
|
||||||
this._variance(node);
|
|
||||||
|
|
||||||
this.print(node.key, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.optional) {
|
|
||||||
this.token("?");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.definite) {
|
|
||||||
this.token("!");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
|
|
||||||
if (node.value) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ClassPrivateProperty(node) {
|
|
||||||
if (node.static) {
|
|
||||||
this.word("static");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.key, node);
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
|
|
||||||
if (node.value) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ClassMethod(node) {
|
|
||||||
this._classMethodHead(node);
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ClassPrivateMethod(node) {
|
|
||||||
this._classMethodHead(node);
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function _classMethodHead(node) {
|
|
||||||
this.printJoin(node.decorators, node);
|
|
||||||
|
|
||||||
if (node.accessibility) {
|
|
||||||
this.word(node.accessibility);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.abstract) {
|
|
||||||
this.word("abstract");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.static) {
|
|
||||||
this.word("static");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._methodHead(node);
|
|
||||||
}
|
|
||||||
|
|
@ -1,292 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.UnaryExpression = UnaryExpression;
|
|
||||||
exports.DoExpression = DoExpression;
|
|
||||||
exports.ParenthesizedExpression = ParenthesizedExpression;
|
|
||||||
exports.UpdateExpression = UpdateExpression;
|
|
||||||
exports.ConditionalExpression = ConditionalExpression;
|
|
||||||
exports.NewExpression = NewExpression;
|
|
||||||
exports.SequenceExpression = SequenceExpression;
|
|
||||||
exports.ThisExpression = ThisExpression;
|
|
||||||
exports.Super = Super;
|
|
||||||
exports.Decorator = Decorator;
|
|
||||||
exports.OptionalMemberExpression = OptionalMemberExpression;
|
|
||||||
exports.OptionalCallExpression = OptionalCallExpression;
|
|
||||||
exports.CallExpression = CallExpression;
|
|
||||||
exports.Import = Import;
|
|
||||||
exports.EmptyStatement = EmptyStatement;
|
|
||||||
exports.ExpressionStatement = ExpressionStatement;
|
|
||||||
exports.AssignmentPattern = AssignmentPattern;
|
|
||||||
exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression;
|
|
||||||
exports.BindExpression = BindExpression;
|
|
||||||
exports.MemberExpression = MemberExpression;
|
|
||||||
exports.MetaProperty = MetaProperty;
|
|
||||||
exports.PrivateName = PrivateName;
|
|
||||||
exports.AwaitExpression = exports.YieldExpression = void 0;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var n = _interopRequireWildcard(require("../node"));
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function UnaryExpression(node) {
|
|
||||||
if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof" || node.operator === "throw") {
|
|
||||||
this.word(node.operator);
|
|
||||||
this.space();
|
|
||||||
} else {
|
|
||||||
this.token(node.operator);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.argument, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DoExpression(node) {
|
|
||||||
this.word("do");
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ParenthesizedExpression(node) {
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function UpdateExpression(node) {
|
|
||||||
if (node.prefix) {
|
|
||||||
this.token(node.operator);
|
|
||||||
this.print(node.argument, node);
|
|
||||||
} else {
|
|
||||||
this.startTerminatorless(true);
|
|
||||||
this.print(node.argument, node);
|
|
||||||
this.endTerminatorless();
|
|
||||||
this.token(node.operator);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConditionalExpression(node) {
|
|
||||||
this.print(node.test, node);
|
|
||||||
this.space();
|
|
||||||
this.token("?");
|
|
||||||
this.space();
|
|
||||||
this.print(node.consequent, node);
|
|
||||||
this.space();
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
this.print(node.alternate, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function NewExpression(node, parent) {
|
|
||||||
this.word("new");
|
|
||||||
this.space();
|
|
||||||
this.print(node.callee, node);
|
|
||||||
|
|
||||||
if (this.format.minified && node.arguments.length === 0 && !node.optional && !t().isCallExpression(parent, {
|
|
||||||
callee: node
|
|
||||||
}) && !t().isMemberExpression(parent) && !t().isNewExpression(parent)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.typeArguments, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
|
|
||||||
if (node.optional) {
|
|
||||||
this.token("?.");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("(");
|
|
||||||
this.printList(node.arguments, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function SequenceExpression(node) {
|
|
||||||
this.printList(node.expressions, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ThisExpression() {
|
|
||||||
this.word("this");
|
|
||||||
}
|
|
||||||
|
|
||||||
function Super() {
|
|
||||||
this.word("super");
|
|
||||||
}
|
|
||||||
|
|
||||||
function Decorator(node) {
|
|
||||||
this.token("@");
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.newline();
|
|
||||||
}
|
|
||||||
|
|
||||||
function OptionalMemberExpression(node) {
|
|
||||||
this.print(node.object, node);
|
|
||||||
|
|
||||||
if (!node.computed && t().isMemberExpression(node.property)) {
|
|
||||||
throw new TypeError("Got a MemberExpression for MemberExpression property");
|
|
||||||
}
|
|
||||||
|
|
||||||
let computed = node.computed;
|
|
||||||
|
|
||||||
if (t().isLiteral(node.property) && typeof node.property.value === "number") {
|
|
||||||
computed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.optional) {
|
|
||||||
this.token("?.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (computed) {
|
|
||||||
this.token("[");
|
|
||||||
this.print(node.property, node);
|
|
||||||
this.token("]");
|
|
||||||
} else {
|
|
||||||
if (!node.optional) {
|
|
||||||
this.token(".");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.property, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function OptionalCallExpression(node) {
|
|
||||||
this.print(node.callee, node);
|
|
||||||
this.print(node.typeArguments, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
|
|
||||||
if (node.optional) {
|
|
||||||
this.token("?.");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("(");
|
|
||||||
this.printList(node.arguments, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function CallExpression(node) {
|
|
||||||
this.print(node.callee, node);
|
|
||||||
this.print(node.typeArguments, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
this.token("(");
|
|
||||||
this.printList(node.arguments, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function Import() {
|
|
||||||
this.word("import");
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildYieldAwait(keyword) {
|
|
||||||
return function (node) {
|
|
||||||
this.word(keyword);
|
|
||||||
|
|
||||||
if (node.delegate) {
|
|
||||||
this.token("*");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.argument) {
|
|
||||||
this.space();
|
|
||||||
const terminatorState = this.startTerminatorless();
|
|
||||||
this.print(node.argument, node);
|
|
||||||
this.endTerminatorless(terminatorState);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const YieldExpression = buildYieldAwait("yield");
|
|
||||||
exports.YieldExpression = YieldExpression;
|
|
||||||
const AwaitExpression = buildYieldAwait("await");
|
|
||||||
exports.AwaitExpression = AwaitExpression;
|
|
||||||
|
|
||||||
function EmptyStatement() {
|
|
||||||
this.semicolon(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExpressionStatement(node) {
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function AssignmentPattern(node) {
|
|
||||||
this.print(node.left, node);
|
|
||||||
if (node.left.optional) this.token("?");
|
|
||||||
this.print(node.left.typeAnnotation, node);
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.right, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AssignmentExpression(node, parent) {
|
|
||||||
const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent);
|
|
||||||
|
|
||||||
if (parens) {
|
|
||||||
this.token("(");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.left, node);
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (node.operator === "in" || node.operator === "instanceof") {
|
|
||||||
this.word(node.operator);
|
|
||||||
} else {
|
|
||||||
this.token(node.operator);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.right, node);
|
|
||||||
|
|
||||||
if (parens) {
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function BindExpression(node) {
|
|
||||||
this.print(node.object, node);
|
|
||||||
this.token("::");
|
|
||||||
this.print(node.callee, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MemberExpression(node) {
|
|
||||||
this.print(node.object, node);
|
|
||||||
|
|
||||||
if (!node.computed && t().isMemberExpression(node.property)) {
|
|
||||||
throw new TypeError("Got a MemberExpression for MemberExpression property");
|
|
||||||
}
|
|
||||||
|
|
||||||
let computed = node.computed;
|
|
||||||
|
|
||||||
if (t().isLiteral(node.property) && typeof node.property.value === "number") {
|
|
||||||
computed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (computed) {
|
|
||||||
this.token("[");
|
|
||||||
this.print(node.property, node);
|
|
||||||
this.token("]");
|
|
||||||
} else {
|
|
||||||
this.token(".");
|
|
||||||
this.print(node.property, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function MetaProperty(node) {
|
|
||||||
this.print(node.meta, node);
|
|
||||||
this.token(".");
|
|
||||||
this.print(node.property, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PrivateName(node) {
|
|
||||||
this.token("#");
|
|
||||||
this.print(node.id, node);
|
|
||||||
}
|
|
||||||
|
|
@ -1,628 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.AnyTypeAnnotation = AnyTypeAnnotation;
|
|
||||||
exports.ArrayTypeAnnotation = ArrayTypeAnnotation;
|
|
||||||
exports.BooleanTypeAnnotation = BooleanTypeAnnotation;
|
|
||||||
exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation;
|
|
||||||
exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation;
|
|
||||||
exports.DeclareClass = DeclareClass;
|
|
||||||
exports.DeclareFunction = DeclareFunction;
|
|
||||||
exports.InferredPredicate = InferredPredicate;
|
|
||||||
exports.DeclaredPredicate = DeclaredPredicate;
|
|
||||||
exports.DeclareInterface = DeclareInterface;
|
|
||||||
exports.DeclareModule = DeclareModule;
|
|
||||||
exports.DeclareModuleExports = DeclareModuleExports;
|
|
||||||
exports.DeclareTypeAlias = DeclareTypeAlias;
|
|
||||||
exports.DeclareOpaqueType = DeclareOpaqueType;
|
|
||||||
exports.DeclareVariable = DeclareVariable;
|
|
||||||
exports.DeclareExportDeclaration = DeclareExportDeclaration;
|
|
||||||
exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration;
|
|
||||||
exports.ExistsTypeAnnotation = ExistsTypeAnnotation;
|
|
||||||
exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
|
|
||||||
exports.FunctionTypeParam = FunctionTypeParam;
|
|
||||||
exports.GenericTypeAnnotation = exports.ClassImplements = exports.InterfaceExtends = InterfaceExtends;
|
|
||||||
exports._interfaceish = _interfaceish;
|
|
||||||
exports._variance = _variance;
|
|
||||||
exports.InterfaceDeclaration = InterfaceDeclaration;
|
|
||||||
exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation;
|
|
||||||
exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation;
|
|
||||||
exports.MixedTypeAnnotation = MixedTypeAnnotation;
|
|
||||||
exports.EmptyTypeAnnotation = EmptyTypeAnnotation;
|
|
||||||
exports.NullableTypeAnnotation = NullableTypeAnnotation;
|
|
||||||
exports.NumberTypeAnnotation = NumberTypeAnnotation;
|
|
||||||
exports.StringTypeAnnotation = StringTypeAnnotation;
|
|
||||||
exports.ThisTypeAnnotation = ThisTypeAnnotation;
|
|
||||||
exports.TupleTypeAnnotation = TupleTypeAnnotation;
|
|
||||||
exports.TypeofTypeAnnotation = TypeofTypeAnnotation;
|
|
||||||
exports.TypeAlias = TypeAlias;
|
|
||||||
exports.TypeAnnotation = TypeAnnotation;
|
|
||||||
exports.TypeParameterDeclaration = exports.TypeParameterInstantiation = TypeParameterInstantiation;
|
|
||||||
exports.TypeParameter = TypeParameter;
|
|
||||||
exports.OpaqueType = OpaqueType;
|
|
||||||
exports.ObjectTypeAnnotation = ObjectTypeAnnotation;
|
|
||||||
exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot;
|
|
||||||
exports.ObjectTypeCallProperty = ObjectTypeCallProperty;
|
|
||||||
exports.ObjectTypeIndexer = ObjectTypeIndexer;
|
|
||||||
exports.ObjectTypeProperty = ObjectTypeProperty;
|
|
||||||
exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty;
|
|
||||||
exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier;
|
|
||||||
exports.UnionTypeAnnotation = UnionTypeAnnotation;
|
|
||||||
exports.TypeCastExpression = TypeCastExpression;
|
|
||||||
exports.Variance = Variance;
|
|
||||||
exports.VoidTypeAnnotation = VoidTypeAnnotation;
|
|
||||||
Object.defineProperty(exports, "NumberLiteralTypeAnnotation", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _types2.NumericLiteral;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Object.defineProperty(exports, "StringLiteralTypeAnnotation", {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _types2.StringLiteral;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _modules = require("./modules");
|
|
||||||
|
|
||||||
var _types2 = require("./types");
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function AnyTypeAnnotation() {
|
|
||||||
this.word("any");
|
|
||||||
}
|
|
||||||
|
|
||||||
function ArrayTypeAnnotation(node) {
|
|
||||||
this.print(node.elementType, node);
|
|
||||||
this.token("[");
|
|
||||||
this.token("]");
|
|
||||||
}
|
|
||||||
|
|
||||||
function BooleanTypeAnnotation() {
|
|
||||||
this.word("boolean");
|
|
||||||
}
|
|
||||||
|
|
||||||
function BooleanLiteralTypeAnnotation(node) {
|
|
||||||
this.word(node.value ? "true" : "false");
|
|
||||||
}
|
|
||||||
|
|
||||||
function NullLiteralTypeAnnotation() {
|
|
||||||
this.word("null");
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareClass(node, parent) {
|
|
||||||
if (!t().isDeclareExportDeclaration(parent)) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("class");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
this._interfaceish(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareFunction(node, parent) {
|
|
||||||
if (!t().isDeclareExportDeclaration(parent)) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("function");
|
|
||||||
this.space();
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.print(node.id.typeAnnotation.typeAnnotation, node);
|
|
||||||
|
|
||||||
if (node.predicate) {
|
|
||||||
this.space();
|
|
||||||
this.print(node.predicate, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function InferredPredicate() {
|
|
||||||
this.token("%");
|
|
||||||
this.word("checks");
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclaredPredicate(node) {
|
|
||||||
this.token("%");
|
|
||||||
this.word("checks");
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.value, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareInterface(node) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
this.InterfaceDeclaration(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareModule(node) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
this.word("module");
|
|
||||||
this.space();
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareModuleExports(node) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
this.word("module");
|
|
||||||
this.token(".");
|
|
||||||
this.word("exports");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareTypeAlias(node) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
this.TypeAlias(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareOpaqueType(node, parent) {
|
|
||||||
if (!t().isDeclareExportDeclaration(parent)) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.OpaqueType(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareVariable(node, parent) {
|
|
||||||
if (!t().isDeclareExportDeclaration(parent)) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("var");
|
|
||||||
this.space();
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.print(node.id.typeAnnotation, node);
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareExportDeclaration(node) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
this.word("export");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (node.default) {
|
|
||||||
this.word("default");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
FlowExportDeclaration.apply(this, arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DeclareExportAllDeclaration() {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
_modules.ExportAllDeclaration.apply(this, arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FlowExportDeclaration(node) {
|
|
||||||
if (node.declaration) {
|
|
||||||
const declar = node.declaration;
|
|
||||||
this.print(declar, node);
|
|
||||||
if (!t().isStatement(declar)) this.semicolon();
|
|
||||||
} else {
|
|
||||||
this.token("{");
|
|
||||||
|
|
||||||
if (node.specifiers.length) {
|
|
||||||
this.space();
|
|
||||||
this.printList(node.specifiers, node);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("}");
|
|
||||||
|
|
||||||
if (node.source) {
|
|
||||||
this.space();
|
|
||||||
this.word("from");
|
|
||||||
this.space();
|
|
||||||
this.print(node.source, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExistsTypeAnnotation() {
|
|
||||||
this.token("*");
|
|
||||||
}
|
|
||||||
|
|
||||||
function FunctionTypeAnnotation(node, parent) {
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
this.token("(");
|
|
||||||
this.printList(node.params, node);
|
|
||||||
|
|
||||||
if (node.rest) {
|
|
||||||
if (node.params.length) {
|
|
||||||
this.token(",");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("...");
|
|
||||||
this.print(node.rest, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(")");
|
|
||||||
|
|
||||||
if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction" || parent.type === "ObjectTypeProperty" && parent.method) {
|
|
||||||
this.token(":");
|
|
||||||
} else {
|
|
||||||
this.space();
|
|
||||||
this.token("=>");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.returnType, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FunctionTypeParam(node) {
|
|
||||||
this.print(node.name, node);
|
|
||||||
if (node.optional) this.token("?");
|
|
||||||
|
|
||||||
if (node.name) {
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function InterfaceExtends(node) {
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interfaceish(node) {
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
|
|
||||||
if (node.extends.length) {
|
|
||||||
this.space();
|
|
||||||
this.word("extends");
|
|
||||||
this.space();
|
|
||||||
this.printList(node.extends, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.mixins && node.mixins.length) {
|
|
||||||
this.space();
|
|
||||||
this.word("mixins");
|
|
||||||
this.space();
|
|
||||||
this.printList(node.mixins, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.implements && node.implements.length) {
|
|
||||||
this.space();
|
|
||||||
this.word("implements");
|
|
||||||
this.space();
|
|
||||||
this.printList(node.implements, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function _variance(node) {
|
|
||||||
if (node.variance) {
|
|
||||||
if (node.variance.kind === "plus") {
|
|
||||||
this.token("+");
|
|
||||||
} else if (node.variance.kind === "minus") {
|
|
||||||
this.token("-");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function InterfaceDeclaration(node) {
|
|
||||||
this.word("interface");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
this._interfaceish(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function andSeparator() {
|
|
||||||
this.space();
|
|
||||||
this.token("&");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
function InterfaceTypeAnnotation(node) {
|
|
||||||
this.word("interface");
|
|
||||||
|
|
||||||
if (node.extends && node.extends.length) {
|
|
||||||
this.space();
|
|
||||||
this.word("extends");
|
|
||||||
this.space();
|
|
||||||
this.printList(node.extends, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function IntersectionTypeAnnotation(node) {
|
|
||||||
this.printJoin(node.types, node, {
|
|
||||||
separator: andSeparator
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function MixedTypeAnnotation() {
|
|
||||||
this.word("mixed");
|
|
||||||
}
|
|
||||||
|
|
||||||
function EmptyTypeAnnotation() {
|
|
||||||
this.word("empty");
|
|
||||||
}
|
|
||||||
|
|
||||||
function NullableTypeAnnotation(node) {
|
|
||||||
this.token("?");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function NumberTypeAnnotation() {
|
|
||||||
this.word("number");
|
|
||||||
}
|
|
||||||
|
|
||||||
function StringTypeAnnotation() {
|
|
||||||
this.word("string");
|
|
||||||
}
|
|
||||||
|
|
||||||
function ThisTypeAnnotation() {
|
|
||||||
this.word("this");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TupleTypeAnnotation(node) {
|
|
||||||
this.token("[");
|
|
||||||
this.printList(node.types, node);
|
|
||||||
this.token("]");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TypeofTypeAnnotation(node) {
|
|
||||||
this.word("typeof");
|
|
||||||
this.space();
|
|
||||||
this.print(node.argument, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TypeAlias(node) {
|
|
||||||
this.word("type");
|
|
||||||
this.space();
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.right, node);
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function TypeAnnotation(node) {
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
if (node.optional) this.token("?");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TypeParameterInstantiation(node) {
|
|
||||||
this.token("<");
|
|
||||||
this.printList(node.params, node, {});
|
|
||||||
this.token(">");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TypeParameter(node) {
|
|
||||||
this._variance(node);
|
|
||||||
|
|
||||||
this.word(node.name);
|
|
||||||
|
|
||||||
if (node.bound) {
|
|
||||||
this.print(node.bound, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.default) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.default, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function OpaqueType(node) {
|
|
||||||
this.word("opaque");
|
|
||||||
this.space();
|
|
||||||
this.word("type");
|
|
||||||
this.space();
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
|
|
||||||
if (node.supertype) {
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
this.print(node.supertype, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.impltype) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.impltype, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectTypeAnnotation(node) {
|
|
||||||
if (node.exact) {
|
|
||||||
this.token("{|");
|
|
||||||
} else {
|
|
||||||
this.token("{");
|
|
||||||
}
|
|
||||||
|
|
||||||
const props = node.properties.concat(node.callProperties || [], node.indexers || [], node.internalSlots || []);
|
|
||||||
|
|
||||||
if (props.length) {
|
|
||||||
this.space();
|
|
||||||
this.printJoin(props, node, {
|
|
||||||
addNewlines(leading) {
|
|
||||||
if (leading && !props[0]) return 1;
|
|
||||||
},
|
|
||||||
|
|
||||||
indent: true,
|
|
||||||
statement: true,
|
|
||||||
iterator: () => {
|
|
||||||
if (props.length !== 1) {
|
|
||||||
this.token(",");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.exact) {
|
|
||||||
this.token("|}");
|
|
||||||
} else {
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectTypeInternalSlot(node) {
|
|
||||||
if (node.static) {
|
|
||||||
this.word("static");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("[");
|
|
||||||
this.token("[");
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.token("]");
|
|
||||||
this.token("]");
|
|
||||||
if (node.optional) this.token("?");
|
|
||||||
|
|
||||||
if (!node.method) {
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectTypeCallProperty(node) {
|
|
||||||
if (node.static) {
|
|
||||||
this.word("static");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectTypeIndexer(node) {
|
|
||||||
if (node.static) {
|
|
||||||
this.word("static");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._variance(node);
|
|
||||||
|
|
||||||
this.token("[");
|
|
||||||
|
|
||||||
if (node.id) {
|
|
||||||
this.print(node.id, node);
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.key, node);
|
|
||||||
this.token("]");
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectTypeProperty(node) {
|
|
||||||
if (node.proto) {
|
|
||||||
this.word("proto");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.static) {
|
|
||||||
this.word("static");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._variance(node);
|
|
||||||
|
|
||||||
this.print(node.key, node);
|
|
||||||
if (node.optional) this.token("?");
|
|
||||||
|
|
||||||
if (!node.method) {
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectTypeSpreadProperty(node) {
|
|
||||||
this.token("...");
|
|
||||||
this.print(node.argument, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function QualifiedTypeIdentifier(node) {
|
|
||||||
this.print(node.qualification, node);
|
|
||||||
this.token(".");
|
|
||||||
this.print(node.id, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function orSeparator() {
|
|
||||||
this.space();
|
|
||||||
this.token("|");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
function UnionTypeAnnotation(node) {
|
|
||||||
this.printJoin(node.types, node, {
|
|
||||||
separator: orSeparator
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function TypeCastExpression(node) {
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function Variance(node) {
|
|
||||||
if (node.kind === "plus") {
|
|
||||||
this.token("+");
|
|
||||||
} else {
|
|
||||||
this.token("-");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function VoidTypeAnnotation() {
|
|
||||||
this.word("void");
|
|
||||||
}
|
|
||||||
|
|
@ -1,137 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
|
|
||||||
var _templateLiterals = require("./template-literals");
|
|
||||||
|
|
||||||
Object.keys(_templateLiterals).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _templateLiterals[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _expressions = require("./expressions");
|
|
||||||
|
|
||||||
Object.keys(_expressions).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _expressions[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _statements = require("./statements");
|
|
||||||
|
|
||||||
Object.keys(_statements).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _statements[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _classes = require("./classes");
|
|
||||||
|
|
||||||
Object.keys(_classes).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _classes[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _methods = require("./methods");
|
|
||||||
|
|
||||||
Object.keys(_methods).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _methods[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _modules = require("./modules");
|
|
||||||
|
|
||||||
Object.keys(_modules).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _modules[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _types = require("./types");
|
|
||||||
|
|
||||||
Object.keys(_types).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _types[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _flow = require("./flow");
|
|
||||||
|
|
||||||
Object.keys(_flow).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _flow[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _base = require("./base");
|
|
||||||
|
|
||||||
Object.keys(_base).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _base[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _jsx = require("./jsx");
|
|
||||||
|
|
||||||
Object.keys(_jsx).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _jsx[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
var _typescript = require("./typescript");
|
|
||||||
|
|
||||||
Object.keys(_typescript).forEach(function (key) {
|
|
||||||
if (key === "default" || key === "__esModule") return;
|
|
||||||
Object.defineProperty(exports, key, {
|
|
||||||
enumerable: true,
|
|
||||||
get: function () {
|
|
||||||
return _typescript[key];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,145 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.JSXAttribute = JSXAttribute;
|
|
||||||
exports.JSXIdentifier = JSXIdentifier;
|
|
||||||
exports.JSXNamespacedName = JSXNamespacedName;
|
|
||||||
exports.JSXMemberExpression = JSXMemberExpression;
|
|
||||||
exports.JSXSpreadAttribute = JSXSpreadAttribute;
|
|
||||||
exports.JSXExpressionContainer = JSXExpressionContainer;
|
|
||||||
exports.JSXSpreadChild = JSXSpreadChild;
|
|
||||||
exports.JSXText = JSXText;
|
|
||||||
exports.JSXElement = JSXElement;
|
|
||||||
exports.JSXOpeningElement = JSXOpeningElement;
|
|
||||||
exports.JSXClosingElement = JSXClosingElement;
|
|
||||||
exports.JSXEmptyExpression = JSXEmptyExpression;
|
|
||||||
exports.JSXFragment = JSXFragment;
|
|
||||||
exports.JSXOpeningFragment = JSXOpeningFragment;
|
|
||||||
exports.JSXClosingFragment = JSXClosingFragment;
|
|
||||||
|
|
||||||
function JSXAttribute(node) {
|
|
||||||
this.print(node.name, node);
|
|
||||||
|
|
||||||
if (node.value) {
|
|
||||||
this.token("=");
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXIdentifier(node) {
|
|
||||||
this.word(node.name);
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXNamespacedName(node) {
|
|
||||||
this.print(node.namespace, node);
|
|
||||||
this.token(":");
|
|
||||||
this.print(node.name, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXMemberExpression(node) {
|
|
||||||
this.print(node.object, node);
|
|
||||||
this.token(".");
|
|
||||||
this.print(node.property, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXSpreadAttribute(node) {
|
|
||||||
this.token("{");
|
|
||||||
this.token("...");
|
|
||||||
this.print(node.argument, node);
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXExpressionContainer(node) {
|
|
||||||
this.token("{");
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXSpreadChild(node) {
|
|
||||||
this.token("{");
|
|
||||||
this.token("...");
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXText(node) {
|
|
||||||
const raw = this.getPossibleRaw(node);
|
|
||||||
|
|
||||||
if (raw != null) {
|
|
||||||
this.token(raw);
|
|
||||||
} else {
|
|
||||||
this.token(node.value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXElement(node) {
|
|
||||||
const open = node.openingElement;
|
|
||||||
this.print(open, node);
|
|
||||||
if (open.selfClosing) return;
|
|
||||||
this.indent();
|
|
||||||
|
|
||||||
for (const child of node.children) {
|
|
||||||
this.print(child, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.dedent();
|
|
||||||
this.print(node.closingElement, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function spaceSeparator() {
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXOpeningElement(node) {
|
|
||||||
this.token("<");
|
|
||||||
this.print(node.name, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
|
|
||||||
if (node.attributes.length > 0) {
|
|
||||||
this.space();
|
|
||||||
this.printJoin(node.attributes, node, {
|
|
||||||
separator: spaceSeparator
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.selfClosing) {
|
|
||||||
this.space();
|
|
||||||
this.token("/>");
|
|
||||||
} else {
|
|
||||||
this.token(">");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXClosingElement(node) {
|
|
||||||
this.token("</");
|
|
||||||
this.print(node.name, node);
|
|
||||||
this.token(">");
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXEmptyExpression(node) {
|
|
||||||
this.printInnerComments(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXFragment(node) {
|
|
||||||
this.print(node.openingFragment, node);
|
|
||||||
this.indent();
|
|
||||||
|
|
||||||
for (const child of node.children) {
|
|
||||||
this.print(child, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.dedent();
|
|
||||||
this.print(node.closingFragment, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXOpeningFragment() {
|
|
||||||
this.token("<");
|
|
||||||
this.token(">");
|
|
||||||
}
|
|
||||||
|
|
||||||
function JSXClosingFragment() {
|
|
||||||
this.token("</");
|
|
||||||
this.token(">");
|
|
||||||
}
|
|
||||||
|
|
@ -1,167 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports._params = _params;
|
|
||||||
exports._parameters = _parameters;
|
|
||||||
exports._param = _param;
|
|
||||||
exports._methodHead = _methodHead;
|
|
||||||
exports._predicate = _predicate;
|
|
||||||
exports._functionHead = _functionHead;
|
|
||||||
exports.FunctionDeclaration = exports.FunctionExpression = FunctionExpression;
|
|
||||||
exports.ArrowFunctionExpression = ArrowFunctionExpression;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function _params(node) {
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
this.token("(");
|
|
||||||
|
|
||||||
this._parameters(node.params, node);
|
|
||||||
|
|
||||||
this.token(")");
|
|
||||||
this.print(node.returnType, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function _parameters(parameters, parent) {
|
|
||||||
for (let i = 0; i < parameters.length; i++) {
|
|
||||||
this._param(parameters[i], parent);
|
|
||||||
|
|
||||||
if (i < parameters.length - 1) {
|
|
||||||
this.token(",");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function _param(parameter, parent) {
|
|
||||||
this.printJoin(parameter.decorators, parameter);
|
|
||||||
this.print(parameter, parent);
|
|
||||||
if (parameter.optional) this.token("?");
|
|
||||||
this.print(parameter.typeAnnotation, parameter);
|
|
||||||
}
|
|
||||||
|
|
||||||
function _methodHead(node) {
|
|
||||||
const kind = node.kind;
|
|
||||||
const key = node.key;
|
|
||||||
|
|
||||||
if (kind === "get" || kind === "set") {
|
|
||||||
this.word(kind);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.async) {
|
|
||||||
this.word("async");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (kind === "method" || kind === "init") {
|
|
||||||
if (node.generator) {
|
|
||||||
this.token("*");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.computed) {
|
|
||||||
this.token("[");
|
|
||||||
this.print(key, node);
|
|
||||||
this.token("]");
|
|
||||||
} else {
|
|
||||||
this.print(key, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.optional) {
|
|
||||||
this.token("?");
|
|
||||||
}
|
|
||||||
|
|
||||||
this._params(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function _predicate(node) {
|
|
||||||
if (node.predicate) {
|
|
||||||
if (!node.returnType) {
|
|
||||||
this.token(":");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.predicate, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function _functionHead(node) {
|
|
||||||
if (node.async) {
|
|
||||||
this.word("async");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("function");
|
|
||||||
if (node.generator) this.token("*");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (node.id) {
|
|
||||||
this.print(node.id, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._params(node);
|
|
||||||
|
|
||||||
this._predicate(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FunctionExpression(node) {
|
|
||||||
this._functionHead(node);
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ArrowFunctionExpression(node) {
|
|
||||||
if (node.async) {
|
|
||||||
this.word("async");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
const firstParam = node.params[0];
|
|
||||||
|
|
||||||
if (node.params.length === 1 && t().isIdentifier(firstParam) && !hasTypes(node, firstParam)) {
|
|
||||||
if (this.format.retainLines && node.loc && node.body.loc && node.loc.start.line < node.body.loc.start.line) {
|
|
||||||
this.token("(");
|
|
||||||
|
|
||||||
if (firstParam.loc && firstParam.loc.start.line > node.loc.start.line) {
|
|
||||||
this.indent();
|
|
||||||
this.print(firstParam, node);
|
|
||||||
this.dedent();
|
|
||||||
|
|
||||||
this._catchUp("start", node.body.loc);
|
|
||||||
} else {
|
|
||||||
this.print(firstParam, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(")");
|
|
||||||
} else {
|
|
||||||
this.print(firstParam, node);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this._params(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._predicate(node);
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.token("=>");
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasTypes(node, param) {
|
|
||||||
return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments;
|
|
||||||
}
|
|
||||||
|
|
@ -1,214 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.ImportSpecifier = ImportSpecifier;
|
|
||||||
exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
|
|
||||||
exports.ExportDefaultSpecifier = ExportDefaultSpecifier;
|
|
||||||
exports.ExportSpecifier = ExportSpecifier;
|
|
||||||
exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier;
|
|
||||||
exports.ExportAllDeclaration = ExportAllDeclaration;
|
|
||||||
exports.ExportNamedDeclaration = ExportNamedDeclaration;
|
|
||||||
exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
|
|
||||||
exports.ImportDeclaration = ImportDeclaration;
|
|
||||||
exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function ImportSpecifier(node) {
|
|
||||||
if (node.importKind === "type" || node.importKind === "typeof") {
|
|
||||||
this.word(node.importKind);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.imported, node);
|
|
||||||
|
|
||||||
if (node.local && node.local.name !== node.imported.name) {
|
|
||||||
this.space();
|
|
||||||
this.word("as");
|
|
||||||
this.space();
|
|
||||||
this.print(node.local, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ImportDefaultSpecifier(node) {
|
|
||||||
this.print(node.local, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExportDefaultSpecifier(node) {
|
|
||||||
this.print(node.exported, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExportSpecifier(node) {
|
|
||||||
this.print(node.local, node);
|
|
||||||
|
|
||||||
if (node.exported && node.local.name !== node.exported.name) {
|
|
||||||
this.space();
|
|
||||||
this.word("as");
|
|
||||||
this.space();
|
|
||||||
this.print(node.exported, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExportNamespaceSpecifier(node) {
|
|
||||||
this.token("*");
|
|
||||||
this.space();
|
|
||||||
this.word("as");
|
|
||||||
this.space();
|
|
||||||
this.print(node.exported, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExportAllDeclaration(node) {
|
|
||||||
this.word("export");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (node.exportKind === "type") {
|
|
||||||
this.word("type");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("*");
|
|
||||||
this.space();
|
|
||||||
this.word("from");
|
|
||||||
this.space();
|
|
||||||
this.print(node.source, node);
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExportNamedDeclaration(node) {
|
|
||||||
if (this.format.decoratorsBeforeExport && t().isClassDeclaration(node.declaration)) {
|
|
||||||
this.printJoin(node.declaration.decorators, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("export");
|
|
||||||
this.space();
|
|
||||||
ExportDeclaration.apply(this, arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExportDefaultDeclaration(node) {
|
|
||||||
if (this.format.decoratorsBeforeExport && t().isClassDeclaration(node.declaration)) {
|
|
||||||
this.printJoin(node.declaration.decorators, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("export");
|
|
||||||
this.space();
|
|
||||||
this.word("default");
|
|
||||||
this.space();
|
|
||||||
ExportDeclaration.apply(this, arguments);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ExportDeclaration(node) {
|
|
||||||
if (node.declaration) {
|
|
||||||
const declar = node.declaration;
|
|
||||||
this.print(declar, node);
|
|
||||||
if (!t().isStatement(declar)) this.semicolon();
|
|
||||||
} else {
|
|
||||||
if (node.exportKind === "type") {
|
|
||||||
this.word("type");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
const specifiers = node.specifiers.slice(0);
|
|
||||||
let hasSpecial = false;
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const first = specifiers[0];
|
|
||||||
|
|
||||||
if (t().isExportDefaultSpecifier(first) || t().isExportNamespaceSpecifier(first)) {
|
|
||||||
hasSpecial = true;
|
|
||||||
this.print(specifiers.shift(), node);
|
|
||||||
|
|
||||||
if (specifiers.length) {
|
|
||||||
this.token(",");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (specifiers.length || !specifiers.length && !hasSpecial) {
|
|
||||||
this.token("{");
|
|
||||||
|
|
||||||
if (specifiers.length) {
|
|
||||||
this.space();
|
|
||||||
this.printList(specifiers, node);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.source) {
|
|
||||||
this.space();
|
|
||||||
this.word("from");
|
|
||||||
this.space();
|
|
||||||
this.print(node.source, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ImportDeclaration(node) {
|
|
||||||
this.word("import");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (node.importKind === "type" || node.importKind === "typeof") {
|
|
||||||
this.word(node.importKind);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
const specifiers = node.specifiers.slice(0);
|
|
||||||
|
|
||||||
if (specifiers && specifiers.length) {
|
|
||||||
while (true) {
|
|
||||||
const first = specifiers[0];
|
|
||||||
|
|
||||||
if (t().isImportDefaultSpecifier(first) || t().isImportNamespaceSpecifier(first)) {
|
|
||||||
this.print(specifiers.shift(), node);
|
|
||||||
|
|
||||||
if (specifiers.length) {
|
|
||||||
this.token(",");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (specifiers.length) {
|
|
||||||
this.token("{");
|
|
||||||
this.space();
|
|
||||||
this.printList(specifiers, node);
|
|
||||||
this.space();
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.word("from");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.source, node);
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ImportNamespaceSpecifier(node) {
|
|
||||||
this.token("*");
|
|
||||||
this.space();
|
|
||||||
this.word("as");
|
|
||||||
this.space();
|
|
||||||
this.print(node.local, node);
|
|
||||||
}
|
|
||||||
|
|
@ -1,319 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.WithStatement = WithStatement;
|
|
||||||
exports.IfStatement = IfStatement;
|
|
||||||
exports.ForStatement = ForStatement;
|
|
||||||
exports.WhileStatement = WhileStatement;
|
|
||||||
exports.DoWhileStatement = DoWhileStatement;
|
|
||||||
exports.LabeledStatement = LabeledStatement;
|
|
||||||
exports.TryStatement = TryStatement;
|
|
||||||
exports.CatchClause = CatchClause;
|
|
||||||
exports.SwitchStatement = SwitchStatement;
|
|
||||||
exports.SwitchCase = SwitchCase;
|
|
||||||
exports.DebuggerStatement = DebuggerStatement;
|
|
||||||
exports.VariableDeclaration = VariableDeclaration;
|
|
||||||
exports.VariableDeclarator = VariableDeclarator;
|
|
||||||
exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForOfStatement = exports.ForInStatement = void 0;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function WithStatement(node) {
|
|
||||||
this.word("with");
|
|
||||||
this.space();
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.object, node);
|
|
||||||
this.token(")");
|
|
||||||
this.printBlock(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function IfStatement(node) {
|
|
||||||
this.word("if");
|
|
||||||
this.space();
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.test, node);
|
|
||||||
this.token(")");
|
|
||||||
this.space();
|
|
||||||
const needsBlock = node.alternate && t().isIfStatement(getLastStatement(node.consequent));
|
|
||||||
|
|
||||||
if (needsBlock) {
|
|
||||||
this.token("{");
|
|
||||||
this.newline();
|
|
||||||
this.indent();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.printAndIndentOnComments(node.consequent, node);
|
|
||||||
|
|
||||||
if (needsBlock) {
|
|
||||||
this.dedent();
|
|
||||||
this.newline();
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.alternate) {
|
|
||||||
if (this.endsWith("}")) this.space();
|
|
||||||
this.word("else");
|
|
||||||
this.space();
|
|
||||||
this.printAndIndentOnComments(node.alternate, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getLastStatement(statement) {
|
|
||||||
if (!t().isStatement(statement.body)) return statement;
|
|
||||||
return getLastStatement(statement.body);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ForStatement(node) {
|
|
||||||
this.word("for");
|
|
||||||
this.space();
|
|
||||||
this.token("(");
|
|
||||||
this.inForStatementInitCounter++;
|
|
||||||
this.print(node.init, node);
|
|
||||||
this.inForStatementInitCounter--;
|
|
||||||
this.token(";");
|
|
||||||
|
|
||||||
if (node.test) {
|
|
||||||
this.space();
|
|
||||||
this.print(node.test, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(";");
|
|
||||||
|
|
||||||
if (node.update) {
|
|
||||||
this.space();
|
|
||||||
this.print(node.update, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(")");
|
|
||||||
this.printBlock(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function WhileStatement(node) {
|
|
||||||
this.word("while");
|
|
||||||
this.space();
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.test, node);
|
|
||||||
this.token(")");
|
|
||||||
this.printBlock(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
const buildForXStatement = function (op) {
|
|
||||||
return function (node) {
|
|
||||||
this.word("for");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (op === "of" && node.await) {
|
|
||||||
this.word("await");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.left, node);
|
|
||||||
this.space();
|
|
||||||
this.word(op);
|
|
||||||
this.space();
|
|
||||||
this.print(node.right, node);
|
|
||||||
this.token(")");
|
|
||||||
this.printBlock(node);
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const ForInStatement = buildForXStatement("in");
|
|
||||||
exports.ForInStatement = ForInStatement;
|
|
||||||
const ForOfStatement = buildForXStatement("of");
|
|
||||||
exports.ForOfStatement = ForOfStatement;
|
|
||||||
|
|
||||||
function DoWhileStatement(node) {
|
|
||||||
this.word("do");
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
this.space();
|
|
||||||
this.word("while");
|
|
||||||
this.space();
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.test, node);
|
|
||||||
this.token(")");
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildLabelStatement(prefix, key = "label") {
|
|
||||||
return function (node) {
|
|
||||||
this.word(prefix);
|
|
||||||
const label = node[key];
|
|
||||||
|
|
||||||
if (label) {
|
|
||||||
this.space();
|
|
||||||
const isLabel = key == "label";
|
|
||||||
const terminatorState = this.startTerminatorless(isLabel);
|
|
||||||
this.print(label, node);
|
|
||||||
this.endTerminatorless(terminatorState);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const ContinueStatement = buildLabelStatement("continue");
|
|
||||||
exports.ContinueStatement = ContinueStatement;
|
|
||||||
const ReturnStatement = buildLabelStatement("return", "argument");
|
|
||||||
exports.ReturnStatement = ReturnStatement;
|
|
||||||
const BreakStatement = buildLabelStatement("break");
|
|
||||||
exports.BreakStatement = BreakStatement;
|
|
||||||
const ThrowStatement = buildLabelStatement("throw", "argument");
|
|
||||||
exports.ThrowStatement = ThrowStatement;
|
|
||||||
|
|
||||||
function LabeledStatement(node) {
|
|
||||||
this.print(node.label, node);
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TryStatement(node) {
|
|
||||||
this.word("try");
|
|
||||||
this.space();
|
|
||||||
this.print(node.block, node);
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (node.handlers) {
|
|
||||||
this.print(node.handlers[0], node);
|
|
||||||
} else {
|
|
||||||
this.print(node.handler, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.finalizer) {
|
|
||||||
this.space();
|
|
||||||
this.word("finally");
|
|
||||||
this.space();
|
|
||||||
this.print(node.finalizer, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function CatchClause(node) {
|
|
||||||
this.word("catch");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (node.param) {
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.param, node);
|
|
||||||
this.token(")");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SwitchStatement(node) {
|
|
||||||
this.word("switch");
|
|
||||||
this.space();
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.discriminant, node);
|
|
||||||
this.token(")");
|
|
||||||
this.space();
|
|
||||||
this.token("{");
|
|
||||||
this.printSequence(node.cases, node, {
|
|
||||||
indent: true,
|
|
||||||
|
|
||||||
addNewlines(leading, cas) {
|
|
||||||
if (!leading && node.cases[node.cases.length - 1] === cas) return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
});
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
function SwitchCase(node) {
|
|
||||||
if (node.test) {
|
|
||||||
this.word("case");
|
|
||||||
this.space();
|
|
||||||
this.print(node.test, node);
|
|
||||||
this.token(":");
|
|
||||||
} else {
|
|
||||||
this.word("default");
|
|
||||||
this.token(":");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.consequent.length) {
|
|
||||||
this.newline();
|
|
||||||
this.printSequence(node.consequent, node, {
|
|
||||||
indent: true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function DebuggerStatement() {
|
|
||||||
this.word("debugger");
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function variableDeclarationIndent() {
|
|
||||||
this.token(",");
|
|
||||||
this.newline();
|
|
||||||
if (this.endsWith("\n")) for (let i = 0; i < 4; i++) this.space(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
function constDeclarationIndent() {
|
|
||||||
this.token(",");
|
|
||||||
this.newline();
|
|
||||||
if (this.endsWith("\n")) for (let i = 0; i < 6; i++) this.space(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
function VariableDeclaration(node, parent) {
|
|
||||||
if (node.declare) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word(node.kind);
|
|
||||||
this.space();
|
|
||||||
let hasInits = false;
|
|
||||||
|
|
||||||
if (!t().isFor(parent)) {
|
|
||||||
for (const declar of node.declarations) {
|
|
||||||
if (declar.init) {
|
|
||||||
hasInits = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let separator;
|
|
||||||
|
|
||||||
if (hasInits) {
|
|
||||||
separator = node.kind === "const" ? constDeclarationIndent : variableDeclarationIndent;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.printList(node.declarations, node, {
|
|
||||||
separator
|
|
||||||
});
|
|
||||||
|
|
||||||
if (t().isFor(parent)) {
|
|
||||||
if (parent.left === node || parent.init === node) return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.semicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
function VariableDeclarator(node) {
|
|
||||||
this.print(node.id, node);
|
|
||||||
if (node.definite) this.token("!");
|
|
||||||
this.print(node.id.typeAnnotation, node);
|
|
||||||
|
|
||||||
if (node.init) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.init, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,33 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.TaggedTemplateExpression = TaggedTemplateExpression;
|
|
||||||
exports.TemplateElement = TemplateElement;
|
|
||||||
exports.TemplateLiteral = TemplateLiteral;
|
|
||||||
|
|
||||||
function TaggedTemplateExpression(node) {
|
|
||||||
this.print(node.tag, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
this.print(node.quasi, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TemplateElement(node, parent) {
|
|
||||||
const isFirst = parent.quasis[0] === node;
|
|
||||||
const isLast = parent.quasis[parent.quasis.length - 1] === node;
|
|
||||||
const value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${");
|
|
||||||
this.token(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TemplateLiteral(node) {
|
|
||||||
const quasis = node.quasis;
|
|
||||||
|
|
||||||
for (let i = 0; i < quasis.length; i++) {
|
|
||||||
this.print(quasis[i], node);
|
|
||||||
|
|
||||||
if (i + 1 < quasis.length) {
|
|
||||||
this.print(node.expressions[i], node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,198 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.Identifier = Identifier;
|
|
||||||
exports.ArgumentPlaceholder = ArgumentPlaceholder;
|
|
||||||
exports.SpreadElement = exports.RestElement = RestElement;
|
|
||||||
exports.ObjectPattern = exports.ObjectExpression = ObjectExpression;
|
|
||||||
exports.ObjectMethod = ObjectMethod;
|
|
||||||
exports.ObjectProperty = ObjectProperty;
|
|
||||||
exports.ArrayPattern = exports.ArrayExpression = ArrayExpression;
|
|
||||||
exports.RegExpLiteral = RegExpLiteral;
|
|
||||||
exports.BooleanLiteral = BooleanLiteral;
|
|
||||||
exports.NullLiteral = NullLiteral;
|
|
||||||
exports.NumericLiteral = NumericLiteral;
|
|
||||||
exports.StringLiteral = StringLiteral;
|
|
||||||
exports.BigIntLiteral = BigIntLiteral;
|
|
||||||
exports.PipelineTopicExpression = PipelineTopicExpression;
|
|
||||||
exports.PipelineBareFunction = PipelineBareFunction;
|
|
||||||
exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _jsesc() {
|
|
||||||
const data = _interopRequireDefault(require("jsesc"));
|
|
||||||
|
|
||||||
_jsesc = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function Identifier(node) {
|
|
||||||
this.exactSource(node.loc, () => {
|
|
||||||
this.word(node.name);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function ArgumentPlaceholder() {
|
|
||||||
this.token("?");
|
|
||||||
}
|
|
||||||
|
|
||||||
function RestElement(node) {
|
|
||||||
this.token("...");
|
|
||||||
this.print(node.argument, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectExpression(node) {
|
|
||||||
const props = node.properties;
|
|
||||||
this.token("{");
|
|
||||||
this.printInnerComments(node);
|
|
||||||
|
|
||||||
if (props.length) {
|
|
||||||
this.space();
|
|
||||||
this.printList(props, node, {
|
|
||||||
indent: true,
|
|
||||||
statement: true
|
|
||||||
});
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectMethod(node) {
|
|
||||||
this.printJoin(node.decorators, node);
|
|
||||||
|
|
||||||
this._methodHead(node);
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectProperty(node) {
|
|
||||||
this.printJoin(node.decorators, node);
|
|
||||||
|
|
||||||
if (node.computed) {
|
|
||||||
this.token("[");
|
|
||||||
this.print(node.key, node);
|
|
||||||
this.token("]");
|
|
||||||
} else {
|
|
||||||
if (t().isAssignmentPattern(node.value) && t().isIdentifier(node.key) && node.key.name === node.value.left.name) {
|
|
||||||
this.print(node.value, node);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.key, node);
|
|
||||||
|
|
||||||
if (node.shorthand && t().isIdentifier(node.key) && t().isIdentifier(node.value) && node.key.name === node.value.name) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
this.print(node.value, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ArrayExpression(node) {
|
|
||||||
const elems = node.elements;
|
|
||||||
const len = elems.length;
|
|
||||||
this.token("[");
|
|
||||||
this.printInnerComments(node);
|
|
||||||
|
|
||||||
for (let i = 0; i < elems.length; i++) {
|
|
||||||
const elem = elems[i];
|
|
||||||
|
|
||||||
if (elem) {
|
|
||||||
if (i > 0) this.space();
|
|
||||||
this.print(elem, node);
|
|
||||||
if (i < len - 1) this.token(",");
|
|
||||||
} else {
|
|
||||||
this.token(",");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("]");
|
|
||||||
}
|
|
||||||
|
|
||||||
function RegExpLiteral(node) {
|
|
||||||
this.word(`/${node.pattern}/${node.flags}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function BooleanLiteral(node) {
|
|
||||||
this.word(node.value ? "true" : "false");
|
|
||||||
}
|
|
||||||
|
|
||||||
function NullLiteral() {
|
|
||||||
this.word("null");
|
|
||||||
}
|
|
||||||
|
|
||||||
function NumericLiteral(node) {
|
|
||||||
const raw = this.getPossibleRaw(node);
|
|
||||||
const value = node.value + "";
|
|
||||||
|
|
||||||
if (raw == null) {
|
|
||||||
this.number(value);
|
|
||||||
} else if (this.format.minified) {
|
|
||||||
this.number(raw.length < value.length ? raw : value);
|
|
||||||
} else {
|
|
||||||
this.number(raw);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function StringLiteral(node) {
|
|
||||||
const raw = this.getPossibleRaw(node);
|
|
||||||
|
|
||||||
if (!this.format.minified && raw != null) {
|
|
||||||
this.token(raw);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const opts = this.format.jsescOption;
|
|
||||||
|
|
||||||
if (this.format.jsonCompatibleStrings) {
|
|
||||||
opts.json = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const val = (0, _jsesc().default)(node.value, opts);
|
|
||||||
return this.token(val);
|
|
||||||
}
|
|
||||||
|
|
||||||
function BigIntLiteral(node) {
|
|
||||||
const raw = this.getPossibleRaw(node);
|
|
||||||
|
|
||||||
if (!this.format.minified && raw != null) {
|
|
||||||
this.token(raw);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(node.value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PipelineTopicExpression(node) {
|
|
||||||
this.print(node.expression, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PipelineBareFunction(node) {
|
|
||||||
this.print(node.callee, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PipelinePrimaryTopicReference() {
|
|
||||||
this.token("#");
|
|
||||||
}
|
|
||||||
|
|
@ -1,715 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.TSTypeAnnotation = TSTypeAnnotation;
|
|
||||||
exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation;
|
|
||||||
exports.TSTypeParameter = TSTypeParameter;
|
|
||||||
exports.TSParameterProperty = TSParameterProperty;
|
|
||||||
exports.TSDeclareFunction = TSDeclareFunction;
|
|
||||||
exports.TSDeclareMethod = TSDeclareMethod;
|
|
||||||
exports.TSQualifiedName = TSQualifiedName;
|
|
||||||
exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration;
|
|
||||||
exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration;
|
|
||||||
exports.TSPropertySignature = TSPropertySignature;
|
|
||||||
exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName;
|
|
||||||
exports.TSMethodSignature = TSMethodSignature;
|
|
||||||
exports.TSIndexSignature = TSIndexSignature;
|
|
||||||
exports.TSAnyKeyword = TSAnyKeyword;
|
|
||||||
exports.TSUnknownKeyword = TSUnknownKeyword;
|
|
||||||
exports.TSNumberKeyword = TSNumberKeyword;
|
|
||||||
exports.TSObjectKeyword = TSObjectKeyword;
|
|
||||||
exports.TSBooleanKeyword = TSBooleanKeyword;
|
|
||||||
exports.TSStringKeyword = TSStringKeyword;
|
|
||||||
exports.TSSymbolKeyword = TSSymbolKeyword;
|
|
||||||
exports.TSVoidKeyword = TSVoidKeyword;
|
|
||||||
exports.TSUndefinedKeyword = TSUndefinedKeyword;
|
|
||||||
exports.TSNullKeyword = TSNullKeyword;
|
|
||||||
exports.TSNeverKeyword = TSNeverKeyword;
|
|
||||||
exports.TSThisType = TSThisType;
|
|
||||||
exports.TSFunctionType = TSFunctionType;
|
|
||||||
exports.TSConstructorType = TSConstructorType;
|
|
||||||
exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType;
|
|
||||||
exports.TSTypeReference = TSTypeReference;
|
|
||||||
exports.TSTypePredicate = TSTypePredicate;
|
|
||||||
exports.TSTypeQuery = TSTypeQuery;
|
|
||||||
exports.TSTypeLiteral = TSTypeLiteral;
|
|
||||||
exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody;
|
|
||||||
exports.tsPrintBraced = tsPrintBraced;
|
|
||||||
exports.TSArrayType = TSArrayType;
|
|
||||||
exports.TSTupleType = TSTupleType;
|
|
||||||
exports.TSOptionalType = TSOptionalType;
|
|
||||||
exports.TSRestType = TSRestType;
|
|
||||||
exports.TSUnionType = TSUnionType;
|
|
||||||
exports.TSIntersectionType = TSIntersectionType;
|
|
||||||
exports.tsPrintUnionOrIntersectionType = tsPrintUnionOrIntersectionType;
|
|
||||||
exports.TSConditionalType = TSConditionalType;
|
|
||||||
exports.TSInferType = TSInferType;
|
|
||||||
exports.TSParenthesizedType = TSParenthesizedType;
|
|
||||||
exports.TSTypeOperator = TSTypeOperator;
|
|
||||||
exports.TSIndexedAccessType = TSIndexedAccessType;
|
|
||||||
exports.TSMappedType = TSMappedType;
|
|
||||||
exports.TSLiteralType = TSLiteralType;
|
|
||||||
exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments;
|
|
||||||
exports.TSInterfaceDeclaration = TSInterfaceDeclaration;
|
|
||||||
exports.TSInterfaceBody = TSInterfaceBody;
|
|
||||||
exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration;
|
|
||||||
exports.TSAsExpression = TSAsExpression;
|
|
||||||
exports.TSTypeAssertion = TSTypeAssertion;
|
|
||||||
exports.TSEnumDeclaration = TSEnumDeclaration;
|
|
||||||
exports.TSEnumMember = TSEnumMember;
|
|
||||||
exports.TSModuleDeclaration = TSModuleDeclaration;
|
|
||||||
exports.TSModuleBlock = TSModuleBlock;
|
|
||||||
exports.TSImportType = TSImportType;
|
|
||||||
exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration;
|
|
||||||
exports.TSExternalModuleReference = TSExternalModuleReference;
|
|
||||||
exports.TSNonNullExpression = TSNonNullExpression;
|
|
||||||
exports.TSExportAssignment = TSExportAssignment;
|
|
||||||
exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration;
|
|
||||||
exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase;
|
|
||||||
|
|
||||||
function TSTypeAnnotation(node) {
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
if (node.optional) this.token("?");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeParameterInstantiation(node) {
|
|
||||||
this.token("<");
|
|
||||||
this.printList(node.params, node, {});
|
|
||||||
this.token(">");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeParameter(node) {
|
|
||||||
this.word(node.name);
|
|
||||||
|
|
||||||
if (node.constraint) {
|
|
||||||
this.space();
|
|
||||||
this.word("extends");
|
|
||||||
this.space();
|
|
||||||
this.print(node.constraint, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.default) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.default, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSParameterProperty(node) {
|
|
||||||
if (node.accessibility) {
|
|
||||||
this.word(node.accessibility);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.readonly) {
|
|
||||||
this.word("readonly");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._param(node.parameter);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSDeclareFunction(node) {
|
|
||||||
if (node.declare) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._functionHead(node);
|
|
||||||
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSDeclareMethod(node) {
|
|
||||||
this._classMethodHead(node);
|
|
||||||
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSQualifiedName(node) {
|
|
||||||
this.print(node.left, node);
|
|
||||||
this.token(".");
|
|
||||||
this.print(node.right, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSCallSignatureDeclaration(node) {
|
|
||||||
this.tsPrintSignatureDeclarationBase(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSConstructSignatureDeclaration(node) {
|
|
||||||
this.word("new");
|
|
||||||
this.space();
|
|
||||||
this.tsPrintSignatureDeclarationBase(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSPropertySignature(node) {
|
|
||||||
const {
|
|
||||||
readonly,
|
|
||||||
initializer
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (readonly) {
|
|
||||||
this.word("readonly");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.tsPrintPropertyOrMethodName(node);
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
|
|
||||||
if (initializer) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(initializer, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function tsPrintPropertyOrMethodName(node) {
|
|
||||||
if (node.computed) {
|
|
||||||
this.token("[");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node.key, node);
|
|
||||||
|
|
||||||
if (node.computed) {
|
|
||||||
this.token("]");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.optional) {
|
|
||||||
this.token("?");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSMethodSignature(node) {
|
|
||||||
this.tsPrintPropertyOrMethodName(node);
|
|
||||||
this.tsPrintSignatureDeclarationBase(node);
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSIndexSignature(node) {
|
|
||||||
const {
|
|
||||||
readonly
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (readonly) {
|
|
||||||
this.word("readonly");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("[");
|
|
||||||
|
|
||||||
this._parameters(node.parameters, node);
|
|
||||||
|
|
||||||
this.token("]");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSAnyKeyword() {
|
|
||||||
this.word("any");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSUnknownKeyword() {
|
|
||||||
this.word("unknown");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSNumberKeyword() {
|
|
||||||
this.word("number");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSObjectKeyword() {
|
|
||||||
this.word("object");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSBooleanKeyword() {
|
|
||||||
this.word("boolean");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSStringKeyword() {
|
|
||||||
this.word("string");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSSymbolKeyword() {
|
|
||||||
this.word("symbol");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSVoidKeyword() {
|
|
||||||
this.word("void");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSUndefinedKeyword() {
|
|
||||||
this.word("undefined");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSNullKeyword() {
|
|
||||||
this.word("null");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSNeverKeyword() {
|
|
||||||
this.word("never");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSThisType() {
|
|
||||||
this.word("this");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSFunctionType(node) {
|
|
||||||
this.tsPrintFunctionOrConstructorType(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSConstructorType(node) {
|
|
||||||
this.word("new");
|
|
||||||
this.space();
|
|
||||||
this.tsPrintFunctionOrConstructorType(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function tsPrintFunctionOrConstructorType(node) {
|
|
||||||
const {
|
|
||||||
typeParameters,
|
|
||||||
parameters
|
|
||||||
} = node;
|
|
||||||
this.print(typeParameters, node);
|
|
||||||
this.token("(");
|
|
||||||
|
|
||||||
this._parameters(parameters, node);
|
|
||||||
|
|
||||||
this.token(")");
|
|
||||||
this.space();
|
|
||||||
this.token("=>");
|
|
||||||
this.space();
|
|
||||||
this.print(node.typeAnnotation.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeReference(node) {
|
|
||||||
this.print(node.typeName, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypePredicate(node) {
|
|
||||||
this.print(node.parameterName);
|
|
||||||
this.space();
|
|
||||||
this.word("is");
|
|
||||||
this.space();
|
|
||||||
this.print(node.typeAnnotation.typeAnnotation);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeQuery(node) {
|
|
||||||
this.word("typeof");
|
|
||||||
this.space();
|
|
||||||
this.print(node.exprName);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeLiteral(node) {
|
|
||||||
this.tsPrintTypeLiteralOrInterfaceBody(node.members, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function tsPrintTypeLiteralOrInterfaceBody(members, node) {
|
|
||||||
this.tsPrintBraced(members, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function tsPrintBraced(members, node) {
|
|
||||||
this.token("{");
|
|
||||||
|
|
||||||
if (members.length) {
|
|
||||||
this.indent();
|
|
||||||
this.newline();
|
|
||||||
|
|
||||||
for (const member of members) {
|
|
||||||
this.print(member, node);
|
|
||||||
this.newline();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.dedent();
|
|
||||||
this.rightBrace();
|
|
||||||
} else {
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSArrayType(node) {
|
|
||||||
this.print(node.elementType, node);
|
|
||||||
this.token("[]");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTupleType(node) {
|
|
||||||
this.token("[");
|
|
||||||
this.printList(node.elementTypes, node);
|
|
||||||
this.token("]");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSOptionalType(node) {
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
this.token("?");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSRestType(node) {
|
|
||||||
this.token("...");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSUnionType(node) {
|
|
||||||
this.tsPrintUnionOrIntersectionType(node, "|");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSIntersectionType(node) {
|
|
||||||
this.tsPrintUnionOrIntersectionType(node, "&");
|
|
||||||
}
|
|
||||||
|
|
||||||
function tsPrintUnionOrIntersectionType(node, sep) {
|
|
||||||
this.printJoin(node.types, node, {
|
|
||||||
separator() {
|
|
||||||
this.space();
|
|
||||||
this.token(sep);
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSConditionalType(node) {
|
|
||||||
this.print(node.checkType);
|
|
||||||
this.space();
|
|
||||||
this.word("extends");
|
|
||||||
this.space();
|
|
||||||
this.print(node.extendsType);
|
|
||||||
this.space();
|
|
||||||
this.token("?");
|
|
||||||
this.space();
|
|
||||||
this.print(node.trueType);
|
|
||||||
this.space();
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
this.print(node.falseType);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSInferType(node) {
|
|
||||||
this.token("infer");
|
|
||||||
this.space();
|
|
||||||
this.print(node.typeParameter);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSParenthesizedType(node) {
|
|
||||||
this.token("(");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeOperator(node) {
|
|
||||||
this.token(node.operator);
|
|
||||||
this.space();
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSIndexedAccessType(node) {
|
|
||||||
this.print(node.objectType, node);
|
|
||||||
this.token("[");
|
|
||||||
this.print(node.indexType, node);
|
|
||||||
this.token("]");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSMappedType(node) {
|
|
||||||
const {
|
|
||||||
readonly,
|
|
||||||
typeParameter,
|
|
||||||
optional
|
|
||||||
} = node;
|
|
||||||
this.token("{");
|
|
||||||
this.space();
|
|
||||||
|
|
||||||
if (readonly) {
|
|
||||||
tokenIfPlusMinus(this, readonly);
|
|
||||||
this.word("readonly");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("[");
|
|
||||||
this.word(typeParameter.name);
|
|
||||||
this.space();
|
|
||||||
this.word("in");
|
|
||||||
this.space();
|
|
||||||
this.print(typeParameter.constraint, typeParameter);
|
|
||||||
this.token("]");
|
|
||||||
|
|
||||||
if (optional) {
|
|
||||||
tokenIfPlusMinus(this, optional);
|
|
||||||
this.token("?");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(":");
|
|
||||||
this.space();
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
this.space();
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
function tokenIfPlusMinus(self, tok) {
|
|
||||||
if (tok !== true) {
|
|
||||||
self.token(tok);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSLiteralType(node) {
|
|
||||||
this.print(node.literal, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSExpressionWithTypeArguments(node) {
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.print(node.typeParameters, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSInterfaceDeclaration(node) {
|
|
||||||
const {
|
|
||||||
declare,
|
|
||||||
id,
|
|
||||||
typeParameters,
|
|
||||||
extends: extendz,
|
|
||||||
body
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (declare) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("interface");
|
|
||||||
this.space();
|
|
||||||
this.print(id, node);
|
|
||||||
this.print(typeParameters, node);
|
|
||||||
|
|
||||||
if (extendz) {
|
|
||||||
this.space();
|
|
||||||
this.word("extends");
|
|
||||||
this.space();
|
|
||||||
this.printList(extendz, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSInterfaceBody(node) {
|
|
||||||
this.tsPrintTypeLiteralOrInterfaceBody(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeAliasDeclaration(node) {
|
|
||||||
const {
|
|
||||||
declare,
|
|
||||||
id,
|
|
||||||
typeParameters,
|
|
||||||
typeAnnotation
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (declare) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("type");
|
|
||||||
this.space();
|
|
||||||
this.print(id, node);
|
|
||||||
this.print(typeParameters, node);
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(typeAnnotation, node);
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSAsExpression(node) {
|
|
||||||
const {
|
|
||||||
expression,
|
|
||||||
typeAnnotation
|
|
||||||
} = node;
|
|
||||||
this.print(expression, node);
|
|
||||||
this.space();
|
|
||||||
this.word("as");
|
|
||||||
this.space();
|
|
||||||
this.print(typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeAssertion(node) {
|
|
||||||
const {
|
|
||||||
typeAnnotation,
|
|
||||||
expression
|
|
||||||
} = node;
|
|
||||||
this.token("<");
|
|
||||||
this.print(typeAnnotation, node);
|
|
||||||
this.token(">");
|
|
||||||
this.space();
|
|
||||||
this.print(expression, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSEnumDeclaration(node) {
|
|
||||||
const {
|
|
||||||
declare,
|
|
||||||
const: isConst,
|
|
||||||
id,
|
|
||||||
members
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (declare) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isConst) {
|
|
||||||
this.word("const");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("enum");
|
|
||||||
this.space();
|
|
||||||
this.print(id, node);
|
|
||||||
this.space();
|
|
||||||
this.tsPrintBraced(members, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSEnumMember(node) {
|
|
||||||
const {
|
|
||||||
id,
|
|
||||||
initializer
|
|
||||||
} = node;
|
|
||||||
this.print(id, node);
|
|
||||||
|
|
||||||
if (initializer) {
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(initializer, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token(",");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSModuleDeclaration(node) {
|
|
||||||
const {
|
|
||||||
declare,
|
|
||||||
id
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (declare) {
|
|
||||||
this.word("declare");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!node.global) {
|
|
||||||
this.word(id.type === "Identifier" ? "namespace" : "module");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(id, node);
|
|
||||||
|
|
||||||
if (!node.body) {
|
|
||||||
this.token(";");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let body = node.body;
|
|
||||||
|
|
||||||
while (body.type === "TSModuleDeclaration") {
|
|
||||||
this.token(".");
|
|
||||||
this.print(body.id, body);
|
|
||||||
body = body.body;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.space();
|
|
||||||
this.print(body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSModuleBlock(node) {
|
|
||||||
this.tsPrintBraced(node.body, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSImportType(node) {
|
|
||||||
const {
|
|
||||||
argument,
|
|
||||||
qualifier,
|
|
||||||
typeParameters
|
|
||||||
} = node;
|
|
||||||
this.word("import");
|
|
||||||
this.token("(");
|
|
||||||
this.print(argument, node);
|
|
||||||
this.token(")");
|
|
||||||
|
|
||||||
if (qualifier) {
|
|
||||||
this.token(".");
|
|
||||||
this.print(qualifier, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeParameters) {
|
|
||||||
this.print(typeParameters, node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSImportEqualsDeclaration(node) {
|
|
||||||
const {
|
|
||||||
isExport,
|
|
||||||
id,
|
|
||||||
moduleReference
|
|
||||||
} = node;
|
|
||||||
|
|
||||||
if (isExport) {
|
|
||||||
this.word("export");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.word("import");
|
|
||||||
this.space();
|
|
||||||
this.print(id, node);
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(moduleReference, node);
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSExternalModuleReference(node) {
|
|
||||||
this.token("require(");
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSNonNullExpression(node) {
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.token("!");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSExportAssignment(node) {
|
|
||||||
this.word("export");
|
|
||||||
this.space();
|
|
||||||
this.token("=");
|
|
||||||
this.space();
|
|
||||||
this.print(node.expression, node);
|
|
||||||
this.token(";");
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSNamespaceExportDeclaration(node) {
|
|
||||||
this.word("export");
|
|
||||||
this.space();
|
|
||||||
this.word("as");
|
|
||||||
this.space();
|
|
||||||
this.word("namespace");
|
|
||||||
this.space();
|
|
||||||
this.print(node.id, node);
|
|
||||||
}
|
|
||||||
|
|
||||||
function tsPrintSignatureDeclarationBase(node) {
|
|
||||||
const {
|
|
||||||
typeParameters,
|
|
||||||
parameters
|
|
||||||
} = node;
|
|
||||||
this.print(typeParameters, node);
|
|
||||||
this.token("(");
|
|
||||||
|
|
||||||
this._parameters(parameters, node);
|
|
||||||
|
|
||||||
this.token(")");
|
|
||||||
this.print(node.typeAnnotation, node);
|
|
||||||
}
|
|
||||||
|
|
@ -1,92 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = _default;
|
|
||||||
exports.CodeGenerator = void 0;
|
|
||||||
|
|
||||||
var _sourceMap = _interopRequireDefault(require("./source-map"));
|
|
||||||
|
|
||||||
var _printer = _interopRequireDefault(require("./printer"));
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
class Generator extends _printer.default {
|
|
||||||
constructor(ast, opts = {}, code) {
|
|
||||||
const format = normalizeOptions(code, opts);
|
|
||||||
const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null;
|
|
||||||
super(format, map);
|
|
||||||
this.ast = ast;
|
|
||||||
}
|
|
||||||
|
|
||||||
generate() {
|
|
||||||
return super.generate(this.ast);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeOptions(code, opts) {
|
|
||||||
const format = {
|
|
||||||
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
|
|
||||||
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
|
|
||||||
shouldPrintComment: opts.shouldPrintComment,
|
|
||||||
retainLines: opts.retainLines,
|
|
||||||
retainFunctionParens: opts.retainFunctionParens,
|
|
||||||
comments: opts.comments == null || opts.comments,
|
|
||||||
compact: opts.compact,
|
|
||||||
minified: opts.minified,
|
|
||||||
concise: opts.concise,
|
|
||||||
jsonCompatibleStrings: opts.jsonCompatibleStrings,
|
|
||||||
indent: {
|
|
||||||
adjustMultilineComment: true,
|
|
||||||
style: " ",
|
|
||||||
base: 0
|
|
||||||
},
|
|
||||||
decoratorsBeforeExport: !!opts.decoratorsBeforeExport,
|
|
||||||
jsescOption: Object.assign({
|
|
||||||
quotes: "double",
|
|
||||||
wrap: true
|
|
||||||
}, opts.jsescOption)
|
|
||||||
};
|
|
||||||
|
|
||||||
if (format.minified) {
|
|
||||||
format.compact = true;
|
|
||||||
|
|
||||||
format.shouldPrintComment = format.shouldPrintComment || (() => format.comments);
|
|
||||||
} else {
|
|
||||||
format.shouldPrintComment = format.shouldPrintComment || (value => format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.compact === "auto") {
|
|
||||||
format.compact = code.length > 500000;
|
|
||||||
|
|
||||||
if (format.compact) {
|
|
||||||
console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (format.compact) {
|
|
||||||
format.indent.adjustMultilineComment = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return format;
|
|
||||||
}
|
|
||||||
|
|
||||||
class CodeGenerator {
|
|
||||||
constructor(ast, opts, code) {
|
|
||||||
this._generator = new Generator(ast, opts, code);
|
|
||||||
}
|
|
||||||
|
|
||||||
generate() {
|
|
||||||
return this._generator.generate();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.CodeGenerator = CodeGenerator;
|
|
||||||
|
|
||||||
function _default(ast, opts, code) {
|
|
||||||
const gen = new Generator(ast, opts, code);
|
|
||||||
return gen.generate();
|
|
||||||
}
|
|
||||||
|
|
@ -1,117 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.needsWhitespace = needsWhitespace;
|
|
||||||
exports.needsWhitespaceBefore = needsWhitespaceBefore;
|
|
||||||
exports.needsWhitespaceAfter = needsWhitespaceAfter;
|
|
||||||
exports.needsParens = needsParens;
|
|
||||||
|
|
||||||
var whitespace = _interopRequireWildcard(require("./whitespace"));
|
|
||||||
|
|
||||||
var parens = _interopRequireWildcard(require("./parentheses"));
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function expandAliases(obj) {
|
|
||||||
const newObj = {};
|
|
||||||
|
|
||||||
function add(type, func) {
|
|
||||||
const fn = newObj[type];
|
|
||||||
newObj[type] = fn ? function (node, parent, stack) {
|
|
||||||
const result = fn(node, parent, stack);
|
|
||||||
return result == null ? func(node, parent, stack) : result;
|
|
||||||
} : func;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const type of Object.keys(obj)) {
|
|
||||||
const aliases = t().FLIPPED_ALIAS_KEYS[type];
|
|
||||||
|
|
||||||
if (aliases) {
|
|
||||||
for (const alias of aliases) {
|
|
||||||
add(alias, obj[type]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
add(type, obj[type]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return newObj;
|
|
||||||
}
|
|
||||||
|
|
||||||
const expandedParens = expandAliases(parens);
|
|
||||||
const expandedWhitespaceNodes = expandAliases(whitespace.nodes);
|
|
||||||
const expandedWhitespaceList = expandAliases(whitespace.list);
|
|
||||||
|
|
||||||
function find(obj, node, parent, printStack) {
|
|
||||||
const fn = obj[node.type];
|
|
||||||
return fn ? fn(node, parent, printStack) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isOrHasCallExpression(node) {
|
|
||||||
if (t().isCallExpression(node)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (t().isMemberExpression(node)) {
|
|
||||||
return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property);
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function needsWhitespace(node, parent, type) {
|
|
||||||
if (!node) return 0;
|
|
||||||
|
|
||||||
if (t().isExpressionStatement(node)) {
|
|
||||||
node = node.expression;
|
|
||||||
}
|
|
||||||
|
|
||||||
let linesInfo = find(expandedWhitespaceNodes, node, parent);
|
|
||||||
|
|
||||||
if (!linesInfo) {
|
|
||||||
const items = find(expandedWhitespaceList, node, parent);
|
|
||||||
|
|
||||||
if (items) {
|
|
||||||
for (let i = 0; i < items.length; i++) {
|
|
||||||
linesInfo = needsWhitespace(items[i], node, type);
|
|
||||||
if (linesInfo) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof linesInfo === "object" && linesInfo !== null) {
|
|
||||||
return linesInfo[type] || 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
function needsWhitespaceBefore(node, parent) {
|
|
||||||
return needsWhitespace(node, parent, "before");
|
|
||||||
}
|
|
||||||
|
|
||||||
function needsWhitespaceAfter(node, parent) {
|
|
||||||
return needsWhitespace(node, parent, "after");
|
|
||||||
}
|
|
||||||
|
|
||||||
function needsParens(node, parent, printStack) {
|
|
||||||
if (!parent) return false;
|
|
||||||
|
|
||||||
if (t().isNewExpression(parent) && parent.callee === node) {
|
|
||||||
if (isOrHasCallExpression(node)) return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return find(expandedParens, node, parent, printStack);
|
|
||||||
}
|
|
||||||
|
|
@ -1,253 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.NullableTypeAnnotation = NullableTypeAnnotation;
|
|
||||||
exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
|
|
||||||
exports.UpdateExpression = UpdateExpression;
|
|
||||||
exports.ObjectExpression = ObjectExpression;
|
|
||||||
exports.DoExpression = DoExpression;
|
|
||||||
exports.Binary = Binary;
|
|
||||||
exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation;
|
|
||||||
exports.TSAsExpression = TSAsExpression;
|
|
||||||
exports.TSTypeAssertion = TSTypeAssertion;
|
|
||||||
exports.TSIntersectionType = exports.TSUnionType = TSUnionType;
|
|
||||||
exports.BinaryExpression = BinaryExpression;
|
|
||||||
exports.SequenceExpression = SequenceExpression;
|
|
||||||
exports.AwaitExpression = exports.YieldExpression = YieldExpression;
|
|
||||||
exports.ClassExpression = ClassExpression;
|
|
||||||
exports.UnaryLike = UnaryLike;
|
|
||||||
exports.FunctionExpression = FunctionExpression;
|
|
||||||
exports.ArrowFunctionExpression = ArrowFunctionExpression;
|
|
||||||
exports.ConditionalExpression = ConditionalExpression;
|
|
||||||
exports.OptionalMemberExpression = OptionalMemberExpression;
|
|
||||||
exports.AssignmentExpression = AssignmentExpression;
|
|
||||||
exports.NewExpression = NewExpression;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
const PRECEDENCE = {
|
|
||||||
"||": 0,
|
|
||||||
"&&": 1,
|
|
||||||
"|": 2,
|
|
||||||
"^": 3,
|
|
||||||
"&": 4,
|
|
||||||
"==": 5,
|
|
||||||
"===": 5,
|
|
||||||
"!=": 5,
|
|
||||||
"!==": 5,
|
|
||||||
"<": 6,
|
|
||||||
">": 6,
|
|
||||||
"<=": 6,
|
|
||||||
">=": 6,
|
|
||||||
in: 6,
|
|
||||||
instanceof: 6,
|
|
||||||
">>": 7,
|
|
||||||
"<<": 7,
|
|
||||||
">>>": 7,
|
|
||||||
"+": 8,
|
|
||||||
"-": 8,
|
|
||||||
"*": 9,
|
|
||||||
"/": 9,
|
|
||||||
"%": 9,
|
|
||||||
"**": 10
|
|
||||||
};
|
|
||||||
|
|
||||||
const isClassExtendsClause = (node, parent) => (t().isClassDeclaration(parent) || t().isClassExpression(parent)) && parent.superClass === node;
|
|
||||||
|
|
||||||
function NullableTypeAnnotation(node, parent) {
|
|
||||||
return t().isArrayTypeAnnotation(parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FunctionTypeAnnotation(node, parent) {
|
|
||||||
return t().isUnionTypeAnnotation(parent) || t().isIntersectionTypeAnnotation(parent) || t().isArrayTypeAnnotation(parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function UpdateExpression(node, parent) {
|
|
||||||
return t().isMemberExpression(parent, {
|
|
||||||
object: node
|
|
||||||
}) || t().isCallExpression(parent, {
|
|
||||||
callee: node
|
|
||||||
}) || t().isNewExpression(parent, {
|
|
||||||
callee: node
|
|
||||||
}) || isClassExtendsClause(node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ObjectExpression(node, parent, printStack) {
|
|
||||||
return isFirstInStatement(printStack, {
|
|
||||||
considerArrow: true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function DoExpression(node, parent, printStack) {
|
|
||||||
return isFirstInStatement(printStack);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Binary(node, parent) {
|
|
||||||
if (node.operator === "**" && t().isBinaryExpression(parent, {
|
|
||||||
operator: "**"
|
|
||||||
})) {
|
|
||||||
return parent.left === node;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isClassExtendsClause(node, parent)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((t().isCallExpression(parent) || t().isNewExpression(parent)) && parent.callee === node || t().isUnaryLike(parent) || t().isMemberExpression(parent) && parent.object === node || t().isAwaitExpression(parent)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (t().isBinary(parent)) {
|
|
||||||
const parentOp = parent.operator;
|
|
||||||
const parentPos = PRECEDENCE[parentOp];
|
|
||||||
const nodeOp = node.operator;
|
|
||||||
const nodePos = PRECEDENCE[nodeOp];
|
|
||||||
|
|
||||||
if (parentPos === nodePos && parent.right === node && !t().isLogicalExpression(parent) || parentPos > nodePos) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function UnionTypeAnnotation(node, parent) {
|
|
||||||
return t().isArrayTypeAnnotation(parent) || t().isNullableTypeAnnotation(parent) || t().isIntersectionTypeAnnotation(parent) || t().isUnionTypeAnnotation(parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSAsExpression() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSTypeAssertion() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function TSUnionType(node, parent) {
|
|
||||||
return t().isTSArrayType(parent) || t().isTSOptionalType(parent) || t().isTSIntersectionType(parent) || t().isTSUnionType(parent) || t().isTSRestType(parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function BinaryExpression(node, parent) {
|
|
||||||
return node.operator === "in" && (t().isVariableDeclarator(parent) || t().isFor(parent));
|
|
||||||
}
|
|
||||||
|
|
||||||
function SequenceExpression(node, parent) {
|
|
||||||
if (t().isForStatement(parent) || t().isThrowStatement(parent) || t().isReturnStatement(parent) || t().isIfStatement(parent) && parent.test === node || t().isWhileStatement(parent) && parent.test === node || t().isForInStatement(parent) && parent.right === node || t().isSwitchStatement(parent) && parent.discriminant === node || t().isExpressionStatement(parent) && parent.expression === node) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function YieldExpression(node, parent) {
|
|
||||||
return t().isBinary(parent) || t().isUnaryLike(parent) || t().isCallExpression(parent) || t().isMemberExpression(parent) || t().isNewExpression(parent) || t().isAwaitExpression(parent) && t().isYieldExpression(node) || t().isConditionalExpression(parent) && node === parent.test || isClassExtendsClause(node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ClassExpression(node, parent, printStack) {
|
|
||||||
return isFirstInStatement(printStack, {
|
|
||||||
considerDefaultExports: true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function UnaryLike(node, parent) {
|
|
||||||
return t().isMemberExpression(parent, {
|
|
||||||
object: node
|
|
||||||
}) || t().isCallExpression(parent, {
|
|
||||||
callee: node
|
|
||||||
}) || t().isNewExpression(parent, {
|
|
||||||
callee: node
|
|
||||||
}) || t().isBinaryExpression(parent, {
|
|
||||||
operator: "**",
|
|
||||||
left: node
|
|
||||||
}) || isClassExtendsClause(node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FunctionExpression(node, parent, printStack) {
|
|
||||||
return isFirstInStatement(printStack, {
|
|
||||||
considerDefaultExports: true
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function ArrowFunctionExpression(node, parent) {
|
|
||||||
return t().isExportDeclaration(parent) || ConditionalExpression(node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConditionalExpression(node, parent) {
|
|
||||||
if (t().isUnaryLike(parent) || t().isBinary(parent) || t().isConditionalExpression(parent, {
|
|
||||||
test: node
|
|
||||||
}) || t().isAwaitExpression(parent) || t().isOptionalMemberExpression(parent) || t().isTaggedTemplateExpression(parent) || t().isTSTypeAssertion(parent) || t().isTSAsExpression(parent)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return UnaryLike(node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function OptionalMemberExpression(node, parent) {
|
|
||||||
return t().isCallExpression(parent) || t().isMemberExpression(parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AssignmentExpression(node) {
|
|
||||||
if (t().isObjectPattern(node.left)) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return ConditionalExpression(...arguments);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function NewExpression(node, parent) {
|
|
||||||
return isClassExtendsClause(node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isFirstInStatement(printStack, {
|
|
||||||
considerArrow = false,
|
|
||||||
considerDefaultExports = false
|
|
||||||
} = {}) {
|
|
||||||
let i = printStack.length - 1;
|
|
||||||
let node = printStack[i];
|
|
||||||
i--;
|
|
||||||
let parent = printStack[i];
|
|
||||||
|
|
||||||
while (i > 0) {
|
|
||||||
if (t().isExpressionStatement(parent, {
|
|
||||||
expression: node
|
|
||||||
}) || t().isTaggedTemplateExpression(parent) || considerDefaultExports && t().isExportDefaultDeclaration(parent, {
|
|
||||||
declaration: node
|
|
||||||
}) || considerArrow && t().isArrowFunctionExpression(parent, {
|
|
||||||
body: node
|
|
||||||
})) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (t().isCallExpression(parent, {
|
|
||||||
callee: node
|
|
||||||
}) || t().isSequenceExpression(parent) && parent.expressions[0] === node || t().isMemberExpression(parent, {
|
|
||||||
object: node
|
|
||||||
}) || t().isConditional(parent, {
|
|
||||||
test: node
|
|
||||||
}) || t().isBinary(parent, {
|
|
||||||
left: node
|
|
||||||
}) || t().isAssignmentExpression(parent, {
|
|
||||||
left: node
|
|
||||||
})) {
|
|
||||||
node = parent;
|
|
||||||
i--;
|
|
||||||
parent = printStack[i];
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
@ -1,192 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.list = exports.nodes = void 0;
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function crawl(node, state = {}) {
|
|
||||||
if (t().isMemberExpression(node)) {
|
|
||||||
crawl(node.object, state);
|
|
||||||
if (node.computed) crawl(node.property, state);
|
|
||||||
} else if (t().isBinary(node) || t().isAssignmentExpression(node)) {
|
|
||||||
crawl(node.left, state);
|
|
||||||
crawl(node.right, state);
|
|
||||||
} else if (t().isCallExpression(node)) {
|
|
||||||
state.hasCall = true;
|
|
||||||
crawl(node.callee, state);
|
|
||||||
} else if (t().isFunction(node)) {
|
|
||||||
state.hasFunction = true;
|
|
||||||
} else if (t().isIdentifier(node)) {
|
|
||||||
state.hasHelper = state.hasHelper || isHelper(node.callee);
|
|
||||||
}
|
|
||||||
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isHelper(node) {
|
|
||||||
if (t().isMemberExpression(node)) {
|
|
||||||
return isHelper(node.object) || isHelper(node.property);
|
|
||||||
} else if (t().isIdentifier(node)) {
|
|
||||||
return node.name === "require" || node.name[0] === "_";
|
|
||||||
} else if (t().isCallExpression(node)) {
|
|
||||||
return isHelper(node.callee);
|
|
||||||
} else if (t().isBinary(node) || t().isAssignmentExpression(node)) {
|
|
||||||
return t().isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right);
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isType(node) {
|
|
||||||
return t().isLiteral(node) || t().isObjectExpression(node) || t().isArrayExpression(node) || t().isIdentifier(node) || t().isMemberExpression(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
const nodes = {
|
|
||||||
AssignmentExpression(node) {
|
|
||||||
const state = crawl(node.right);
|
|
||||||
|
|
||||||
if (state.hasCall && state.hasHelper || state.hasFunction) {
|
|
||||||
return {
|
|
||||||
before: state.hasFunction,
|
|
||||||
after: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
SwitchCase(node, parent) {
|
|
||||||
return {
|
|
||||||
before: node.consequent.length || parent.cases[0] === node,
|
|
||||||
after: !node.consequent.length && parent.cases[parent.cases.length - 1] === node
|
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
LogicalExpression(node) {
|
|
||||||
if (t().isFunction(node.left) || t().isFunction(node.right)) {
|
|
||||||
return {
|
|
||||||
after: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
Literal(node) {
|
|
||||||
if (node.value === "use strict") {
|
|
||||||
return {
|
|
||||||
after: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
CallExpression(node) {
|
|
||||||
if (t().isFunction(node.callee) || isHelper(node)) {
|
|
||||||
return {
|
|
||||||
before: true,
|
|
||||||
after: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
VariableDeclaration(node) {
|
|
||||||
for (let i = 0; i < node.declarations.length; i++) {
|
|
||||||
const declar = node.declarations[i];
|
|
||||||
let enabled = isHelper(declar.id) && !isType(declar.init);
|
|
||||||
|
|
||||||
if (!enabled) {
|
|
||||||
const state = crawl(declar.init);
|
|
||||||
enabled = isHelper(declar.init) && state.hasCall || state.hasFunction;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (enabled) {
|
|
||||||
return {
|
|
||||||
before: true,
|
|
||||||
after: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
IfStatement(node) {
|
|
||||||
if (t().isBlockStatement(node.consequent)) {
|
|
||||||
return {
|
|
||||||
before: true,
|
|
||||||
after: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
exports.nodes = nodes;
|
|
||||||
|
|
||||||
nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) {
|
|
||||||
if (parent.properties[0] === node) {
|
|
||||||
return {
|
|
||||||
before: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
nodes.ObjectTypeCallProperty = function (node, parent) {
|
|
||||||
if (parent.callProperties[0] === node && (!parent.properties || !parent.properties.length)) {
|
|
||||||
return {
|
|
||||||
before: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
nodes.ObjectTypeIndexer = function (node, parent) {
|
|
||||||
if (parent.indexers[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length)) {
|
|
||||||
return {
|
|
||||||
before: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
nodes.ObjectTypeInternalSlot = function (node, parent) {
|
|
||||||
if (parent.internalSlots[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length) && (!parent.indexers || !parent.indexers.length)) {
|
|
||||||
return {
|
|
||||||
before: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const list = {
|
|
||||||
VariableDeclaration(node) {
|
|
||||||
return node.declarations.map(decl => decl.init);
|
|
||||||
},
|
|
||||||
|
|
||||||
ArrayExpression(node) {
|
|
||||||
return node.elements;
|
|
||||||
},
|
|
||||||
|
|
||||||
ObjectExpression(node) {
|
|
||||||
return node.properties;
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
exports.list = list;
|
|
||||||
[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function ([type, amounts]) {
|
|
||||||
if (typeof amounts === "boolean") {
|
|
||||||
amounts = {
|
|
||||||
after: amounts,
|
|
||||||
before: amounts
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
[type].concat(t().FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) {
|
|
||||||
nodes[type] = function () {
|
|
||||||
return amounts;
|
|
||||||
};
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,501 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = void 0;
|
|
||||||
|
|
||||||
function _isInteger() {
|
|
||||||
const data = _interopRequireDefault(require("lodash/isInteger"));
|
|
||||||
|
|
||||||
_isInteger = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _repeat() {
|
|
||||||
const data = _interopRequireDefault(require("lodash/repeat"));
|
|
||||||
|
|
||||||
_repeat = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var _buffer = _interopRequireDefault(require("./buffer"));
|
|
||||||
|
|
||||||
var n = _interopRequireWildcard(require("./node"));
|
|
||||||
|
|
||||||
function t() {
|
|
||||||
const data = _interopRequireWildcard(require("@babel/types"));
|
|
||||||
|
|
||||||
t = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
var generatorFunctions = _interopRequireWildcard(require("./generators"));
|
|
||||||
|
|
||||||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
const SCIENTIFIC_NOTATION = /e/i;
|
|
||||||
const ZERO_DECIMAL_INTEGER = /\.0+$/;
|
|
||||||
const NON_DECIMAL_LITERAL = /^0[box]/;
|
|
||||||
|
|
||||||
class Printer {
|
|
||||||
constructor(format, map) {
|
|
||||||
this.inForStatementInitCounter = 0;
|
|
||||||
this._printStack = [];
|
|
||||||
this._indent = 0;
|
|
||||||
this._insideAux = false;
|
|
||||||
this._printedCommentStarts = {};
|
|
||||||
this._parenPushNewlineState = null;
|
|
||||||
this._noLineTerminator = false;
|
|
||||||
this._printAuxAfterOnNextUserNode = false;
|
|
||||||
this._printedComments = new WeakSet();
|
|
||||||
this._endsWithInteger = false;
|
|
||||||
this._endsWithWord = false;
|
|
||||||
this.format = format || {};
|
|
||||||
this._buf = new _buffer.default(map);
|
|
||||||
}
|
|
||||||
|
|
||||||
generate(ast) {
|
|
||||||
this.print(ast);
|
|
||||||
|
|
||||||
this._maybeAddAuxComment();
|
|
||||||
|
|
||||||
return this._buf.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
indent() {
|
|
||||||
if (this.format.compact || this.format.concise) return;
|
|
||||||
this._indent++;
|
|
||||||
}
|
|
||||||
|
|
||||||
dedent() {
|
|
||||||
if (this.format.compact || this.format.concise) return;
|
|
||||||
this._indent--;
|
|
||||||
}
|
|
||||||
|
|
||||||
semicolon(force = false) {
|
|
||||||
this._maybeAddAuxComment();
|
|
||||||
|
|
||||||
this._append(";", !force);
|
|
||||||
}
|
|
||||||
|
|
||||||
rightBrace() {
|
|
||||||
if (this.format.minified) {
|
|
||||||
this._buf.removeLastSemicolon();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("}");
|
|
||||||
}
|
|
||||||
|
|
||||||
space(force = false) {
|
|
||||||
if (this.format.compact) return;
|
|
||||||
|
|
||||||
if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) {
|
|
||||||
this._space();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
word(str) {
|
|
||||||
if (this._endsWithWord || this.endsWith("/") && str.indexOf("/") === 0) {
|
|
||||||
this._space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._maybeAddAuxComment();
|
|
||||||
|
|
||||||
this._append(str);
|
|
||||||
|
|
||||||
this._endsWithWord = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
number(str) {
|
|
||||||
this.word(str);
|
|
||||||
this._endsWithInteger = (0, _isInteger().default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== ".";
|
|
||||||
}
|
|
||||||
|
|
||||||
token(str) {
|
|
||||||
if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) {
|
|
||||||
this._space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this._maybeAddAuxComment();
|
|
||||||
|
|
||||||
this._append(str);
|
|
||||||
}
|
|
||||||
|
|
||||||
newline(i) {
|
|
||||||
if (this.format.retainLines || this.format.compact) return;
|
|
||||||
|
|
||||||
if (this.format.concise) {
|
|
||||||
this.space();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.endsWith("\n\n")) return;
|
|
||||||
if (typeof i !== "number") i = 1;
|
|
||||||
i = Math.min(2, i);
|
|
||||||
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
|
|
||||||
if (i <= 0) return;
|
|
||||||
|
|
||||||
for (let j = 0; j < i; j++) {
|
|
||||||
this._newline();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
endsWith(str) {
|
|
||||||
return this._buf.endsWith(str);
|
|
||||||
}
|
|
||||||
|
|
||||||
removeTrailingNewline() {
|
|
||||||
this._buf.removeTrailingNewline();
|
|
||||||
}
|
|
||||||
|
|
||||||
exactSource(loc, cb) {
|
|
||||||
this._catchUp("start", loc);
|
|
||||||
|
|
||||||
this._buf.exactSource(loc, cb);
|
|
||||||
}
|
|
||||||
|
|
||||||
source(prop, loc) {
|
|
||||||
this._catchUp(prop, loc);
|
|
||||||
|
|
||||||
this._buf.source(prop, loc);
|
|
||||||
}
|
|
||||||
|
|
||||||
withSource(prop, loc, cb) {
|
|
||||||
this._catchUp(prop, loc);
|
|
||||||
|
|
||||||
this._buf.withSource(prop, loc, cb);
|
|
||||||
}
|
|
||||||
|
|
||||||
_space() {
|
|
||||||
this._append(" ", true);
|
|
||||||
}
|
|
||||||
|
|
||||||
_newline() {
|
|
||||||
this._append("\n", true);
|
|
||||||
}
|
|
||||||
|
|
||||||
_append(str, queue = false) {
|
|
||||||
this._maybeAddParen(str);
|
|
||||||
|
|
||||||
this._maybeIndent(str);
|
|
||||||
|
|
||||||
if (queue) this._buf.queue(str);else this._buf.append(str);
|
|
||||||
this._endsWithWord = false;
|
|
||||||
this._endsWithInteger = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
_maybeIndent(str) {
|
|
||||||
if (this._indent && this.endsWith("\n") && str[0] !== "\n") {
|
|
||||||
this._buf.queue(this._getIndent());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_maybeAddParen(str) {
|
|
||||||
const parenPushNewlineState = this._parenPushNewlineState;
|
|
||||||
if (!parenPushNewlineState) return;
|
|
||||||
this._parenPushNewlineState = null;
|
|
||||||
let i;
|
|
||||||
|
|
||||||
for (i = 0; i < str.length && str[i] === " "; i++) continue;
|
|
||||||
|
|
||||||
if (i === str.length) return;
|
|
||||||
const cha = str[i];
|
|
||||||
|
|
||||||
if (cha !== "\n") {
|
|
||||||
if (cha !== "/") return;
|
|
||||||
if (i + 1 === str.length) return;
|
|
||||||
const chaPost = str[i + 1];
|
|
||||||
if (chaPost !== "/" && chaPost !== "*") return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.token("(");
|
|
||||||
this.indent();
|
|
||||||
parenPushNewlineState.printed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
_catchUp(prop, loc) {
|
|
||||||
if (!this.format.retainLines) return;
|
|
||||||
const pos = loc ? loc[prop] : null;
|
|
||||||
|
|
||||||
if (pos && pos.line !== null) {
|
|
||||||
const count = pos.line - this._buf.getCurrentLine();
|
|
||||||
|
|
||||||
for (let i = 0; i < count; i++) {
|
|
||||||
this._newline();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_getIndent() {
|
|
||||||
return (0, _repeat().default)(this.format.indent.style, this._indent);
|
|
||||||
}
|
|
||||||
|
|
||||||
startTerminatorless(isLabel = false) {
|
|
||||||
if (isLabel) {
|
|
||||||
this._noLineTerminator = true;
|
|
||||||
return null;
|
|
||||||
} else {
|
|
||||||
return this._parenPushNewlineState = {
|
|
||||||
printed: false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
endTerminatorless(state) {
|
|
||||||
this._noLineTerminator = false;
|
|
||||||
|
|
||||||
if (state && state.printed) {
|
|
||||||
this.dedent();
|
|
||||||
this.newline();
|
|
||||||
this.token(")");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
print(node, parent) {
|
|
||||||
if (!node) return;
|
|
||||||
const oldConcise = this.format.concise;
|
|
||||||
|
|
||||||
if (node._compact) {
|
|
||||||
this.format.concise = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const printMethod = this[node.type];
|
|
||||||
|
|
||||||
if (!printMethod) {
|
|
||||||
throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
this._printStack.push(node);
|
|
||||||
|
|
||||||
const oldInAux = this._insideAux;
|
|
||||||
this._insideAux = !node.loc;
|
|
||||||
|
|
||||||
this._maybeAddAuxComment(this._insideAux && !oldInAux);
|
|
||||||
|
|
||||||
let needsParens = n.needsParens(node, parent, this._printStack);
|
|
||||||
|
|
||||||
if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) {
|
|
||||||
needsParens = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (needsParens) this.token("(");
|
|
||||||
|
|
||||||
this._printLeadingComments(node);
|
|
||||||
|
|
||||||
const loc = t().isProgram(node) || t().isFile(node) ? null : node.loc;
|
|
||||||
this.withSource("start", loc, () => {
|
|
||||||
printMethod.call(this, node, parent);
|
|
||||||
});
|
|
||||||
|
|
||||||
this._printTrailingComments(node);
|
|
||||||
|
|
||||||
if (needsParens) this.token(")");
|
|
||||||
|
|
||||||
this._printStack.pop();
|
|
||||||
|
|
||||||
this.format.concise = oldConcise;
|
|
||||||
this._insideAux = oldInAux;
|
|
||||||
}
|
|
||||||
|
|
||||||
_maybeAddAuxComment(enteredPositionlessNode) {
|
|
||||||
if (enteredPositionlessNode) this._printAuxBeforeComment();
|
|
||||||
if (!this._insideAux) this._printAuxAfterComment();
|
|
||||||
}
|
|
||||||
|
|
||||||
_printAuxBeforeComment() {
|
|
||||||
if (this._printAuxAfterOnNextUserNode) return;
|
|
||||||
this._printAuxAfterOnNextUserNode = true;
|
|
||||||
const comment = this.format.auxiliaryCommentBefore;
|
|
||||||
|
|
||||||
if (comment) {
|
|
||||||
this._printComment({
|
|
||||||
type: "CommentBlock",
|
|
||||||
value: comment
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_printAuxAfterComment() {
|
|
||||||
if (!this._printAuxAfterOnNextUserNode) return;
|
|
||||||
this._printAuxAfterOnNextUserNode = false;
|
|
||||||
const comment = this.format.auxiliaryCommentAfter;
|
|
||||||
|
|
||||||
if (comment) {
|
|
||||||
this._printComment({
|
|
||||||
type: "CommentBlock",
|
|
||||||
value: comment
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getPossibleRaw(node) {
|
|
||||||
const extra = node.extra;
|
|
||||||
|
|
||||||
if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
|
|
||||||
return extra.raw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
printJoin(nodes, parent, opts = {}) {
|
|
||||||
if (!nodes || !nodes.length) return;
|
|
||||||
if (opts.indent) this.indent();
|
|
||||||
const newlineOpts = {
|
|
||||||
addNewlines: opts.addNewlines
|
|
||||||
};
|
|
||||||
|
|
||||||
for (let i = 0; i < nodes.length; i++) {
|
|
||||||
const node = nodes[i];
|
|
||||||
if (!node) continue;
|
|
||||||
if (opts.statement) this._printNewline(true, node, parent, newlineOpts);
|
|
||||||
this.print(node, parent);
|
|
||||||
|
|
||||||
if (opts.iterator) {
|
|
||||||
opts.iterator(node, i);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts.separator && i < nodes.length - 1) {
|
|
||||||
opts.separator.call(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts.statement) this._printNewline(false, node, parent, newlineOpts);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts.indent) this.dedent();
|
|
||||||
}
|
|
||||||
|
|
||||||
printAndIndentOnComments(node, parent) {
|
|
||||||
const indent = node.leadingComments && node.leadingComments.length > 0;
|
|
||||||
if (indent) this.indent();
|
|
||||||
this.print(node, parent);
|
|
||||||
if (indent) this.dedent();
|
|
||||||
}
|
|
||||||
|
|
||||||
printBlock(parent) {
|
|
||||||
const node = parent.body;
|
|
||||||
|
|
||||||
if (!t().isEmptyStatement(node)) {
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.print(node, parent);
|
|
||||||
}
|
|
||||||
|
|
||||||
_printTrailingComments(node) {
|
|
||||||
this._printComments(this._getComments(false, node));
|
|
||||||
}
|
|
||||||
|
|
||||||
_printLeadingComments(node) {
|
|
||||||
this._printComments(this._getComments(true, node));
|
|
||||||
}
|
|
||||||
|
|
||||||
printInnerComments(node, indent = true) {
|
|
||||||
if (!node.innerComments || !node.innerComments.length) return;
|
|
||||||
if (indent) this.indent();
|
|
||||||
|
|
||||||
this._printComments(node.innerComments);
|
|
||||||
|
|
||||||
if (indent) this.dedent();
|
|
||||||
}
|
|
||||||
|
|
||||||
printSequence(nodes, parent, opts = {}) {
|
|
||||||
opts.statement = true;
|
|
||||||
return this.printJoin(nodes, parent, opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
printList(items, parent, opts = {}) {
|
|
||||||
if (opts.separator == null) {
|
|
||||||
opts.separator = commaSeparator;
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.printJoin(items, parent, opts);
|
|
||||||
}
|
|
||||||
|
|
||||||
_printNewline(leading, node, parent, opts) {
|
|
||||||
if (this.format.retainLines || this.format.compact) return;
|
|
||||||
|
|
||||||
if (this.format.concise) {
|
|
||||||
this.space();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let lines = 0;
|
|
||||||
|
|
||||||
if (this._buf.hasContent()) {
|
|
||||||
if (!leading) lines++;
|
|
||||||
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
|
|
||||||
const needs = leading ? n.needsWhitespaceBefore : n.needsWhitespaceAfter;
|
|
||||||
if (needs(node, parent)) lines++;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.newline(lines);
|
|
||||||
}
|
|
||||||
|
|
||||||
_getComments(leading, node) {
|
|
||||||
return node && (leading ? node.leadingComments : node.trailingComments) || [];
|
|
||||||
}
|
|
||||||
|
|
||||||
_printComment(comment) {
|
|
||||||
if (!this.format.shouldPrintComment(comment.value)) return;
|
|
||||||
if (comment.ignore) return;
|
|
||||||
if (this._printedComments.has(comment)) return;
|
|
||||||
|
|
||||||
this._printedComments.add(comment);
|
|
||||||
|
|
||||||
if (comment.start != null) {
|
|
||||||
if (this._printedCommentStarts[comment.start]) return;
|
|
||||||
this._printedCommentStarts[comment.start] = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isBlockComment = comment.type === "CommentBlock";
|
|
||||||
this.newline(this._buf.hasContent() && !this._noLineTerminator && isBlockComment ? 1 : 0);
|
|
||||||
if (!this.endsWith("[") && !this.endsWith("{")) this.space();
|
|
||||||
let val = !isBlockComment && !this._noLineTerminator ? `//${comment.value}\n` : `/*${comment.value}*/`;
|
|
||||||
|
|
||||||
if (isBlockComment && this.format.indent.adjustMultilineComment) {
|
|
||||||
const offset = comment.loc && comment.loc.start.column;
|
|
||||||
|
|
||||||
if (offset) {
|
|
||||||
const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
|
|
||||||
val = val.replace(newlineRegex, "\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
const indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn());
|
|
||||||
val = val.replace(/\n(?!$)/g, `\n${(0, _repeat().default)(" ", indentSize)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.endsWith("/")) this._space();
|
|
||||||
this.withSource("start", comment.loc, () => {
|
|
||||||
this._append(val);
|
|
||||||
});
|
|
||||||
this.newline(isBlockComment && !this._noLineTerminator ? 1 : 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
_printComments(comments) {
|
|
||||||
if (!comments || !comments.length) return;
|
|
||||||
|
|
||||||
for (const comment of comments) {
|
|
||||||
this._printComment(comment);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.default = Printer;
|
|
||||||
Object.assign(Printer.prototype, generatorFunctions);
|
|
||||||
|
|
||||||
function commaSeparator() {
|
|
||||||
this.token(",");
|
|
||||||
this.space();
|
|
||||||
}
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
"use strict";
|
|
||||||
|
|
||||||
Object.defineProperty(exports, "__esModule", {
|
|
||||||
value: true
|
|
||||||
});
|
|
||||||
exports.default = void 0;
|
|
||||||
|
|
||||||
function _sourceMap() {
|
|
||||||
const data = _interopRequireDefault(require("source-map"));
|
|
||||||
|
|
||||||
_sourceMap = function () {
|
|
||||||
return data;
|
|
||||||
};
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
||||||
|
|
||||||
class SourceMap {
|
|
||||||
constructor(opts, code) {
|
|
||||||
this._cachedMap = null;
|
|
||||||
this._code = code;
|
|
||||||
this._opts = opts;
|
|
||||||
this._rawMappings = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
get() {
|
|
||||||
if (!this._cachedMap) {
|
|
||||||
const map = this._cachedMap = new (_sourceMap().default.SourceMapGenerator)({
|
|
||||||
sourceRoot: this._opts.sourceRoot
|
|
||||||
});
|
|
||||||
const code = this._code;
|
|
||||||
|
|
||||||
if (typeof code === "string") {
|
|
||||||
map.setSourceContent(this._opts.sourceFileName, code);
|
|
||||||
} else if (typeof code === "object") {
|
|
||||||
Object.keys(code).forEach(sourceFileName => {
|
|
||||||
map.setSourceContent(sourceFileName, code[sourceFileName]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
this._rawMappings.forEach(map.addMapping, map);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this._cachedMap.toJSON();
|
|
||||||
}
|
|
||||||
|
|
||||||
getRawMappings() {
|
|
||||||
return this._rawMappings.slice();
|
|
||||||
}
|
|
||||||
|
|
||||||
mark(generatedLine, generatedColumn, line, column, identifierName, filename, force) {
|
|
||||||
if (this._lastGenLine !== generatedLine && line === null) return;
|
|
||||||
|
|
||||||
if (!force && this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._cachedMap = null;
|
|
||||||
this._lastGenLine = generatedLine;
|
|
||||||
this._lastSourceLine = line;
|
|
||||||
this._lastSourceColumn = column;
|
|
||||||
|
|
||||||
this._rawMappings.push({
|
|
||||||
name: identifierName || undefined,
|
|
||||||
generated: {
|
|
||||||
line: generatedLine,
|
|
||||||
column: generatedColumn
|
|
||||||
},
|
|
||||||
source: line == null ? undefined : filename || this._opts.sourceFileName,
|
|
||||||
original: line == null ? undefined : {
|
|
||||||
line: line,
|
|
||||||
column: column
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.default = SourceMap;
|
|
||||||
|
|
@ -1,301 +0,0 @@
|
||||||
# Change Log
|
|
||||||
|
|
||||||
## 0.5.6
|
|
||||||
|
|
||||||
* Fix for regression when people were using numbers as names in source maps. See
|
|
||||||
#236.
|
|
||||||
|
|
||||||
## 0.5.5
|
|
||||||
|
|
||||||
* Fix "regression" of unsupported, implementation behavior that half the world
|
|
||||||
happens to have come to depend on. See #235.
|
|
||||||
|
|
||||||
* Fix regression involving function hoisting in SpiderMonkey. See #233.
|
|
||||||
|
|
||||||
## 0.5.4
|
|
||||||
|
|
||||||
* Large performance improvements to source-map serialization. See #228 and #229.
|
|
||||||
|
|
||||||
## 0.5.3
|
|
||||||
|
|
||||||
* Do not include unnecessary distribution files. See
|
|
||||||
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
|
|
||||||
|
|
||||||
## 0.5.2
|
|
||||||
|
|
||||||
* Include browser distributions of the library in package.json's `files`. See
|
|
||||||
issue #212.
|
|
||||||
|
|
||||||
## 0.5.1
|
|
||||||
|
|
||||||
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
|
|
||||||
ff05274becc9e6e1295ed60f3ea090d31d843379.
|
|
||||||
|
|
||||||
## 0.5.0
|
|
||||||
|
|
||||||
* Node 0.8 is no longer supported.
|
|
||||||
|
|
||||||
* Use webpack instead of dryice for bundling.
|
|
||||||
|
|
||||||
* Big speedups serializing source maps. See pull request #203.
|
|
||||||
|
|
||||||
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
|
|
||||||
explicitly start with the source root. See issue #199.
|
|
||||||
|
|
||||||
## 0.4.4
|
|
||||||
|
|
||||||
* Fix an issue where using a `SourceMapGenerator` after having created a
|
|
||||||
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
|
|
||||||
issue #191.
|
|
||||||
|
|
||||||
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
|
|
||||||
different mappings as duplicates of each other and avoid generating them. See
|
|
||||||
issue #192.
|
|
||||||
|
|
||||||
## 0.4.3
|
|
||||||
|
|
||||||
* A very large number of performance improvements, particularly when parsing
|
|
||||||
source maps. Collectively about 75% of time shaved off of the source map
|
|
||||||
parsing benchmark!
|
|
||||||
|
|
||||||
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
|
|
||||||
searching in the presence of a column option. See issue #177.
|
|
||||||
|
|
||||||
* Fix a bug with joining a source and its source root when the source is above
|
|
||||||
the root. See issue #182.
|
|
||||||
|
|
||||||
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
|
|
||||||
determine when all sources' contents are inlined into the source map. See
|
|
||||||
issue #190.
|
|
||||||
|
|
||||||
## 0.4.2
|
|
||||||
|
|
||||||
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
|
|
||||||
dependent projects. Issue #169.
|
|
||||||
|
|
||||||
* Add an optional `column` argument to
|
|
||||||
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
|
|
||||||
with no mappings. Issues #172 and #173.
|
|
||||||
|
|
||||||
## 0.4.1
|
|
||||||
|
|
||||||
* Fix accidentally defining a global variable. #170.
|
|
||||||
|
|
||||||
## 0.4.0
|
|
||||||
|
|
||||||
* The default direction for fuzzy searching was changed back to its original
|
|
||||||
direction. See #164.
|
|
||||||
|
|
||||||
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
|
|
||||||
the fuzzy searching direction. See #167.
|
|
||||||
|
|
||||||
* About an 8% speed up in parsing source maps. See #159.
|
|
||||||
|
|
||||||
* Added a benchmark for parsing and generating source maps.
|
|
||||||
|
|
||||||
## 0.3.0
|
|
||||||
|
|
||||||
* Change the default direction that searching for positions fuzzes when there is
|
|
||||||
not an exact match. See #154.
|
|
||||||
|
|
||||||
* Support for environments using json2.js for JSON serialization. See #156.
|
|
||||||
|
|
||||||
## 0.2.0
|
|
||||||
|
|
||||||
* Support for consuming "indexed" source maps which do not have any remote
|
|
||||||
sections. See pull request #127. This introduces a minor backwards
|
|
||||||
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
|
|
||||||
methods.
|
|
||||||
|
|
||||||
## 0.1.43
|
|
||||||
|
|
||||||
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
|
|
||||||
#148 for some discussion and issues #150, #151, and #152 for implementations.
|
|
||||||
|
|
||||||
## 0.1.42
|
|
||||||
|
|
||||||
* Fix an issue where `SourceNode`s from different versions of the source-map
|
|
||||||
library couldn't be used in conjunction with each other. See issue #142.
|
|
||||||
|
|
||||||
## 0.1.41
|
|
||||||
|
|
||||||
* Fix a bug with getting the source content of relative sources with a "./"
|
|
||||||
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
|
|
||||||
|
|
||||||
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
|
|
||||||
column span of each mapping.
|
|
||||||
|
|
||||||
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
|
|
||||||
all generated positions associated with a given original source and line.
|
|
||||||
|
|
||||||
## 0.1.40
|
|
||||||
|
|
||||||
* Performance improvements for parsing source maps in SourceMapConsumer.
|
|
||||||
|
|
||||||
## 0.1.39
|
|
||||||
|
|
||||||
* Fix a bug where setting a source's contents to null before any source content
|
|
||||||
had been set before threw a TypeError. See issue #131.
|
|
||||||
|
|
||||||
## 0.1.38
|
|
||||||
|
|
||||||
* Fix a bug where finding relative paths from an empty path were creating
|
|
||||||
absolute paths. See issue #129.
|
|
||||||
|
|
||||||
## 0.1.37
|
|
||||||
|
|
||||||
* Fix a bug where if the source root was an empty string, relative source paths
|
|
||||||
would turn into absolute source paths. Issue #124.
|
|
||||||
|
|
||||||
## 0.1.36
|
|
||||||
|
|
||||||
* Allow the `names` mapping property to be an empty string. Issue #121.
|
|
||||||
|
|
||||||
## 0.1.35
|
|
||||||
|
|
||||||
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
|
|
||||||
to specify a path that relative sources in the second parameter should be
|
|
||||||
relative to. Issue #105.
|
|
||||||
|
|
||||||
* If no file property is given to a `SourceMapGenerator`, then the resulting
|
|
||||||
source map will no longer have a `null` file property. The property will
|
|
||||||
simply not exist. Issue #104.
|
|
||||||
|
|
||||||
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
|
|
||||||
Issue #116.
|
|
||||||
|
|
||||||
## 0.1.34
|
|
||||||
|
|
||||||
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
|
|
||||||
|
|
||||||
* Fix bug involving source contents and the
|
|
||||||
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
|
|
||||||
|
|
||||||
## 0.1.33
|
|
||||||
|
|
||||||
* Fix some edge cases surrounding path joining and URL resolution.
|
|
||||||
|
|
||||||
* Add a third parameter for relative path to
|
|
||||||
`SourceMapGenerator.prototype.applySourceMap`.
|
|
||||||
|
|
||||||
* Fix issues with mappings and EOLs.
|
|
||||||
|
|
||||||
## 0.1.32
|
|
||||||
|
|
||||||
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
|
|
||||||
(issue 92).
|
|
||||||
|
|
||||||
* Fixed test runner to actually report number of failed tests as its process
|
|
||||||
exit code.
|
|
||||||
|
|
||||||
* Fixed a typo when reporting bad mappings (issue 87).
|
|
||||||
|
|
||||||
## 0.1.31
|
|
||||||
|
|
||||||
* Delay parsing the mappings in SourceMapConsumer until queried for a source
|
|
||||||
location.
|
|
||||||
|
|
||||||
* Support Sass source maps (which at the time of writing deviate from the spec
|
|
||||||
in small ways) in SourceMapConsumer.
|
|
||||||
|
|
||||||
## 0.1.30
|
|
||||||
|
|
||||||
* Do not join source root with a source, when the source is a data URI.
|
|
||||||
|
|
||||||
* Extend the test runner to allow running single specific test files at a time.
|
|
||||||
|
|
||||||
* Performance improvements in `SourceNode.prototype.walk` and
|
|
||||||
`SourceMapConsumer.prototype.eachMapping`.
|
|
||||||
|
|
||||||
* Source map browser builds will now work inside Workers.
|
|
||||||
|
|
||||||
* Better error messages when attempting to add an invalid mapping to a
|
|
||||||
`SourceMapGenerator`.
|
|
||||||
|
|
||||||
## 0.1.29
|
|
||||||
|
|
||||||
* Allow duplicate entries in the `names` and `sources` arrays of source maps
|
|
||||||
(usually from TypeScript) we are parsing. Fixes github issue 72.
|
|
||||||
|
|
||||||
## 0.1.28
|
|
||||||
|
|
||||||
* Skip duplicate mappings when creating source maps from SourceNode; github
|
|
||||||
issue 75.
|
|
||||||
|
|
||||||
## 0.1.27
|
|
||||||
|
|
||||||
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
|
|
||||||
we don't use it anyway.
|
|
||||||
|
|
||||||
## 0.1.26
|
|
||||||
|
|
||||||
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
|
|
||||||
|
|
||||||
## 0.1.25
|
|
||||||
|
|
||||||
* Make compatible with browserify
|
|
||||||
|
|
||||||
## 0.1.24
|
|
||||||
|
|
||||||
* Fix issue with absolute paths and `file://` URIs. See
|
|
||||||
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
|
|
||||||
|
|
||||||
## 0.1.23
|
|
||||||
|
|
||||||
* Fix issue with absolute paths and sourcesContent, github issue 64.
|
|
||||||
|
|
||||||
## 0.1.22
|
|
||||||
|
|
||||||
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
|
|
||||||
|
|
||||||
## 0.1.21
|
|
||||||
|
|
||||||
* Fixed handling of sources that start with a slash so that they are relative to
|
|
||||||
the source root's host.
|
|
||||||
|
|
||||||
## 0.1.20
|
|
||||||
|
|
||||||
* Fixed github issue #43: absolute URLs aren't joined with the source root
|
|
||||||
anymore.
|
|
||||||
|
|
||||||
## 0.1.19
|
|
||||||
|
|
||||||
* Using Travis CI to run tests.
|
|
||||||
|
|
||||||
## 0.1.18
|
|
||||||
|
|
||||||
* Fixed a bug in the handling of sourceRoot.
|
|
||||||
|
|
||||||
## 0.1.17
|
|
||||||
|
|
||||||
* Added SourceNode.fromStringWithSourceMap.
|
|
||||||
|
|
||||||
## 0.1.16
|
|
||||||
|
|
||||||
* Added missing documentation.
|
|
||||||
|
|
||||||
* Fixed the generating of empty mappings in SourceNode.
|
|
||||||
|
|
||||||
## 0.1.15
|
|
||||||
|
|
||||||
* Added SourceMapGenerator.applySourceMap.
|
|
||||||
|
|
||||||
## 0.1.14
|
|
||||||
|
|
||||||
* The sourceRoot is now handled consistently.
|
|
||||||
|
|
||||||
## 0.1.13
|
|
||||||
|
|
||||||
* Added SourceMapGenerator.fromSourceMap.
|
|
||||||
|
|
||||||
## 0.1.12
|
|
||||||
|
|
||||||
* SourceNode now generates empty mappings too.
|
|
||||||
|
|
||||||
## 0.1.11
|
|
||||||
|
|
||||||
* Added name support to SourceNode.
|
|
||||||
|
|
||||||
## 0.1.10
|
|
||||||
|
|
||||||
* Added sourcesContent support to the customer and generator.
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
|
|
||||||
Copyright (c) 2009-2011, Mozilla Foundation and contributors
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
* Redistributions of source code must retain the above copyright notice, this
|
|
||||||
list of conditions and the following disclaimer.
|
|
||||||
|
|
||||||
* Redistributions in binary form must reproduce the above copyright notice,
|
|
||||||
this list of conditions and the following disclaimer in the documentation
|
|
||||||
and/or other materials provided with the distribution.
|
|
||||||
|
|
||||||
* Neither the names of the Mozilla Foundation nor the names of project
|
|
||||||
contributors may be used to endorse or promote products derived from this
|
|
||||||
software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
|
||||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
||||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
||||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
||||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
||||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
||||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
||||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
||||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
@ -1,729 +0,0 @@
|
||||||
# Source Map
|
|
||||||
|
|
||||||
[](https://travis-ci.org/mozilla/source-map)
|
|
||||||
|
|
||||||
[](https://www.npmjs.com/package/source-map)
|
|
||||||
|
|
||||||
This is a library to generate and consume the source map format
|
|
||||||
[described here][format].
|
|
||||||
|
|
||||||
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
|
|
||||||
|
|
||||||
## Use with Node
|
|
||||||
|
|
||||||
$ npm install source-map
|
|
||||||
|
|
||||||
## Use on the Web
|
|
||||||
|
|
||||||
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
<!-- `npm run toc` to regenerate the Table of Contents -->
|
|
||||||
|
|
||||||
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
|
|
||||||
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
|
|
||||||
## Table of Contents
|
|
||||||
|
|
||||||
- [Examples](#examples)
|
|
||||||
- [Consuming a source map](#consuming-a-source-map)
|
|
||||||
- [Generating a source map](#generating-a-source-map)
|
|
||||||
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
|
|
||||||
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
|
|
||||||
- [API](#api)
|
|
||||||
- [SourceMapConsumer](#sourcemapconsumer)
|
|
||||||
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
|
|
||||||
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
|
|
||||||
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
|
|
||||||
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
|
|
||||||
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
|
|
||||||
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
|
|
||||||
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
|
|
||||||
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
|
|
||||||
- [SourceMapGenerator](#sourcemapgenerator)
|
|
||||||
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
|
|
||||||
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
|
|
||||||
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
|
|
||||||
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
|
|
||||||
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
|
|
||||||
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
|
|
||||||
- [SourceNode](#sourcenode)
|
|
||||||
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
|
|
||||||
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
|
|
||||||
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
|
|
||||||
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
|
|
||||||
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
|
|
||||||
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
|
|
||||||
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
|
|
||||||
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
|
|
||||||
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
|
|
||||||
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
|
|
||||||
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
|
|
||||||
|
|
||||||
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
### Consuming a source map
|
|
||||||
|
|
||||||
```js
|
|
||||||
var rawSourceMap = {
|
|
||||||
version: 3,
|
|
||||||
file: 'min.js',
|
|
||||||
names: ['bar', 'baz', 'n'],
|
|
||||||
sources: ['one.js', 'two.js'],
|
|
||||||
sourceRoot: 'http://example.com/www/js/',
|
|
||||||
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
|
|
||||||
};
|
|
||||||
|
|
||||||
var smc = new SourceMapConsumer(rawSourceMap);
|
|
||||||
|
|
||||||
console.log(smc.sources);
|
|
||||||
// [ 'http://example.com/www/js/one.js',
|
|
||||||
// 'http://example.com/www/js/two.js' ]
|
|
||||||
|
|
||||||
console.log(smc.originalPositionFor({
|
|
||||||
line: 2,
|
|
||||||
column: 28
|
|
||||||
}));
|
|
||||||
// { source: 'http://example.com/www/js/two.js',
|
|
||||||
// line: 2,
|
|
||||||
// column: 10,
|
|
||||||
// name: 'n' }
|
|
||||||
|
|
||||||
console.log(smc.generatedPositionFor({
|
|
||||||
source: 'http://example.com/www/js/two.js',
|
|
||||||
line: 2,
|
|
||||||
column: 10
|
|
||||||
}));
|
|
||||||
// { line: 2, column: 28 }
|
|
||||||
|
|
||||||
smc.eachMapping(function (m) {
|
|
||||||
// ...
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Generating a source map
|
|
||||||
|
|
||||||
In depth guide:
|
|
||||||
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
|
|
||||||
|
|
||||||
#### With SourceNode (high level API)
|
|
||||||
|
|
||||||
```js
|
|
||||||
function compile(ast) {
|
|
||||||
switch (ast.type) {
|
|
||||||
case 'BinaryExpression':
|
|
||||||
return new SourceNode(
|
|
||||||
ast.location.line,
|
|
||||||
ast.location.column,
|
|
||||||
ast.location.source,
|
|
||||||
[compile(ast.left), " + ", compile(ast.right)]
|
|
||||||
);
|
|
||||||
case 'Literal':
|
|
||||||
return new SourceNode(
|
|
||||||
ast.location.line,
|
|
||||||
ast.location.column,
|
|
||||||
ast.location.source,
|
|
||||||
String(ast.value)
|
|
||||||
);
|
|
||||||
// ...
|
|
||||||
default:
|
|
||||||
throw new Error("Bad AST");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var ast = parse("40 + 2", "add.js");
|
|
||||||
console.log(compile(ast).toStringWithSourceMap({
|
|
||||||
file: 'add.js'
|
|
||||||
}));
|
|
||||||
// { code: '40 + 2',
|
|
||||||
// map: [object SourceMapGenerator] }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### With SourceMapGenerator (low level API)
|
|
||||||
|
|
||||||
```js
|
|
||||||
var map = new SourceMapGenerator({
|
|
||||||
file: "source-mapped.js"
|
|
||||||
});
|
|
||||||
|
|
||||||
map.addMapping({
|
|
||||||
generated: {
|
|
||||||
line: 10,
|
|
||||||
column: 35
|
|
||||||
},
|
|
||||||
source: "foo.js",
|
|
||||||
original: {
|
|
||||||
line: 33,
|
|
||||||
column: 2
|
|
||||||
},
|
|
||||||
name: "christopher"
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(map.toString());
|
|
||||||
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
|
|
||||||
```
|
|
||||||
|
|
||||||
## API
|
|
||||||
|
|
||||||
Get a reference to the module:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// Node.js
|
|
||||||
var sourceMap = require('source-map');
|
|
||||||
|
|
||||||
// Browser builds
|
|
||||||
var sourceMap = window.sourceMap;
|
|
||||||
|
|
||||||
// Inside Firefox
|
|
||||||
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
|
|
||||||
```
|
|
||||||
|
|
||||||
### SourceMapConsumer
|
|
||||||
|
|
||||||
A SourceMapConsumer instance represents a parsed source map which we can query
|
|
||||||
for information about the original file positions by giving it a file position
|
|
||||||
in the generated source.
|
|
||||||
|
|
||||||
#### new SourceMapConsumer(rawSourceMap)
|
|
||||||
|
|
||||||
The only parameter is the raw source map (either as a string which can be
|
|
||||||
`JSON.parse`'d, or an object). According to the spec, source maps have the
|
|
||||||
following attributes:
|
|
||||||
|
|
||||||
* `version`: Which version of the source map spec this map is following.
|
|
||||||
|
|
||||||
* `sources`: An array of URLs to the original source files.
|
|
||||||
|
|
||||||
* `names`: An array of identifiers which can be referenced by individual
|
|
||||||
mappings.
|
|
||||||
|
|
||||||
* `sourceRoot`: Optional. The URL root from which all sources are relative.
|
|
||||||
|
|
||||||
* `sourcesContent`: Optional. An array of contents of the original source files.
|
|
||||||
|
|
||||||
* `mappings`: A string of base64 VLQs which contain the actual mappings.
|
|
||||||
|
|
||||||
* `file`: Optional. The generated filename this source map is associated with.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.computeColumnSpans()
|
|
||||||
|
|
||||||
Compute the last column for each generated mapping. The last column is
|
|
||||||
inclusive.
|
|
||||||
|
|
||||||
```js
|
|
||||||
// Before:
|
|
||||||
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
|
|
||||||
// [ { line: 2,
|
|
||||||
// column: 1 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 10 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 20 } ]
|
|
||||||
|
|
||||||
consumer.computeColumnSpans();
|
|
||||||
|
|
||||||
// After:
|
|
||||||
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
|
|
||||||
// [ { line: 2,
|
|
||||||
// column: 1,
|
|
||||||
// lastColumn: 9 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 10,
|
|
||||||
// lastColumn: 19 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 20,
|
|
||||||
// lastColumn: Infinity } ]
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
|
|
||||||
|
|
||||||
Returns the original source, line, and column information for the generated
|
|
||||||
source's line and column positions provided. The only argument is an object with
|
|
||||||
the following properties:
|
|
||||||
|
|
||||||
* `line`: The line number in the generated source.
|
|
||||||
|
|
||||||
* `column`: The column number in the generated source.
|
|
||||||
|
|
||||||
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
|
|
||||||
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
|
|
||||||
element that is smaller than or greater than the one we are searching for,
|
|
||||||
respectively, if the exact element cannot be found. Defaults to
|
|
||||||
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
|
|
||||||
|
|
||||||
and an object is returned with the following properties:
|
|
||||||
|
|
||||||
* `source`: The original source file, or null if this information is not
|
|
||||||
available.
|
|
||||||
|
|
||||||
* `line`: The line number in the original source, or null if this information is
|
|
||||||
not available.
|
|
||||||
|
|
||||||
* `column`: The column number in the original source, or null if this
|
|
||||||
information is not available.
|
|
||||||
|
|
||||||
* `name`: The original identifier, or null if this information is not available.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.originalPositionFor({ line: 2, column: 10 })
|
|
||||||
// { source: 'foo.coffee',
|
|
||||||
// line: 2,
|
|
||||||
// column: 2,
|
|
||||||
// name: null }
|
|
||||||
|
|
||||||
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
|
|
||||||
// { source: null,
|
|
||||||
// line: null,
|
|
||||||
// column: null,
|
|
||||||
// name: null }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
|
|
||||||
|
|
||||||
Returns the generated line and column information for the original source,
|
|
||||||
line, and column positions provided. The only argument is an object with
|
|
||||||
the following properties:
|
|
||||||
|
|
||||||
* `source`: The filename of the original source.
|
|
||||||
|
|
||||||
* `line`: The line number in the original source.
|
|
||||||
|
|
||||||
* `column`: The column number in the original source.
|
|
||||||
|
|
||||||
and an object is returned with the following properties:
|
|
||||||
|
|
||||||
* `line`: The line number in the generated source, or null.
|
|
||||||
|
|
||||||
* `column`: The column number in the generated source, or null.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
|
|
||||||
// { line: 1,
|
|
||||||
// column: 56 }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
|
|
||||||
|
|
||||||
Returns all generated line and column information for the original source, line,
|
|
||||||
and column provided. If no column is provided, returns all mappings
|
|
||||||
corresponding to a either the line we are searching for or the next closest line
|
|
||||||
that has any mappings. Otherwise, returns all mappings corresponding to the
|
|
||||||
given line and either the column we are searching for or the next closest column
|
|
||||||
that has any offsets.
|
|
||||||
|
|
||||||
The only argument is an object with the following properties:
|
|
||||||
|
|
||||||
* `source`: The filename of the original source.
|
|
||||||
|
|
||||||
* `line`: The line number in the original source.
|
|
||||||
|
|
||||||
* `column`: Optional. The column number in the original source.
|
|
||||||
|
|
||||||
and an array of objects is returned, each with the following properties:
|
|
||||||
|
|
||||||
* `line`: The line number in the generated source, or null.
|
|
||||||
|
|
||||||
* `column`: The column number in the generated source, or null.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
|
|
||||||
// [ { line: 2,
|
|
||||||
// column: 1 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 10 },
|
|
||||||
// { line: 2,
|
|
||||||
// column: 20 } ]
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
|
|
||||||
|
|
||||||
Return true if we have the embedded source content for every source listed in
|
|
||||||
the source map, false otherwise.
|
|
||||||
|
|
||||||
In other words, if this method returns `true`, then
|
|
||||||
`consumer.sourceContentFor(s)` will succeed for every source `s` in
|
|
||||||
`consumer.sources`.
|
|
||||||
|
|
||||||
```js
|
|
||||||
// ...
|
|
||||||
if (consumer.hasContentsOfAllSources()) {
|
|
||||||
consumerReadyCallback(consumer);
|
|
||||||
} else {
|
|
||||||
fetchSources(consumer, consumerReadyCallback);
|
|
||||||
}
|
|
||||||
// ...
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
|
|
||||||
|
|
||||||
Returns the original source content for the source provided. The only
|
|
||||||
argument is the URL of the original source file.
|
|
||||||
|
|
||||||
If the source content for the given source is not found, then an error is
|
|
||||||
thrown. Optionally, pass `true` as the second param to have `null` returned
|
|
||||||
instead.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.sources
|
|
||||||
// [ "my-cool-lib.clj" ]
|
|
||||||
|
|
||||||
consumer.sourceContentFor("my-cool-lib.clj")
|
|
||||||
// "..."
|
|
||||||
|
|
||||||
consumer.sourceContentFor("this is not in the source map");
|
|
||||||
// Error: "this is not in the source map" is not in the source map
|
|
||||||
|
|
||||||
consumer.sourceContentFor("this is not in the source map", true);
|
|
||||||
// null
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
|
|
||||||
|
|
||||||
Iterate over each mapping between an original source/line/column and a
|
|
||||||
generated line/column in this source map.
|
|
||||||
|
|
||||||
* `callback`: The function that is called with each mapping. Mappings have the
|
|
||||||
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
|
|
||||||
name }`
|
|
||||||
|
|
||||||
* `context`: Optional. If specified, this object will be the value of `this`
|
|
||||||
every time that `callback` is called.
|
|
||||||
|
|
||||||
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
|
|
||||||
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
|
|
||||||
the mappings sorted by the generated file's line/column order or the
|
|
||||||
original's source/line/column order, respectively. Defaults to
|
|
||||||
`SourceMapConsumer.GENERATED_ORDER`.
|
|
||||||
|
|
||||||
```js
|
|
||||||
consumer.eachMapping(function (m) { console.log(m); })
|
|
||||||
// ...
|
|
||||||
// { source: 'illmatic.js',
|
|
||||||
// generatedLine: 1,
|
|
||||||
// generatedColumn: 0,
|
|
||||||
// originalLine: 1,
|
|
||||||
// originalColumn: 0,
|
|
||||||
// name: null }
|
|
||||||
// { source: 'illmatic.js',
|
|
||||||
// generatedLine: 2,
|
|
||||||
// generatedColumn: 0,
|
|
||||||
// originalLine: 2,
|
|
||||||
// originalColumn: 0,
|
|
||||||
// name: null }
|
|
||||||
// ...
|
|
||||||
```
|
|
||||||
### SourceMapGenerator
|
|
||||||
|
|
||||||
An instance of the SourceMapGenerator represents a source map which is being
|
|
||||||
built incrementally.
|
|
||||||
|
|
||||||
#### new SourceMapGenerator([startOfSourceMap])
|
|
||||||
|
|
||||||
You may pass an object with the following properties:
|
|
||||||
|
|
||||||
* `file`: The filename of the generated source that this source map is
|
|
||||||
associated with.
|
|
||||||
|
|
||||||
* `sourceRoot`: A root for all relative URLs in this source map.
|
|
||||||
|
|
||||||
* `skipValidation`: Optional. When `true`, disables validation of mappings as
|
|
||||||
they are added. This can improve performance but should be used with
|
|
||||||
discretion, as a last resort. Even then, one should avoid using this flag when
|
|
||||||
running tests, if possible.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var generator = new sourceMap.SourceMapGenerator({
|
|
||||||
file: "my-generated-javascript-file.js",
|
|
||||||
sourceRoot: "http://example.com/app/js/"
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
|
|
||||||
|
|
||||||
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
|
|
||||||
|
|
||||||
* `sourceMapConsumer` The SourceMap.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.addMapping(mapping)
|
|
||||||
|
|
||||||
Add a single mapping from original source line and column to the generated
|
|
||||||
source's line and column for this source map being created. The mapping object
|
|
||||||
should have the following properties:
|
|
||||||
|
|
||||||
* `generated`: An object with the generated line and column positions.
|
|
||||||
|
|
||||||
* `original`: An object with the original line and column positions.
|
|
||||||
|
|
||||||
* `source`: The original source file (relative to the sourceRoot).
|
|
||||||
|
|
||||||
* `name`: An optional original token name for this mapping.
|
|
||||||
|
|
||||||
```js
|
|
||||||
generator.addMapping({
|
|
||||||
source: "module-one.scm",
|
|
||||||
original: { line: 128, column: 0 },
|
|
||||||
generated: { line: 3, column: 456 }
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
|
|
||||||
|
|
||||||
Set the source content for an original source file.
|
|
||||||
|
|
||||||
* `sourceFile` the URL of the original source file.
|
|
||||||
|
|
||||||
* `sourceContent` the content of the source file.
|
|
||||||
|
|
||||||
```js
|
|
||||||
generator.setSourceContent("module-one.scm",
|
|
||||||
fs.readFileSync("path/to/module-one.scm"))
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
|
|
||||||
|
|
||||||
Applies a SourceMap for a source file to the SourceMap.
|
|
||||||
Each mapping to the supplied source file is rewritten using the
|
|
||||||
supplied SourceMap. Note: The resolution for the resulting mappings
|
|
||||||
is the minimum of this map and the supplied map.
|
|
||||||
|
|
||||||
* `sourceMapConsumer`: The SourceMap to be applied.
|
|
||||||
|
|
||||||
* `sourceFile`: Optional. The filename of the source file.
|
|
||||||
If omitted, sourceMapConsumer.file will be used, if it exists.
|
|
||||||
Otherwise an error will be thrown.
|
|
||||||
|
|
||||||
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
|
|
||||||
to be applied. If relative, it is relative to the SourceMap.
|
|
||||||
|
|
||||||
This parameter is needed when the two SourceMaps aren't in the same
|
|
||||||
directory, and the SourceMap to be applied contains relative source
|
|
||||||
paths. If so, those relative source paths need to be rewritten
|
|
||||||
relative to the SourceMap.
|
|
||||||
|
|
||||||
If omitted, it is assumed that both SourceMaps are in the same directory,
|
|
||||||
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
|
|
||||||
|
|
||||||
#### SourceMapGenerator.prototype.toString()
|
|
||||||
|
|
||||||
Renders the source map being generated to a string.
|
|
||||||
|
|
||||||
```js
|
|
||||||
generator.toString()
|
|
||||||
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
|
|
||||||
```
|
|
||||||
|
|
||||||
### SourceNode
|
|
||||||
|
|
||||||
SourceNodes provide a way to abstract over interpolating and/or concatenating
|
|
||||||
snippets of generated JavaScript source code, while maintaining the line and
|
|
||||||
column information associated between those snippets and the original source
|
|
||||||
code. This is useful as the final intermediate representation a compiler might
|
|
||||||
use before outputting the generated JS and source map.
|
|
||||||
|
|
||||||
#### new SourceNode([line, column, source[, chunk[, name]]])
|
|
||||||
|
|
||||||
* `line`: The original line number associated with this source node, or null if
|
|
||||||
it isn't associated with an original line.
|
|
||||||
|
|
||||||
* `column`: The original column number associated with this source node, or null
|
|
||||||
if it isn't associated with an original column.
|
|
||||||
|
|
||||||
* `source`: The original source's filename; null if no filename is provided.
|
|
||||||
|
|
||||||
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
|
|
||||||
below.
|
|
||||||
|
|
||||||
* `name`: Optional. The original identifier.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.cpp", [
|
|
||||||
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
|
|
||||||
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
|
|
||||||
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
|
|
||||||
]);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
|
|
||||||
|
|
||||||
Creates a SourceNode from generated code and a SourceMapConsumer.
|
|
||||||
|
|
||||||
* `code`: The generated code
|
|
||||||
|
|
||||||
* `sourceMapConsumer` The SourceMap for the generated code
|
|
||||||
|
|
||||||
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
|
|
||||||
should be relative to.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
|
|
||||||
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
|
|
||||||
consumer);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.add(chunk)
|
|
||||||
|
|
||||||
Add a chunk of generated JS to this source node.
|
|
||||||
|
|
||||||
* `chunk`: A string snippet of generated JS code, another instance of
|
|
||||||
`SourceNode`, or an array where each member is one of those things.
|
|
||||||
|
|
||||||
```js
|
|
||||||
node.add(" + ");
|
|
||||||
node.add(otherNode);
|
|
||||||
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.prepend(chunk)
|
|
||||||
|
|
||||||
Prepend a chunk of generated JS to this source node.
|
|
||||||
|
|
||||||
* `chunk`: A string snippet of generated JS code, another instance of
|
|
||||||
`SourceNode`, or an array where each member is one of those things.
|
|
||||||
|
|
||||||
```js
|
|
||||||
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
|
|
||||||
|
|
||||||
Set the source content for a source file. This will be added to the
|
|
||||||
`SourceMap` in the `sourcesContent` field.
|
|
||||||
|
|
||||||
* `sourceFile`: The filename of the source file
|
|
||||||
|
|
||||||
* `sourceContent`: The content of the source file
|
|
||||||
|
|
||||||
```js
|
|
||||||
node.setSourceContent("module-one.scm",
|
|
||||||
fs.readFileSync("path/to/module-one.scm"))
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.walk(fn)
|
|
||||||
|
|
||||||
Walk over the tree of JS snippets in this node and its children. The walking
|
|
||||||
function is called once for each snippet of JS and is passed that snippet and
|
|
||||||
the its original associated source's line/column location.
|
|
||||||
|
|
||||||
* `fn`: The traversal function.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.js", [
|
|
||||||
new SourceNode(3, 4, "b.js", "uno"),
|
|
||||||
"dos",
|
|
||||||
[
|
|
||||||
"tres",
|
|
||||||
new SourceNode(5, 6, "c.js", "quatro")
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
|
|
||||||
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
|
|
||||||
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
|
|
||||||
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
|
|
||||||
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.walkSourceContents(fn)
|
|
||||||
|
|
||||||
Walk over the tree of SourceNodes. The walking function is called for each
|
|
||||||
source file content and is passed the filename and source content.
|
|
||||||
|
|
||||||
* `fn`: The traversal function.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var a = new SourceNode(1, 2, "a.js", "generated from a");
|
|
||||||
a.setSourceContent("a.js", "original a");
|
|
||||||
var b = new SourceNode(1, 2, "b.js", "generated from b");
|
|
||||||
b.setSourceContent("b.js", "original b");
|
|
||||||
var c = new SourceNode(1, 2, "c.js", "generated from c");
|
|
||||||
c.setSourceContent("c.js", "original c");
|
|
||||||
|
|
||||||
var node = new SourceNode(null, null, null, [a, b, c]);
|
|
||||||
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
|
|
||||||
// WALK: a.js : original a
|
|
||||||
// WALK: b.js : original b
|
|
||||||
// WALK: c.js : original c
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.join(sep)
|
|
||||||
|
|
||||||
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
|
|
||||||
between each of this source node's children.
|
|
||||||
|
|
||||||
* `sep`: The separator.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
|
|
||||||
var operand = new SourceNode(3, 4, "a.rs", "=");
|
|
||||||
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
|
|
||||||
|
|
||||||
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
|
|
||||||
var joinedNode = node.join(" ");
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.replaceRight(pattern, replacement)
|
|
||||||
|
|
||||||
Call `String.prototype.replace` on the very right-most source snippet. Useful
|
|
||||||
for trimming white space from the end of a source node, etc.
|
|
||||||
|
|
||||||
* `pattern`: The pattern to replace.
|
|
||||||
|
|
||||||
* `replacement`: The thing to replace the pattern with.
|
|
||||||
|
|
||||||
```js
|
|
||||||
// Trim trailing white space.
|
|
||||||
node.replaceRight(/\s*$/, "");
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.toString()
|
|
||||||
|
|
||||||
Return the string representation of this source node. Walks over the tree and
|
|
||||||
concatenates all the various snippets together to one string.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.js", [
|
|
||||||
new SourceNode(3, 4, "b.js", "uno"),
|
|
||||||
"dos",
|
|
||||||
[
|
|
||||||
"tres",
|
|
||||||
new SourceNode(5, 6, "c.js", "quatro")
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
node.toString()
|
|
||||||
// 'unodostresquatro'
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
|
|
||||||
|
|
||||||
Returns the string representation of this tree of source nodes, plus a
|
|
||||||
SourceMapGenerator which contains all the mappings between the generated and
|
|
||||||
original sources.
|
|
||||||
|
|
||||||
The arguments are the same as those to `new SourceMapGenerator`.
|
|
||||||
|
|
||||||
```js
|
|
||||||
var node = new SourceNode(1, 2, "a.js", [
|
|
||||||
new SourceNode(3, 4, "b.js", "uno"),
|
|
||||||
"dos",
|
|
||||||
[
|
|
||||||
"tres",
|
|
||||||
new SourceNode(5, 6, "c.js", "quatro")
|
|
||||||
]
|
|
||||||
]);
|
|
||||||
|
|
||||||
node.toStringWithSourceMap({ file: "my-output-file.js" })
|
|
||||||
// { code: 'unodostresquatro',
|
|
||||||
// map: [object SourceMapGenerator] }
|
|
||||||
```
|
|
||||||
3091
node_modules/@babel/generator/node_modules/source-map/dist/source-map.debug.js
generated
vendored
3091
node_modules/@babel/generator/node_modules/source-map/dist/source-map.debug.js
generated
vendored
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue