1
0
mirror of https://github.com/S2-/minifyfromhtml.git synced 2025-08-02 20:00:05 +02:00

update node modules

This commit is contained in:
s2
2019-03-29 15:56:41 +01:00
parent f114871153
commit 89c32fb4e6
8347 changed files with 390123 additions and 159877 deletions

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"git.ignoreLimitWarning": true
}

View File

@@ -1 +0,0 @@
#mywidget{border:2px solid red}

View File

@@ -1 +0,0 @@
var spectacularwidget=function(a){a.innerHTML='this is so spectacular!'};window.spectacularwidget=spectacularwidget;

View File

@@ -4,6 +4,7 @@ let path = require('path');
let jsdom = require('jsdom'); let jsdom = require('jsdom');
let JSDOM = jsdom.JSDOM; let JSDOM = jsdom.JSDOM;
let babel = require("babel-core"); let babel = require("babel-core");
let babelMinify = require('babel-minify');
let CleanCSS = require('clean-css'); let CleanCSS = require('clean-css');
let usage = `usage: let usage = `usage:
@@ -80,6 +81,9 @@ readStdin(function(html) {
for (let i = 0; i < scripts.length; i++) { for (let i = 0; i < scripts.length; i++) {
let script = scripts[i]; let script = scripts[i];
console.log(babel);
babel.transformFile(script, {}, function(err, result) { babel.transformFile(script, {}, function(err, result) {
if (err) { if (err) {
console.error(err); console.error(err);

16
node_modules/.bin/acorn generated vendored
View File

@@ -1 +1,15 @@
../acorn/bin/acorn #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../acorn/bin/acorn" "$@"
ret=$?
else
node "$basedir/../acorn/bin/acorn" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/acorn.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\acorn\bin\acorn" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\acorn\bin\acorn" %*
)

16
node_modules/.bin/babel-minify generated vendored
View File

@@ -1 +1,15 @@
../babel-minify/bin/minify.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../babel-minify/bin/minify.js" "$@"
ret=$?
else
node "$basedir/../babel-minify/bin/minify.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/babel-minify.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\babel-minify\bin\minify.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\babel-minify\bin\minify.js" %*
)

16
node_modules/.bin/babylon generated vendored
View File

@@ -1 +1,15 @@
../babylon/bin/babylon.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../babylon/bin/babylon.js" "$@"
ret=$?
else
node "$basedir/../babylon/bin/babylon.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/babylon.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\babylon\bin\babylon.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\babylon\bin\babylon.js" %*
)

16
node_modules/.bin/escodegen generated vendored
View File

@@ -1 +1,15 @@
../escodegen/bin/escodegen.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../escodegen/bin/escodegen.js" "$@"
ret=$?
else
node "$basedir/../escodegen/bin/escodegen.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/escodegen.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\escodegen\bin\escodegen.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\escodegen\bin\escodegen.js" %*
)

16
node_modules/.bin/esgenerate generated vendored
View File

@@ -1 +1,15 @@
../escodegen/bin/esgenerate.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../escodegen/bin/esgenerate.js" "$@"
ret=$?
else
node "$basedir/../escodegen/bin/esgenerate.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/esgenerate.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\escodegen\bin\esgenerate.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\escodegen\bin\esgenerate.js" %*
)

16
node_modules/.bin/esparse generated vendored
View File

@@ -1 +1,15 @@
../esprima/bin/esparse.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../esprima/bin/esparse.js" "$@"
ret=$?
else
node "$basedir/../esprima/bin/esparse.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/esparse.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\esprima\bin\esparse.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\esprima\bin\esparse.js" %*
)

16
node_modules/.bin/esvalidate generated vendored
View File

@@ -1 +1,15 @@
../esprima/bin/esvalidate.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../esprima/bin/esvalidate.js" "$@"
ret=$?
else
node "$basedir/../esprima/bin/esvalidate.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/esvalidate.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\esprima\bin\esvalidate.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\esprima\bin\esvalidate.js" %*
)

16
node_modules/.bin/jsesc generated vendored
View File

@@ -1 +1,15 @@
../jsesc/bin/jsesc #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../jsesc/bin/jsesc" "$@"
ret=$?
else
node "$basedir/../jsesc/bin/jsesc" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/jsesc.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\jsesc\bin\jsesc" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\jsesc\bin\jsesc" %*
)

16
node_modules/.bin/json5 generated vendored
View File

@@ -1 +1,15 @@
../json5/lib/cli.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../json5/lib/cli.js" "$@"
ret=$?
else
node "$basedir/../json5/lib/cli.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/json5.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\json5\lib\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\json5\lib\cli.js" %*
)

16
node_modules/.bin/loose-envify generated vendored
View File

@@ -1 +1,15 @@
../loose-envify/cli.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../loose-envify/cli.js" "$@"
ret=$?
else
node "$basedir/../loose-envify/cli.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/loose-envify.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\loose-envify\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\loose-envify\cli.js" %*
)

16
node_modules/.bin/minify generated vendored
View File

@@ -1 +1,15 @@
../babel-minify/bin/minify.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../babel-minify/bin/minify.js" "$@"
ret=$?
else
node "$basedir/../babel-minify/bin/minify.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/minify.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\babel-minify\bin\minify.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\babel-minify\bin\minify.js" %*
)

16
node_modules/.bin/mkdirp generated vendored
View File

@@ -1 +1,15 @@
../mkdirp/bin/cmd.js #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@"
ret=$?
else
node "$basedir/../mkdirp/bin/cmd.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/mkdirp.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\mkdirp\bin\cmd.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\mkdirp\bin\cmd.js" %*
)

15
node_modules/.bin/parser generated vendored Normal file
View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../@babel/parser/bin/babel-parser.js" "$@"
ret=$?
else
node "$basedir/../@babel/parser/bin/babel-parser.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/parser.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\@babel\parser\bin\babel-parser.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\@babel\parser\bin\babel-parser.js" %*
)

16
node_modules/.bin/semver generated vendored
View File

@@ -1 +1,15 @@
../semver/bin/semver #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../semver/bin/semver" "$@"
ret=$?
else
node "$basedir/../semver/bin/semver" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/semver.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\semver\bin\semver" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\semver\bin\semver" %*
)

16
node_modules/.bin/sshpk-conv generated vendored
View File

@@ -1 +1,15 @@
../sshpk/bin/sshpk-conv #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../sshpk/bin/sshpk-conv" "$@"
ret=$?
else
node "$basedir/../sshpk/bin/sshpk-conv" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/sshpk-conv.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-conv" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\sshpk\bin\sshpk-conv" %*
)

16
node_modules/.bin/sshpk-sign generated vendored
View File

@@ -1 +1,15 @@
../sshpk/bin/sshpk-sign #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../sshpk/bin/sshpk-sign" "$@"
ret=$?
else
node "$basedir/../sshpk/bin/sshpk-sign" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/sshpk-sign.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-sign" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\sshpk\bin\sshpk-sign" %*
)

16
node_modules/.bin/sshpk-verify generated vendored
View File

@@ -1 +1,15 @@
../sshpk/bin/sshpk-verify #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../sshpk/bin/sshpk-verify" "$@"
ret=$?
else
node "$basedir/../sshpk/bin/sshpk-verify" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/sshpk-verify.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-verify" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\sshpk\bin\sshpk-verify" %*
)

16
node_modules/.bin/uuid generated vendored
View File

@@ -1 +1,15 @@
../uuid/bin/uuid #!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../uuid/bin/uuid" "$@"
ret=$?
else
node "$basedir/../uuid/bin/uuid" "$@"
ret=$?
fi
exit $ret

7
node_modules/.bin/uuid.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\uuid\bin\uuid" %*
)

View File

@@ -1,142 +0,0 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
## Install
```sh
npm install --save-dev @babel/code-frame
```
## Usage
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor()
}`;
const location = { start: { line: 2, column: 16 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```
```
1 | class Foo {
> 2 | constructor()
| ^
3 | }
```
If the column number is not known, you may omit it.
You can also pass an `end` hash in `location`.
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor() {
console.log("hello");
}
}`;
const location = { start: { line: 2, column: 17 }, end: { line: 4, column: 3 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```
```
1 | class Foo {
> 2 | constructor() {
| ^
> 3 | console.log("hello");
| ^^^^^^^^^^^^^^^^^^^^^^^^^
> 4 | }
| ^^^
5 | };
```
## Options
### `highlightCode`
`boolean`, defaults to `false`.
Toggles syntax highlighting the code as JavaScript for terminals.
### `linesAbove`
`number`, defaults to `2`.
Adjust the number of lines to show above the error.
### `linesBelow`
`number`, defaults to `3`.
Adjust the number of lines to show below the error.
### `forceColor`
`boolean`, defaults to `false`.
Enable this to forcibly syntax highlight the code as JavaScript (for non-terminals); overrides `highlightCode`.
### `message`
`string`, otherwise nothing
Pass in a string to be displayed inline (if possible) next to the highlighted
location in the code. If it can't be positioned inline, it will be placed above
the code frame.
```
1 | class Foo {
> 2 | constructor()
| ^ Missing {
3 | };
```
## Upgrading from prior versions
Prior to version 7, the only API exposed by this module was for a single line and optional column pointer. The old API will now log a deprecation warning.
The new API takes a `location` object, similar to what is available in an AST.
This is an example of the deprecated (but still available) API:
```js
import codeFrame from '@babel/code-frame';
const rawLines = `class Foo {
constructor()
}`;
const lineNumber = 2;
const colNumber = 16;
const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });
console.log(result);
```
To get the same highlighting using the new API:
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor() {
console.log("hello");
}
}`;
const location = { start: { line: 2, column: 16 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```

View File

@@ -1,185 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.codeFrameColumns = codeFrameColumns;
exports.default = _default;
function _highlight() {
var data = _interopRequireWildcard(require("@babel/highlight"));
_highlight = function _highlight() {
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; } }
var deprecationWarningShown = false;
function getDefs(chalk) {
return {
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold
};
}
var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) {
var startLoc = Object.assign({}, {
column: 0,
line: -1
}, loc.start);
var endLoc = Object.assign({}, startLoc, loc.end);
var _ref = opts || {},
_ref$linesAbove = _ref.linesAbove,
linesAbove = _ref$linesAbove === void 0 ? 2 : _ref$linesAbove,
_ref$linesBelow = _ref.linesBelow,
linesBelow = _ref$linesBelow === void 0 ? 3 : _ref$linesBelow;
var startLine = startLoc.line;
var startColumn = startLoc.column;
var endLine = endLoc.line;
var endColumn = endLoc.column;
var start = Math.max(startLine - (linesAbove + 1), 0);
var end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
var lineDiff = endLine - startLine;
var markerLines = {};
if (lineDiff) {
for (var i = 0; i <= lineDiff; i++) {
var lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
var sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
var _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: start,
end: end,
markerLines: markerLines
};
}
function codeFrameColumns(rawLines, loc, opts) {
if (opts === void 0) {
opts = {};
}
var highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts);
var chalk = (0, _highlight().getChalk)(opts);
var defs = getDefs(chalk);
var maybeHighlight = function maybeHighlight(chalkFn, string) {
return highlighted ? chalkFn(string) : string;
};
if (highlighted) rawLines = (0, _highlight().default)(rawLines, opts);
var lines = rawLines.split(NEWLINE);
var _getMarkerLines = getMarkerLines(loc, lines, opts),
start = _getMarkerLines.start,
end = _getMarkerLines.end,
markerLines = _getMarkerLines.markerLines;
var hasColumns = loc.start && typeof loc.start.column === "number";
var numberMaxWidth = String(end).length;
var frame = lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var paddedNumber = (" " + number).slice(-numberMaxWidth);
var gutter = " " + paddedNumber + " | ";
var hasMarker = markerLines[number];
var lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
var markerLine = "";
if (Array.isArray(hasMarker)) {
var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
var 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 (opts === void 0) {
opts = {};
}
if (!deprecationWarningShown) {
deprecationWarningShown = true;
var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
var deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
var location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}

View File

@@ -1,51 +0,0 @@
{
"_from": "@babel/code-frame@7.0.0-beta.46",
"_id": "@babel/code-frame@7.0.0-beta.46",
"_inBundle": false,
"_integrity": "sha512-7BKRkmYaPZm3Yff5HGZJKCz7RqZ5jUjknsXT6Gz5YKG23J3uq9hAj0epncCB0rlqmnZ8Q+UUpQB2tCR5mT37vw==",
"_location": "/@babel/code-frame",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/code-frame@7.0.0-beta.46",
"name": "@babel/code-frame",
"escapedName": "@babel%2fcode-frame",
"scope": "@babel",
"rawSpec": "7.0.0-beta.46",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.46"
},
"_requiredBy": [
"/@babel/core",
"/@babel/template",
"/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0-beta.46.tgz",
"_shasum": "e0d002100805daab1461c0fcb32a07e304f3a4f4",
"_spec": "@babel/code-frame@7.0.0-beta.46",
"_where": "/home/s2/Documents/Code/minifyfromhtml/node_modules/@babel/core",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/highlight": "7.0.0-beta.46"
},
"deprecated": false,
"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-beta.46"
}

22
node_modules/@babel/core/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
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.

251
node_modules/@babel/core/README.md generated vendored
View File

@@ -2,249 +2,18 @@
> Babel compiler 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.
```javascript ## Install
var babel = require("@babel/core");
import { transform } from "@babel/core"; Using npm:
import * as babel from "@babel/core";
```sh
npm install --save-dev @babel/core
``` ```
All transformations will use your local configuration files (`.babelrc` or in `package.json`). See [options](#options) to disable it. or using yarn:
```sh
## babel.transform(code: string, [options?](#options): Object, callback: Function) yarn add @babel/core --dev
Transforms the passed in `code`. Calling a callback with an object with the generated code,
source map, and AST.
```js
babel.transform(code, options, function(err, result) {
result; // => { code, map, ast }
});
``` ```
**Example**
```js
babel.transform("code();", options, function(err, result) {
result.code;
result.map;
result.ast;
});
```
### Compat Note:
In Babel 6, this method was synchronous and `transformSync` did not exist. For backward-compatibility,
this function will behave synchronously if no callback is given. If you're starting with Babel 7
and need synchronous behavior, please use `transformSync` since this backward-compat may be dropped in
future major versions of Babel.
## babel.transformSync(code: string, [options?](#options): Object)
Transforms the passed in `code`. Returning an object with the generated code,
source map, and AST.
```js
babel.transformSync(code, options) // => { code, map, ast }
```
**Example**
```js
var result = babel.transformSync("code();", options);
result.code;
result.map;
result.ast;
```
## babel.transformFile(filename: string, [options?](#options): Object, callback: Function)
Asynchronously transforms the entire contents of a file.
```js
babel.transformFile(filename, options, callback)
```
**Example**
```js
babel.transformFile("filename.js", options, function (err, result) {
result; // => { code, map, ast }
});
```
## babel.transformFileSync(filename: string, [options?](#options): Object)
Synchronous version of `babel.transformFile`. Returns the transformed contents of
the `filename`.
```js
babel.transformFileSync(filename, options) // => { code, map, ast }
```
**Example**
```js
babel.transformFileSync("filename.js", options).code;
```
## babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object, callback: Function): FileNode | null
Given an [AST](https://astexplorer.net/), transform it.
```js
const sourceCode = "if (true) return;";
const parsedAst = babylon.parse(sourceCode, { allowReturnOutsideFunction: true });
babel.transformFromAst(parsedAst, sourceCode, options, function(err, result) {
const { code, map, ast } = result;
});
```
### Compat Note:
In Babel 6, this method was synchronous and `transformFromAstSync` did not exist. For backward-compatibility,
this function will behave synchronously if no callback is given. If you're starting with Babel 7
and need synchronous behavior, please use `transformFromAstSync` since this backward-compat may be dropped in
future major versions of Babel.
## babel.transformFromAstSync(ast: Object, code?: string, [options?](#options): Object)
Given an [AST](https://astexplorer.net/), transform it.
```js
const sourceCode = "if (true) return;";
const parsedAst = babylon.parse(sourceCode, { allowReturnOutsideFunction: true });
const { code, map, ast } = babel.transformFromAstSync(parsedAst, sourceCode, options);
```
## babel.parse(code: string, [options?](#options): Object)
Given some code, parse it using Babel's standard behavior. Referenced presets and
plugins will be loaded such that optional syntax plugins are automatically
enabled.
## Advanced APIs
Many systems that wrap Babel like to automatically inject plugins and presets,
or override options. To accomplish this goal, Babel exposes several functions
that aid in loading the configuration part-way without transforming.
### babel.loadOptions([options?](#options): Object)
Resolve Babel's options fully, resulting in an options object where:
* `opts.plugins` is a full list of `Plugin` instances.
* `opts.presets` is empty and all presets are flattened into `opts`.
* It can be safely passed back to Babel. Fields like `babelrc` have been set to
false so that later calls to Babel will not make a second attempt to load
config files.
`Plugin` instances aren't meant to be manipulated directly, but often
callers will serialize this `opts` to JSON to use it as a cache key representing
the options Babel has received. Caching on this isn't 100% guaranteed to
invalidate properly, but it is the best we have at the moment.
### babel.loadPartialConfig([options?](#options): Object): PartialConfig
To allow systems to easily manipulate and validate a user's config, this function
resolves the plugins and presets and proceeds no further. The expectation is
that callers will take the config's `.options`, manipulate it as then see fit
and pass it back to Babel again.
* `babelrc: string | void` - The path of the `.babelrc` file, if there was one.
* `babelignore: string | void` - The path of the `.babelignore` file, if there was one.
* `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back to Babel again.
* `plugins: Array<ConfigItem>` - See below.
* `presets: Array<ConfigItem>` - See below.
* It can be safely passed back to Babel. Fields like `babelrc` have been set
to false so that later calls to Babel will not make a second attempt to
load config files.
* `hasFilesystemConfig(): boolean` - Check if the resolved config loaded any settings from the filesystem.
[`ConfigItem`](#configitem-type) instances expose properties to introspect the values, but each
item should be treated as immutable. If changes are desired, the item should be
removed from the list and replaced with either a normal Babel config value, or
with a replacement item created by `babel.createConfigItem`. See that
function for information about `ConfigItem` fields.
### babel.createConfigItem(value: string | {} | Function | [string | {} | Function, {} | void], { dirname?: string, type?: "preset" | "plugin" }): ConfigItem
Allows build tooling to create and cache config items up front. If this function
is called multiple times for a given plugin, Babel will call the plugin's function itself
multiple times. If you have a clear set of expected plugins and presets to
inject, pre-constructing the config items would be recommended.
### `ConfigItem` type
Each `ConfigItem` exposes all of the information Babel knows. The fields are:
* `value: {} | Function` - The resolved value of the plugin.
* `options: {} | void` - The options object passed to the plugin.
* `dirname: string` - The path that the options are relative to.
* `name: string | void` - The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]`
* `file: Object | void` - Information about the plugin's file, if Babel knows it.
* `request: string` - The file that the user requested, e.g. `"@babel/env"`
* `resolved: string` - The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"`
## Options
<blockquote class="babel-callout babel-callout-info">
<h4>Babel CLI</h4>
<p>
You can pass these options from the Babel CLI like so:
</p>
<p>
<code>babel --name<span class="o">=</span>value</code>
</p>
</blockquote>
Following is a table of the options you can use:
| Option | Default | Description |
| ------------------------ | -------------------- | ------------------------------- |
| `ast` | `false` | Include the AST in the returned object |
| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code |
| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code |
| `root` | `"."` | Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of.|
| `configFile` | `undefined` | The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files.|
| `babelrc` | `true` | Specify whether or not to use .babelrc and .babelignore files. Not available when using the CLI, [use `--no-babelrc` instead](https://babeljs.io/docs/usage/cli/#babel-ignoring-babelrc) |
| `babelrcRoots` | `(root)` | Specify which packages should be search for .babelrc files when they are being compiled. `true` to _always_ search, or a path string or an array of paths to packages to search inside of. Defaults to only searching the "root" package. |
| `envName` | env vars | Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"` |
| `code` | `true` | Enable code generation |
| `comments` | `true` | Output comments in generated output |
| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB |
| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the `envName` is `production` |
| `extends` | `null` | A path to a `.babelrc` file to extend |
| `filename` | `"unknown"` | Filename for use in errors etc |
| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot` |
| `generatorOpts` | `{}` | An object containing the options to be passed down to the babel code generator, @babel/generator |
| `getModuleId` | `null` | Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used |
| `highlightCode` | `true` | ANSI highlight syntax error code frames |
| `ignore` | `null` | Opposite to the `only` option. `ignore` is disregarded if `only` is specified |
| `inputSourceMap` | `null` | A source map object that the output source map will be based on |
| `minified` | `false` | Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) |
| `moduleId` | `null` | Specify a custom name for module ids |
| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) |
| `moduleRoot` | `(sourceRoot)` | Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions |
| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim |
| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon |
| `plugins` | `[]` | List of [plugins](https://babeljs.io/docs/plugins/) to load and use |
| `presets` | `[]` | List of [presets](https://babeljs.io/docs/plugins/#presets) (a set of plugins) to load and use |
| `retainLines` | `false` | Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE:** This will not retain the columns) |
| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used |
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map |
| `sourceMaps` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option |
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative |
| `sourceType` | `"module"` | Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to _guess_, based on the presence of ES6 `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`. |
| `wrapPluginVisitorMethod`| `null` | An optional callback that can be used to wrap visitor methods. **NOTE:** This is useful for things like introspection, and not really needed for implementing anything. Called as `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.

View File

@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.makeStrongCache = makeStrongCache; exports.makeStrongCache = makeStrongCache;
exports.makeWeakCache = makeWeakCache; exports.makeWeakCache = makeWeakCache;
exports.assertSimpleType = assertSimpleType;
function makeStrongCache(handler) { function makeStrongCache(handler) {
return makeCachedFunction(new Map(), handler); return makeCachedFunction(new Map(), handler);
@@ -16,47 +17,35 @@ function makeWeakCache(handler) {
function makeCachedFunction(callCache, handler) { function makeCachedFunction(callCache, handler) {
return function cachedFunction(arg, data) { return function cachedFunction(arg, data) {
var cachedValue = callCache.get(arg); let cachedValue = callCache.get(arg);
if (cachedValue) { if (cachedValue) {
for (var _iterator = cachedValue, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { for (const _ref of cachedValue) {
var _ref2; const {
value,
if (_isArray) { valid
if (_i >= _iterator.length) break; } = _ref;
_ref2 = _iterator[_i++]; if (valid(data)) return value;
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var _ref3 = _ref2;
var _value = _ref3.value,
_valid = _ref3.valid;
if (_valid(data)) return _value;
} }
} }
var cache = new CacheConfigurator(data); const cache = new CacheConfigurator(data);
var value = handler(arg, cache); const value = handler(arg, cache);
if (!cache.configured()) cache.forever(); if (!cache.configured()) cache.forever();
cache.deactivate(); cache.deactivate();
switch (cache.mode()) { switch (cache.mode()) {
case "forever": case "forever":
cachedValue = [{ cachedValue = [{
value: value, value,
valid: function valid() { valid: () => true
return true;
}
}]; }];
callCache.set(arg, cachedValue); callCache.set(arg, cachedValue);
break; break;
case "invalidate": case "invalidate":
cachedValue = [{ cachedValue = [{
value: value, value,
valid: cache.validator() valid: cache.validator()
}]; }];
callCache.set(arg, cachedValue); callCache.set(arg, cachedValue);
@@ -65,12 +54,12 @@ function makeCachedFunction(callCache, handler) {
case "valid": case "valid":
if (cachedValue) { if (cachedValue) {
cachedValue.push({ cachedValue.push({
value: value, value,
valid: cache.validator() valid: cache.validator()
}); });
} else { } else {
cachedValue = [{ cachedValue = [{
value: value, value,
valid: cache.validator() valid: cache.validator()
}]; }];
callCache.set(arg, cachedValue); callCache.set(arg, cachedValue);
@@ -82,8 +71,8 @@ function makeCachedFunction(callCache, handler) {
}; };
} }
var CacheConfigurator = function () { class CacheConfigurator {
function CacheConfigurator(data) { constructor(data) {
this._active = true; this._active = true;
this._never = false; this._never = false;
this._forever = false; this._forever = false;
@@ -93,20 +82,18 @@ var CacheConfigurator = function () {
this._data = data; this._data = data;
} }
var _proto = CacheConfigurator.prototype; simple() {
_proto.simple = function simple() {
return makeSimpleConfigurator(this); return makeSimpleConfigurator(this);
}; }
_proto.mode = function mode() { mode() {
if (this._never) return "never"; if (this._never) return "never";
if (this._forever) return "forever"; if (this._forever) return "forever";
if (this._invalidate) return "invalidate"; if (this._invalidate) return "invalidate";
return "valid"; return "valid";
}; }
_proto.forever = function forever() { forever() {
if (!this._active) { if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed."); throw new Error("Cannot change caching after evaluation has completed.");
} }
@@ -117,9 +104,9 @@ var CacheConfigurator = function () {
this._forever = true; this._forever = true;
this._configured = true; this._configured = true;
}; }
_proto.never = function never() { never() {
if (!this._active) { if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed."); throw new Error("Cannot change caching after evaluation has completed.");
} }
@@ -130,9 +117,9 @@ var CacheConfigurator = function () {
this._never = true; this._never = true;
this._configured = true; this._configured = true;
}; }
_proto.using = function using(handler) { using(handler) {
if (!this._active) { if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed."); throw new Error("Cannot change caching after evaluation has completed.");
} }
@@ -142,14 +129,14 @@ var CacheConfigurator = function () {
} }
this._configured = true; this._configured = true;
var key = handler(this._data); const key = handler(this._data);
this._pairs.push([key, handler]); this._pairs.push([key, handler]);
return key; return key;
}; }
_proto.invalidate = function invalidate(handler) { invalidate(handler) {
if (!this._active) { if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed."); throw new Error("Cannot change caching after evaluation has completed.");
} }
@@ -160,34 +147,27 @@ var CacheConfigurator = function () {
this._invalidate = true; this._invalidate = true;
this._configured = true; this._configured = true;
var key = handler(this._data); const key = handler(this._data);
this._pairs.push([key, handler]); this._pairs.push([key, handler]);
return key; return key;
}; }
_proto.validator = function validator() { validator() {
var pairs = this._pairs; const pairs = this._pairs;
return function (data) { return data => pairs.every(([key, fn]) => key === fn(data));
return pairs.every(function (_ref4) { }
var key = _ref4[0],
fn = _ref4[1];
return key === fn(data);
});
};
};
_proto.deactivate = function deactivate() { deactivate() {
this._active = false; this._active = false;
}; }
_proto.configured = function configured() { configured() {
return this._configured; return this._configured;
}; }
return CacheConfigurator; }
}();
function makeSimpleConfigurator(cache) { function makeSimpleConfigurator(cache) {
function cacheFn(val) { function cacheFn(val) {
@@ -196,28 +176,24 @@ function makeSimpleConfigurator(cache) {
return; return;
} }
return cache.using(val); return cache.using(() => assertSimpleType(val()));
} }
cacheFn.forever = function () { cacheFn.forever = () => cache.forever();
return cache.forever();
};
cacheFn.never = function () { cacheFn.never = () => cache.never();
return cache.never();
};
cacheFn.using = function (cb) { cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
return cache.using(function () {
return cb();
});
};
cacheFn.invalidate = function (cb) { cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
return cache.invalidate(function () {
return cb();
});
};
return cacheFn; 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;
}

View File

@@ -3,23 +3,14 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.buildPresetChain = buildPresetChain;
exports.buildRootChain = buildRootChain; exports.buildRootChain = buildRootChain;
exports.buildPresetChain = void 0; exports.buildPresetChainWalker = void 0;
function _path() { function _path() {
var data = _interopRequireDefault(require("path")); const data = _interopRequireDefault(require("path"));
_path = function _path() { _path = function () {
return data;
};
return data;
}
function _micromatch() {
var data = _interopRequireDefault(require("micromatch"));
_micromatch = function _micromatch() {
return data; return data;
}; };
@@ -27,9 +18,9 @@ function _micromatch() {
} }
function _debug() { function _debug() {
var data = _interopRequireDefault(require("debug")); const data = _interopRequireDefault(require("debug"));
_debug = function _debug() { _debug = function () {
return data; return data;
}; };
@@ -38,6 +29,8 @@ function _debug() {
var _options = require("./validation/options"); var _options = require("./validation/options");
var _patternToRegex = _interopRequireDefault(require("./pattern-to-regex"));
var _files = require("./files"); var _files = require("./files");
var _caching = require("./caching"); var _caching = require("./caching");
@@ -46,255 +39,223 @@ var _configDescriptors = require("./config-descriptors");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var debug = (0, _debug().default)("babel:config:config-chain"); const debug = (0, _debug().default)("babel:config:config-chain");
var buildPresetChain = makeChainWalker({
init: function init(arg) { function buildPresetChain(arg, context) {
return arg; const chain = buildPresetChainWalker(arg, context);
}, if (!chain) return null;
root: function root(preset) { return {
return loadPresetDescriptors(preset); plugins: dedupDescriptors(chain.plugins),
}, presets: dedupDescriptors(chain.presets),
env: function env(preset, envName) { options: chain.options.map(o => normalizeOptions(o))
return loadPresetEnvDescriptors(preset)(envName); };
}, }
overrides: function overrides(preset, index) {
return loadPresetOverridesDescriptors(preset)(index); const buildPresetChainWalker = makeChainWalker({
}, init: arg => arg,
overridesEnv: function overridesEnv(preset, index, envName) { root: preset => loadPresetDescriptors(preset),
return loadPresetOverridesEnvDescriptors(preset)(index)(envName); env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),
} overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),
}); overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName)
exports.buildPresetChain = buildPresetChain;
var loadPresetDescriptors = (0, _caching.makeWeakCache)(function (preset) {
return buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors);
});
var loadPresetEnvDescriptors = (0, _caching.makeWeakCache)(function (preset) {
return (0, _caching.makeStrongCache)(function (envName) {
return buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName);
});
});
var loadPresetOverridesDescriptors = (0, _caching.makeWeakCache)(function (preset) {
return (0, _caching.makeStrongCache)(function (index) {
return buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index);
});
});
var loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCache)(function (preset) {
return (0, _caching.makeStrongCache)(function (index) {
return (0, _caching.makeStrongCache)(function (envName) {
return buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, 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) { function buildRootChain(opts, context) {
var programmaticChain = loadProgrammaticChain({ const programmaticChain = loadProgrammaticChain({
options: opts, options: opts,
dirname: context.cwd dirname: context.cwd
}, context); }, context);
if (!programmaticChain) return null; if (!programmaticChain) return null;
var _opts$root = opts.root, let configFile;
rootDir = _opts$root === void 0 ? "." : _opts$root,
_opts$babelrc = opts.babelrc,
babelrc = _opts$babelrc === void 0 ? true : _opts$babelrc,
babelrcRoots = opts.babelrcRoots,
_opts$configFile = opts.configFile,
configFileName = _opts$configFile === void 0 ? true : _opts$configFile;
var absoluteRoot = _path().default.resolve(context.cwd, rootDir); if (typeof opts.configFile === "string") {
configFile = (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller);
var configFile; } else if (opts.configFile !== false) {
configFile = (0, _files.findRootConfig)(context.root, context.envName, context.caller);
if (typeof configFileName === "string") {
configFile = (0, _files.loadConfig)(configFileName, context.cwd, context.envName);
} else if (configFileName === true) {
configFile = (0, _files.findRootConfig)(absoluteRoot, context.envName);
} }
var configFileChain = emptyChain(); let {
babelrc,
babelrcRoots
} = opts;
let babelrcRootsDirectory = context.cwd;
const configFileChain = emptyChain();
if (configFile) { if (configFile) {
var result = loadFileChain(configFile, context); const validatedFile = validateConfigFile(configFile);
const result = loadFileChain(validatedFile, context);
if (!result) return null; if (!result) return null;
if (babelrc === undefined) {
babelrc = validatedFile.options.babelrc;
}
if (babelrcRoots === undefined) {
babelrcRootsDirectory = validatedFile.dirname;
babelrcRoots = validatedFile.options.babelrcRoots;
}
mergeChain(configFileChain, result); mergeChain(configFileChain, result);
} }
var pkgData = typeof context.filename === "string" ? (0, _files.findPackageData)(context.filename) : null; const pkgData = typeof context.filename === "string" ? (0, _files.findPackageData)(context.filename) : null;
var ignoreFile, babelrcFile; let ignoreFile, babelrcFile;
var fileChain = emptyChain(); const fileChain = emptyChain();
if (babelrc && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, absoluteRoot)) { if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) {
var _findRelativeConfig = (0, _files.findRelativeConfig)(pkgData, context.envName); ({
ignore: ignoreFile,
ignoreFile = _findRelativeConfig.ignore; config: babelrcFile
babelrcFile = _findRelativeConfig.config; } = (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller));
if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) {
return null; return null;
} }
if (babelrcFile) { if (babelrcFile) {
var _result = loadFileChain(babelrcFile, context); const result = loadFileChain(validateBabelrcFile(babelrcFile), context);
if (!result) return null;
if (!_result) return null; mergeChain(fileChain, result);
mergeChain(fileChain, _result);
} }
} }
var chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain);
return { return {
plugins: dedupDescriptors(chain.plugins), plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets), presets: dedupDescriptors(chain.presets),
options: chain.options.map(function (o) { options: chain.options.map(o => normalizeOptions(o)),
return normalizeOptions(o);
}),
ignore: ignoreFile || undefined, ignore: ignoreFile || undefined,
babelrc: babelrcFile || undefined, babelrc: babelrcFile || undefined,
config: configFile || undefined config: configFile || undefined
}; };
} }
function babelrcLoadEnabled(context, pkgData, babelrcRoots, absoluteRoot) { function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) {
if (typeof babelrcRoots === "boolean") return babelrcRoots; if (typeof babelrcRoots === "boolean") return babelrcRoots;
const absoluteRoot = context.root;
if (babelrcRoots === undefined) { if (babelrcRoots === undefined) {
return pkgData.directories.indexOf(absoluteRoot) !== -1; return pkgData.directories.indexOf(absoluteRoot) !== -1;
} }
var babelrcPatterns = babelrcRoots; let babelrcPatterns = babelrcRoots;
if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns]; if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns];
babelrcPatterns = babelrcPatterns.map(function (pat) { babelrcPatterns = babelrcPatterns.map(pat => {
return _path().default.resolve(context.cwd, pat); return typeof pat === "string" ? _path().default.resolve(babelrcRootsDirectory, pat) : pat;
}); });
if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {
return pkgData.directories.indexOf(absoluteRoot) !== -1; return pkgData.directories.indexOf(absoluteRoot) !== -1;
} }
return (0, _micromatch().default)(pkgData.directories, babelrcPatterns).length > 0; 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);
});
});
} }
var loadProgrammaticChain = makeChainWalker({ const validateConfigFile = (0, _caching.makeWeakCache)(file => ({
init: function init(arg) {
return arg;
},
root: function root(input) {
return buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors);
},
env: function env(input, envName) {
return buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName);
},
overrides: function overrides(input, index) {
return buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index);
},
overridesEnv: function overridesEnv(input, index, envName) {
return buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName);
}
});
var loadFileChain = makeChainWalker({
init: function init(input) {
return validateFile(input);
},
root: function root(file) {
return loadFileDescriptors(file);
},
env: function env(file, envName) {
return loadFileEnvDescriptors(file)(envName);
},
overrides: function overrides(file, index) {
return loadFileOverridesDescriptors(file)(index);
},
overridesEnv: function overridesEnv(file, index, envName) {
return loadFileOverridesEnvDescriptors(file)(index)(envName);
}
});
var validateFile = (0, _caching.makeWeakCache)(function (file) {
return {
filepath: file.filepath, filepath: file.filepath,
dirname: file.dirname, dirname: file.dirname,
options: (0, _options.validate)("file", file.options) 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)
}); });
var loadFileDescriptors = (0, _caching.makeWeakCache)(function (file) { const loadFileChain = makeChainWalker({
return buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors); root: file => loadFileDescriptors(file),
}); env: (file, envName) => loadFileEnvDescriptors(file)(envName),
var loadFileEnvDescriptors = (0, _caching.makeWeakCache)(function (file) { overrides: (file, index) => loadFileOverridesDescriptors(file)(index),
return (0, _caching.makeStrongCache)(function (envName) { overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName)
return buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName);
});
});
var loadFileOverridesDescriptors = (0, _caching.makeWeakCache)(function (file) {
return (0, _caching.makeStrongCache)(function (index) {
return buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index);
});
});
var loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCache)(function (file) {
return (0, _caching.makeStrongCache)(function (index) {
return (0, _caching.makeStrongCache)(function (envName) {
return buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, 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(_ref, alias, descriptors) { function buildRootDescriptors({
var dirname = _ref.dirname, dirname,
options = _ref.options; options
}, alias, descriptors) {
return descriptors(dirname, options, alias); return descriptors(dirname, options, alias);
} }
function buildEnvDescriptors(_ref2, alias, descriptors, envName) { function buildEnvDescriptors({
var dirname = _ref2.dirname, dirname,
options = _ref2.options; options
var opts = options.env && options.env[envName]; }, alias, descriptors, envName) {
return opts ? descriptors(dirname, opts, alias + ".env[\"" + envName + "\"]") : null; const opts = options.env && options.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null;
} }
function buildOverrideDescriptors(_ref3, alias, descriptors, index) { function buildOverrideDescriptors({
var dirname = _ref3.dirname, dirname,
options = _ref3.options; options
var opts = options.overrides && options.overrides[index]; }, alias, descriptors, index) {
const opts = options.overrides && options.overrides[index];
if (!opts) throw new Error("Assertion failure - missing override"); if (!opts) throw new Error("Assertion failure - missing override");
return descriptors(dirname, opts, alias + ".overrides[" + index + "]"); return descriptors(dirname, opts, `${alias}.overrides[${index}]`);
} }
function buildOverrideEnvDescriptors(_ref4, alias, descriptors, index, envName) { function buildOverrideEnvDescriptors({
var dirname = _ref4.dirname, dirname,
options = _ref4.options; options
var override = options.overrides && options.overrides[index]; }, alias, descriptors, index, envName) {
const override = options.overrides && options.overrides[index];
if (!override) throw new Error("Assertion failure - missing override"); if (!override) throw new Error("Assertion failure - missing override");
var opts = override.env && override.env[envName]; const opts = override.env && override.env[envName];
return opts ? descriptors(dirname, opts, alias + ".overrides[" + index + "].env[\"" + envName + "\"]") : null; return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null;
} }
function makeChainWalker(_ref5) { function makeChainWalker({
var init = _ref5.init, root,
root = _ref5.root, env,
env = _ref5.env, overrides,
overrides = _ref5.overrides, overridesEnv
overridesEnv = _ref5.overridesEnv; }) {
return function (arg, context, files) { return (input, context, files = new Set()) => {
if (files === void 0) { const {
files = new Set(); dirname
} } = input;
const flattenedConfigs = [];
var input = init(arg); const rootOpts = root(input);
var dirname = input.dirname;
var flattenedConfigs = [];
var rootOpts = root(input);
if (configIsApplicable(rootOpts, dirname, context)) { if (configIsApplicable(rootOpts, dirname, context)) {
flattenedConfigs.push(rootOpts); flattenedConfigs.push(rootOpts);
var envOpts = env(input, context.envName); const envOpts = env(input, context.envName);
if (envOpts && configIsApplicable(envOpts, dirname, context)) { if (envOpts && configIsApplicable(envOpts, dirname, context)) {
flattenedConfigs.push(envOpts); flattenedConfigs.push(envOpts);
} }
(rootOpts.options.overrides || []).forEach(function (_, index) { (rootOpts.options.overrides || []).forEach((_, index) => {
var overrideOps = overrides(input, index); const overrideOps = overrides(input, index);
if (configIsApplicable(overrideOps, dirname, context)) { if (configIsApplicable(overrideOps, dirname, context)) {
flattenedConfigs.push(overrideOps); flattenedConfigs.push(overrideOps);
var overrideEnvOpts = overridesEnv(input, index, context.envName); const overrideEnvOpts = overridesEnv(input, index, context.envName);
if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) { if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) {
flattenedConfigs.push(overrideEnvOpts); flattenedConfigs.push(overrideEnvOpts);
@@ -303,20 +264,18 @@ function makeChainWalker(_ref5) {
}); });
} }
if (flattenedConfigs.some(function (_ref6) { if (flattenedConfigs.some(({
var _ref6$options = _ref6.options, options: {
ignore = _ref6$options.ignore, ignore,
only = _ref6$options.only; only
return shouldIgnore(context, ignore, only, dirname); }
})) { }) => shouldIgnore(context, ignore, only, dirname))) {
return null; return null;
} }
var chain = emptyChain(); const chain = emptyChain();
for (var _i = 0; _i < flattenedConfigs.length; _i++) {
var op = flattenedConfigs[_i];
for (const op of flattenedConfigs) {
if (!mergeExtendsChain(chain, op.options, dirname, context, files)) { if (!mergeExtendsChain(chain, op.options, dirname, context, files)) {
return null; return null;
} }
@@ -330,16 +289,14 @@ function makeChainWalker(_ref5) {
function mergeExtendsChain(chain, opts, dirname, context, files) { function mergeExtendsChain(chain, opts, dirname, context, files) {
if (opts.extends === undefined) return true; if (opts.extends === undefined) return true;
var file = (0, _files.loadConfig)(opts.extends, dirname, context.envName); const file = (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller);
if (files.has(file)) { 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, function (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"));
return " - " + file.filepath;
}).join("\n"));
} }
files.add(file); files.add(file);
var fileChain = loadFileChain(file, context, files); const fileChain = loadFileChain(validateExtendFile(file), context, files);
files.delete(file); files.delete(file);
if (!fileChain) return false; if (!fileChain) return false;
mergeChain(chain, fileChain); mergeChain(chain, fileChain);
@@ -347,29 +304,20 @@ function mergeExtendsChain(chain, opts, dirname, context, files) {
} }
function mergeChain(target, source) { function mergeChain(target, source) {
var _target$options, _target$plugins, _target$presets; target.options.push(...source.options);
target.plugins.push(...source.plugins);
(_target$options = target.options).push.apply(_target$options, source.options); target.presets.push(...source.presets);
(_target$plugins = target.plugins).push.apply(_target$plugins, source.plugins);
(_target$presets = target.presets).push.apply(_target$presets, source.presets);
return target; return target;
} }
function mergeChainOpts(target, _ref7) { function mergeChainOpts(target, {
var _target$plugins2, _target$presets2; options,
plugins,
var options = _ref7.options, presets
plugins = _ref7.plugins, }) {
presets = _ref7.presets;
target.options.push(options); target.options.push(options);
target.plugins.push(...plugins());
(_target$plugins2 = target.plugins).push.apply(_target$plugins2, plugins()); target.presets.push(...presets());
(_target$presets2 = target.presets).push.apply(_target$presets2, presets());
return target; return target;
} }
@@ -382,16 +330,20 @@ function emptyChain() {
} }
function normalizeOptions(opts) { function normalizeOptions(opts) {
var options = Object.assign({}, opts); const options = Object.assign({}, opts);
delete options.extends; delete options.extends;
delete options.env; delete options.env;
delete options.overrides;
delete options.plugins; delete options.plugins;
delete options.presets; delete options.presets;
delete options.passPerPreset; delete options.passPerPreset;
delete options.ignore; delete options.ignore;
delete options.only; delete options.only;
delete options.test;
delete options.include;
delete options.exclude;
if (options.sourceMap) { if (options.hasOwnProperty("sourceMap")) {
options.sourceMaps = options.sourceMap; options.sourceMaps = options.sourceMap;
delete options.sourceMap; delete options.sourceMap;
} }
@@ -400,44 +352,27 @@ function normalizeOptions(opts) {
} }
function dedupDescriptors(items) { function dedupDescriptors(items) {
var map = new Map(); const map = new Map();
var descriptors = []; const descriptors = [];
for (var _iterator = items, _isArray = Array.isArray(_iterator), _i2 = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref8;
if (_isArray) {
if (_i2 >= _iterator.length) break;
_ref8 = _iterator[_i2++];
} else {
_i2 = _iterator.next();
if (_i2.done) break;
_ref8 = _i2.value;
}
var item = _ref8;
for (const item of items) {
if (typeof item.value === "function") { if (typeof item.value === "function") {
var fnKey = item.value; const fnKey = item.value;
var nameMap = map.get(fnKey); let nameMap = map.get(fnKey);
if (!nameMap) { if (!nameMap) {
nameMap = new Map(); nameMap = new Map();
map.set(fnKey, nameMap); map.set(fnKey, nameMap);
} }
var desc = nameMap.get(item.name); let desc = nameMap.get(item.name);
if (!desc) { if (!desc) {
desc = { desc = {
value: null value: item
}; };
descriptors.push(desc); descriptors.push(desc);
if (!item.ownPass) nameMap.set(item.name, desc); if (!item.ownPass) nameMap.set(item.name, desc);
}
if (item.options === false) {
desc.value = null;
} else { } else {
desc.value = item; desc.value = item;
} }
@@ -448,111 +383,57 @@ function dedupDescriptors(items) {
} }
} }
return descriptors.reduce(function (acc, desc) { return descriptors.reduce((acc, desc) => {
if (desc.value) acc.push(desc.value); acc.push(desc.value);
return acc; return acc;
}, []); }, []);
} }
function configIsApplicable(_ref9, dirname, context) { function configIsApplicable({
var options = _ref9.options; 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)); 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) { function configFieldIsApplicable(context, test, dirname) {
if (context.filename === null) { const patterns = Array.isArray(test) ? test : [test];
throw new Error("Configuration contains explicit test/include/exclude checks, but no filename was passed to Babel"); return matchesPatterns(context, patterns, dirname);
}
var ctx = context;
var patterns = Array.isArray(test) ? test : [test];
return matchesPatterns(ctx, patterns, dirname, false);
} }
function shouldIgnore(context, ignore, only, dirname) { function shouldIgnore(context, ignore, only, dirname) {
if (ignore) { if (ignore && matchesPatterns(context, ignore, dirname)) {
if (context.filename === null) {
throw new Error("Configuration contains ignore checks, but no filename was passed to Babel");
}
var ctx = context;
if (matchesPatterns(ctx, ignore, dirname)) {
debug("Ignored %o because it matched one of %O from %o", context.filename, ignore, dirname); debug("Ignored %o because it matched one of %O from %o", context.filename, ignore, dirname);
return true; return true;
} }
}
if (only) { if (only && !matchesPatterns(context, only, dirname)) {
if (context.filename === null) {
throw new Error("Configuration contains ignore checks, but no filename was passed to Babel");
}
var _ctx = context;
if (!matchesPatterns(_ctx, only, dirname)) {
debug("Ignored %o because it failed to match one of %O from %o", context.filename, only, dirname); debug("Ignored %o because it failed to match one of %O from %o", context.filename, only, dirname);
return true; return true;
} }
}
return false; return false;
} }
function matchesPatterns(context, patterns, dirname, allowNegation) { function matchesPatterns(context, patterns, dirname) {
if (allowNegation === void 0) { return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context));
allowNegation = true;
}
var res = [];
var strings = [];
var fns = [];
patterns.forEach(function (pattern) {
if (typeof pattern === "string") strings.push(pattern);else if (typeof pattern === "function") fns.push(pattern);else res.push(pattern);
});
var filename = context.filename;
if (res.some(function (re) {
return re.test(context.filename);
})) return true;
if (fns.some(function (fn) {
return fn(filename);
})) return true;
if (strings.length > 0) {
var possibleDirs = getPossibleDirs(context);
var absolutePatterns = strings.map(function (pattern) {
var negate = pattern[0] === "!";
if (negate && !allowNegation) {
throw new Error("Negation of file paths is not supported.");
}
if (negate) pattern = pattern.slice(1);
return (negate ? "!" : "") + _path().default.resolve(dirname, pattern);
});
if ((0, _micromatch().default)(possibleDirs, absolutePatterns, {
nocase: true,
nonegate: !allowNegation
}).length > 0) {
return true;
}
}
return false;
} }
var getPossibleDirs = (0, _caching.makeWeakCache)(function (context) { function matchPattern(pattern, dirname, pathToTest, context) {
var current = context.filename; if (typeof pattern === "function") {
if (current === null) return []; return !!pattern(pathToTest, {
var possibleDirs = [current]; dirname,
envName: context.envName,
while (true) { caller: context.caller
var previous = current; });
current = _path().default.dirname(current);
if (previous === current) break;
possibleDirs.push(current);
} }
return possibleDirs; 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);
}

View File

@@ -13,85 +13,89 @@ var _item = require("./item");
var _caching = require("./caching"); 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) { function createCachedDescriptors(dirname, options, alias) {
var plugins = options.plugins, const {
presets = options.presets, plugins,
passPerPreset = options.passPerPreset; presets,
passPerPreset
} = options;
return { return {
options: options, options,
plugins: plugins ? function () { plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => [],
return createCachedPluginDescriptors(plugins, dirname)(alias); presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => []
} : function () {
return [];
},
presets: presets ? function () {
return createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset);
} : function () {
return [];
}
}; };
} }
function createUncachedDescriptors(dirname, options, alias) { function createUncachedDescriptors(dirname, options, alias) {
var plugins; let plugins;
var presets; let presets;
return { return {
options: options, options,
plugins: function (_plugins) { plugins: () => {
function plugins() {
return _plugins.apply(this, arguments);
}
plugins.toString = function () {
return _plugins.toString();
};
return plugins;
}(function () {
if (!plugins) { if (!plugins) {
plugins = createPluginDescriptors(options.plugins || [], dirname, alias); plugins = createPluginDescriptors(options.plugins || [], dirname, alias);
} }
return plugins; return plugins;
}), },
presets: function (_presets) { presets: () => {
function presets() {
return _presets.apply(this, arguments);
}
presets.toString = function () {
return _presets.toString();
};
return presets;
}(function () {
if (!presets) { if (!presets) {
presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset); presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset);
} }
return presets; return presets;
}) }
}; };
} }
var createCachedPresetDescriptors = (0, _caching.makeWeakCache)(function (items, cache) { const PRESET_DESCRIPTOR_CACHE = new WeakMap();
var dirname = cache.using(function (dir) { const createCachedPresetDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
return dir; 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))));
return (0, _caching.makeStrongCache)(function (alias) {
return (0, _caching.makeStrongCache)(function (passPerPreset) {
return createPresetDescriptors(items, dirname, alias, passPerPreset);
});
});
}); });
var createCachedPluginDescriptors = (0, _caching.makeWeakCache)(function (items, cache) { const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
var dirname = cache.using(function (dir) { const createCachedPluginDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
return dir; const dirname = cache.using(dir => dir);
}); return (0, _caching.makeStrongCache)(alias => createPluginDescriptors(items, dirname, alias).map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)));
return (0, _caching.makeStrongCache)(function (alias) {
return createPluginDescriptors(items, dirname, alias);
});
}); });
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) { function createPresetDescriptors(items, dirname, alias, passPerPreset) {
return createDescriptors("preset", items, dirname, alias, passPerPreset); return createDescriptors("preset", items, dirname, alias, passPerPreset);
@@ -102,67 +106,60 @@ function createPluginDescriptors(items, dirname, alias) {
} }
function createDescriptors(type, items, dirname, alias, ownPass) { function createDescriptors(type, items, dirname, alias, ownPass) {
var descriptors = items.map(function (item, index) { const descriptors = items.map((item, index) => createDescriptor(item, dirname, {
return createDescriptor(item, dirname, { type,
type: type, alias: `${alias}$${index}`,
alias: alias + "$" + index,
ownPass: !!ownPass ownPass: !!ownPass
}); }));
});
assertNoDuplicates(descriptors); assertNoDuplicates(descriptors);
return descriptors; return descriptors;
} }
function createDescriptor(pair, dirname, _ref) { function createDescriptor(pair, dirname, {
var type = _ref.type, type,
alias = _ref.alias, alias,
ownPass = _ref.ownPass; ownPass
var desc = (0, _item.getItemDescriptor)(pair); }) {
const desc = (0, _item.getItemDescriptor)(pair);
if (desc) { if (desc) {
return desc; return desc;
} }
var name; let name;
var options; let options;
var value = pair; let value = pair;
if (Array.isArray(value)) { if (Array.isArray(value)) {
if (value.length === 3) { if (value.length === 3) {
var _value = value; [value, options, name] = value;
value = _value[0];
options = _value[1];
name = _value[2];
} else { } else {
var _value2 = value; [value, options] = value;
value = _value2[0];
options = _value2[1];
} }
} }
var file = undefined; let file = undefined;
var filepath = null; let filepath = null;
if (typeof value === "string") { if (typeof value === "string") {
if (typeof type !== "string") { if (typeof type !== "string") {
throw new Error("To resolve a string-based item, the type of item must be given"); throw new Error("To resolve a string-based item, the type of item must be given");
} }
var resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset; const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset;
var _request = value; const request = value;
({
var _resolver = resolver(value, dirname); filepath,
value
filepath = _resolver.filepath; } = resolver(value, dirname));
value = _resolver.value;
file = { file = {
request: _request, request,
resolved: filepath resolved: filepath
}; };
} }
if (!value) { if (!value) {
throw new Error("Unexpected falsy value: " + String(value)); throw new Error(`Unexpected falsy value: ${String(value)}`);
} }
if (typeof value === "object" && value.__esModule) { if (typeof value === "object" && value.__esModule) {
@@ -174,42 +171,30 @@ function createDescriptor(pair, dirname, _ref) {
} }
if (typeof value !== "object" && typeof value !== "function") { if (typeof value !== "object" && typeof value !== "function") {
throw new Error("Unsupported format: " + typeof value + ". Expected an object or a function."); throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`);
} }
if (filepath !== null && typeof value === "object" && value) { if (filepath !== null && typeof value === "object" && value) {
throw new Error("Plugin/Preset files are not allowed to export objects, only functions. In " + filepath); throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`);
} }
return { return {
name: name, name,
alias: filepath || alias, alias: filepath || alias,
value: value, value,
options: options, options,
dirname: dirname, dirname,
ownPass: ownPass, ownPass,
file: file file
}; };
} }
function assertNoDuplicates(items) { function assertNoDuplicates(items) {
var map = new Map(); const map = new Map();
for (var _iterator = items, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { for (const item of items) {
var _ref2;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var item = _ref2;
if (typeof item.value !== "function") continue; if (typeof item.value !== "function") continue;
var nameMap = map.get(item.value); let nameMap = map.get(item.value);
if (!nameMap) { if (!nameMap) {
nameMap = new Set(); nameMap = new Set();
@@ -217,7 +202,7 @@ function assertNoDuplicates(items) {
} }
if (nameMap.has(item.name)) { 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 neen separate names, e.g.", "", " plugins: [", " ['some-plugin', {}],", " ['some-plugin', {}, 'some unique name'],", " ]"].join("\n")); 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); nameMap.add(item.name);

View File

@@ -3,14 +3,15 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.findConfigUpwards = findConfigUpwards;
exports.findRelativeConfig = findRelativeConfig; exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig; exports.findRootConfig = findRootConfig;
exports.loadConfig = loadConfig; exports.loadConfig = loadConfig;
function _debug() { function _debug() {
var data = _interopRequireDefault(require("debug")); const data = _interopRequireDefault(require("debug"));
_debug = function _debug() { _debug = function () {
return data; return data;
}; };
@@ -18,9 +19,9 @@ function _debug() {
} }
function _path() { function _path() {
var data = _interopRequireDefault(require("path")); const data = _interopRequireDefault(require("path"));
_path = function _path() { _path = function () {
return data; return data;
}; };
@@ -28,9 +29,9 @@ function _path() {
} }
function _fs() { function _fs() {
var data = _interopRequireDefault(require("fs")); const data = _interopRequireDefault(require("fs"));
_fs = function _fs() { _fs = function () {
return data; return data;
}; };
@@ -38,9 +39,9 @@ function _fs() {
} }
function _json() { function _json() {
var data = _interopRequireDefault(require("json5")); const data = _interopRequireDefault(require("json5"));
_json = function _json() { _json = function () {
return data; return data;
}; };
@@ -48,9 +49,9 @@ function _json() {
} }
function _resolve() { function _resolve() {
var data = _interopRequireDefault(require("resolve")); const data = _interopRequireDefault(require("resolve"));
_resolve = function _resolve() { _resolve = function () {
return data; return data;
}; };
@@ -63,49 +64,57 @@ var _configApi = _interopRequireDefault(require("../helpers/config-api"));
var _utils = require("./utils"); var _utils = require("./utils");
var _patternToRegex = _interopRequireDefault(require("../pattern-to-regex"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var debug = (0, _debug().default)("babel:config:loading:files:configuration"); const debug = (0, _debug().default)("babel:config:loading:files:configuration");
var BABEL_CONFIG_JS_FILENAME = "babel.config.js"; const BABEL_CONFIG_JS_FILENAME = "babel.config.js";
var BABELRC_FILENAME = ".babelrc"; const BABELRC_FILENAME = ".babelrc";
var BABELRC_JS_FILENAME = ".babelrc.js"; const BABELRC_JS_FILENAME = ".babelrc.js";
var BABELIGNORE_FILENAME = ".babelignore"; const BABELIGNORE_FILENAME = ".babelignore";
function findRelativeConfig(packageData, envName) { function findConfigUpwards(rootDir) {
var config = null; let dirname = rootDir;
var ignore = null;
var dirname = _path().default.dirname(packageData.filepath); while (true) {
if (_fs().default.existsSync(_path().default.join(dirname, BABEL_CONFIG_JS_FILENAME))) {
var _loop = function _loop() { return dirname;
if (_isArray) {
if (_i >= _iterator.length) return "break";
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) return "break";
_ref = _i.value;
} }
var loc = _ref; 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) { if (!config) {
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce(function (previousConfig, name) { config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce((previousConfig, name) => {
var filepath = _path().default.join(loc, name); const filepath = _path().default.join(loc, name);
var config = readConfig(filepath, envName); const config = readConfig(filepath, envName, caller);
if (config && previousConfig) { if (config && previousConfig) {
throw new Error("Multiple configuration files found. Please remove one:\n" + (" - " + _path().default.basename(previousConfig.filepath) + "\n") + (" - " + name + "\n") + ("from " + loc)); throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().default.basename(previousConfig.filepath)}\n` + ` - ${name}\n` + `from ${loc}`);
} }
return config || previousConfig; return config || previousConfig;
}, null); }, null);
var pkgConfig = packageData.pkg && packageData.pkg.dirname === loc ? packageToBabelConfig(packageData.pkg) : null; const pkgConfig = packageData.pkg && packageData.pkg.dirname === loc ? packageToBabelConfig(packageData.pkg) : null;
if (pkgConfig) { if (pkgConfig) {
if (config) { 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)); 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; config = pkgConfig;
@@ -117,7 +126,7 @@ function findRelativeConfig(packageData, envName) {
} }
if (!ignore) { if (!ignore) {
var ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME); const ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME);
ignore = readIgnoreConfig(ignoreLoc); ignore = readIgnoreConfig(ignoreLoc);
@@ -125,26 +134,18 @@ function findRelativeConfig(packageData, envName) {
debug("Found ignore %o from %o.", ignore.filepath, dirname); debug("Found ignore %o from %o.", ignore.filepath, dirname);
} }
} }
};
for (var _iterator = packageData.directories, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
var _ret = _loop();
if (_ret === "break") break;
} }
return { return {
config: config, config,
ignore: ignore ignore
}; };
} }
function findRootConfig(dirname, envName) { function findRootConfig(dirname, envName, caller) {
var filepath = _path().default.resolve(dirname, BABEL_CONFIG_JS_FILENAME); const filepath = _path().default.resolve(dirname, BABEL_CONFIG_JS_FILENAME);
var conf = readConfig(filepath, envName); const conf = readConfig(filepath, envName, caller);
if (conf) { if (conf) {
debug("Found root config %o in $o.", BABEL_CONFIG_JS_FILENAME, dirname); debug("Found root config %o in $o.", BABEL_CONFIG_JS_FILENAME, dirname);
@@ -153,29 +154,30 @@ function findRootConfig(dirname, envName) {
return conf; return conf;
} }
function loadConfig(name, dirname, envName) { function loadConfig(name, dirname, envName, caller) {
var filepath = _resolve().default.sync(name, { const filepath = _resolve().default.sync(name, {
basedir: dirname basedir: dirname
}); });
var conf = readConfig(filepath, envName); const conf = readConfig(filepath, envName, caller);
if (!conf) { if (!conf) {
throw new Error("Config file " + filepath + " contains no configuration data"); throw new Error(`Config file ${filepath} contains no configuration data`);
} }
debug("Loaded config %o from $o.", name, dirname); debug("Loaded config %o from $o.", name, dirname);
return conf; return conf;
} }
function readConfig(filepath, envName) { function readConfig(filepath, envName, caller) {
return _path().default.extname(filepath) === ".js" ? readConfigJS(filepath, { return _path().default.extname(filepath) === ".js" ? readConfigJS(filepath, {
envName: envName envName,
caller
}) : readConfigJSON5(filepath); }) : readConfigJSON5(filepath);
} }
var LOADING_CONFIGS = new Set(); const LOADING_CONFIGS = new Set();
var readConfigJS = (0, _caching.makeStrongCache)(function (filepath, cache) { const readConfigJS = (0, _caching.makeStrongCache)((filepath, cache) => {
if (!_fs().default.existsSync(filepath)) { if (!_fs().default.existsSync(filepath)) {
cache.forever(); cache.forever();
return null; return null;
@@ -185,22 +187,22 @@ var readConfigJS = (0, _caching.makeStrongCache)(function (filepath, cache) {
cache.never(); cache.never();
debug("Auto-ignoring usage of config %o.", filepath); debug("Auto-ignoring usage of config %o.", filepath);
return { return {
filepath: filepath, filepath,
dirname: _path().default.dirname(filepath), dirname: _path().default.dirname(filepath),
options: {} options: {}
}; };
} }
var options; let options;
try { try {
LOADING_CONFIGS.add(filepath); LOADING_CONFIGS.add(filepath);
var configModule = require(filepath); const configModule = require(filepath);
options = configModule && configModule.__esModule ? configModule.default || undefined : configModule; options = configModule && configModule.__esModule ? configModule.default || undefined : configModule;
} catch (err) { } catch (err) {
err.message = filepath + ": Error while loading config - " + err.message; err.message = `${filepath}: Error while loading config - ${err.message}`;
throw err; throw err;
} finally { } finally {
LOADING_CONFIGS.delete(filepath); LOADING_CONFIGS.delete(filepath);
@@ -212,25 +214,25 @@ var readConfigJS = (0, _caching.makeStrongCache)(function (filepath, cache) {
} }
if (!options || typeof options !== "object" || Array.isArray(options)) { if (!options || typeof options !== "object" || Array.isArray(options)) {
throw new Error(filepath + ": Configuration should be an exported JavaScript object."); throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`);
} }
if (typeof options.then === "function") { 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."); 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 { return {
filepath: filepath, filepath,
dirname: _path().default.dirname(filepath), dirname: _path().default.dirname(filepath),
options: options options
}; };
}); });
var packageToBabelConfig = (0, _caching.makeWeakCache)(function (file) { const packageToBabelConfig = (0, _caching.makeWeakCache)(file => {
if (typeof file.options.babel === "undefined") return null; const babel = file.options["babel"];
var babel = file.options.babel; if (typeof babel === "undefined") return null;
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
throw new Error(file.filepath + ": .babel property must be an object"); throw new Error(`${file.filepath}: .babel property must be an object`);
} }
return { return {
@@ -239,45 +241,83 @@ var packageToBabelConfig = (0, _caching.makeWeakCache)(function (file) {
options: babel options: babel
}; };
}); });
var readConfigJSON5 = (0, _utils.makeStaticFileCache)(function (filepath, content) { const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => {
var options; let options;
try { try {
options = _json().default.parse(content); options = _json().default.parse(content);
} catch (err) { } catch (err) {
err.message = filepath + ": Error while parsing config - " + err.message; err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err; throw err;
} }
if (!options) throw new Error(filepath + ": No config detected"); if (!options) throw new Error(`${filepath}: No config detected`);
if (typeof options !== "object") { if (typeof options !== "object") {
throw new Error(filepath + ": Config returned typeof " + typeof options); throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
} }
if (Array.isArray(options)) { if (Array.isArray(options)) {
throw new Error(filepath + ": Expected config object but found array"); throw new Error(`${filepath}: Expected config object but found array`);
} }
return { return {
filepath: filepath, filepath,
dirname: _path().default.dirname(filepath), dirname: _path().default.dirname(filepath),
options: options options
}; };
}); });
var readIgnoreConfig = (0, _utils.makeStaticFileCache)(function (filepath, content) { const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => {
var ignore = content.split("\n").map(function (line) { const ignoreDir = _path().default.dirname(filepath);
return line.replace(/#(.*?)$/, "").trim();
}).filter(function (line) { const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line);
return !!line;
}); for (const pattern of ignorePatterns) {
if (pattern[0] === "!") {
throw new Error(`Negation of file paths is not supported.`);
}
}
return { return {
filepath: filepath, filepath,
dirname: _path().default.dirname(filepath), dirname: _path().default.dirname(filepath),
ignore: ignore ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir))
}; };
}); });
function throwConfigError() { function throwConfigError() {
throw new Error("Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured\nfor various types of caching, using the first param of their handler functions:\n\nmodule.exports = function(api) {\n // The API exposes the following:\n\n // Cache the returned value forever and don't call this function again.\n api.cache(true);\n\n // Don't cache at all. Not recommended because it will be very slow.\n api.cache(false);\n\n // Cached based on the value of some function. If this function returns a value different from\n // a previously-encountered value, the plugins will re-evaluate.\n var env = api.cache(() => process.env.NODE_ENV);\n\n // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for\n // any possible NODE_ENV value that might come up during plugin execution.\n var isProd = api.cache(() => process.env.NODE_ENV === \"production\");\n\n // .cache(fn) will perform a linear search though instances to find the matching plugin based\n // based on previous instantiated plugins. If you want to recreate the plugin and discard the\n // previous instance whenever something changes, you may use:\n var isProd = api.cache.invalidate(() => process.env.NODE_ENV === \"production\");\n\n // Note, we also expose the following more-verbose versions of the above examples:\n api.cache.forever(); // api.cache(true)\n api.cache.never(); // api.cache(false)\n api.cache.using(fn); // api.cache(fn)\n\n // Return the value that will be cached.\n return { };\n};"); 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 { };
};`);
} }

View File

@@ -3,6 +3,7 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.findConfigUpwards = findConfigUpwards;
exports.findPackageData = findPackageData; exports.findPackageData = findPackageData;
exports.findRelativeConfig = findRelativeConfig; exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig; exports.findRootConfig = findRootConfig;
@@ -12,16 +13,20 @@ exports.resolvePreset = resolvePreset;
exports.loadPlugin = loadPlugin; exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset; exports.loadPreset = loadPreset;
function findConfigUpwards(rootDir) {
return null;
}
function findPackageData(filepath) { function findPackageData(filepath) {
return { return {
filepath: filepath, filepath,
directories: [], directories: [],
pkg: null, pkg: null,
isPackage: false isPackage: false
}; };
} }
function findRelativeConfig(pkgData, envName) { function findRelativeConfig(pkgData, envName, caller) {
return { return {
pkg: null, pkg: null,
config: null, config: null,
@@ -29,12 +34,12 @@ function findRelativeConfig(pkgData, envName) {
}; };
} }
function findRootConfig(dirname, envName) { function findRootConfig(dirname, envName, caller) {
return null; return null;
} }
function loadConfig(name, dirname, envName) { function loadConfig(name, dirname, envName, caller) {
throw new Error("Cannot load " + name + " relative to " + dirname + " in a browser"); throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
} }
function resolvePlugin(name, dirname) { function resolvePlugin(name, dirname) {
@@ -46,9 +51,9 @@ function resolvePreset(name, dirname) {
} }
function loadPlugin(name, dirname) { function loadPlugin(name, dirname) {
throw new Error("Cannot load plugin " + name + " relative to " + dirname + " in a browser"); throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`);
} }
function loadPreset(name, dirname) { function loadPreset(name, dirname) {
throw new Error("Cannot load preset " + name + " relative to " + dirname + " in a browser"); throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`);
} }

View File

@@ -5,49 +5,55 @@ Object.defineProperty(exports, "__esModule", {
}); });
Object.defineProperty(exports, "findPackageData", { Object.defineProperty(exports, "findPackageData", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _package.findPackageData; return _package.findPackageData;
} }
}); });
Object.defineProperty(exports, "findConfigUpwards", {
enumerable: true,
get: function () {
return _configuration.findConfigUpwards;
}
});
Object.defineProperty(exports, "findRelativeConfig", { Object.defineProperty(exports, "findRelativeConfig", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _configuration.findRelativeConfig; return _configuration.findRelativeConfig;
} }
}); });
Object.defineProperty(exports, "findRootConfig", { Object.defineProperty(exports, "findRootConfig", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _configuration.findRootConfig; return _configuration.findRootConfig;
} }
}); });
Object.defineProperty(exports, "loadConfig", { Object.defineProperty(exports, "loadConfig", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _configuration.loadConfig; return _configuration.loadConfig;
} }
}); });
Object.defineProperty(exports, "resolvePlugin", { Object.defineProperty(exports, "resolvePlugin", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _plugins.resolvePlugin; return _plugins.resolvePlugin;
} }
}); });
Object.defineProperty(exports, "resolvePreset", { Object.defineProperty(exports, "resolvePreset", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _plugins.resolvePreset; return _plugins.resolvePreset;
} }
}); });
Object.defineProperty(exports, "loadPlugin", { Object.defineProperty(exports, "loadPlugin", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _plugins.loadPlugin; return _plugins.loadPlugin;
} }
}); });
Object.defineProperty(exports, "loadPreset", { Object.defineProperty(exports, "loadPreset", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _plugins.loadPreset; return _plugins.loadPreset;
} }
}); });

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.findPackageData = findPackageData; exports.findPackageData = findPackageData;
function _path() { function _path() {
var data = _interopRequireDefault(require("path")); const data = _interopRequireDefault(require("path"));
_path = function _path() { _path = function () {
return data; return data;
}; };
@@ -19,20 +19,20 @@ var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var PACKAGE_FILENAME = "package.json"; const PACKAGE_FILENAME = "package.json";
function findPackageData(filepath) { function findPackageData(filepath) {
var pkg = null; let pkg = null;
var directories = []; const directories = [];
var isPackage = true; let isPackage = true;
var dirname = _path().default.dirname(filepath); let dirname = _path().default.dirname(filepath);
while (!pkg && _path().default.basename(dirname) !== "node_modules") { while (!pkg && _path().default.basename(dirname) !== "node_modules") {
directories.push(dirname); directories.push(dirname);
pkg = readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME)); pkg = readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME));
var nextLoc = _path().default.dirname(dirname); const nextLoc = _path().default.dirname(dirname);
if (dirname === nextLoc) { if (dirname === nextLoc) {
isPackage = false; isPackage = false;
@@ -43,34 +43,34 @@ function findPackageData(filepath) {
} }
return { return {
filepath: filepath, filepath,
directories: directories, directories,
pkg: pkg, pkg,
isPackage: isPackage isPackage
}; };
} }
var readConfigPackage = (0, _utils.makeStaticFileCache)(function (filepath, content) { const readConfigPackage = (0, _utils.makeStaticFileCache)((filepath, content) => {
var options; let options;
try { try {
options = JSON.parse(content); options = JSON.parse(content);
} catch (err) { } catch (err) {
err.message = filepath + ": Error while parsing JSON - " + err.message; err.message = `${filepath}: Error while parsing JSON - ${err.message}`;
throw err; throw err;
} }
if (typeof options !== "object") { if (typeof options !== "object") {
throw new Error(filepath + ": Config returned typeof " + typeof options); throw new Error(`${filepath}: Config returned typeof ${typeof options}`);
} }
if (Array.isArray(options)) { if (Array.isArray(options)) {
throw new Error(filepath + ": Expected config object but found array"); throw new Error(`${filepath}: Expected config object but found array`);
} }
return { return {
filepath: filepath, filepath,
dirname: _path().default.dirname(filepath), dirname: _path().default.dirname(filepath),
options: options options
}; };
}); });

View File

@@ -9,9 +9,9 @@ exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset; exports.loadPreset = loadPreset;
function _debug() { function _debug() {
var data = _interopRequireDefault(require("debug")); const data = _interopRequireDefault(require("debug"));
_debug = function _debug() { _debug = function () {
return data; return data;
}; };
@@ -19,9 +19,9 @@ function _debug() {
} }
function _resolve() { function _resolve() {
var data = _interopRequireDefault(require("resolve")); const data = _interopRequireDefault(require("resolve"));
_resolve = function _resolve() { _resolve = function () {
return data; return data;
}; };
@@ -29,9 +29,9 @@ function _resolve() {
} }
function _path() { function _path() {
var data = _interopRequireDefault(require("path")); const data = _interopRequireDefault(require("path"));
_path = function _path() { _path = function () {
return data; return data;
}; };
@@ -40,14 +40,15 @@ function _path() {
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var debug = (0, _debug().default)("babel:config:loading:files:plugins"); const debug = (0, _debug().default)("babel:config:loading:files:plugins");
var EXACT_RE = /^module:/; const EXACT_RE = /^module:/;
var BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
var BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
var BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
var BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
var OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-plugin-|[^/]+\/)/; const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
var OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-preset-|[^/]+\/)/; const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
function resolvePlugin(name, dirname) { function resolvePlugin(name, dirname) {
return resolveStandardizedName("plugin", name, dirname); return resolveStandardizedName("plugin", name, dirname);
@@ -58,47 +59,43 @@ function resolvePreset(name, dirname) {
} }
function loadPlugin(name, dirname) { function loadPlugin(name, dirname) {
var filepath = resolvePlugin(name, dirname); const filepath = resolvePlugin(name, dirname);
if (!filepath) { if (!filepath) {
throw new Error("Plugin " + name + " not found relative to " + dirname); throw new Error(`Plugin ${name} not found relative to ${dirname}`);
} }
var value = requireModule("plugin", filepath); const value = requireModule("plugin", filepath);
debug("Loaded plugin %o from %o.", name, dirname); debug("Loaded plugin %o from %o.", name, dirname);
return { return {
filepath: filepath, filepath,
value: value value
}; };
} }
function loadPreset(name, dirname) { function loadPreset(name, dirname) {
var filepath = resolvePreset(name, dirname); const filepath = resolvePreset(name, dirname);
if (!filepath) { if (!filepath) {
throw new Error("Preset " + name + " not found relative to " + dirname); throw new Error(`Preset ${name} not found relative to ${dirname}`);
} }
var value = requireModule("preset", filepath); const value = requireModule("preset", filepath);
debug("Loaded preset %o from %o.", name, dirname); debug("Loaded preset %o from %o.", name, dirname);
return { return {
filepath: filepath, filepath,
value: value value
}; };
} }
function standardizeName(type, name) { function standardizeName(type, name) {
if (_path().default.isAbsolute(name)) return name; if (_path().default.isAbsolute(name)) return name;
var isPreset = type === "preset"; 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(EXACT_RE, ""); 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) { function resolveStandardizedName(type, name, dirname = process.cwd()) {
if (dirname === void 0) { const standardizedName = standardizeName(type, name);
dirname = process.cwd();
}
var standardizedName = standardizeName(type, name);
try { try {
return _resolve().default.sync(standardizedName, { return _resolve().default.sync(standardizedName, {
@@ -108,7 +105,7 @@ function resolveStandardizedName(type, name, dirname) {
if (e.code !== "MODULE_NOT_FOUND") throw e; if (e.code !== "MODULE_NOT_FOUND") throw e;
if (standardizedName !== name) { if (standardizedName !== name) {
var resolvedOriginal = false; let resolvedOriginal = false;
try { try {
_resolve().default.sync(name, { _resolve().default.sync(name, {
@@ -119,11 +116,11 @@ function resolveStandardizedName(type, name, dirname) {
} catch (e2) {} } catch (e2) {}
if (resolvedOriginal) { if (resolvedOriginal) {
e.message += "\n- If you want to resolve \"" + name + "\", use \"module:" + name + "\""; e.message += `\n- If you want to resolve "${name}", use "module:${name}"`;
} }
} }
var resolvedBabel = false; let resolvedBabel = false;
try { try {
_resolve().default.sync(standardizeName(type, "@babel/" + name), { _resolve().default.sync(standardizeName(type, "@babel/" + name), {
@@ -134,11 +131,11 @@ function resolveStandardizedName(type, name, dirname) {
} catch (e2) {} } catch (e2) {}
if (resolvedBabel) { if (resolvedBabel) {
e.message += "\n- Did you mean \"@babel/" + name + "\"?"; e.message += `\n- Did you mean "@babel/${name}"?`;
} }
var resolvedOppositeType = false; let resolvedOppositeType = false;
var oppositeType = type === "preset" ? "plugin" : "preset"; const oppositeType = type === "preset" ? "plugin" : "preset";
try { try {
_resolve().default.sync(standardizeName(oppositeType, name), { _resolve().default.sync(standardizeName(oppositeType, name), {
@@ -149,18 +146,18 @@ function resolveStandardizedName(type, name, dirname) {
} catch (e2) {} } catch (e2) {}
if (resolvedOppositeType) { if (resolvedOppositeType) {
e.message += "\n- Did you accidentally pass a " + type + " as a " + oppositeType + "?"; e.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;
} }
throw e; throw e;
} }
} }
var LOADING_MODULES = new Set(); const LOADING_MODULES = new Set();
function requireModule(type, name) { function requireModule(type, name) {
if (LOADING_MODULES.has(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.'); 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 { try {

View File

@@ -1 +0,0 @@
"use strict";

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.makeStaticFileCache = makeStaticFileCache; exports.makeStaticFileCache = makeStaticFileCache;
function _fs() { function _fs() {
var data = _interopRequireDefault(require("fs")); const data = _interopRequireDefault(require("fs"));
_fs = function _fs() { _fs = function () {
return data; return data;
}; };
@@ -20,10 +20,8 @@ var _caching = require("../caching");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function makeStaticFileCache(fn) { function makeStaticFileCache(fn) {
return (0, _caching.makeStrongCache)(function (filepath, cache) { return (0, _caching.makeStrongCache)((filepath, cache) => {
if (cache.invalidate(function () { if (cache.invalidate(() => fileMtime(filepath)) === null) {
return fileMtime(filepath);
}) === null) {
cache.forever(); cache.forever();
return null; return null;
} }

View File

@@ -16,9 +16,9 @@ var _item = require("./item");
var _configChain = require("./config-chain"); var _configChain = require("./config-chain");
function _traverse() { function _traverse() {
var data = _interopRequireDefault(require("@babel/traverse")); const data = _interopRequireDefault(require("@babel/traverse"));
_traverse = function _traverse() { _traverse = function () {
return data; return data;
}; };
@@ -40,78 +40,74 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
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 _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) { function loadFullConfig(inputOpts) {
var result = (0, _partial.default)(inputOpts); const result = (0, _partial.default)(inputOpts);
if (!result) { if (!result) {
return null; return null;
} }
var options = result.options, const {
context = result.context; options,
var optionDefaults = {}; context
var passes = [[]]; } = result;
const optionDefaults = {};
const passes = [[]];
try { try {
var plugins = options.plugins, const {
presets = options.presets; plugins,
presets
} = options;
if (!plugins || !presets) { if (!plugins || !presets) {
throw new Error("Assertion failure - plugins and presets exist"); throw new Error("Assertion failure - plugins and presets exist");
} }
var ignored = function recurseDescriptors(config, pass) { const ignored = function recurseDescriptors(config, pass) {
var plugins = config.plugins.map(function (descriptor) { const plugins = config.plugins.reduce((acc, descriptor) => {
return loadPluginDescriptor(descriptor, context); if (descriptor.options !== false) {
}); acc.push(loadPluginDescriptor(descriptor, context));
var presets = config.presets.map(function (descriptor) {
return {
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass
};
});
if (presets.length > 0) {
passes.splice.apply(passes, [1, 0].concat(presets.map(function (o) {
return o.pass;
}).filter(function (p) {
return p !== pass;
})));
for (var _iterator = presets, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref2;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
} }
var _ref3 = _ref2; return acc;
var preset = _ref3.preset, }, []);
_pass = _ref3.pass; const presets = config.presets.reduce((acc, descriptor) => {
if (!preset) return true; if (descriptor.options !== false) {
acc.push({
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass
});
}
var _ignored = recurseDescriptors({ 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, plugins: preset.plugins,
presets: preset.presets presets: preset.presets
}, _pass); }, pass);
if (ignored) return true;
if (_ignored) return true; preset.options.forEach(opts => {
preset.options.forEach(function (opts) {
(0, _util.mergeOptions)(optionDefaults, opts); (0, _util.mergeOptions)(optionDefaults, opts);
}); });
} }
} }
if (plugins.length > 0) { if (plugins.length > 0) {
pass.unshift.apply(pass, plugins); pass.unshift(...plugins);
} }
}({ }({
plugins: plugins.map(function (item) { plugins: plugins.map(item => {
var desc = (0, _item.getItemDescriptor)(item); const desc = (0, _item.getItemDescriptor)(item);
if (!desc) { if (!desc) {
throw new Error("Assertion failure - must be config item"); throw new Error("Assertion failure - must be config item");
@@ -119,8 +115,8 @@ function loadFullConfig(inputOpts) {
return desc; return desc;
}), }),
presets: presets.map(function (item) { presets: presets.map(item => {
var desc = (0, _item.getItemDescriptor)(item); const desc = (0, _item.getItemDescriptor)(item);
if (!desc) { if (!desc) {
throw new Error("Assertion failure - must be config item"); throw new Error("Assertion failure - must be config item");
@@ -133,22 +129,18 @@ function loadFullConfig(inputOpts) {
if (ignored) return null; if (ignored) return null;
} catch (e) { } catch (e) {
if (!/^\[BABEL\]/.test(e.message)) { if (!/^\[BABEL\]/.test(e.message)) {
e.message = "[BABEL] " + (context.filename || "unknown") + ": " + e.message; e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
} }
throw e; throw e;
} }
var opts = optionDefaults; const opts = optionDefaults;
(0, _util.mergeOptions)(opts, options); (0, _util.mergeOptions)(opts, options);
opts.plugins = passes[0]; opts.plugins = passes[0];
opts.presets = passes.slice(1).filter(function (plugins) { opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({
return plugins.length > 0; plugins
}).map(function (plugins) { }));
return {
plugins: plugins
};
});
opts.passPerPreset = opts.presets.length > 0; opts.passPerPreset = opts.presets.length > 0;
return { return {
options: opts, options: opts,
@@ -156,23 +148,24 @@ function loadFullConfig(inputOpts) {
}; };
} }
var loadDescriptor = (0, _caching.makeWeakCache)(function (_ref4, cache) { const loadDescriptor = (0, _caching.makeWeakCache)(({
var value = _ref4.value, value,
options = _ref4.options, options,
dirname = _ref4.dirname, dirname,
alias = _ref4.alias; alias
}, cache) => {
if (options === false) throw new Error("Assertion failure"); if (options === false) throw new Error("Assertion failure");
options = options || {}; options = options || {};
var item = value; let item = value;
if (typeof value === "function") { if (typeof value === "function") {
var api = Object.assign({}, context, (0, _configApi.default)(cache)); const api = Object.assign({}, context, (0, _configApi.default)(cache));
try { try {
item = value(api, options, dirname); item = value(api, options, dirname);
} catch (e) { } catch (e) {
if (alias) { if (alias) {
e.message += " (While processing: " + JSON.stringify(alias) + ")"; e.message += ` (While processing: ${JSON.stringify(alias)})`;
} }
throw e; throw e;
@@ -184,14 +177,14 @@ var loadDescriptor = (0, _caching.makeWeakCache)(function (_ref4, cache) {
} }
if (typeof item.then === "function") { 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."); 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 { return {
value: item, value: item,
options: options, options,
dirname: dirname, dirname,
alias: alias alias
}; };
}); });
@@ -207,29 +200,28 @@ function loadPluginDescriptor(descriptor, context) {
return instantiatePlugin(loadDescriptor(descriptor, context), context); return instantiatePlugin(loadDescriptor(descriptor, context), context);
} }
var instantiatePlugin = (0, _caching.makeWeakCache)(function (_ref5, cache) { const instantiatePlugin = (0, _caching.makeWeakCache)(({
var value = _ref5.value, value,
options = _ref5.options, options,
dirname = _ref5.dirname, dirname,
alias = _ref5.alias; alias
var pluginObj = (0, _plugins.validatePluginObject)(value); }, cache) => {
var plugin = Object.assign({}, pluginObj); const pluginObj = (0, _plugins.validatePluginObject)(value);
const plugin = Object.assign({}, pluginObj);
if (plugin.visitor) { if (plugin.visitor) {
plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor)); plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor));
} }
if (plugin.inherits) { if (plugin.inherits) {
var inheritsDescriptor = { const inheritsDescriptor = {
name: undefined, name: undefined,
alias: alias + "$inherits", alias: `${alias}$inherits`,
value: plugin.inherits, value: plugin.inherits,
options: options, options,
dirname: dirname dirname
}; };
var inherits = cache.invalidate(function (data) { const inherits = cache.invalidate(data => loadPluginDescriptor(inheritsDescriptor, data));
return loadPluginDescriptor(inheritsDescriptor, data);
});
plugin.pre = chain(inherits.pre, plugin.pre); plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post); plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions);
@@ -239,42 +231,27 @@ var instantiatePlugin = (0, _caching.makeWeakCache)(function (_ref5, cache) {
return new _plugin.default(plugin, options, alias); return new _plugin.default(plugin, options, alias);
}); });
var loadPresetDescriptor = function loadPresetDescriptor(descriptor, context) { const loadPresetDescriptor = (descriptor, context) => {
return (0, _configChain.buildPresetChain)(instantiatePreset(loadDescriptor(descriptor, context)), context); return (0, _configChain.buildPresetChain)(instantiatePreset(loadDescriptor(descriptor, context)), context);
}; };
var instantiatePreset = (0, _caching.makeWeakCache)(function (_ref6) { const instantiatePreset = (0, _caching.makeWeakCache)(({
var value = _ref6.value, value,
dirname = _ref6.dirname, dirname,
alias = _ref6.alias; alias
}) => {
return { return {
options: (0, _options.validate)("preset", value), options: (0, _options.validate)("preset", value),
alias: alias, alias,
dirname: dirname dirname
}; };
}); });
function chain(a, b) { function chain(a, b) {
var fns = [a, b].filter(Boolean); const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0]; if (fns.length <= 1) return fns[0];
return function () { return function (...args) {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { for (const fn of fns) {
args[_key] = arguments[_key];
}
for (var _iterator2 = fns, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref7;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref7 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref7 = _i2.value;
}
var fn = _ref7;
fn.apply(this, args); fn.apply(this, args);
} }
}; };

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = makeAPI; exports.default = makeAPI;
function _semver() { function _semver() {
var data = _interopRequireDefault(require("semver")); const data = _interopRequireDefault(require("semver"));
_semver = function _semver() { _semver = function () {
return data; return data;
}; };
@@ -17,15 +17,20 @@ function _semver() {
var _ = require("../../"); var _ = require("../../");
var _caching = require("../caching");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function makeAPI(cache) { function makeAPI(cache) {
var env = function env(value) { const env = value => cache.using(data => {
return cache.using(function (data) {
if (typeof value === "undefined") return data.envName; if (typeof value === "undefined") return data.envName;
if (typeof value === "function") return value(data.envName);
if (typeof value === "function") {
return (0, _caching.assertSimpleType)(value(data.envName));
}
if (!Array.isArray(value)) value = [value]; if (!Array.isArray(value)) value = [value];
return value.some(function (entry) { return value.some(entry => {
if (typeof entry !== "string") { if (typeof entry !== "string") {
throw new Error("Unexpected non-string value"); throw new Error("Unexpected non-string value");
} }
@@ -33,16 +38,17 @@ function makeAPI(cache) {
return entry === data.envName; return entry === data.envName;
}); });
}); });
};
const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller)));
return { return {
version: _.version, version: _.version,
cache: cache.simple(), cache: cache.simple(),
env: env, env,
async: function async() { async: () => false,
return false; caller,
}, assertVersion,
assertVersion: assertVersion tokTypes: undefined
}; };
} }
@@ -52,7 +58,7 @@ function assertVersion(range) {
throw new Error("Expected string or integer value."); throw new Error("Expected string or integer value.");
} }
range = "^" + range + ".0.0-0"; range = `^${range}.0.0-0`;
} }
if (typeof range !== "string") { if (typeof range !== "string") {
@@ -60,13 +66,13 @@ function assertVersion(range) {
} }
if (_semver().default.satisfies(_.version, range)) return; if (_semver().default.satisfies(_.version, range)) return;
var limit = Error.stackTraceLimit; const limit = Error.stackTraceLimit;
if (typeof limit === "number" && limit < 25) { if (typeof limit === "number" && limit < 25) {
Error.stackTraceLimit = 25; Error.stackTraceLimit = 25;
} }
var 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."); 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") { if (typeof limit === "number") {
Error.stackTraceLimit = limit; Error.stackTraceLimit = limit;
@@ -75,6 +81,6 @@ function assertVersion(range) {
throw Object.assign(err, { throw Object.assign(err, {
code: "BABEL_VERSION_UNSUPPORTED", code: "BABEL_VERSION_UNSUPPORTED",
version: _.version, version: _.version,
range: range range
}); });
} }

View File

@@ -5,10 +5,6 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.getEnv = getEnv; exports.getEnv = getEnv;
function getEnv(defaultValue) { function getEnv(defaultValue = "development") {
if (defaultValue === void 0) {
defaultValue = "development";
}
return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;
} }

View File

@@ -6,17 +6,16 @@ Object.defineProperty(exports, "__esModule", {
exports.loadOptions = loadOptions; exports.loadOptions = loadOptions;
Object.defineProperty(exports, "default", { Object.defineProperty(exports, "default", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _full.default; return _full.default;
} }
}); });
Object.defineProperty(exports, "loadPartialConfig", { Object.defineProperty(exports, "loadPartialConfig", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _partial.loadPartialConfig; return _partial.loadPartialConfig;
} }
}); });
exports.OptionManager = void 0;
var _full = _interopRequireDefault(require("./full")); var _full = _interopRequireDefault(require("./full"));
@@ -25,20 +24,6 @@ var _partial = require("./partial");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function loadOptions(opts) { function loadOptions(opts) {
var config = (0, _full.default)(opts); const config = (0, _full.default)(opts);
return config ? config.options : null; return config ? config.options : null;
} }
var OptionManager = function () {
function OptionManager() {}
var _proto = OptionManager.prototype;
_proto.init = function init(opts) {
return loadOptions(opts);
};
return OptionManager;
}();
exports.OptionManager = OptionManager;

View File

@@ -8,9 +8,9 @@ exports.createConfigItem = createConfigItem;
exports.getItemDescriptor = getItemDescriptor; exports.getItemDescriptor = getItemDescriptor;
function _path() { function _path() {
var data = _interopRequireDefault(require("path")); const data = _interopRequireDefault(require("path"));
_path = function _path() { _path = function () {
return data; return data;
}; };
@@ -25,14 +25,12 @@ function createItemFromDescriptor(desc) {
return new ConfigItem(desc); return new ConfigItem(desc);
} }
function createConfigItem(value, _temp) { function createConfigItem(value, {
var _ref = _temp === void 0 ? {} : _temp, dirname = ".",
_ref$dirname = _ref.dirname, type
dirname = _ref$dirname === void 0 ? "." : _ref$dirname, } = {}) {
type = _ref.type; const descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), {
type,
var descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), {
type: type,
alias: "programmatic item" alias: "programmatic item"
}); });
return createItemFromDescriptor(descriptor); return createItemFromDescriptor(descriptor);
@@ -46,16 +44,12 @@ function getItemDescriptor(item) {
return undefined; return undefined;
} }
var ConfigItem = function ConfigItem(descriptor) { class ConfigItem {
constructor(descriptor) {
this._descriptor = descriptor; this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", { Object.defineProperty(this, "_descriptor", {
enumerable: false enumerable: false
}); });
if (this._descriptor.options === false) {
throw new Error("Assertion failure - unexpected false options");
}
this.value = this._descriptor.value; this.value = this._descriptor.value;
this.options = this._descriptor.options; this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname; this.dirname = this._descriptor.dirname;
@@ -65,6 +59,8 @@ var ConfigItem = function ConfigItem(descriptor) {
resolved: this._descriptor.file.resolved resolved: this._descriptor.file.resolved
} : undefined; } : undefined;
Object.freeze(this); Object.freeze(this);
}; }
}
Object.freeze(ConfigItem.prototype); Object.freeze(ConfigItem.prototype);

View File

@@ -7,9 +7,9 @@ exports.default = loadPrivatePartialConfig;
exports.loadPartialConfig = loadPartialConfig; exports.loadPartialConfig = loadPartialConfig;
function _path() { function _path() {
var data = _interopRequireDefault(require("path")); const data = _interopRequireDefault(require("path"));
_path = function _path() { _path = function () {
return data; return data;
}; };
@@ -28,45 +28,78 @@ var _environment = require("./helpers/environment");
var _options = require("./validation/options"); var _options = require("./validation/options");
var _files = require("./files");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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) { function loadPrivatePartialConfig(inputOpts) {
if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) { if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) {
throw new Error("Babel options must be an object, null, or undefined"); throw new Error("Babel options must be an object, null, or undefined");
} }
var args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {}; const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {};
var _args$envName = args.envName, const {
envName = _args$envName === void 0 ? (0, _environment.getEnv)() : _args$envName, envName = (0, _environment.getEnv)(),
_args$cwd = args.cwd, cwd = ".",
cwd = _args$cwd === void 0 ? "." : _args$cwd; root: rootDir = ".",
rootMode = "root",
caller
} = args;
var absoluteCwd = _path().default.resolve(cwd); const absoluteCwd = _path().default.resolve(cwd);
var context = { const absoluteRootDir = resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode);
filename: args.filename ? _path().default.resolve(cwd, args.filename) : null, const context = {
filename: typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined,
cwd: absoluteCwd, cwd: absoluteCwd,
envName: envName root: absoluteRootDir,
envName,
caller
}; };
var configChain = (0, _configChain.buildRootChain)(args, context); const configChain = (0, _configChain.buildRootChain)(args, context);
if (!configChain) return null; if (!configChain) return null;
var options = {}; const options = {};
configChain.options.forEach(function (opts) { configChain.options.forEach(opts => {
(0, _util.mergeOptions)(options, opts); (0, _util.mergeOptions)(options, opts);
}); });
options.babelrc = false; options.babelrc = false;
options.envName = envName; options.configFile = false;
options.cwd = absoluteCwd;
options.passPerPreset = false; options.passPerPreset = false;
options.plugins = configChain.plugins.map(function (descriptor) { options.envName = context.envName;
return (0, _item.createItemFromDescriptor)(descriptor); options.cwd = context.cwd;
}); options.root = context.root;
options.presets = configChain.presets.map(function (descriptor) { options.filename = typeof context.filename === "string" ? context.filename : undefined;
return (0, _item.createItemFromDescriptor)(descriptor); options.plugins = configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
}); options.presets = configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
return { return {
options: options, options,
context: context, context,
ignore: configChain.ignore, ignore: configChain.ignore,
babelrc: configChain.babelrc, babelrc: configChain.babelrc,
config: configChain.config config: configChain.config
@@ -74,13 +107,15 @@ function loadPrivatePartialConfig(inputOpts) {
} }
function loadPartialConfig(inputOpts) { function loadPartialConfig(inputOpts) {
var result = loadPrivatePartialConfig(inputOpts); const result = loadPrivatePartialConfig(inputOpts);
if (!result) return null; if (!result) return null;
var options = result.options, const {
babelrc = result.babelrc, options,
ignore = result.ignore, babelrc,
config = result.config; ignore,
(options.plugins || []).forEach(function (item) { config
} = result;
(options.plugins || []).forEach(item => {
if (item.value instanceof _plugin.default) { if (item.value instanceof _plugin.default) {
throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()");
} }
@@ -88,8 +123,8 @@ function loadPartialConfig(inputOpts) {
return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined); return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined);
} }
var PartialConfig = function () { class PartialConfig {
function PartialConfig(options, babelrc, ignore, config) { constructor(options, babelrc, ignore, config) {
this.options = options; this.options = options;
this.babelignore = ignore; this.babelignore = ignore;
this.babelrc = babelrc; this.babelrc = babelrc;
@@ -97,13 +132,10 @@ var PartialConfig = function () {
Object.freeze(this); Object.freeze(this);
} }
var _proto = PartialConfig.prototype; hasFilesystemConfig() {
_proto.hasFilesystemConfig = function hasFilesystemConfig() {
return this.babelrc !== undefined || this.config !== undefined; return this.babelrc !== undefined || this.config !== undefined;
}; }
return PartialConfig; }
}();
Object.freeze(PartialConfig.prototype); Object.freeze(PartialConfig.prototype);

View File

@@ -0,0 +1,52 @@
"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(""));
}

View File

@@ -5,7 +5,8 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = void 0; exports.default = void 0;
var Plugin = function Plugin(plugin, options, key) { class Plugin {
constructor(plugin, options, key) {
this.key = plugin.name || key; this.key = plugin.name || key;
this.manipulateOptions = plugin.manipulateOptions; this.manipulateOptions = plugin.manipulateOptions;
this.post = plugin.post; this.post = plugin.post;
@@ -14,6 +15,8 @@ var Plugin = function Plugin(plugin, options, key) {
this.parserOverride = plugin.parserOverride; this.parserOverride = plugin.parserOverride;
this.generatorOverride = plugin.generatorOverride; this.generatorOverride = plugin.generatorOverride;
this.options = options; this.options = options;
}; }
}
exports.default = Plugin; exports.default = Plugin;

View File

@@ -6,34 +6,25 @@ Object.defineProperty(exports, "__esModule", {
exports.mergeOptions = mergeOptions; exports.mergeOptions = mergeOptions;
function mergeOptions(target, source) { function mergeOptions(target, source) {
var _arr = Object.keys(source); for (const k of Object.keys(source)) {
for (var _i = 0; _i < _arr.length; _i++) {
var k = _arr[_i];
if (k === "parserOpts" && source.parserOpts) { if (k === "parserOpts" && source.parserOpts) {
var parserOpts = source.parserOpts; const parserOpts = source.parserOpts;
var targetObj = target.parserOpts = target.parserOpts || {}; const targetObj = target.parserOpts = target.parserOpts || {};
mergeDefaultFields(targetObj, parserOpts); mergeDefaultFields(targetObj, parserOpts);
} else if (k === "generatorOpts" && source.generatorOpts) { } else if (k === "generatorOpts" && source.generatorOpts) {
var generatorOpts = source.generatorOpts; const generatorOpts = source.generatorOpts;
const targetObj = target.generatorOpts = target.generatorOpts || {};
var _targetObj = target.generatorOpts = target.generatorOpts || {}; mergeDefaultFields(targetObj, generatorOpts);
mergeDefaultFields(_targetObj, generatorOpts);
} else { } else {
var val = source[k]; const val = source[k];
if (val !== undefined) target[k] = val; if (val !== undefined) target[k] = val;
} }
} }
} }
function mergeDefaultFields(target, source) { function mergeDefaultFields(target, source) {
var _arr2 = Object.keys(source); for (const k of Object.keys(source)) {
const val = source[k];
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var k = _arr2[_i2];
var val = source[k];
if (val !== undefined) target[k] = val; if (val !== undefined) target[k] = val;
} }
} }

View File

@@ -3,9 +3,13 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.msg = msg;
exports.access = access;
exports.assertRootMode = assertRootMode;
exports.assertSourceMaps = assertSourceMaps; exports.assertSourceMaps = assertSourceMaps;
exports.assertCompact = assertCompact; exports.assertCompact = assertCompact;
exports.assertSourceType = assertSourceType; exports.assertSourceType = assertSourceType;
exports.assertCallerMetadata = assertCallerMetadata;
exports.assertInputSourceMap = assertInputSourceMap; exports.assertInputSourceMap = assertInputSourceMap;
exports.assertString = assertString; exports.assertString = assertString;
exports.assertFunction = assertFunction; exports.assertFunction = assertFunction;
@@ -18,109 +22,166 @@ exports.assertConfigFileSearch = assertConfigFileSearch;
exports.assertBabelrcSearch = assertBabelrcSearch; exports.assertBabelrcSearch = assertBabelrcSearch;
exports.assertPluginList = assertPluginList; exports.assertPluginList = assertPluginList;
function assertSourceMaps(key, value) { 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") { if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") {
throw new Error("." + key + " must be a boolean, \"inline\", \"both\", or undefined"); throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`);
} }
return value; return value;
} }
function assertCompact(key, value) { function assertCompact(loc, value) {
if (value !== undefined && typeof value !== "boolean" && value !== "auto") { if (value !== undefined && typeof value !== "boolean" && value !== "auto") {
throw new Error("." + key + " must be a boolean, \"auto\", or undefined"); throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`);
} }
return value; return value;
} }
function assertSourceType(key, value) { function assertSourceType(loc, value) {
if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") { if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") {
throw new Error("." + key + " must be \"module\", \"script\", \"unambiguous\", or undefined"); throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`);
} }
return value; return value;
} }
function assertInputSourceMap(key, 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)) { if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) {
throw new Error(".inputSourceMap must be a boolean, object, or undefined"); throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);
} }
return value; return value;
} }
function assertString(key, value) { function assertString(loc, value) {
if (value !== undefined && typeof value !== "string") { if (value !== undefined && typeof value !== "string") {
throw new Error("." + key + " must be a string, or undefined"); throw new Error(`${msg(loc)} must be a string, or undefined`);
} }
return value; return value;
} }
function assertFunction(key, value) { function assertFunction(loc, value) {
if (value !== undefined && typeof value !== "function") { if (value !== undefined && typeof value !== "function") {
throw new Error("." + key + " must be a function, or undefined"); throw new Error(`${msg(loc)} must be a function, or undefined`);
} }
return value; return value;
} }
function assertBoolean(key, value) { function assertBoolean(loc, value) {
if (value !== undefined && typeof value !== "boolean") { if (value !== undefined && typeof value !== "boolean") {
throw new Error("." + key + " must be a boolean, or undefined"); throw new Error(`${msg(loc)} must be a boolean, or undefined`);
} }
return value; return value;
} }
function assertObject(key, value) { function assertObject(loc, value) {
if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) { if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) {
throw new Error("." + key + " must be an object, or undefined"); throw new Error(`${msg(loc)} must be an object, or undefined`);
} }
return value; return value;
} }
function assertArray(key, value) { function assertArray(loc, value) {
if (value != null && !Array.isArray(value)) { if (value != null && !Array.isArray(value)) {
throw new Error("." + key + " must be an array, or undefined"); throw new Error(`${msg(loc)} must be an array, or undefined`);
} }
return value; return value;
} }
function assertIgnoreList(key, value) { function assertIgnoreList(loc, value) {
var arr = assertArray(key, value); const arr = assertArray(loc, value);
if (arr) { if (arr) {
arr.forEach(function (item, i) { arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item));
return assertIgnoreItem(key, i, item);
});
} }
return arr; return arr;
} }
function assertIgnoreItem(key, index, value) { function assertIgnoreItem(loc, value) {
if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) {
throw new Error("." + key + "[" + index + "] must be an array of string/Funtion/RegExp values, or undefined"); throw new Error(`${msg(loc)} must be an array of string/Funtion/RegExp values, or undefined`);
} }
return value; return value;
} }
function assertConfigApplicableTest(key, value) { function assertConfigApplicableTest(loc, value) {
if (value === undefined) return value; if (value === undefined) return value;
if (Array.isArray(value)) { if (Array.isArray(value)) {
value.forEach(function (item, i) { value.forEach((item, i) => {
if (!checkValidTest(item)) { if (!checkValidTest(item)) {
throw new Error("." + key + "[" + i + "] must be a string/Function/RegExp."); throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`);
} }
}); });
} else if (!checkValidTest(value)) { } else if (!checkValidTest(value)) {
throw new Error("." + key + " must be a string/Function/RegExp, or an array of those"); throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`);
} }
return value; return value;
@@ -130,79 +191,77 @@ function checkValidTest(value) {
return typeof value === "string" || typeof value === "function" || value instanceof RegExp; return typeof value === "string" || typeof value === "function" || value instanceof RegExp;
} }
function assertConfigFileSearch(key, value) { function assertConfigFileSearch(loc, value) {
if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") {
throw new Error("." + key + " must be a undefined, a boolean, a string, " + ("got " + JSON.stringify(value))); throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`);
} }
return value; return value;
} }
function assertBabelrcSearch(key, value) { function assertBabelrcSearch(loc, value) {
if (value === undefined || typeof value === "boolean") return value; if (value === undefined || typeof value === "boolean") return value;
if (Array.isArray(value)) { if (Array.isArray(value)) {
value.forEach(function (item, i) { value.forEach((item, i) => {
if (typeof item !== "string") { if (!checkValidTest(item)) {
throw new Error("." + key + "[" + i + "] must be a string."); throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`);
} }
}); });
} else if (typeof value !== "string") { } else if (!checkValidTest(value)) {
throw new Error("." + key + " must be a undefined, a boolean, a string, " + ("or an array of strings, got " + JSON.stringify(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; return value;
} }
function assertPluginList(key, value) { function assertPluginList(loc, value) {
var arr = assertArray(key, value); const arr = assertArray(loc, value);
if (arr) { if (arr) {
arr.forEach(function (item, i) { arr.forEach((item, i) => assertPluginItem(access(loc, i), item));
return assertPluginItem(key, i, item);
});
} }
return arr; return arr;
} }
function assertPluginItem(key, index, value) { function assertPluginItem(loc, value) {
if (Array.isArray(value)) { if (Array.isArray(value)) {
if (value.length === 0) { if (value.length === 0) {
throw new Error("." + key + "[" + index + "] must include an object"); throw new Error(`${msg(loc)} must include an object`);
} }
if (value.length > 3) { if (value.length > 3) {
throw new Error("." + key + "[" + index + "] may only be a two-tuple or three-tuple"); throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);
} }
assertPluginTarget(key, index, true, value[0]); assertPluginTarget(access(loc, 0), value[0]);
if (value.length > 1) { if (value.length > 1) {
var opts = value[1]; const opts = value[1];
if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts))) { if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts))) {
throw new Error("." + key + "[" + index + "][1] must be an object, false, or undefined"); throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`);
} }
} }
if (value.length === 3) { if (value.length === 3) {
var name = value[2]; const name = value[2];
if (name !== undefined && typeof name !== "string") { if (name !== undefined && typeof name !== "string") {
throw new Error("." + key + "[" + index + "][2] must be a string, or undefined"); throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`);
} }
} }
} else { } else {
assertPluginTarget(key, index, false, value); assertPluginTarget(loc, value);
} }
return value; return value;
} }
function assertPluginTarget(key, index, inArray, value) { function assertPluginTarget(loc, value) {
if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") {
throw new Error("." + key + "[" + index + "]" + (inArray ? "[0]" : "") + " must be a string, object, function"); throw new Error(`${msg(loc)} must be a string, object, function`);
} }
return value; return value;

View File

@@ -13,33 +13,37 @@ var _optionAssertions = require("./option-assertions");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ROOT_VALIDATORS = { const ROOT_VALIDATORS = {
cwd: _optionAssertions.assertString, cwd: _optionAssertions.assertString,
root: _optionAssertions.assertString, root: _optionAssertions.assertString,
rootMode: _optionAssertions.assertRootMode,
configFile: _optionAssertions.assertConfigFileSearch, configFile: _optionAssertions.assertConfigFileSearch,
caller: _optionAssertions.assertCallerMetadata,
filename: _optionAssertions.assertString, filename: _optionAssertions.assertString,
filenameRelative: _optionAssertions.assertString, filenameRelative: _optionAssertions.assertString,
babelrc: _optionAssertions.assertBoolean,
babelrcRoots: _optionAssertions.assertBabelrcSearch,
code: _optionAssertions.assertBoolean, code: _optionAssertions.assertBoolean,
ast: _optionAssertions.assertBoolean, ast: _optionAssertions.assertBoolean,
envName: _optionAssertions.assertString envName: _optionAssertions.assertString
}; };
var NONPRESET_VALIDATORS = { const BABELRC_VALIDATORS = {
extends: _optionAssertions.assertString, babelrc: _optionAssertions.assertBoolean,
env: assertEnvSet, babelrcRoots: _optionAssertions.assertBabelrcSearch
ignore: _optionAssertions.assertIgnoreList,
only: _optionAssertions.assertIgnoreList,
overrides: assertOverridesList,
test: _optionAssertions.assertConfigApplicableTest,
include: _optionAssertions.assertConfigApplicableTest,
exclude: _optionAssertions.assertConfigApplicableTest
}; };
var COMMON_VALIDATORS = { const NONPRESET_VALIDATORS = {
extends: _optionAssertions.assertString,
ignore: _optionAssertions.assertIgnoreList,
only: _optionAssertions.assertIgnoreList
};
const COMMON_VALIDATORS = {
inputSourceMap: _optionAssertions.assertInputSourceMap, inputSourceMap: _optionAssertions.assertInputSourceMap,
presets: _optionAssertions.assertPluginList, presets: _optionAssertions.assertPluginList,
plugins: _optionAssertions.assertPluginList, plugins: _optionAssertions.assertPluginList,
passPerPreset: _optionAssertions.assertBoolean, passPerPreset: _optionAssertions.assertBoolean,
env: assertEnvSet,
overrides: assertOverridesList,
test: _optionAssertions.assertConfigApplicableTest,
include: _optionAssertions.assertConfigApplicableTest,
exclude: _optionAssertions.assertConfigApplicableTest,
retainLines: _optionAssertions.assertBoolean, retainLines: _optionAssertions.assertBoolean,
comments: _optionAssertions.assertBoolean, comments: _optionAssertions.assertBoolean,
shouldPrintComment: _optionAssertions.assertFunction, shouldPrintComment: _optionAssertions.assertFunction,
@@ -62,44 +66,60 @@ var COMMON_VALIDATORS = {
generatorOpts: _optionAssertions.assertObject generatorOpts: _optionAssertions.assertObject
}; };
function getSource(loc) {
return loc.type === "root" ? loc.source : getSource(loc.parent);
}
function validate(type, opts) { function validate(type, opts) {
return validateNested({
type: "root",
source: type
}, opts);
}
function validateNested(loc, opts) {
const type = getSource(loc);
assertNoDuplicateSourcemap(opts); assertNoDuplicateSourcemap(opts);
Object.keys(opts).forEach(function (key) { Object.keys(opts).forEach(key => {
const optLoc = {
type: "option",
name: key,
parent: loc
};
if (type === "preset" && NONPRESET_VALIDATORS[key]) { if (type === "preset" && NONPRESET_VALIDATORS[key]) {
throw new Error("." + key + " is not allowed in preset options"); throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in preset options`);
} }
if (type !== "arguments" && ROOT_VALIDATORS[key]) { if (type !== "arguments" && ROOT_VALIDATORS[key]) {
throw new Error("." + key + " is only allowed in root programmatic options"); throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`);
} }
if (type === "env" && key === "env") { if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) {
throw new Error("." + key + " is not allowed inside another env block"); 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`);
} }
if (type === "env" && key === "overrides") { throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`);
throw new Error("." + key + " is not allowed inside an env block");
} }
if (type === "override" && key === "overrides") { const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError;
throw new Error("." + key + " is not allowed inside an overrides block"); validator(optLoc, opts[key]);
}
var validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || ROOT_VALIDATORS[key];
if (validator) validator(key, opts[key]);else throw buildUnknownError(key);
}); });
return opts; return opts;
} }
function buildUnknownError(key) { function throwUnknownError(loc) {
const key = loc.name;
if (_removed.default[key]) { if (_removed.default[key]) {
var _removed$key = _removed.default[key], const {
message = _removed$key.message, message,
_removed$key$version = _removed$key.version, version = 5
version = _removed$key$version === void 0 ? 5 : _removed$key$version; } = _removed.default[key];
throw new ReferenceError("Using removed Babel " + version + " option: ." + key + " - " + message); throw new ReferenceError(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`);
} else { } else {
var unknownOptErr = "Unknown option: ." + key + ". Check out http://babeljs.io/docs/usage/options/ for more information about options."; 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); throw new ReferenceError(unknownOptErr);
} }
} }
@@ -114,48 +134,53 @@ function assertNoDuplicateSourcemap(opts) {
} }
} }
function assertEnvSet(key, value) { function assertEnvSet(loc, value) {
var obj = (0, _optionAssertions.assertObject)(key, 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) { if (obj) {
var _arr = Object.keys(obj); for (const envName of Object.keys(obj)) {
const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]);
for (var _i = 0; _i < _arr.length; _i++) { if (!env) continue;
var _key = _arr[_i]; const envLoc = {
type: "env",
var _env = (0, _optionAssertions.assertObject)(_key, obj[_key]); name: envName,
parent
if (_env) validate("env", _env); };
validateNested(envLoc, env);
} }
} }
return obj; return obj;
} }
function assertOverridesList(key, value) { function assertOverridesList(loc, value) {
var arr = (0, _optionAssertions.assertArray)(key, value); if (loc.parent.type === "env") {
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`);
if (arr) {
for (var _iterator = arr.entries(), _isArray = Array.isArray(_iterator), _i2 = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i2 >= _iterator.length) break;
_ref = _iterator[_i2++];
} else {
_i2 = _iterator.next();
if (_i2.done) break;
_ref = _i2.value;
} }
var _ref2 = _ref, if (loc.parent.type === "overrides") {
index = _ref2[0], throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`);
item = _ref2[1]; }
var _env2 = (0, _optionAssertions.assertObject)("" + index, item); const parent = loc.parent;
const arr = (0, _optionAssertions.assertArray)(loc, value);
if (!_env2) throw new Error("." + key + "[" + index + "] must be an object"); if (arr) {
validate("override", _env2); 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);
} }
} }

View File

@@ -7,7 +7,7 @@ exports.validatePluginObject = validatePluginObject;
var _optionAssertions = require("./option-assertions"); var _optionAssertions = require("./option-assertions");
var VALIDATORS = { const VALIDATORS = {
name: _optionAssertions.assertString, name: _optionAssertions.assertString,
manipulateOptions: _optionAssertions.assertFunction, manipulateOptions: _optionAssertions.assertFunction,
pre: _optionAssertions.assertFunction, pre: _optionAssertions.assertFunction,
@@ -19,15 +19,13 @@ var VALIDATORS = {
}; };
function assertVisitorMap(key, value) { function assertVisitorMap(key, value) {
var obj = (0, _optionAssertions.assertObject)(key, value); const obj = (0, _optionAssertions.assertObject)(key, value);
if (obj) { if (obj) {
Object.keys(obj).forEach(function (prop) { Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));
return assertVisitorHandler(prop, obj[prop]);
});
if (obj.enter || obj.exit) { if (obj.enter || obj.exit) {
throw new Error("." + key + " cannot contain catch-all \"enter\" or \"exit\" handlers. Please target individual nodes."); throw new Error(`.${key} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`);
} }
} }
@@ -36,22 +34,22 @@ function assertVisitorMap(key, value) {
function assertVisitorHandler(key, value) { function assertVisitorHandler(key, value) {
if (value && typeof value === "object") { if (value && typeof value === "object") {
Object.keys(value).forEach(function (handler) { Object.keys(value).forEach(handler => {
if (handler !== "enter" && handler !== "exit") { if (handler !== "enter" && handler !== "exit") {
throw new Error(".visitor[\"" + key + "\"] may only have .enter and/or .exit handlers."); throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`);
} }
}); });
} else if (typeof value !== "function") { } else if (typeof value !== "function") {
throw new Error(".visitor[\"" + key + "\"] must be a function"); throw new Error(`.visitor["${key}"] must be a function`);
} }
return value; return value;
} }
function validatePluginObject(obj) { function validatePluginObject(obj) {
Object.keys(obj).forEach(function (key) { Object.keys(obj).forEach(key => {
var validator = VALIDATORS[key]; const validator = VALIDATORS[key];
if (validator) validator(key, obj[key]);else throw new Error("." + key + " is not a valid Plugin property"); if (validator) validator(key, obj[key]);else throw new Error(`.${key} is not a valid Plugin property`);
}); });
return obj; return obj;
} }

163
node_modules/@babel/core/lib/index.js generated vendored
View File

@@ -6,119 +6,149 @@ Object.defineProperty(exports, "__esModule", {
exports.Plugin = Plugin; exports.Plugin = Plugin;
Object.defineProperty(exports, "File", { Object.defineProperty(exports, "File", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _file.default; return _file.default;
} }
}); });
Object.defineProperty(exports, "buildExternalHelpers", { Object.defineProperty(exports, "buildExternalHelpers", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _buildExternalHelpers.default; return _buildExternalHelpers.default;
} }
}); });
Object.defineProperty(exports, "resolvePlugin", { Object.defineProperty(exports, "resolvePlugin", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _files.resolvePlugin; return _files.resolvePlugin;
} }
}); });
Object.defineProperty(exports, "resolvePreset", { Object.defineProperty(exports, "resolvePreset", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _files.resolvePreset; return _files.resolvePreset;
} }
}); });
Object.defineProperty(exports, "version", { Object.defineProperty(exports, "version", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _package.version; return _package.version;
} }
}); });
Object.defineProperty(exports, "getEnv", { Object.defineProperty(exports, "getEnv", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _environment.getEnv; return _environment.getEnv;
} }
}); });
Object.defineProperty(exports, "tokTypes", {
enumerable: true,
get: function () {
return _parser().tokTypes;
}
});
Object.defineProperty(exports, "traverse", { Object.defineProperty(exports, "traverse", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _traverse().default; return _traverse().default;
} }
}); });
Object.defineProperty(exports, "template", { Object.defineProperty(exports, "template", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _template().default; return _template().default;
} }
}); });
Object.defineProperty(exports, "createConfigItem", {
enumerable: true,
get: function () {
return _item.createConfigItem;
}
});
Object.defineProperty(exports, "loadPartialConfig", { Object.defineProperty(exports, "loadPartialConfig", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _config.loadPartialConfig; return _config.loadPartialConfig;
} }
}); });
Object.defineProperty(exports, "loadOptions", { Object.defineProperty(exports, "loadOptions", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _config.loadOptions; return _config.loadOptions;
} }
}); });
Object.defineProperty(exports, "OptionManager", {
enumerable: true,
get: function get() {
return _config.OptionManager;
}
});
Object.defineProperty(exports, "createConfigItem", {
enumerable: true,
get: function get() {
return _item.createConfigItem;
}
});
Object.defineProperty(exports, "transform", { Object.defineProperty(exports, "transform", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _transform.default; return _transform.transform;
} }
}); });
Object.defineProperty(exports, "transformSync", { Object.defineProperty(exports, "transformSync", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _transformSync.default; return _transform.transformSync;
}
});
Object.defineProperty(exports, "transformAsync", {
enumerable: true,
get: function () {
return _transform.transformAsync;
} }
}); });
Object.defineProperty(exports, "transformFile", { Object.defineProperty(exports, "transformFile", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _transformFile.default; return _transformFile.transformFile;
} }
}); });
Object.defineProperty(exports, "transformFileSync", { Object.defineProperty(exports, "transformFileSync", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _transformFileSync.default; return _transformFile.transformFileSync;
}
});
Object.defineProperty(exports, "transformFileAsync", {
enumerable: true,
get: function () {
return _transformFile.transformFileAsync;
} }
}); });
Object.defineProperty(exports, "transformFromAst", { Object.defineProperty(exports, "transformFromAst", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _transformAst.default; return _transformAst.transformFromAst;
} }
}); });
Object.defineProperty(exports, "transformFromAstSync", { Object.defineProperty(exports, "transformFromAstSync", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _transformAstSync.default; return _transformAst.transformFromAstSync;
}
});
Object.defineProperty(exports, "transformFromAstAsync", {
enumerable: true,
get: function () {
return _transformAst.transformFromAstAsync;
} }
}); });
Object.defineProperty(exports, "parse", { Object.defineProperty(exports, "parse", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _parse.default; return _parse.parse;
} }
}); });
exports.types = exports.DEFAULT_EXTENSIONS = void 0; 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 _file = _interopRequireDefault(require("./transformation/file/file"));
@@ -131,9 +161,9 @@ var _package = require("../package.json");
var _environment = require("./config/helpers/environment"); var _environment = require("./config/helpers/environment");
function _types() { function _types() {
var data = _interopRequireWildcard(require("@babel/types")); const data = _interopRequireWildcard(require("@babel/types"));
_types = function _types() { _types = function () {
return data; return data;
}; };
@@ -142,15 +172,25 @@ function _types() {
Object.defineProperty(exports, "types", { Object.defineProperty(exports, "types", {
enumerable: true, enumerable: true,
get: function get() { get: function () {
return _types(); return _types();
} }
}); });
function _traverse() { function _parser() {
var data = _interopRequireDefault(require("@babel/traverse")); const data = require("@babel/parser");
_traverse = function _traverse() { _parser = function () {
return data;
};
return data;
}
function _traverse() {
const data = _interopRequireDefault(require("@babel/traverse"));
_traverse = function () {
return data; return data;
}; };
@@ -158,40 +198,43 @@ function _traverse() {
} }
function _template() { function _template() {
var data = _interopRequireDefault(require("@babel/template")); const data = _interopRequireDefault(require("@babel/template"));
_template = function _template() { _template = function () {
return data; return data;
}; };
return data; return data;
} }
var _config = require("./config");
var _item = require("./config/item"); var _item = require("./config/item");
var _transform = _interopRequireDefault(require("./transform")); var _config = require("./config");
var _transformSync = _interopRequireDefault(require("./transform-sync")); var _transform = require("./transform");
var _transformFile = _interopRequireDefault(require("./transform-file")); var _transformFile = require("./transform-file");
var _transformFileSync = _interopRequireDefault(require("./transform-file-sync")); var _transformAst = require("./transform-ast");
var _transformAst = _interopRequireDefault(require("./transform-ast")); var _parse = require("./parse");
var _transformAstSync = _interopRequireDefault(require("./transform-ast-sync"));
var _parse = _interopRequireDefault(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 _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 }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Plugin(alias) { const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]);
throw new Error("The (" + alias + ") Babel 5 plugin is being run with an unsupported Babel version."); exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
class OptionManager {
init(opts) {
return (0, _config.loadOptions)(opts);
}
} }
var DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]); exports.OptionManager = OptionManager;
exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
function Plugin(alias) {
throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`);
}

View File

@@ -3,7 +3,9 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = parse; exports.parseSync = parseSync;
exports.parseAsync = parseAsync;
exports.parse = void 0;
var _config = _interopRequireDefault(require("./config")); var _config = _interopRequireDefault(require("./config"));
@@ -13,13 +15,51 @@ var _normalizeOpts = _interopRequireDefault(require("./transformation/normalize-
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function parse(code, opts) { const parse = function parse(code, opts, callback) {
var config = (0, _config.default)(opts); if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (callback === undefined) return parseSync(code, opts);
const config = (0, _config.default)(opts);
if (config === null) { if (config === null) {
return null; return null;
} }
var file = (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code); const cb = callback;
return file.ast; 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);
});
});
} }

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = _default; exports.default = _default;
function helpers() { function helpers() {
var data = _interopRequireWildcard(require("@babel/helpers")); const data = _interopRequireWildcard(require("@babel/helpers"));
helpers = function helpers() { helpers = function () {
return data; return data;
}; };
@@ -16,9 +16,9 @@ function helpers() {
} }
function _generator() { function _generator() {
var data = _interopRequireDefault(require("@babel/generator")); const data = _interopRequireDefault(require("@babel/generator"));
_generator = function _generator() { _generator = function () {
return data; return data;
}; };
@@ -26,9 +26,9 @@ function _generator() {
} }
function _template() { function _template() {
var data = _interopRequireDefault(require("@babel/template")); const data = _interopRequireDefault(require("@babel/template"));
_template = function _template() { _template = function () {
return data; return data;
}; };
@@ -36,49 +36,55 @@ function _template() {
} }
function t() { function t() {
var data = _interopRequireWildcard(require("@babel/types")); const data = _interopRequireWildcard(require("@babel/types"));
t = function t() { t = function () {
return data; return data;
}; };
return data; return data;
} }
var _templateObject = _taggedTemplateLiteralLoose(["\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n "]);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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 _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 _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; } const buildUmdWrapper = replacements => _template().default`
(function (root, factory) {
var buildUmdWrapper = function buildUmdWrapper(replacements) { if (typeof define === "function" && define.amd) {
return (0, _template().default)(_templateObject)(replacements); 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) { function buildGlobal(whitelist) {
var namespace = t().identifier("babelHelpers"); const namespace = t().identifier("babelHelpers");
var body = []; const body = [];
var container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body)); const container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body));
var 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"))]))]); 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([])))])); body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))]));
buildHelpers(body, namespace, whitelist); buildHelpers(body, namespace, whitelist);
return tree; return tree;
} }
function buildModule(whitelist) { function buildModule(whitelist) {
var body = []; const body = [];
var refs = buildHelpers(body, null, whitelist); const refs = buildHelpers(body, null, whitelist);
body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(function (name) { body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(name => {
return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name)); return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name));
}))); })));
return t().program(body, [], "module"); return t().program(body, [], "module");
} }
function buildUmd(whitelist) { function buildUmd(whitelist) {
var namespace = t().identifier("babelHelpers"); const namespace = t().identifier("babelHelpers");
var body = []; const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))])); body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))]));
buildHelpers(body, namespace, whitelist); buildHelpers(body, namespace, whitelist);
return t().program([buildUmdWrapper({ return t().program([buildUmdWrapper({
@@ -92,40 +98,35 @@ function buildUmd(whitelist) {
} }
function buildVar(whitelist) { function buildVar(whitelist) {
var namespace = t().identifier("babelHelpers"); const namespace = t().identifier("babelHelpers");
var body = []; const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))])); body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))]));
var tree = t().program(body); const tree = t().program(body);
buildHelpers(body, namespace, whitelist); buildHelpers(body, namespace, whitelist);
body.push(t().expressionStatement(namespace)); body.push(t().expressionStatement(namespace));
return tree; return tree;
} }
function buildHelpers(body, namespace, whitelist) { function buildHelpers(body, namespace, whitelist) {
var getHelperReference = function getHelperReference(name) { const getHelperReference = name => {
return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier("_" + name); return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`);
}; };
var refs = {}; const refs = {};
helpers().list.forEach(function (name) { helpers().list.forEach(function (name) {
if (whitelist && whitelist.indexOf(name) < 0) return; if (whitelist && whitelist.indexOf(name) < 0) return;
var ref = refs[name] = getHelperReference(name); const ref = refs[name] = getHelperReference(name);
const {
var _helpers$get = helpers().get(name, getHelperReference, ref), nodes
nodes = _helpers$get.nodes; } = helpers().get(name, getHelperReference, ref);
body.push(...nodes);
body.push.apply(body, nodes);
}); });
return refs; return refs;
} }
function _default(whitelist, outputType) { function _default(whitelist, outputType = "global") {
if (outputType === void 0) { let tree;
outputType = "global"; const build = {
}
var tree;
var build = {
global: buildGlobal, global: buildGlobal,
module: buildModule, module: buildModule,
umd: buildUmd, umd: buildUmd,
@@ -135,7 +136,7 @@ function _default(whitelist, outputType) {
if (build) { if (build) {
tree = build(whitelist); tree = build(whitelist);
} else { } else {
throw new Error("Unsupported output type " + outputType); throw new Error(`Unsupported output type ${outputType}`);
} }
return (0, _generator().default)(tree).code; return (0, _generator().default)(tree).code;

View File

@@ -1,19 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transformFromAstSync;
var _config = _interopRequireDefault(require("./config"));
var _transformation = require("./transformation");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function transformFromAstSync(ast, code, opts) {
var 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);
}

View File

@@ -3,26 +3,26 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = void 0; exports.transformFromAstSync = transformFromAstSync;
exports.transformFromAstAsync = transformFromAstAsync;
exports.transformFromAst = void 0;
var _config = _interopRequireDefault(require("./config")); var _config = _interopRequireDefault(require("./config"));
var _transformation = require("./transformation"); var _transformation = require("./transformation");
var _transformAstSync = _interopRequireDefault(require("./transform-ast-sync"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var transformFromAst = function transformFromAst(ast, code, opts, callback) { const transformFromAst = function transformFromAst(ast, code, opts, callback) {
if (typeof opts === "function") { if (typeof opts === "function") {
opts = undefined;
callback = opts; callback = opts;
opts = undefined;
} }
if (callback === undefined) return (0, _transformAstSync.default)(ast, code, opts); if (callback === undefined) return transformFromAstSync(ast, code, opts);
var cb = callback; const cb = callback;
process.nextTick(function () { process.nextTick(() => {
var cfg; let cfg;
try { try {
cfg = (0, _config.default)(opts); cfg = (0, _config.default)(opts);
@@ -36,4 +36,19 @@ var transformFromAst = function transformFromAst(ast, code, opts, callback) {
}); });
}; };
exports.default = transformFromAst; 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);
});
});
}

View File

@@ -3,16 +3,24 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = transformFile; exports.transformFileSync = transformFileSync;
exports.transformFileAsync = transformFileAsync;
function transformFile(filename, opts, callback) { exports.transformFile = void 0;
if (opts === void 0) {
opts = {};
}
const transformFile = function transformFile(filename, opts, callback) {
if (typeof opts === "function") { if (typeof opts === "function") {
callback = opts; callback = opts;
} }
callback(new Error("Transforming files is not supported in browsers"), null); 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"));
} }

View File

@@ -1,10 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transformFileSync;
function transformFileSync() {
throw new Error("Transforming files is not supported in browsers");
}

View File

@@ -1,40 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transformFileSync;
function _fs() {
var data = _interopRequireDefault(require("fs"));
_fs = function _fs() {
return data;
};
return data;
}
var _config = _interopRequireDefault(require("./config"));
var _transformation = require("./transformation");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function transformFileSync(filename, opts) {
var options;
if (opts == null) {
options = {
filename: filename
};
} else if (opts && typeof opts === "object") {
options = Object.assign({}, opts, {
filename: filename
});
}
var config = (0, _config.default)(options);
if (config === null) return null;
return (0, _transformation.runSync)(config, _fs().default.readFileSync(filename, "utf8"));
}

View File

@@ -3,12 +3,14 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = void 0; exports.transformFileSync = transformFileSync;
exports.transformFileAsync = transformFileAsync;
exports.transformFile = void 0;
function _fs() { function _fs() {
var data = _interopRequireDefault(require("fs")); const data = _interopRequireDefault(require("fs"));
_fs = function _fs() { _fs = function () {
return data; return data;
}; };
@@ -21,8 +23,10 @@ var _transformation = require("./transformation");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var transformFile = function transformFile(filename, opts, callback) { ({});
var options;
const transformFile = function transformFile(filename, opts, callback) {
let options;
if (typeof opts === "function") { if (typeof opts === "function") {
callback = opts; callback = opts;
@@ -31,16 +35,16 @@ var transformFile = function transformFile(filename, opts, callback) {
if (opts == null) { if (opts == null) {
options = { options = {
filename: filename filename
}; };
} else if (opts && typeof opts === "object") { } else if (opts && typeof opts === "object") {
options = Object.assign({}, opts, { options = Object.assign({}, opts, {
filename: filename filename
}); });
} }
process.nextTick(function () { process.nextTick(() => {
var cfg; let cfg;
try { try {
cfg = (0, _config.default)(options); cfg = (0, _config.default)(options);
@@ -49,7 +53,7 @@ var transformFile = function transformFile(filename, opts, callback) {
return callback(err); return callback(err);
} }
var config = cfg; const config = cfg;
_fs().default.readFile(filename, "utf8", function (err, code) { _fs().default.readFile(filename, "utf8", function (err, code) {
if (err) return callback(err, null); if (err) return callback(err, null);
@@ -58,4 +62,30 @@ var transformFile = function transformFile(filename, opts, callback) {
}); });
}; };
exports.default = transformFile; 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);
});
});
}

View File

@@ -1,18 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transformSync;
var _config = _interopRequireDefault(require("./config"));
var _transformation = require("./transformation");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function transformSync(code, opts) {
var config = (0, _config.default)(opts);
if (config === null) return null;
return (0, _transformation.runSync)(config, code);
}

View File

@@ -3,26 +3,26 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = void 0; exports.transformSync = transformSync;
exports.transformAsync = transformAsync;
exports.transform = void 0;
var _config = _interopRequireDefault(require("./config")); var _config = _interopRequireDefault(require("./config"));
var _transformation = require("./transformation"); var _transformation = require("./transformation");
var _transformSync = _interopRequireDefault(require("./transform-sync"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var transform = function transform(code, opts, callback) { const transform = function transform(code, opts, callback) {
if (typeof opts === "function") { if (typeof opts === "function") {
opts = undefined;
callback = opts; callback = opts;
opts = undefined;
} }
if (callback === undefined) return (0, _transformSync.default)(code, opts); if (callback === undefined) return transformSync(code, opts);
var cb = callback; const cb = callback;
process.nextTick(function () { process.nextTick(() => {
var cfg; let cfg;
try { try {
cfg = (0, _config.default)(opts); cfg = (0, _config.default)(opts);
@@ -35,4 +35,18 @@ var transform = function transform(code, opts, callback) {
}); });
}; };
exports.default = transform; 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);
});
});
}

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = loadBlockHoistPlugin; exports.default = loadBlockHoistPlugin;
function _sortBy() { function _sortBy() {
var data = _interopRequireDefault(require("lodash/sortBy")); const data = _interopRequireDefault(require("lodash/sortBy"));
_sortBy = function _sortBy() { _sortBy = function () {
return data; return data;
}; };
@@ -19,11 +19,11 @@ var _config = _interopRequireDefault(require("../config"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var LOADED_PLUGIN; let LOADED_PLUGIN;
function loadBlockHoistPlugin() { function loadBlockHoistPlugin() {
if (!LOADED_PLUGIN) { if (!LOADED_PLUGIN) {
var config = (0, _config.default)({ const config = (0, _config.default)({
babelrc: false, babelrc: false,
configFile: false, configFile: false,
plugins: [blockHoistPlugin] plugins: [blockHoistPlugin]
@@ -35,16 +35,17 @@ function loadBlockHoistPlugin() {
return LOADED_PLUGIN; return LOADED_PLUGIN;
} }
var blockHoistPlugin = { const blockHoistPlugin = {
name: "internal.blockHoist", name: "internal.blockHoist",
visitor: { visitor: {
Block: { Block: {
exit: function exit(_ref) { exit({
var node = _ref.node; node
var hasChange = false; }) {
let hasChange = false;
for (var i = 0; i < node.body.length; i++) { for (let i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i]; const bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) { if (bodyNode && bodyNode._blockHoist != null) {
hasChange = true; hasChange = true;
@@ -54,12 +55,13 @@ var blockHoistPlugin = {
if (!hasChange) return; if (!hasChange) return;
node.body = (0, _sortBy().default)(node.body, function (bodyNode) { node.body = (0, _sortBy().default)(node.body, function (bodyNode) {
var priority = bodyNode && bodyNode._blockHoist; let priority = bodyNode && bodyNode._blockHoist;
if (priority == null) priority = 1; if (priority == null) priority = 1;
if (priority === true) priority = 2; if (priority === true) priority = 2;
return -1 * priority; return -1 * priority;
}); });
} }
} }
} }
}; };

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = void 0; exports.default = void 0;
function helpers() { function helpers() {
var data = _interopRequireWildcard(require("@babel/helpers")); const data = _interopRequireWildcard(require("@babel/helpers"));
helpers = function helpers() { helpers = function () {
return data; return data;
}; };
@@ -16,9 +16,9 @@ function helpers() {
} }
function _traverse() { function _traverse() {
var data = _interopRequireWildcard(require("@babel/traverse")); const data = _interopRequireWildcard(require("@babel/traverse"));
_traverse = function _traverse() { _traverse = function () {
return data; return data;
}; };
@@ -26,9 +26,9 @@ function _traverse() {
} }
function _codeFrame() { function _codeFrame() {
var data = require("@babel/code-frame"); const data = require("@babel/code-frame");
_codeFrame = function _codeFrame() { _codeFrame = function () {
return data; return data;
}; };
@@ -36,47 +36,64 @@ function _codeFrame() {
} }
function t() { function t() {
var data = _interopRequireWildcard(require("@babel/types")); const data = _interopRequireWildcard(require("@babel/types"));
t = function t() { t = function () {
return data; return data;
}; };
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; } } 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; } }
var errorVisitor = { const errorVisitor = {
enter: function enter(path, state) { enter(path, state) {
var loc = path.node.loc; const loc = path.node.loc;
if (loc) { if (loc) {
state.loc = loc; state.loc = loc;
path.stop(); path.stop();
} }
} }
}; };
var File = function () { class File {
function File(options, _ref) { constructor(options, {
var code = _ref.code, code,
ast = _ref.ast, ast,
shebang = _ref.shebang, inputMap
inputMap = _ref.inputMap; }) {
this._map = new Map(); this._map = new Map();
this.declarations = {}; this.declarations = {};
this.path = null; this.path = null;
this.ast = {}; this.ast = {};
this.metadata = {}; this.metadata = {};
this.hub = new (_traverse().Hub)(this);
this.code = ""; this.code = "";
this.shebang = "";
this.inputMap = null; 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.opts = options;
this.code = code; this.code = code;
this.ast = ast; this.ast = ast;
this.shebang = shebang;
this.inputMap = inputMap; this.inputMap = inputMap;
this.path = _traverse().NodePath.get({ this.path = _traverse().NodePath.get({
hub: this.hub, hub: this.hub,
@@ -88,44 +105,58 @@ var File = function () {
this.scope = this.path.scope; this.scope = this.path.scope;
} }
var _proto = File.prototype; 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()'.");
}
_proto.set = function set(key, val) {
this._map.set(key, val); this._map.set(key, val);
}; }
_proto.get = function get(key) { get(key) {
return this._map.get(key); return this._map.get(key);
}; }
_proto.has = function has(key) { has(key) {
return this._map.has(key); return this._map.has(key);
}; }
_proto.getModuleName = function getModuleName() { getModuleName() {
var _opts = this.opts, const {
filename = _opts.filename, filename,
_opts$filenameRelativ = _opts.filenameRelative, filenameRelative = filename,
filenameRelative = _opts$filenameRelativ === void 0 ? filename : _opts$filenameRelativ, moduleId,
moduleId = _opts.moduleId, moduleIds = !!moduleId,
_opts$moduleIds = _opts.moduleIds, getModuleId,
moduleIds = _opts$moduleIds === void 0 ? !!moduleId : _opts$moduleIds, sourceRoot: sourceRootTmp,
getModuleId = _opts.getModuleId, moduleRoot = sourceRootTmp,
sourceRootTmp = _opts.sourceRoot, sourceRoot = moduleRoot
_opts$moduleRoot = _opts.moduleRoot, } = this.opts;
moduleRoot = _opts$moduleRoot === void 0 ? sourceRootTmp : _opts$moduleRoot,
_opts$sourceRoot = _opts.sourceRoot,
sourceRoot = _opts$sourceRoot === void 0 ? moduleRoot : _opts$sourceRoot;
if (!moduleIds) return null; if (!moduleIds) return null;
if (moduleId != null && !getModuleId) { if (moduleId != null && !getModuleId) {
return moduleId; return moduleId;
} }
var moduleName = moduleRoot != null ? moduleRoot + "/" : ""; let moduleName = moduleRoot != null ? moduleRoot + "/" : "";
if (filenameRelative) { if (filenameRelative) {
var sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : ""; const sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : "";
moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, ""); moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, "");
} }
@@ -136,112 +167,100 @@ var File = function () {
} else { } else {
return moduleName; return moduleName;
} }
}; }
_proto.resolveModuleSource = function resolveModuleSource(source) { addImport() {
return source;
};
_proto.addImport = function 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'."); 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'.");
}; }
_proto.addHelper = function addHelper(name) { availableHelper(name, versionRange) {
var _this = this; let minVersion;
var declar = this.declarations[name]; 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); if (declar) return t().cloneNode(declar);
var generator = this.get("helperGenerator"); const generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) { if (generator) {
var res = generator(name); const res = generator(name);
if (res) return res; if (res) return res;
} else if (runtime) {
return t().memberExpression(t().cloneNode(runtime), t().identifier(name));
} }
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
var dependencies = {}; const dependencies = {};
for (var _iterator = helpers().getDependencies(name), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { for (const dep of helpers().getDependencies(name)) {
var _ref2;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var dep = _ref2;
dependencies[dep] = this.addHelper(dep); dependencies[dep] = this.addHelper(dep);
} }
var _helpers$get = helpers().get(name, function (dep) { const {
return dependencies[dep]; nodes,
}, uid, Object.keys(this.scope.getAllBindings())), globals
nodes = _helpers$get.nodes, } = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings()));
globals = _helpers$get.globals; globals.forEach(name => {
if (this.path.scope.hasBinding(name, true)) {
globals.forEach(function (name) { this.path.scope.rename(name);
if (_this.path.scope.hasBinding(name, true)) {
_this.path.scope.rename(name);
} }
}); });
nodes.forEach(function (node) { nodes.forEach(node => {
node._compact = true; node._compact = true;
}); });
this.path.unshiftContainer("body", nodes); this.path.unshiftContainer("body", nodes);
this.path.get("body").forEach(function (path) { this.path.get("body").forEach(path => {
if (nodes.indexOf(path.node) === -1) return; if (nodes.indexOf(path.node) === -1) return;
if (path.isVariableDeclaration()) _this.scope.registerDeclaration(path); if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);
}); });
return uid; return uid;
};
_proto.addTemplateObject = function addTemplateObject() {
throw new Error("This function has been moved into the template literal transform itself.");
};
_proto.buildCodeFrameError = function buildCodeFrameError(node, msg, Error) {
if (Error === void 0) {
Error = SyntaxError;
} }
var loc = node && (node.loc || node._loc); addTemplateObject() {
msg = this.opts.filename + ": " + msg; 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) { if (!loc && node) {
var state = { const state = {
loc: null loc: null
}; };
(0, _traverse().default)(node, errorVisitor, this.scope, state); (0, _traverse().default)(node, errorVisitor, this.scope, state);
loc = state.loc; loc = state.loc;
var txt = "This is an error on an internal node. Probably an internal error."; let txt = "This is an error on an internal node. Probably an internal error.";
if (loc) txt += " Location has been estimated."; if (loc) txt += " Location has been estimated.";
msg += " (" + txt + ")"; msg += ` (${txt})`;
} }
if (loc) { if (loc) {
var _opts$highlightCode = this.opts.highlightCode, const {
highlightCode = _opts$highlightCode === void 0 ? true : _opts$highlightCode; highlightCode = true
} = this.opts;
msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, { msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, {
start: { start: {
line: loc.start.line, line: loc.start.line,
column: loc.start.column + 1 column: loc.start.column + 1
} }
}, { }, {
highlightCode: highlightCode highlightCode
}); });
} }
return new Error(msg); return new Error(msg);
}; }
return File; }
}();
exports.default = File; exports.default = File;

View File

@@ -6,19 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = generateCode; exports.default = generateCode;
function _convertSourceMap() { function _convertSourceMap() {
var data = _interopRequireDefault(require("convert-source-map")); const data = _interopRequireDefault(require("convert-source-map"));
_convertSourceMap = function _convertSourceMap() { _convertSourceMap = function () {
return data;
};
return data;
}
function _sourceMap() {
var data = _interopRequireDefault(require("source-map"));
_sourceMap = function _sourceMap() {
return data; return data;
}; };
@@ -26,63 +16,42 @@ function _sourceMap() {
} }
function _generator() { function _generator() {
var data = _interopRequireDefault(require("@babel/generator")); const data = _interopRequireDefault(require("@babel/generator"));
_generator = function _generator() { _generator = function () {
return data; return data;
}; };
return data; return data;
} }
var _mergeMap = _interopRequireDefault(require("./merge-map"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function generateCode(pluginPasses, file) { function generateCode(pluginPasses, file) {
var opts = file.opts, const {
ast = file.ast, opts,
shebang = file.shebang, ast,
code = file.code, code,
inputMap = file.inputMap; inputMap
var results = []; } = file;
const results = [];
for (var _iterator = pluginPasses, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { for (const plugins of pluginPasses) {
var _ref; for (const plugin of plugins) {
const {
if (_isArray) { generatorOverride
if (_i >= _iterator.length) break; } = plugin;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var plugins = _ref;
for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var plugin = _ref2;
var generatorOverride = plugin.generatorOverride;
if (generatorOverride) { if (generatorOverride) {
var _result2 = generatorOverride(ast, opts.generatorOpts, code, _generator().default); const result = generatorOverride(ast, opts.generatorOpts, code, _generator().default);
if (result !== undefined) results.push(result);
if (_result2 !== undefined) results.push(_result2);
} }
} }
} }
var result; let result;
if (results.length === 0) { if (results.length === 0) {
result = (0, _generator().default)(ast, opts.generatorOpts, code); result = (0, _generator().default)(ast, opts.generatorOpts, code);
@@ -90,22 +59,19 @@ function generateCode(pluginPasses, file) {
result = results[0]; result = results[0];
if (typeof result.then === "function") { 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."); 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 { } else {
throw new Error("More than one plugin attempted to override codegen."); throw new Error("More than one plugin attempted to override codegen.");
} }
var _result = result, let {
outputCode = _result.code, code: outputCode,
outputMap = _result.map; map: outputMap
} = result;
if (shebang) {
outputCode = shebang + "\n" + outputCode;
}
if (outputMap && inputMap) { if (outputMap && inputMap) {
outputMap = mergeSourceMap(inputMap.toObject(), outputMap); outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap);
} }
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
@@ -117,39 +83,7 @@ function generateCode(pluginPasses, file) {
} }
return { return {
outputCode: outputCode, outputCode,
outputMap: outputMap outputMap
}; };
} }
function mergeSourceMap(inputMap, map) {
var inputMapConsumer = new (_sourceMap().default.SourceMapConsumer)(inputMap);
var outputMapConsumer = new (_sourceMap().default.SourceMapConsumer)(map);
var mergedGenerator = new (_sourceMap().default.SourceMapGenerator)({
file: inputMapConsumer.file,
sourceRoot: inputMapConsumer.sourceRoot
});
var source = outputMapConsumer.sources[0];
inputMapConsumer.eachMapping(function (mapping) {
var generatedPosition = outputMapConsumer.generatedPositionFor({
line: mapping.generatedLine,
column: mapping.generatedColumn,
source: source
});
if (generatedPosition.column != null) {
mergedGenerator.addMapping({
source: mapping.source,
original: mapping.source == null ? null : {
line: mapping.originalLine,
column: mapping.originalColumn
},
generated: generatedPosition,
name: mapping.name
});
}
});
var mergedMap = mergedGenerator.toJSON();
inputMap.mappings = mergedMap.mappings;
return inputMap;
}

View File

@@ -0,0 +1,255 @@
"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;
}

View File

@@ -7,9 +7,9 @@ exports.runAsync = runAsync;
exports.runSync = runSync; exports.runSync = runSync;
function _traverse() { function _traverse() {
var data = _interopRequireDefault(require("@babel/traverse")); const data = _interopRequireDefault(require("@babel/traverse"));
_traverse = function _traverse() { _traverse = function () {
return data; return data;
}; };
@@ -29,7 +29,7 @@ var _generate = _interopRequireDefault(require("./file/generate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function runAsync(config, code, ast, callback) { function runAsync(config, code, ast, callback) {
var result; let result;
try { try {
result = runSync(config, code, ast); result = runSync(config, code, ast);
@@ -41,14 +41,13 @@ function runAsync(config, code, ast, callback) {
} }
function runSync(config, code, ast) { function runSync(config, code, ast) {
var file = (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); const file = (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast);
transformFile(file, config.passes); transformFile(file, config.passes);
var opts = file.opts; const opts = file.opts;
const {
var _ref = opts.code !== false ? (0, _generate.default)(config.passes, file) : {}, outputCode,
outputCode = _ref.outputCode, outputMap
outputMap = _ref.outputMap; } = opts.code !== false ? (0, _generate.default)(config.passes, file) : {};
return { return {
metadata: file.metadata, metadata: file.metadata,
options: opts, options: opts,
@@ -60,72 +59,42 @@ function runSync(config, code, ast) {
} }
function transformFile(file, pluginPasses) { function transformFile(file, pluginPasses) {
for (var _iterator = pluginPasses, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { for (const pluginPairs of pluginPasses) {
var _ref2; const passPairs = [];
const passes = [];
const visitors = [];
if (_isArray) { for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) {
if (_i >= _iterator.length) break; const pass = new _pluginPass.default(file, plugin.key, plugin.options);
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var pluginPairs = _ref2;
var passPairs = [];
var passes = [];
var visitors = [];
for (var _iterator2 = pluginPairs.concat([(0, _blockHoistPlugin.default)()]), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref3;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref3 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref3 = _i2.value;
}
var plugin = _ref3;
var pass = new _pluginPass.default(file, plugin.key, plugin.options);
passPairs.push([plugin, pass]); passPairs.push([plugin, pass]);
passes.push(pass); passes.push(pass);
visitors.push(plugin.visitor); visitors.push(plugin.visitor);
} }
for (var _i3 = 0; _i3 < passPairs.length; _i3++) { for (const [plugin, pass] of passPairs) {
var _passPairs$_i = passPairs[_i3], const fn = plugin.pre;
_plugin = _passPairs$_i[0],
_pass = _passPairs$_i[1];
var fn = _plugin.pre;
if (fn) { if (fn) {
var result = fn.call(_pass, file); const result = fn.call(pass, file);
if (isThenable(result)) { 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."); 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.`);
} }
} }
} }
var visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod);
(0, _traverse().default)(file.ast, visitor, file.scope); (0, _traverse().default)(file.ast, visitor, file.scope);
for (var _i4 = 0; _i4 < passPairs.length; _i4++) { for (const [plugin, pass] of passPairs) {
var _passPairs$_i2 = passPairs[_i4], const fn = plugin.post;
_plugin2 = _passPairs$_i2[0],
_pass2 = _passPairs$_i2[1];
var _fn = _plugin2.post;
if (_fn) { if (fn) {
var _result = _fn.call(_pass2, file); const result = fn.call(pass, file);
if (isThenable(_result)) { 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."); 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.`);
} }
} }
} }
@@ -133,5 +102,5 @@ function transformFile(file, pluginPasses) {
} }
function isThenable(val) { function isThenable(val) {
return !!val && (typeof val === "object" || typeof val === "function") && typeof val.then === "function"; return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
} }

View File

@@ -5,10 +5,40 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = normalizeFile; exports.default = normalizeFile;
function t() { function _path() {
var data = _interopRequireWildcard(require("@babel/types")); const data = _interopRequireDefault(require("path"));
t = function t() { _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;
}; };
@@ -16,19 +46,19 @@ function t() {
} }
function _convertSourceMap() { function _convertSourceMap() {
var data = _interopRequireDefault(require("convert-source-map")); const data = _interopRequireDefault(require("convert-source-map"));
_convertSourceMap = function _convertSourceMap() { _convertSourceMap = function () {
return data; return data;
}; };
return data; return data;
} }
function _babylon() { function _parser() {
var data = require("babylon"); const data = require("@babel/parser");
_babylon = function _babylon() { _parser = function () {
return data; return data;
}; };
@@ -36,9 +66,9 @@ function _babylon() {
} }
function _codeFrame() { function _codeFrame() {
var data = require("@babel/code-frame"); const data = require("@babel/code-frame");
_codeFrame = function _codeFrame() { _codeFrame = function () {
return data; return data;
}; };
@@ -49,32 +79,51 @@ var _file = _interopRequireDefault(require("./file/file"));
var _missingPluginHelper = _interopRequireDefault(require("./util/missing-plugin-helper")); var _missingPluginHelper = _interopRequireDefault(require("./util/missing-plugin-helper"));
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 _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; } }
var shebangRegex = /^#!.*/; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = (0, _debug().default)("babel:transform:file");
function normalizeFile(pluginPasses, options, code, ast) { function normalizeFile(pluginPasses, options, code, ast) {
code = "" + (code || ""); code = `${code || ""}`;
var shebang = null; let inputMap = null;
var inputMap = null;
if (options.inputSourceMap !== false) { if (options.inputSourceMap !== false) {
if (typeof options.inputSourceMap === "object") {
inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap);
}
if (!inputMap) {
try {
inputMap = _convertSourceMap().default.fromSource(code); inputMap = _convertSourceMap().default.fromSource(code);
if (inputMap) { if (inputMap) {
code = _convertSourceMap().default.removeComments(code); code = _convertSourceMap().default.removeComments(code);
} else if (typeof options.inputSourceMap === "object") { }
inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap); } catch (err) {
debug("discarding unknown inline input sourcemap", err);
code = _convertSourceMap().default.removeComments(code);
} }
} }
var shebangMatch = shebangRegex.exec(code); if (!inputMap) {
if (typeof options.filename === "string") {
try {
inputMap = _convertSourceMap().default.fromMapFileSource(code, _path().default.dirname(options.filename));
if (shebangMatch) { if (inputMap) {
shebang = shebangMatch[0]; code = _convertSourceMap().default.removeMapFileComments(code);
code = code.replace(shebangRegex, ""); }
} 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) {
@@ -83,64 +132,45 @@ function normalizeFile(pluginPasses, options, code, ast) {
} else if (ast.type !== "File") { } else if (ast.type !== "File") {
throw new Error("AST root must be a Program or File node"); throw new Error("AST root must be a Program or File node");
} }
ast = (0, _cloneDeep().default)(ast);
} else { } else {
ast = parser(pluginPasses, options, code); ast = parser(pluginPasses, options, code);
} }
return new _file.default(options, { return new _file.default(options, {
code: code, code,
ast: ast, ast,
shebang: shebang, inputMap
inputMap: inputMap
}); });
} }
function parser(pluginPasses, options, code) { function parser(pluginPasses, {
parserOpts,
highlightCode = true,
filename = "unknown"
}, code) {
try { try {
var results = []; const results = [];
for (var _iterator = pluginPasses, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { for (const plugins of pluginPasses) {
var _ref; for (const plugin of plugins) {
const {
if (_isArray) { parserOverride
if (_i >= _iterator.length) break; } = plugin;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var plugins = _ref;
for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var plugin = _ref2;
var parserOverride = plugin.parserOverride;
if (parserOverride) { if (parserOverride) {
var _ast = parserOverride(code, options.parserOpts, _babylon().parse); const ast = parserOverride(code, parserOpts, _parser().parse);
if (ast !== undefined) results.push(ast);
if (_ast !== undefined) results.push(_ast);
} }
} }
} }
if (results.length === 0) { if (results.length === 0) {
return (0, _babylon().parse)(code, options.parserOpts); return (0, _parser().parse)(code, parserOpts);
} else if (results.length === 1) { } else if (results.length === 1) {
if (typeof results[0].then === "function") { 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."); 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]; return results[0];
@@ -152,21 +182,25 @@ function parser(pluginPasses, options, code) {
err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file.";
} }
var loc = err.loc, const {
missingPlugin = err.missingPlugin; loc,
missingPlugin
} = err;
if (loc) { if (loc) {
var codeFrame = (0, _codeFrame().codeFrameColumns)(code, { const codeFrame = (0, _codeFrame().codeFrameColumns)(code, {
start: { start: {
line: loc.line, line: loc.line,
column: loc.column + 1 column: loc.column + 1
} }
}, options); }, {
highlightCode
});
if (missingPlugin) { if (missingPlugin) {
err.message = (options.filename || "unknown") + ": " + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame); err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame);
} else { } else {
err.message = (options.filename || "unknown") + ": " + err.message + "\n\n" + codeFrame; err.message = `${filename}: ${err.message}\n\n` + codeFrame;
} }
err.code = "BABEL_PARSE_ERROR"; err.code = "BABEL_PARSE_ERROR";

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = normalizeOptions; exports.default = normalizeOptions;
function _path() { function _path() {
var data = _interopRequireDefault(require("path")); const data = _interopRequireDefault(require("path"));
_path = function _path() { _path = function () {
return data; return data;
}; };
@@ -18,74 +18,43 @@ function _path() {
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function normalizeOptions(config) { function normalizeOptions(config) {
var _config$options = config.options, const {
filename = _config$options.filename, filename,
_config$options$filen = _config$options.filenameRelative, cwd,
filenameRelative = _config$options$filen === void 0 ? filename || "unknown" : _config$options$filen, filenameRelative = typeof filename === "string" ? _path().default.relative(cwd, filename) : "unknown",
_config$options$sourc = _config$options.sourceType, sourceType = "module",
sourceType = _config$options$sourc === void 0 ? "module" : _config$options$sourc, inputSourceMap,
inputSourceMap = _config$options.inputSourceMap, sourceMaps = !!inputSourceMap,
_config$options$sourc2 = _config$options.sourceMaps, moduleRoot,
sourceMaps = _config$options$sourc2 === void 0 ? !!inputSourceMap : _config$options$sourc2, sourceRoot = moduleRoot,
moduleRoot = _config$options.moduleRoot, sourceFileName = _path().default.basename(filenameRelative),
_config$options$sourc3 = _config$options.sourceRoot, comments = true,
sourceRoot = _config$options$sourc3 === void 0 ? moduleRoot : _config$options$sourc3, compact = "auto"
_config$options$sourc4 = _config$options.sourceFileName, } = config.options;
sourceFileName = _config$options$sourc4 === void 0 ? filenameRelative : _config$options$sourc4, const opts = config.options;
_config$options$comme = _config$options.comments, const options = Object.assign({}, opts, {
comments = _config$options$comme === void 0 ? true : _config$options$comme,
_config$options$compa = _config$options.compact,
compact = _config$options$compa === void 0 ? "auto" : _config$options$compa;
var opts = config.options;
var options = Object.assign({}, opts, {
parserOpts: Object.assign({ parserOpts: Object.assign({
sourceType: _path().default.extname(filenameRelative) === ".mjs" ? "module" : sourceType, sourceType: _path().default.extname(filenameRelative) === ".mjs" ? "module" : sourceType,
sourceFileName: filename, sourceFileName: filename,
plugins: [] plugins: []
}, opts.parserOpts), }, opts.parserOpts),
generatorOpts: Object.assign({ generatorOpts: Object.assign({
filename: filename, filename,
auxiliaryCommentBefore: opts.auxiliaryCommentBefore, auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter, auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
retainLines: opts.retainLines, retainLines: opts.retainLines,
comments: comments, comments,
shouldPrintComment: opts.shouldPrintComment, shouldPrintComment: opts.shouldPrintComment,
compact: compact, compact,
minified: opts.minified, minified: opts.minified,
sourceMaps: sourceMaps, sourceMaps,
sourceRoot: sourceRoot, sourceRoot,
sourceFileName: sourceFileName sourceFileName
}, opts.generatorOpts) }, opts.generatorOpts)
}); });
for (var _iterator = config.passes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { for (const plugins of config.passes) {
var _ref; for (const plugin of plugins) {
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var plugins = _ref;
for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var plugin = _ref2;
if (plugin.manipulateOptions) { if (plugin.manipulateOptions) {
plugin.manipulateOptions(options, options.parserOpts); plugin.manipulateOptions(options, options.parserOpts);
} }

View File

@@ -5,42 +5,44 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = void 0; exports.default = void 0;
var PluginPass = function () { class PluginPass {
function PluginPass(file, key, options) { constructor(file, key, options) {
this._map = new Map(); this._map = new Map();
this.key = key; this.key = key;
this.file = file; this.file = file;
this.opts = options || {}; this.opts = options || {};
this.filename = typeof file.opts.filename === "string" ? file.opts.filename : undefined; this.cwd = file.opts.cwd;
this.filename = file.opts.filename;
} }
var _proto = PluginPass.prototype; set(key, val) {
_proto.set = function set(key, val) {
this._map.set(key, val); this._map.set(key, val);
}; }
_proto.get = function get(key) { get(key) {
return this._map.get(key); return this._map.get(key);
}; }
_proto.addHelper = function addHelper(name) { availableHelper(name, versionRange) {
return this.file.availableHelper(name, versionRange);
}
addHelper(name) {
return this.file.addHelper(name); return this.file.addHelper(name);
}; }
_proto.addImport = function addImport() { addImport() {
return this.file.addImport(); return this.file.addImport();
}; }
_proto.getModuleName = function getModuleName() { getModuleName() {
return this.file.getModuleName(); return this.file.getModuleName();
}; }
_proto.buildCodeFrameError = function buildCodeFrameError(node, msg, Error) { buildCodeFrameError(node, msg, Error) {
return this.file.buildCodeFrameError(node, msg, Error); return this.file.buildCodeFrameError(node, msg, Error);
}; }
return PluginPass; }
}();
exports.default = PluginPass; exports.default = PluginPass;

View File

@@ -4,17 +4,7 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = generateMissingPluginMessage; exports.default = generateMissingPluginMessage;
var pluginNameMap = { const pluginNameMap = {
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"
}
},
classProperties: { classProperties: {
syntax: { syntax: {
name: "@babel/plugin-syntax-class-properties", name: "@babel/plugin-syntax-class-properties",
@@ -147,26 +137,6 @@ var pluginNameMap = {
url: "https://git.io/vb4yS" url: "https://git.io/vb4yS"
} }
}, },
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"
}
},
optionalChaining: { optionalChaining: {
syntax: { syntax: {
name: "@babel/plugin-syntax-optional-chaining", name: "@babel/plugin-syntax-optional-chaining",
@@ -206,30 +176,61 @@ var pluginNameMap = {
name: "@babel/plugin-transform-typescript", name: "@babel/plugin-transform-typescript",
url: "https://git.io/vb4Sm" 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"
}
} }
}; };
var getNameURLCombination = function getNameURLCombination(_ref) { const getNameURLCombination = ({
var name = _ref.name, name,
url = _ref.url; url
return name + " (" + url + ")"; }) => `${name} (${url})`;
};
function generateMissingPluginMessage(missingPluginName, loc, codeFrame) { function generateMissingPluginMessage(missingPluginName, loc, codeFrame) {
var helpMessage = "Support for the experimental syntax '" + missingPluginName + "' isn't currently enabled " + ("(" + loc.line + ":" + (loc.column + 1) + "):\n\n") + codeFrame; let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame;
var pluginInfo = pluginNameMap[missingPluginName]; const pluginInfo = pluginNameMap[missingPluginName];
if (pluginInfo) { if (pluginInfo) {
var syntaxPlugin = pluginInfo.syntax, const {
transformPlugin = pluginInfo.transform; syntax: syntaxPlugin,
transform: transformPlugin
} = pluginInfo;
if (syntaxPlugin) { if (syntaxPlugin) {
if (transformPlugin) { if (transformPlugin) {
var transformPluginInfo = getNameURLCombination(transformPlugin); const transformPluginInfo = getNameURLCombination(transformPlugin);
helpMessage += "\n\nAdd " + transformPluginInfo + " to the 'plugins' section of your Babel config " + "to enable transformation."; helpMessage += `\n\nAdd ${transformPluginInfo} to the 'plugins' section of your Babel config ` + `to enable transformation.`;
} else { } else {
var syntaxPluginInfo = getNameURLCombination(syntaxPlugin); const syntaxPluginInfo = getNameURLCombination(syntaxPlugin);
helpMessage += "\n\nAdd " + syntaxPluginInfo + " to the 'plugins' section of your Babel config " + "to enable parsing."; helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`;
} }
} }
} }

View File

@@ -1 +0,0 @@
../babylon/bin/babylon.js

15
node_modules/@babel/core/node_modules/.bin/jsesc generated vendored Normal file
View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../jsesc/bin/jsesc" "$@"
ret=$?
else
node "$basedir/../jsesc/bin/jsesc" "$@"
ret=$?
fi
exit $ret

7
node_modules/@babel/core/node_modules/.bin/jsesc.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\jsesc\bin\jsesc" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\jsesc\bin\jsesc" %*
)

15
node_modules/@babel/core/node_modules/.bin/json5 generated vendored Normal file
View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../json5/lib/cli.js" "$@"
ret=$?
else
node "$basedir/../json5/lib/cli.js" "$@"
ret=$?
fi
exit $ret

7
node_modules/@babel/core/node_modules/.bin/json5.cmd generated vendored Normal file
View File

@@ -0,0 +1,7 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\json5\lib\cli.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\json5\lib\cli.js" %*
)

View File

@@ -0,0 +1,22 @@
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.

View File

@@ -0,0 +1,19 @@
# @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
```

View File

@@ -0,0 +1,173 @@
"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);
}

View File

@@ -0,0 +1,51 @@
{
"_from": "@babel/code-frame@^7.0.0",
"_id": "@babel/code-frame@7.0.0",
"_inBundle": false,
"_integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==",
"_location": "/@babel/core/@babel/code-frame",
"_phantomChildren": {},
"_requested": {
"type": "range",
"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/core/@babel/template",
"/@babel/core/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz",
"_shasum": "06e2ab19bdb535385559aabb5ba59729482800f8",
"_spec": "@babel/code-frame@^7.0.0",
"_where": "E:\\projects\\p\\minifyfromhtml\\node_modules\\@babel\\core",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/highlight": "^7.0.0"
},
"deprecated": false,
"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"
}

View File

@@ -0,0 +1,22 @@
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.

View File

@@ -0,0 +1,19 @@
# @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
```

View File

@@ -0,0 +1,257 @@
"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;

View File

@@ -0,0 +1,97 @@
"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();
}
}

Some files were not shown because too many files have changed in this diff Show More