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

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.
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
var babel = require("@babel/core");
import { transform } from "@babel/core";
import * as babel from "@babel/core";
## Install
Using npm:
```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:
## babel.transform(code: string, [options?](#options): Object, callback: Function)
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 }
});
```sh
yarn add @babel/core --dev
```
**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.makeWeakCache = makeWeakCache;
exports.assertSimpleType = assertSimpleType;
function makeStrongCache(handler) {
return makeCachedFunction(new Map(), handler);
@@ -16,47 +17,35 @@ function makeWeakCache(handler) {
function makeCachedFunction(callCache, handler) {
return function cachedFunction(arg, data) {
var cachedValue = callCache.get(arg);
let cachedValue = callCache.get(arg);
if (cachedValue) {
for (var _iterator = cachedValue, _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;
var _value = _ref3.value,
_valid = _ref3.valid;
if (_valid(data)) return _value;
for (const _ref of cachedValue) {
const {
value,
valid
} = _ref;
if (valid(data)) return value;
}
}
var cache = new CacheConfigurator(data);
var value = handler(arg, cache);
const cache = new CacheConfigurator(data);
const value = handler(arg, cache);
if (!cache.configured()) cache.forever();
cache.deactivate();
switch (cache.mode()) {
case "forever":
cachedValue = [{
value: value,
valid: function valid() {
return true;
}
value,
valid: () => true
}];
callCache.set(arg, cachedValue);
break;
case "invalidate":
cachedValue = [{
value: value,
value,
valid: cache.validator()
}];
callCache.set(arg, cachedValue);
@@ -65,12 +54,12 @@ function makeCachedFunction(callCache, handler) {
case "valid":
if (cachedValue) {
cachedValue.push({
value: value,
value,
valid: cache.validator()
});
} else {
cachedValue = [{
value: value,
value,
valid: cache.validator()
}];
callCache.set(arg, cachedValue);
@@ -82,8 +71,8 @@ function makeCachedFunction(callCache, handler) {
};
}
var CacheConfigurator = function () {
function CacheConfigurator(data) {
class CacheConfigurator {
constructor(data) {
this._active = true;
this._never = false;
this._forever = false;
@@ -93,20 +82,18 @@ var CacheConfigurator = function () {
this._data = data;
}
var _proto = CacheConfigurator.prototype;
_proto.simple = function simple() {
simple() {
return makeSimpleConfigurator(this);
};
}
_proto.mode = function mode() {
mode() {
if (this._never) return "never";
if (this._forever) return "forever";
if (this._invalidate) return "invalidate";
return "valid";
};
}
_proto.forever = function forever() {
forever() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
@@ -117,9 +104,9 @@ var CacheConfigurator = function () {
this._forever = true;
this._configured = true;
};
}
_proto.never = function never() {
never() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
@@ -130,9 +117,9 @@ var CacheConfigurator = function () {
this._never = true;
this._configured = true;
};
}
_proto.using = function using(handler) {
using(handler) {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
@@ -142,14 +129,14 @@ var CacheConfigurator = function () {
}
this._configured = true;
var key = handler(this._data);
const key = handler(this._data);
this._pairs.push([key, handler]);
return key;
};
}
_proto.invalidate = function invalidate(handler) {
invalidate(handler) {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
@@ -160,34 +147,27 @@ var CacheConfigurator = function () {
this._invalidate = true;
this._configured = true;
var key = handler(this._data);
const key = handler(this._data);
this._pairs.push([key, handler]);
return key;
};
}
_proto.validator = function validator() {
var pairs = this._pairs;
return function (data) {
return pairs.every(function (_ref4) {
var key = _ref4[0],
fn = _ref4[1];
return key === fn(data);
});
};
};
validator() {
const pairs = this._pairs;
return data => pairs.every(([key, fn]) => key === fn(data));
}
_proto.deactivate = function deactivate() {
deactivate() {
this._active = false;
};
}
_proto.configured = function configured() {
configured() {
return this._configured;
};
}
return CacheConfigurator;
}();
}
function makeSimpleConfigurator(cache) {
function cacheFn(val) {
@@ -196,28 +176,24 @@ function makeSimpleConfigurator(cache) {
return;
}
return cache.using(val);
return cache.using(() => assertSimpleType(val()));
}
cacheFn.forever = function () {
return cache.forever();
};
cacheFn.forever = () => cache.forever();
cacheFn.never = function () {
return cache.never();
};
cacheFn.never = () => cache.never();
cacheFn.using = function (cb) {
return cache.using(function () {
return cb();
});
};
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
cacheFn.invalidate = function (cb) {
return cache.invalidate(function () {
return cb();
});
};
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
return cacheFn;
}
function assertSimpleType(value) {
if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") {
throw new Error("Cache keys must be either string, boolean, number, null, or undefined.");
}
return value;
}

View File

@@ -3,23 +3,14 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildPresetChain = buildPresetChain;
exports.buildRootChain = buildRootChain;
exports.buildPresetChain = void 0;
exports.buildPresetChainWalker = void 0;
function _path() {
var data = _interopRequireDefault(require("path"));
const data = _interopRequireDefault(require("path"));
_path = function _path() {
return data;
};
return data;
}
function _micromatch() {
var data = _interopRequireDefault(require("micromatch"));
_micromatch = function _micromatch() {
_path = function () {
return data;
};
@@ -27,9 +18,9 @@ function _micromatch() {
}
function _debug() {
var data = _interopRequireDefault(require("debug"));
const data = _interopRequireDefault(require("debug"));
_debug = function _debug() {
_debug = function () {
return data;
};
@@ -38,6 +29,8 @@ function _debug() {
var _options = require("./validation/options");
var _patternToRegex = _interopRequireDefault(require("./pattern-to-regex"));
var _files = require("./files");
var _caching = require("./caching");
@@ -46,255 +39,223 @@ var _configDescriptors = require("./config-descriptors");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var debug = (0, _debug().default)("babel:config:config-chain");
var buildPresetChain = makeChainWalker({
init: function init(arg) {
return arg;
},
root: function root(preset) {
return loadPresetDescriptors(preset);
},
env: function env(preset, envName) {
return loadPresetEnvDescriptors(preset)(envName);
},
overrides: function overrides(preset, index) {
return loadPresetOverridesDescriptors(preset)(index);
},
overridesEnv: function overridesEnv(preset, index, envName) {
return 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);
});
});
const debug = (0, _debug().default)("babel:config:config-chain");
function buildPresetChain(arg, context) {
const chain = buildPresetChainWalker(arg, context);
if (!chain) return null;
return {
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options.map(o => normalizeOptions(o))
};
}
const buildPresetChainWalker = makeChainWalker({
init: arg => arg,
root: preset => loadPresetDescriptors(preset),
env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),
overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),
overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName)
});
exports.buildPresetChainWalker = buildPresetChainWalker;
const loadPresetDescriptors = (0, _caching.makeWeakCache)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors));
const loadPresetEnvDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName)));
const loadPresetOverridesDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index)));
const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(index => (0, _caching.makeStrongCache)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName))));
function buildRootChain(opts, context) {
var programmaticChain = loadProgrammaticChain({
const programmaticChain = loadProgrammaticChain({
options: opts,
dirname: context.cwd
}, context);
if (!programmaticChain) return null;
var _opts$root = opts.root,
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;
let configFile;
var absoluteRoot = _path().default.resolve(context.cwd, rootDir);
var configFile;
if (typeof configFileName === "string") {
configFile = (0, _files.loadConfig)(configFileName, context.cwd, context.envName);
} else if (configFileName === true) {
configFile = (0, _files.findRootConfig)(absoluteRoot, context.envName);
if (typeof opts.configFile === "string") {
configFile = (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller);
} else if (opts.configFile !== false) {
configFile = (0, _files.findRootConfig)(context.root, context.envName, context.caller);
}
var configFileChain = emptyChain();
let {
babelrc,
babelrcRoots
} = opts;
let babelrcRootsDirectory = context.cwd;
const configFileChain = emptyChain();
if (configFile) {
var result = loadFileChain(configFile, context);
const validatedFile = validateConfigFile(configFile);
const result = loadFileChain(validatedFile, context);
if (!result) return null;
if (babelrc === undefined) {
babelrc = validatedFile.options.babelrc;
}
if (babelrcRoots === undefined) {
babelrcRootsDirectory = validatedFile.dirname;
babelrcRoots = validatedFile.options.babelrcRoots;
}
mergeChain(configFileChain, result);
}
var pkgData = typeof context.filename === "string" ? (0, _files.findPackageData)(context.filename) : null;
var ignoreFile, babelrcFile;
var fileChain = emptyChain();
const pkgData = typeof context.filename === "string" ? (0, _files.findPackageData)(context.filename) : null;
let ignoreFile, babelrcFile;
const fileChain = emptyChain();
if (babelrc && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, absoluteRoot)) {
var _findRelativeConfig = (0, _files.findRelativeConfig)(pkgData, context.envName);
ignoreFile = _findRelativeConfig.ignore;
babelrcFile = _findRelativeConfig.config;
if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) {
({
ignore: ignoreFile,
config: babelrcFile
} = (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller));
if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) {
return null;
}
if (babelrcFile) {
var _result = loadFileChain(babelrcFile, context);
if (!_result) return null;
mergeChain(fileChain, _result);
const result = loadFileChain(validateBabelrcFile(babelrcFile), context);
if (!result) return null;
mergeChain(fileChain, result);
}
}
var chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain);
const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain);
return {
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options.map(function (o) {
return normalizeOptions(o);
}),
options: chain.options.map(o => normalizeOptions(o)),
ignore: ignoreFile || undefined,
babelrc: babelrcFile || undefined,
config: configFile || undefined
};
}
function babelrcLoadEnabled(context, pkgData, babelrcRoots, absoluteRoot) {
function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) {
if (typeof babelrcRoots === "boolean") return babelrcRoots;
const absoluteRoot = context.root;
if (babelrcRoots === undefined) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
var babelrcPatterns = babelrcRoots;
let babelrcPatterns = babelrcRoots;
if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns];
babelrcPatterns = babelrcPatterns.map(function (pat) {
return _path().default.resolve(context.cwd, pat);
babelrcPatterns = babelrcPatterns.map(pat => {
return typeof pat === "string" ? _path().default.resolve(babelrcRootsDirectory, pat) : pat;
});
if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {
return pkgData.directories.indexOf(absoluteRoot) !== -1;
}
return (0, _micromatch().default)(pkgData.directories, babelrcPatterns).length > 0;
}
return babelrcPatterns.some(pat => {
if (typeof pat === "string") {
pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory);
}
var loadProgrammaticChain = makeChainWalker({
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,
dirname: file.dirname,
options: (0, _options.validate)("file", file.options)
};
});
var loadFileDescriptors = (0, _caching.makeWeakCache)(function (file) {
return buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors);
});
var loadFileEnvDescriptors = (0, _caching.makeWeakCache)(function (file) {
return (0, _caching.makeStrongCache)(function (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);
return pkgData.directories.some(directory => {
return matchPattern(pat, babelrcRootsDirectory, directory, context);
});
});
});
}
function buildRootDescriptors(_ref, alias, descriptors) {
var dirname = _ref.dirname,
options = _ref.options;
const validateConfigFile = (0, _caching.makeWeakCache)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("configfile", file.options)
}));
const validateBabelrcFile = (0, _caching.makeWeakCache)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("babelrcfile", file.options)
}));
const validateExtendFile = (0, _caching.makeWeakCache)(file => ({
filepath: file.filepath,
dirname: file.dirname,
options: (0, _options.validate)("extendsfile", file.options)
}));
const loadProgrammaticChain = makeChainWalker({
root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors),
env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName),
overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index),
overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName)
});
const loadFileChain = makeChainWalker({
root: file => loadFileDescriptors(file),
env: (file, envName) => loadFileEnvDescriptors(file)(envName),
overrides: (file, index) => loadFileOverridesDescriptors(file)(index),
overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName)
});
const loadFileDescriptors = (0, _caching.makeWeakCache)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors));
const loadFileEnvDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName)));
const loadFileOverridesDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index)));
const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(index => (0, _caching.makeStrongCache)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName))));
function buildRootDescriptors({
dirname,
options
}, alias, descriptors) {
return descriptors(dirname, options, alias);
}
function buildEnvDescriptors(_ref2, alias, descriptors, envName) {
var dirname = _ref2.dirname,
options = _ref2.options;
var opts = options.env && options.env[envName];
return opts ? descriptors(dirname, opts, alias + ".env[\"" + envName + "\"]") : null;
function buildEnvDescriptors({
dirname,
options
}, alias, descriptors, envName) {
const opts = options.env && options.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null;
}
function buildOverrideDescriptors(_ref3, alias, descriptors, index) {
var dirname = _ref3.dirname,
options = _ref3.options;
var opts = options.overrides && options.overrides[index];
function buildOverrideDescriptors({
dirname,
options
}, alias, descriptors, index) {
const opts = options.overrides && options.overrides[index];
if (!opts) throw new Error("Assertion failure - missing override");
return descriptors(dirname, opts, alias + ".overrides[" + index + "]");
return descriptors(dirname, opts, `${alias}.overrides[${index}]`);
}
function buildOverrideEnvDescriptors(_ref4, alias, descriptors, index, envName) {
var dirname = _ref4.dirname,
options = _ref4.options;
var override = options.overrides && options.overrides[index];
function buildOverrideEnvDescriptors({
dirname,
options
}, alias, descriptors, index, envName) {
const override = options.overrides && options.overrides[index];
if (!override) throw new Error("Assertion failure - missing override");
var opts = override.env && override.env[envName];
return opts ? descriptors(dirname, opts, alias + ".overrides[" + index + "].env[\"" + envName + "\"]") : null;
const opts = override.env && override.env[envName];
return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null;
}
function makeChainWalker(_ref5) {
var init = _ref5.init,
root = _ref5.root,
env = _ref5.env,
overrides = _ref5.overrides,
overridesEnv = _ref5.overridesEnv;
return function (arg, context, files) {
if (files === void 0) {
files = new Set();
}
var input = init(arg);
var dirname = input.dirname;
var flattenedConfigs = [];
var rootOpts = root(input);
function makeChainWalker({
root,
env,
overrides,
overridesEnv
}) {
return (input, context, files = new Set()) => {
const {
dirname
} = input;
const flattenedConfigs = [];
const rootOpts = root(input);
if (configIsApplicable(rootOpts, dirname, context)) {
flattenedConfigs.push(rootOpts);
var envOpts = env(input, context.envName);
const envOpts = env(input, context.envName);
if (envOpts && configIsApplicable(envOpts, dirname, context)) {
flattenedConfigs.push(envOpts);
}
(rootOpts.options.overrides || []).forEach(function (_, index) {
var overrideOps = overrides(input, index);
(rootOpts.options.overrides || []).forEach((_, index) => {
const overrideOps = overrides(input, index);
if (configIsApplicable(overrideOps, dirname, context)) {
flattenedConfigs.push(overrideOps);
var overrideEnvOpts = overridesEnv(input, index, context.envName);
const overrideEnvOpts = overridesEnv(input, index, context.envName);
if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) {
flattenedConfigs.push(overrideEnvOpts);
@@ -303,20 +264,18 @@ function makeChainWalker(_ref5) {
});
}
if (flattenedConfigs.some(function (_ref6) {
var _ref6$options = _ref6.options,
ignore = _ref6$options.ignore,
only = _ref6$options.only;
return shouldIgnore(context, ignore, only, dirname);
})) {
if (flattenedConfigs.some(({
options: {
ignore,
only
}
}) => shouldIgnore(context, ignore, only, dirname))) {
return null;
}
var chain = emptyChain();
for (var _i = 0; _i < flattenedConfigs.length; _i++) {
var op = flattenedConfigs[_i];
const chain = emptyChain();
for (const op of flattenedConfigs) {
if (!mergeExtendsChain(chain, op.options, dirname, context, files)) {
return null;
}
@@ -330,16 +289,14 @@ function makeChainWalker(_ref5) {
function mergeExtendsChain(chain, opts, dirname, context, files) {
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)) {
throw new Error("Configuration cycle detected loading " + file.filepath + ".\n" + "File already loaded following the config chain:\n" + Array.from(files, function (file) {
return " - " + file.filepath;
}).join("\n"));
throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n"));
}
files.add(file);
var fileChain = loadFileChain(file, context, files);
const fileChain = loadFileChain(validateExtendFile(file), context, files);
files.delete(file);
if (!fileChain) return false;
mergeChain(chain, fileChain);
@@ -347,29 +304,20 @@ function mergeExtendsChain(chain, opts, dirname, context, files) {
}
function mergeChain(target, source) {
var _target$options, _target$plugins, _target$presets;
(_target$options = target.options).push.apply(_target$options, source.options);
(_target$plugins = target.plugins).push.apply(_target$plugins, source.plugins);
(_target$presets = target.presets).push.apply(_target$presets, source.presets);
target.options.push(...source.options);
target.plugins.push(...source.plugins);
target.presets.push(...source.presets);
return target;
}
function mergeChainOpts(target, _ref7) {
var _target$plugins2, _target$presets2;
var options = _ref7.options,
plugins = _ref7.plugins,
presets = _ref7.presets;
function mergeChainOpts(target, {
options,
plugins,
presets
}) {
target.options.push(options);
(_target$plugins2 = target.plugins).push.apply(_target$plugins2, plugins());
(_target$presets2 = target.presets).push.apply(_target$presets2, presets());
target.plugins.push(...plugins());
target.presets.push(...presets());
return target;
}
@@ -382,16 +330,20 @@ function emptyChain() {
}
function normalizeOptions(opts) {
var options = Object.assign({}, opts);
const options = Object.assign({}, opts);
delete options.extends;
delete options.env;
delete options.overrides;
delete options.plugins;
delete options.presets;
delete options.passPerPreset;
delete options.ignore;
delete options.only;
delete options.test;
delete options.include;
delete options.exclude;
if (options.sourceMap) {
if (options.hasOwnProperty("sourceMap")) {
options.sourceMaps = options.sourceMap;
delete options.sourceMap;
}
@@ -400,44 +352,27 @@ function normalizeOptions(opts) {
}
function dedupDescriptors(items) {
var map = new Map();
var 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;
const map = new Map();
const descriptors = [];
for (const item of items) {
if (typeof item.value === "function") {
var fnKey = item.value;
var nameMap = map.get(fnKey);
const fnKey = item.value;
let nameMap = map.get(fnKey);
if (!nameMap) {
nameMap = new Map();
map.set(fnKey, nameMap);
}
var desc = nameMap.get(item.name);
let desc = nameMap.get(item.name);
if (!desc) {
desc = {
value: null
value: item
};
descriptors.push(desc);
if (!item.ownPass) nameMap.set(item.name, desc);
}
if (item.options === false) {
desc.value = null;
} else {
desc.value = item;
}
@@ -448,111 +383,57 @@ function dedupDescriptors(items) {
}
}
return descriptors.reduce(function (acc, desc) {
if (desc.value) acc.push(desc.value);
return descriptors.reduce((acc, desc) => {
acc.push(desc.value);
return acc;
}, []);
}
function configIsApplicable(_ref9, dirname, context) {
var options = _ref9.options;
function configIsApplicable({
options
}, dirname, context) {
return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname));
}
function configFieldIsApplicable(context, test, dirname) {
if (context.filename === null) {
throw new Error("Configuration contains explicit test/include/exclude checks, but no filename was passed to Babel");
}
var ctx = context;
var patterns = Array.isArray(test) ? test : [test];
return matchesPatterns(ctx, patterns, dirname, false);
const patterns = Array.isArray(test) ? test : [test];
return matchesPatterns(context, patterns, dirname);
}
function shouldIgnore(context, ignore, only, dirname) {
if (ignore) {
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);
return true;
}
if (ignore && matchesPatterns(context, ignore, dirname)) {
debug("Ignored %o because it matched one of %O from %o", context.filename, ignore, dirname);
return true;
}
if (only) {
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);
return true;
}
if (only && !matchesPatterns(context, only, dirname)) {
debug("Ignored %o because it failed to match one of %O from %o", context.filename, only, dirname);
return true;
}
return false;
}
function matchesPatterns(context, patterns, dirname, allowNegation) {
if (allowNegation === void 0) {
allowNegation = true;
}
function matchesPatterns(context, patterns, dirname) {
return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context));
}
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);
function matchPattern(pattern, dirname, pathToTest, context) {
if (typeof pattern === "function") {
return !!pattern(pathToTest, {
dirname,
envName: context.envName,
caller: context.caller
});
if ((0, _micromatch().default)(possibleDirs, absolutePatterns, {
nocase: true,
nonegate: !allowNegation
}).length > 0) {
return true;
}
}
return false;
}
var getPossibleDirs = (0, _caching.makeWeakCache)(function (context) {
var current = context.filename;
if (current === null) return [];
var possibleDirs = [current];
while (true) {
var previous = current;
current = _path().default.dirname(current);
if (previous === current) break;
possibleDirs.push(current);
if (typeof pathToTest !== "string") {
throw new Error(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`);
}
return possibleDirs;
});
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");
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) {
var plugins = options.plugins,
presets = options.presets,
passPerPreset = options.passPerPreset;
const {
plugins,
presets,
passPerPreset
} = options;
return {
options: options,
plugins: plugins ? function () {
return createCachedPluginDescriptors(plugins, dirname)(alias);
} : function () {
return [];
},
presets: presets ? function () {
return createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset);
} : function () {
return [];
}
options,
plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => [],
presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => []
};
}
function createUncachedDescriptors(dirname, options, alias) {
var plugins;
var presets;
let plugins;
let presets;
return {
options: options,
plugins: function (_plugins) {
function plugins() {
return _plugins.apply(this, arguments);
}
plugins.toString = function () {
return _plugins.toString();
};
return plugins;
}(function () {
options,
plugins: () => {
if (!plugins) {
plugins = createPluginDescriptors(options.plugins || [], dirname, alias);
}
return plugins;
}),
presets: function (_presets) {
function presets() {
return _presets.apply(this, arguments);
}
presets.toString = function () {
return _presets.toString();
};
return presets;
}(function () {
},
presets: () => {
if (!presets) {
presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset);
}
return presets;
})
}
};
}
var createCachedPresetDescriptors = (0, _caching.makeWeakCache)(function (items, cache) {
var dirname = cache.using(function (dir) {
return dir;
});
return (0, _caching.makeStrongCache)(function (alias) {
return (0, _caching.makeStrongCache)(function (passPerPreset) {
return createPresetDescriptors(items, dirname, alias, passPerPreset);
});
});
const PRESET_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPresetDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
const dirname = cache.using(dir => dir);
return (0, _caching.makeStrongCache)(alias => (0, _caching.makeStrongCache)(passPerPreset => createPresetDescriptors(items, dirname, alias, passPerPreset).map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc))));
});
var createCachedPluginDescriptors = (0, _caching.makeWeakCache)(function (items, cache) {
var dirname = cache.using(function (dir) {
return dir;
});
return (0, _caching.makeStrongCache)(function (alias) {
return createPluginDescriptors(items, dirname, alias);
});
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPluginDescriptors = (0, _caching.makeWeakCache)((items, cache) => {
const dirname = cache.using(dir => dir);
return (0, _caching.makeStrongCache)(alias => createPluginDescriptors(items, dirname, alias).map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)));
});
const DEFAULT_OPTIONS = {};
function loadCachedDescriptor(cache, desc) {
const {
value,
options = DEFAULT_OPTIONS
} = desc;
if (options === false) return desc;
let cacheByOptions = cache.get(value);
if (!cacheByOptions) {
cacheByOptions = new WeakMap();
cache.set(value, cacheByOptions);
}
let possibilities = cacheByOptions.get(options);
if (!possibilities) {
possibilities = [];
cacheByOptions.set(options, possibilities);
}
if (possibilities.indexOf(desc) === -1) {
const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc));
if (matches.length > 0) {
return matches[0];
}
possibilities.push(desc);
}
return desc;
}
function createPresetDescriptors(items, dirname, alias, passPerPreset) {
return createDescriptors("preset", items, dirname, alias, passPerPreset);
@@ -102,67 +106,60 @@ function createPluginDescriptors(items, dirname, alias) {
}
function createDescriptors(type, items, dirname, alias, ownPass) {
var descriptors = items.map(function (item, index) {
return createDescriptor(item, dirname, {
type: type,
alias: alias + "$" + index,
ownPass: !!ownPass
});
});
const descriptors = items.map((item, index) => createDescriptor(item, dirname, {
type,
alias: `${alias}$${index}`,
ownPass: !!ownPass
}));
assertNoDuplicates(descriptors);
return descriptors;
}
function createDescriptor(pair, dirname, _ref) {
var type = _ref.type,
alias = _ref.alias,
ownPass = _ref.ownPass;
var desc = (0, _item.getItemDescriptor)(pair);
function createDescriptor(pair, dirname, {
type,
alias,
ownPass
}) {
const desc = (0, _item.getItemDescriptor)(pair);
if (desc) {
return desc;
}
var name;
var options;
var value = pair;
let name;
let options;
let value = pair;
if (Array.isArray(value)) {
if (value.length === 3) {
var _value = value;
value = _value[0];
options = _value[1];
name = _value[2];
[value, options, name] = value;
} else {
var _value2 = value;
value = _value2[0];
options = _value2[1];
[value, options] = value;
}
}
var file = undefined;
var filepath = null;
let file = undefined;
let filepath = null;
if (typeof value === "string") {
if (typeof type !== "string") {
throw new Error("To resolve a string-based item, the type of item must be given");
}
var resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset;
var _request = value;
var _resolver = resolver(value, dirname);
filepath = _resolver.filepath;
value = _resolver.value;
const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset;
const request = value;
({
filepath,
value
} = resolver(value, dirname));
file = {
request: _request,
request,
resolved: filepath
};
}
if (!value) {
throw new Error("Unexpected falsy value: " + String(value));
throw new Error(`Unexpected falsy value: ${String(value)}`);
}
if (typeof value === "object" && value.__esModule) {
@@ -174,42 +171,30 @@ function createDescriptor(pair, dirname, _ref) {
}
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) {
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 {
name: name,
name,
alias: filepath || alias,
value: value,
options: options,
dirname: dirname,
ownPass: ownPass,
file: file
value,
options,
dirname,
ownPass,
file
};
}
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]();;) {
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;
for (const item of items) {
if (typeof item.value !== "function") continue;
var nameMap = map.get(item.value);
let nameMap = map.get(item.value);
if (!nameMap) {
nameMap = new Set();
@@ -217,7 +202,7 @@ function assertNoDuplicates(items) {
}
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);

View File

@@ -3,14 +3,15 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.findConfigUpwards = findConfigUpwards;
exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig;
exports.loadConfig = loadConfig;
function _debug() {
var data = _interopRequireDefault(require("debug"));
const data = _interopRequireDefault(require("debug"));
_debug = function _debug() {
_debug = function () {
return data;
};
@@ -18,9 +19,9 @@ function _debug() {
}
function _path() {
var data = _interopRequireDefault(require("path"));
const data = _interopRequireDefault(require("path"));
_path = function _path() {
_path = function () {
return data;
};
@@ -28,9 +29,9 @@ function _path() {
}
function _fs() {
var data = _interopRequireDefault(require("fs"));
const data = _interopRequireDefault(require("fs"));
_fs = function _fs() {
_fs = function () {
return data;
};
@@ -38,9 +39,9 @@ function _fs() {
}
function _json() {
var data = _interopRequireDefault(require("json5"));
const data = _interopRequireDefault(require("json5"));
_json = function _json() {
_json = function () {
return data;
};
@@ -48,9 +49,9 @@ function _json() {
}
function _resolve() {
var data = _interopRequireDefault(require("resolve"));
const data = _interopRequireDefault(require("resolve"));
_resolve = function _resolve() {
_resolve = function () {
return data;
};
@@ -63,49 +64,57 @@ var _configApi = _interopRequireDefault(require("../helpers/config-api"));
var _utils = require("./utils");
var _patternToRegex = _interopRequireDefault(require("../pattern-to-regex"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var debug = (0, _debug().default)("babel:config:loading:files:configuration");
var BABEL_CONFIG_JS_FILENAME = "babel.config.js";
var BABELRC_FILENAME = ".babelrc";
var BABELRC_JS_FILENAME = ".babelrc.js";
var BABELIGNORE_FILENAME = ".babelignore";
const debug = (0, _debug().default)("babel:config:loading:files:configuration");
const BABEL_CONFIG_JS_FILENAME = "babel.config.js";
const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const BABELIGNORE_FILENAME = ".babelignore";
function findRelativeConfig(packageData, envName) {
var config = null;
var ignore = null;
function findConfigUpwards(rootDir) {
let dirname = rootDir;
var dirname = _path().default.dirname(packageData.filepath);
var _loop = function _loop() {
if (_isArray) {
if (_i >= _iterator.length) return "break";
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) return "break";
_ref = _i.value;
while (true) {
if (_fs().default.existsSync(_path().default.join(dirname, BABEL_CONFIG_JS_FILENAME))) {
return dirname;
}
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) {
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce(function (previousConfig, name) {
var filepath = _path().default.join(loc, name);
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce((previousConfig, name) => {
const filepath = _path().default.join(loc, name);
var config = readConfig(filepath, envName);
const config = readConfig(filepath, envName, caller);
if (config && previousConfig) {
throw new Error("Multiple configuration files found. Please remove one:\n" + (" - " + _path().default.basename(previousConfig.filepath) + "\n") + (" - " + name + "\n") + ("from " + loc));
throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().default.basename(previousConfig.filepath)}\n` + ` - ${name}\n` + `from ${loc}`);
}
return config || previousConfig;
}, null);
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 (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;
@@ -117,7 +126,7 @@ function findRelativeConfig(packageData, envName) {
}
if (!ignore) {
var ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME);
const ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME);
ignore = readIgnoreConfig(ignoreLoc);
@@ -125,26 +134,18 @@ function findRelativeConfig(packageData, envName) {
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 {
config: config,
ignore: ignore
config,
ignore
};
}
function findRootConfig(dirname, envName) {
var filepath = _path().default.resolve(dirname, BABEL_CONFIG_JS_FILENAME);
function findRootConfig(dirname, envName, caller) {
const filepath = _path().default.resolve(dirname, BABEL_CONFIG_JS_FILENAME);
var conf = readConfig(filepath, envName);
const conf = readConfig(filepath, envName, caller);
if (conf) {
debug("Found root config %o in $o.", BABEL_CONFIG_JS_FILENAME, dirname);
@@ -153,29 +154,30 @@ function findRootConfig(dirname, envName) {
return conf;
}
function loadConfig(name, dirname, envName) {
var filepath = _resolve().default.sync(name, {
function loadConfig(name, dirname, envName, caller) {
const filepath = _resolve().default.sync(name, {
basedir: dirname
});
var conf = readConfig(filepath, envName);
const conf = readConfig(filepath, envName, caller);
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);
return conf;
}
function readConfig(filepath, envName) {
function readConfig(filepath, envName, caller) {
return _path().default.extname(filepath) === ".js" ? readConfigJS(filepath, {
envName: envName
envName,
caller
}) : readConfigJSON5(filepath);
}
var LOADING_CONFIGS = new Set();
var readConfigJS = (0, _caching.makeStrongCache)(function (filepath, cache) {
const LOADING_CONFIGS = new Set();
const readConfigJS = (0, _caching.makeStrongCache)((filepath, cache) => {
if (!_fs().default.existsSync(filepath)) {
cache.forever();
return null;
@@ -185,22 +187,22 @@ var readConfigJS = (0, _caching.makeStrongCache)(function (filepath, cache) {
cache.never();
debug("Auto-ignoring usage of config %o.", filepath);
return {
filepath: filepath,
filepath,
dirname: _path().default.dirname(filepath),
options: {}
};
}
var options;
let options;
try {
LOADING_CONFIGS.add(filepath);
var configModule = require(filepath);
const configModule = require(filepath);
options = configModule && configModule.__esModule ? configModule.default || undefined : configModule;
} catch (err) {
err.message = filepath + ": Error while loading config - " + err.message;
err.message = `${filepath}: Error while loading config - ${err.message}`;
throw err;
} finally {
LOADING_CONFIGS.delete(filepath);
@@ -212,25 +214,25 @@ var readConfigJS = (0, _caching.makeStrongCache)(function (filepath, cache) {
}
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") {
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 {
filepath: filepath,
filepath,
dirname: _path().default.dirname(filepath),
options: options
options
};
});
var packageToBabelConfig = (0, _caching.makeWeakCache)(function (file) {
if (typeof file.options.babel === "undefined") return null;
var babel = file.options.babel;
const packageToBabelConfig = (0, _caching.makeWeakCache)(file => {
const babel = file.options["babel"];
if (typeof babel === "undefined") return null;
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
throw new Error(file.filepath + ": .babel property must be an object");
throw new Error(`${file.filepath}: .babel property must be an object`);
}
return {
@@ -239,45 +241,83 @@ var packageToBabelConfig = (0, _caching.makeWeakCache)(function (file) {
options: babel
};
});
var readConfigJSON5 = (0, _utils.makeStaticFileCache)(function (filepath, content) {
var options;
const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => {
let options;
try {
options = _json().default.parse(content);
} catch (err) {
err.message = filepath + ": Error while parsing config - " + err.message;
err.message = `${filepath}: Error while parsing config - ${err.message}`;
throw err;
}
if (!options) throw new Error(filepath + ": No config detected");
if (!options) throw new Error(`${filepath}: No config detected`);
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)) {
throw new Error(filepath + ": Expected config object but found array");
throw new Error(`${filepath}: Expected config object but found array`);
}
return {
filepath: filepath,
filepath,
dirname: _path().default.dirname(filepath),
options: options
options
};
});
var readIgnoreConfig = (0, _utils.makeStaticFileCache)(function (filepath, content) {
var ignore = content.split("\n").map(function (line) {
return line.replace(/#(.*?)$/, "").trim();
}).filter(function (line) {
return !!line;
});
const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => {
const ignoreDir = _path().default.dirname(filepath);
const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line);
for (const pattern of ignorePatterns) {
if (pattern[0] === "!") {
throw new Error(`Negation of file paths is not supported.`);
}
}
return {
filepath: filepath,
filepath,
dirname: _path().default.dirname(filepath),
ignore: ignore
ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir))
};
});
function throwConfigError() {
throw new Error("Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured\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", {
value: true
});
exports.findConfigUpwards = findConfigUpwards;
exports.findPackageData = findPackageData;
exports.findRelativeConfig = findRelativeConfig;
exports.findRootConfig = findRootConfig;
@@ -12,16 +13,20 @@ exports.resolvePreset = resolvePreset;
exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset;
function findConfigUpwards(rootDir) {
return null;
}
function findPackageData(filepath) {
return {
filepath: filepath,
filepath,
directories: [],
pkg: null,
isPackage: false
};
}
function findRelativeConfig(pkgData, envName) {
function findRelativeConfig(pkgData, envName, caller) {
return {
pkg: null,
config: null,
@@ -29,12 +34,12 @@ function findRelativeConfig(pkgData, envName) {
};
}
function findRootConfig(dirname, envName) {
function findRootConfig(dirname, envName, caller) {
return null;
}
function loadConfig(name, dirname, envName) {
throw new Error("Cannot load " + name + " relative to " + dirname + " in a browser");
function loadConfig(name, dirname, envName, caller) {
throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
}
function resolvePlugin(name, dirname) {
@@ -46,9 +51,9 @@ function resolvePreset(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) {
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", {
enumerable: true,
get: function get() {
get: function () {
return _package.findPackageData;
}
});
Object.defineProperty(exports, "findConfigUpwards", {
enumerable: true,
get: function () {
return _configuration.findConfigUpwards;
}
});
Object.defineProperty(exports, "findRelativeConfig", {
enumerable: true,
get: function get() {
get: function () {
return _configuration.findRelativeConfig;
}
});
Object.defineProperty(exports, "findRootConfig", {
enumerable: true,
get: function get() {
get: function () {
return _configuration.findRootConfig;
}
});
Object.defineProperty(exports, "loadConfig", {
enumerable: true,
get: function get() {
get: function () {
return _configuration.loadConfig;
}
});
Object.defineProperty(exports, "resolvePlugin", {
enumerable: true,
get: function get() {
get: function () {
return _plugins.resolvePlugin;
}
});
Object.defineProperty(exports, "resolvePreset", {
enumerable: true,
get: function get() {
get: function () {
return _plugins.resolvePreset;
}
});
Object.defineProperty(exports, "loadPlugin", {
enumerable: true,
get: function get() {
get: function () {
return _plugins.loadPlugin;
}
});
Object.defineProperty(exports, "loadPreset", {
enumerable: true,
get: function get() {
get: function () {
return _plugins.loadPreset;
}
});

View File

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

View File

@@ -9,9 +9,9 @@ exports.loadPlugin = loadPlugin;
exports.loadPreset = loadPreset;
function _debug() {
var data = _interopRequireDefault(require("debug"));
const data = _interopRequireDefault(require("debug"));
_debug = function _debug() {
_debug = function () {
return data;
};
@@ -19,9 +19,9 @@ function _debug() {
}
function _resolve() {
var data = _interopRequireDefault(require("resolve"));
const data = _interopRequireDefault(require("resolve"));
_resolve = function _resolve() {
_resolve = function () {
return data;
};
@@ -29,9 +29,9 @@ function _resolve() {
}
function _path() {
var data = _interopRequireDefault(require("path"));
const data = _interopRequireDefault(require("path"));
_path = function _path() {
_path = function () {
return data;
};
@@ -40,14 +40,15 @@ function _path() {
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var debug = (0, _debug().default)("babel:config:loading:files:plugins");
var EXACT_RE = /^module:/;
var BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
var BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
var BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
var BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
var OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-plugin-|[^/]+\/)/;
var OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-preset-|[^/]+\/)/;
const debug = (0, _debug().default)("babel:config:loading:files:plugins");
const EXACT_RE = /^module:/;
const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
function resolvePlugin(name, dirname) {
return resolveStandardizedName("plugin", name, dirname);
@@ -58,47 +59,43 @@ function resolvePreset(name, dirname) {
}
function loadPlugin(name, dirname) {
var filepath = resolvePlugin(name, dirname);
const filepath = resolvePlugin(name, dirname);
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);
return {
filepath: filepath,
value: value
filepath,
value
};
}
function loadPreset(name, dirname) {
var filepath = resolvePreset(name, dirname);
const filepath = resolvePreset(name, dirname);
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);
return {
filepath: filepath,
value: value
filepath,
value
};
}
function standardizeName(type, name) {
if (_path().default.isAbsolute(name)) return name;
var 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, "");
const isPreset = type === "preset";
return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, "");
}
function resolveStandardizedName(type, name, dirname) {
if (dirname === void 0) {
dirname = process.cwd();
}
var standardizedName = standardizeName(type, name);
function resolveStandardizedName(type, name, dirname = process.cwd()) {
const standardizedName = standardizeName(type, name);
try {
return _resolve().default.sync(standardizedName, {
@@ -108,7 +105,7 @@ function resolveStandardizedName(type, name, dirname) {
if (e.code !== "MODULE_NOT_FOUND") throw e;
if (standardizedName !== name) {
var resolvedOriginal = false;
let resolvedOriginal = false;
try {
_resolve().default.sync(name, {
@@ -119,11 +116,11 @@ function resolveStandardizedName(type, name, dirname) {
} catch (e2) {}
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 {
_resolve().default.sync(standardizeName(type, "@babel/" + name), {
@@ -134,11 +131,11 @@ function resolveStandardizedName(type, name, dirname) {
} catch (e2) {}
if (resolvedBabel) {
e.message += "\n- Did you mean \"@babel/" + name + "\"?";
e.message += `\n- Did you mean "@babel/${name}"?`;
}
var resolvedOppositeType = false;
var oppositeType = type === "preset" ? "plugin" : "preset";
let resolvedOppositeType = false;
const oppositeType = type === "preset" ? "plugin" : "preset";
try {
_resolve().default.sync(standardizeName(oppositeType, name), {
@@ -149,18 +146,18 @@ function resolveStandardizedName(type, name, dirname) {
} catch (e2) {}
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;
}
}
var LOADING_MODULES = new Set();
const LOADING_MODULES = new Set();
function requireModule(type, name) {
if (LOADING_MODULES.has(name)) {
throw new Error("Reentrant " + type + " detected trying to load \"" + name + "\". This module is not ignored " + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.');
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 {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,17 +6,16 @@ Object.defineProperty(exports, "__esModule", {
exports.loadOptions = loadOptions;
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
get: function () {
return _full.default;
}
});
Object.defineProperty(exports, "loadPartialConfig", {
enumerable: true,
get: function get() {
get: function () {
return _partial.loadPartialConfig;
}
});
exports.OptionManager = void 0;
var _full = _interopRequireDefault(require("./full"));
@@ -25,20 +24,6 @@ var _partial = require("./partial");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function loadOptions(opts) {
var config = (0, _full.default)(opts);
const config = (0, _full.default)(opts);
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;
function _path() {
var data = _interopRequireDefault(require("path"));
const data = _interopRequireDefault(require("path"));
_path = function _path() {
_path = function () {
return data;
};
@@ -25,14 +25,12 @@ function createItemFromDescriptor(desc) {
return new ConfigItem(desc);
}
function createConfigItem(value, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$dirname = _ref.dirname,
dirname = _ref$dirname === void 0 ? "." : _ref$dirname,
type = _ref.type;
var descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), {
type: type,
function createConfigItem(value, {
dirname = ".",
type
} = {}) {
const descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), {
type,
alias: "programmatic item"
});
return createItemFromDescriptor(descriptor);
@@ -46,25 +44,23 @@ function getItemDescriptor(item) {
return undefined;
}
var ConfigItem = function ConfigItem(descriptor) {
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", {
enumerable: false
});
if (this._descriptor.options === false) {
throw new Error("Assertion failure - unexpected false options");
class ConfigItem {
constructor(descriptor) {
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", {
enumerable: false
});
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;
this.name = this._descriptor.name;
this.file = this._descriptor.file ? {
request: this._descriptor.file.request,
resolved: this._descriptor.file.resolved
} : undefined;
Object.freeze(this);
}
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;
this.name = this._descriptor.name;
this.file = this._descriptor.file ? {
request: this._descriptor.file.request,
resolved: this._descriptor.file.resolved
} : undefined;
Object.freeze(this);
};
}
Object.freeze(ConfigItem.prototype);

View File

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

View File

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

View File

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

View File

@@ -13,33 +13,37 @@ var _optionAssertions = require("./option-assertions");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ROOT_VALIDATORS = {
const ROOT_VALIDATORS = {
cwd: _optionAssertions.assertString,
root: _optionAssertions.assertString,
rootMode: _optionAssertions.assertRootMode,
configFile: _optionAssertions.assertConfigFileSearch,
caller: _optionAssertions.assertCallerMetadata,
filename: _optionAssertions.assertString,
filenameRelative: _optionAssertions.assertString,
babelrc: _optionAssertions.assertBoolean,
babelrcRoots: _optionAssertions.assertBabelrcSearch,
code: _optionAssertions.assertBoolean,
ast: _optionAssertions.assertBoolean,
envName: _optionAssertions.assertString
};
var NONPRESET_VALIDATORS = {
extends: _optionAssertions.assertString,
env: assertEnvSet,
ignore: _optionAssertions.assertIgnoreList,
only: _optionAssertions.assertIgnoreList,
overrides: assertOverridesList,
test: _optionAssertions.assertConfigApplicableTest,
include: _optionAssertions.assertConfigApplicableTest,
exclude: _optionAssertions.assertConfigApplicableTest
const BABELRC_VALIDATORS = {
babelrc: _optionAssertions.assertBoolean,
babelrcRoots: _optionAssertions.assertBabelrcSearch
};
var COMMON_VALIDATORS = {
const NONPRESET_VALIDATORS = {
extends: _optionAssertions.assertString,
ignore: _optionAssertions.assertIgnoreList,
only: _optionAssertions.assertIgnoreList
};
const COMMON_VALIDATORS = {
inputSourceMap: _optionAssertions.assertInputSourceMap,
presets: _optionAssertions.assertPluginList,
plugins: _optionAssertions.assertPluginList,
passPerPreset: _optionAssertions.assertBoolean,
env: assertEnvSet,
overrides: assertOverridesList,
test: _optionAssertions.assertConfigApplicableTest,
include: _optionAssertions.assertConfigApplicableTest,
exclude: _optionAssertions.assertConfigApplicableTest,
retainLines: _optionAssertions.assertBoolean,
comments: _optionAssertions.assertBoolean,
shouldPrintComment: _optionAssertions.assertFunction,
@@ -62,44 +66,60 @@ var COMMON_VALIDATORS = {
generatorOpts: _optionAssertions.assertObject
};
function getSource(loc) {
return loc.type === "root" ? loc.source : getSource(loc.parent);
}
function validate(type, opts) {
return validateNested({
type: "root",
source: type
}, opts);
}
function validateNested(loc, opts) {
const type = getSource(loc);
assertNoDuplicateSourcemap(opts);
Object.keys(opts).forEach(function (key) {
Object.keys(opts).forEach(key => {
const optLoc = {
type: "option",
name: key,
parent: loc
};
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]) {
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") {
throw new Error("." + key + " is not allowed inside another env block");
if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) {
if (type === "babelrcfile" || type === "extendsfile") {
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`);
}
throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`);
}
if (type === "env" && key === "overrides") {
throw new Error("." + key + " is not allowed inside an env block");
}
if (type === "override" && key === "overrides") {
throw new Error("." + key + " is not allowed inside an overrides block");
}
var validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || ROOT_VALIDATORS[key];
if (validator) validator(key, opts[key]);else throw buildUnknownError(key);
const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError;
validator(optLoc, opts[key]);
});
return opts;
}
function buildUnknownError(key) {
function throwUnknownError(loc) {
const key = loc.name;
if (_removed.default[key]) {
var _removed$key = _removed.default[key],
message = _removed$key.message,
_removed$key$version = _removed$key.version,
version = _removed$key$version === void 0 ? 5 : _removed$key$version;
throw new ReferenceError("Using removed Babel " + version + " option: ." + key + " - " + message);
const {
message,
version = 5
} = _removed.default[key];
throw new ReferenceError(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`);
} 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);
}
}
@@ -114,48 +134,53 @@ function assertNoDuplicateSourcemap(opts) {
}
}
function assertEnvSet(key, value) {
var obj = (0, _optionAssertions.assertObject)(key, value);
function assertEnvSet(loc, value) {
if (loc.parent.type === "env") {
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside of another .env block`);
}
const parent = loc.parent;
const obj = (0, _optionAssertions.assertObject)(loc, value);
if (obj) {
var _arr = Object.keys(obj);
for (var _i = 0; _i < _arr.length; _i++) {
var _key = _arr[_i];
var _env = (0, _optionAssertions.assertObject)(_key, obj[_key]);
if (_env) validate("env", _env);
for (const envName of Object.keys(obj)) {
const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]);
if (!env) continue;
const envLoc = {
type: "env",
name: envName,
parent
};
validateNested(envLoc, env);
}
}
return obj;
}
function assertOverridesList(key, value) {
var arr = (0, _optionAssertions.assertArray)(key, value);
function assertOverridesList(loc, value) {
if (loc.parent.type === "env") {
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`);
}
if (loc.parent.type === "overrides") {
throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`);
}
const parent = loc.parent;
const arr = (0, _optionAssertions.assertArray)(loc, value);
if (arr) {
for (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,
index = _ref2[0],
item = _ref2[1];
var _env2 = (0, _optionAssertions.assertObject)("" + index, item);
if (!_env2) throw new Error("." + key + "[" + index + "] must be an object");
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 VALIDATORS = {
const VALIDATORS = {
name: _optionAssertions.assertString,
manipulateOptions: _optionAssertions.assertFunction,
pre: _optionAssertions.assertFunction,
@@ -19,15 +19,13 @@ var VALIDATORS = {
};
function assertVisitorMap(key, value) {
var obj = (0, _optionAssertions.assertObject)(key, value);
const obj = (0, _optionAssertions.assertObject)(key, value);
if (obj) {
Object.keys(obj).forEach(function (prop) {
return assertVisitorHandler(prop, obj[prop]);
});
Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));
if (obj.enter || obj.exit) {
throw new Error("." + key + " cannot contain catch-all \"enter\" or \"exit\" handlers. Please target individual nodes.");
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) {
if (value && typeof value === "object") {
Object.keys(value).forEach(function (handler) {
Object.keys(value).forEach(handler => {
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") {
throw new Error(".visitor[\"" + key + "\"] must be a function");
throw new Error(`.visitor["${key}"] must be a function`);
}
return value;
}
function validatePluginObject(obj) {
Object.keys(obj).forEach(function (key) {
var validator = VALIDATORS[key];
if (validator) validator(key, obj[key]);else throw new Error("." + key + " is not a valid Plugin property");
Object.keys(obj).forEach(key => {
const validator = VALIDATORS[key];
if (validator) validator(key, obj[key]);else throw new Error(`.${key} is not a valid Plugin property`);
});
return obj;
}

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

@@ -6,119 +6,149 @@ Object.defineProperty(exports, "__esModule", {
exports.Plugin = Plugin;
Object.defineProperty(exports, "File", {
enumerable: true,
get: function get() {
get: function () {
return _file.default;
}
});
Object.defineProperty(exports, "buildExternalHelpers", {
enumerable: true,
get: function get() {
get: function () {
return _buildExternalHelpers.default;
}
});
Object.defineProperty(exports, "resolvePlugin", {
enumerable: true,
get: function get() {
get: function () {
return _files.resolvePlugin;
}
});
Object.defineProperty(exports, "resolvePreset", {
enumerable: true,
get: function get() {
get: function () {
return _files.resolvePreset;
}
});
Object.defineProperty(exports, "version", {
enumerable: true,
get: function get() {
get: function () {
return _package.version;
}
});
Object.defineProperty(exports, "getEnv", {
enumerable: true,
get: function get() {
get: function () {
return _environment.getEnv;
}
});
Object.defineProperty(exports, "tokTypes", {
enumerable: true,
get: function () {
return _parser().tokTypes;
}
});
Object.defineProperty(exports, "traverse", {
enumerable: true,
get: function get() {
get: function () {
return _traverse().default;
}
});
Object.defineProperty(exports, "template", {
enumerable: true,
get: function get() {
get: function () {
return _template().default;
}
});
Object.defineProperty(exports, "createConfigItem", {
enumerable: true,
get: function () {
return _item.createConfigItem;
}
});
Object.defineProperty(exports, "loadPartialConfig", {
enumerable: true,
get: function get() {
get: function () {
return _config.loadPartialConfig;
}
});
Object.defineProperty(exports, "loadOptions", {
enumerable: true,
get: function get() {
get: function () {
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", {
enumerable: true,
get: function get() {
return _transform.default;
get: function () {
return _transform.transform;
}
});
Object.defineProperty(exports, "transformSync", {
enumerable: true,
get: function get() {
return _transformSync.default;
get: function () {
return _transform.transformSync;
}
});
Object.defineProperty(exports, "transformAsync", {
enumerable: true,
get: function () {
return _transform.transformAsync;
}
});
Object.defineProperty(exports, "transformFile", {
enumerable: true,
get: function get() {
return _transformFile.default;
get: function () {
return _transformFile.transformFile;
}
});
Object.defineProperty(exports, "transformFileSync", {
enumerable: true,
get: function get() {
return _transformFileSync.default;
get: function () {
return _transformFile.transformFileSync;
}
});
Object.defineProperty(exports, "transformFileAsync", {
enumerable: true,
get: function () {
return _transformFile.transformFileAsync;
}
});
Object.defineProperty(exports, "transformFromAst", {
enumerable: true,
get: function get() {
return _transformAst.default;
get: function () {
return _transformAst.transformFromAst;
}
});
Object.defineProperty(exports, "transformFromAstSync", {
enumerable: true,
get: function get() {
return _transformAstSync.default;
get: function () {
return _transformAst.transformFromAstSync;
}
});
Object.defineProperty(exports, "transformFromAstAsync", {
enumerable: true,
get: function () {
return _transformAst.transformFromAstAsync;
}
});
Object.defineProperty(exports, "parse", {
enumerable: true,
get: function get() {
return _parse.default;
get: function () {
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"));
@@ -131,9 +161,9 @@ var _package = require("../package.json");
var _environment = require("./config/helpers/environment");
function _types() {
var data = _interopRequireWildcard(require("@babel/types"));
const data = _interopRequireWildcard(require("@babel/types"));
_types = function _types() {
_types = function () {
return data;
};
@@ -142,15 +172,25 @@ function _types() {
Object.defineProperty(exports, "types", {
enumerable: true,
get: function get() {
get: function () {
return _types();
}
});
function _traverse() {
var data = _interopRequireDefault(require("@babel/traverse"));
function _parser() {
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;
};
@@ -158,40 +198,43 @@ function _traverse() {
}
function _template() {
var data = _interopRequireDefault(require("@babel/template"));
const data = _interopRequireDefault(require("@babel/template"));
_template = function _template() {
_template = function () {
return data;
};
return data;
}
var _config = require("./config");
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 _transformAstSync = _interopRequireDefault(require("./transform-ast-sync"));
var _parse = _interopRequireDefault(require("./parse"));
var _parse = require("./parse");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Plugin(alias) {
throw new Error("The (" + alias + ") Babel 5 plugin is being run with an unsupported Babel version.");
const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]);
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.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
exports.OptionManager = OptionManager;
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", {
value: true
});
exports.default = parse;
exports.parseSync = parseSync;
exports.parseAsync = parseAsync;
exports.parse = void 0;
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 parse(code, opts) {
var config = (0, _config.default)(opts);
const parse = function parse(code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (callback === undefined) return parseSync(code, opts);
const config = (0, _config.default)(opts);
if (config === null) {
return null;
}
var file = (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code);
return file.ast;
const cb = callback;
process.nextTick(() => {
let ast = null;
try {
const cfg = (0, _config.default)(opts);
if (cfg === null) return cb(null, null);
ast = (0, _normalizeFile.default)(cfg.passes, (0, _normalizeOpts.default)(cfg), code).ast;
} catch (err) {
return cb(err);
}
cb(null, ast);
});
};
exports.parse = parse;
function parseSync(code, opts) {
const config = (0, _config.default)(opts);
if (config === null) {
return null;
}
return (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code).ast;
}
function parseAsync(code, opts) {
return new Promise((res, rej) => {
parse(code, opts, (err, result) => {
if (err == null) res(result);else rej(err);
});
});
}

View File

@@ -6,9 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = _default;
function helpers() {
var data = _interopRequireWildcard(require("@babel/helpers"));
const data = _interopRequireWildcard(require("@babel/helpers"));
helpers = function helpers() {
helpers = function () {
return data;
};
@@ -16,9 +16,9 @@ function helpers() {
}
function _generator() {
var data = _interopRequireDefault(require("@babel/generator"));
const data = _interopRequireDefault(require("@babel/generator"));
_generator = function _generator() {
_generator = function () {
return data;
};
@@ -26,9 +26,9 @@ function _generator() {
}
function _template() {
var data = _interopRequireDefault(require("@babel/template"));
const data = _interopRequireDefault(require("@babel/template"));
_template = function _template() {
_template = function () {
return data;
};
@@ -36,49 +36,55 @@ function _template() {
}
function t() {
var data = _interopRequireWildcard(require("@babel/types"));
const data = _interopRequireWildcard(require("@babel/types"));
t = function t() {
t = function () {
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 _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; }
var buildUmdWrapper = function buildUmdWrapper(replacements) {
return (0, _template().default)(_templateObject)(replacements);
};
const buildUmdWrapper = replacements => _template().default`
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_ARGUMENTS, factory);
} else if (typeof exports === "object") {
factory(COMMON_ARGUMENTS);
} else {
factory(BROWSER_ARGUMENTS);
}
})(UMD_ROOT, function (FACTORY_PARAMETERS) {
FACTORY_BODY
});
`(replacements);
function buildGlobal(whitelist) {
var namespace = t().identifier("babelHelpers");
var body = [];
var 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 namespace = t().identifier("babelHelpers");
const body = [];
const container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body));
const tree = t().program([t().expressionStatement(t().callExpression(container, [t().conditionalExpression(t().binaryExpression("===", t().unaryExpression("typeof", t().identifier("global")), t().stringLiteral("undefined")), t().identifier("self"), t().identifier("global"))]))]);
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))]));
buildHelpers(body, namespace, whitelist);
return tree;
}
function buildModule(whitelist) {
var body = [];
var refs = buildHelpers(body, null, whitelist);
body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(function (name) {
const body = [];
const refs = buildHelpers(body, null, whitelist);
body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(name => {
return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name));
})));
return t().program(body, [], "module");
}
function buildUmd(whitelist) {
var namespace = t().identifier("babelHelpers");
var body = [];
const namespace = t().identifier("babelHelpers");
const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))]));
buildHelpers(body, namespace, whitelist);
return t().program([buildUmdWrapper({
@@ -92,40 +98,35 @@ function buildUmd(whitelist) {
}
function buildVar(whitelist) {
var namespace = t().identifier("babelHelpers");
var body = [];
const namespace = t().identifier("babelHelpers");
const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))]));
var tree = t().program(body);
const tree = t().program(body);
buildHelpers(body, namespace, whitelist);
body.push(t().expressionStatement(namespace));
return tree;
}
function buildHelpers(body, namespace, whitelist) {
var getHelperReference = function getHelperReference(name) {
return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier("_" + name);
const getHelperReference = name => {
return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`);
};
var refs = {};
const refs = {};
helpers().list.forEach(function (name) {
if (whitelist && whitelist.indexOf(name) < 0) return;
var ref = refs[name] = getHelperReference(name);
var _helpers$get = helpers().get(name, getHelperReference, ref),
nodes = _helpers$get.nodes;
body.push.apply(body, nodes);
const ref = refs[name] = getHelperReference(name);
const {
nodes
} = helpers().get(name, getHelperReference, ref);
body.push(...nodes);
});
return refs;
}
function _default(whitelist, outputType) {
if (outputType === void 0) {
outputType = "global";
}
var tree;
var build = {
function _default(whitelist, outputType = "global") {
let tree;
const build = {
global: buildGlobal,
module: buildModule,
umd: buildUmd,
@@ -135,7 +136,7 @@ function _default(whitelist, outputType) {
if (build) {
tree = build(whitelist);
} else {
throw new Error("Unsupported output type " + outputType);
throw new Error(`Unsupported output type ${outputType}`);
}
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", {
value: true
});
exports.default = void 0;
exports.transformFromAstSync = transformFromAstSync;
exports.transformFromAstAsync = transformFromAstAsync;
exports.transformFromAst = void 0;
var _config = _interopRequireDefault(require("./config"));
var _transformation = require("./transformation");
var _transformAstSync = _interopRequireDefault(require("./transform-ast-sync"));
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") {
opts = undefined;
callback = opts;
opts = undefined;
}
if (callback === undefined) return (0, _transformAstSync.default)(ast, code, opts);
var cb = callback;
process.nextTick(function () {
var cfg;
if (callback === undefined) return transformFromAstSync(ast, code, opts);
const cb = callback;
process.nextTick(() => {
let cfg;
try {
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", {
value: true
});
exports.default = transformFile;
function transformFile(filename, opts, callback) {
if (opts === void 0) {
opts = {};
}
exports.transformFileSync = transformFileSync;
exports.transformFileAsync = transformFileAsync;
exports.transformFile = void 0;
const transformFile = function transformFile(filename, opts, callback) {
if (typeof opts === "function") {
callback = opts;
}
callback(new Error("Transforming files is not supported in browsers"), null);
};
exports.transformFile = transformFile;
function transformFileSync() {
throw new Error("Transforming files is not supported in browsers");
}
function transformFileAsync() {
return Promise.reject(new Error("Transforming files is not supported in browsers"));
}

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", {
value: true
});
exports.default = void 0;
exports.transformFileSync = transformFileSync;
exports.transformFileAsync = transformFileAsync;
exports.transformFile = void 0;
function _fs() {
var data = _interopRequireDefault(require("fs"));
const data = _interopRequireDefault(require("fs"));
_fs = function _fs() {
_fs = function () {
return data;
};
@@ -21,8 +23,10 @@ var _transformation = require("./transformation");
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") {
callback = opts;
@@ -31,16 +35,16 @@ var transformFile = function transformFile(filename, opts, callback) {
if (opts == null) {
options = {
filename: filename
filename
};
} else if (opts && typeof opts === "object") {
options = Object.assign({}, opts, {
filename: filename
filename
});
}
process.nextTick(function () {
var cfg;
process.nextTick(() => {
let cfg;
try {
cfg = (0, _config.default)(options);
@@ -49,7 +53,7 @@ var transformFile = function transformFile(filename, opts, callback) {
return callback(err);
}
var config = cfg;
const config = cfg;
_fs().default.readFile(filename, "utf8", function (err, code) {
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", {
value: true
});
exports.default = void 0;
exports.transformSync = transformSync;
exports.transformAsync = transformAsync;
exports.transform = void 0;
var _config = _interopRequireDefault(require("./config"));
var _transformation = require("./transformation");
var _transformSync = _interopRequireDefault(require("./transform-sync"));
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") {
opts = undefined;
callback = opts;
opts = undefined;
}
if (callback === undefined) return (0, _transformSync.default)(code, opts);
var cb = callback;
process.nextTick(function () {
var cfg;
if (callback === undefined) return transformSync(code, opts);
const cb = callback;
process.nextTick(() => {
let cfg;
try {
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;
function _sortBy() {
var data = _interopRequireDefault(require("lodash/sortBy"));
const data = _interopRequireDefault(require("lodash/sortBy"));
_sortBy = function _sortBy() {
_sortBy = function () {
return data;
};
@@ -19,11 +19,11 @@ var _config = _interopRequireDefault(require("../config"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var LOADED_PLUGIN;
let LOADED_PLUGIN;
function loadBlockHoistPlugin() {
if (!LOADED_PLUGIN) {
var config = (0, _config.default)({
const config = (0, _config.default)({
babelrc: false,
configFile: false,
plugins: [blockHoistPlugin]
@@ -35,16 +35,17 @@ function loadBlockHoistPlugin() {
return LOADED_PLUGIN;
}
var blockHoistPlugin = {
const blockHoistPlugin = {
name: "internal.blockHoist",
visitor: {
Block: {
exit: function exit(_ref) {
var node = _ref.node;
var hasChange = false;
exit({
node
}) {
let hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
for (let i = 0; i < node.body.length; i++) {
const bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) {
hasChange = true;
@@ -54,12 +55,13 @@ var blockHoistPlugin = {
if (!hasChange) return;
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 === true) priority = 2;
return -1 * priority;
});
}
}
}
};

View File

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

View File

@@ -6,19 +6,9 @@ Object.defineProperty(exports, "__esModule", {
exports.default = generateCode;
function _convertSourceMap() {
var data = _interopRequireDefault(require("convert-source-map"));
const data = _interopRequireDefault(require("convert-source-map"));
_convertSourceMap = function _convertSourceMap() {
return data;
};
return data;
}
function _sourceMap() {
var data = _interopRequireDefault(require("source-map"));
_sourceMap = function _sourceMap() {
_convertSourceMap = function () {
return data;
};
@@ -26,63 +16,42 @@ function _sourceMap() {
}
function _generator() {
var data = _interopRequireDefault(require("@babel/generator"));
const data = _interopRequireDefault(require("@babel/generator"));
_generator = function _generator() {
_generator = function () {
return data;
};
return data;
}
var _mergeMap = _interopRequireDefault(require("./merge-map"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function generateCode(pluginPasses, file) {
var opts = file.opts,
ast = file.ast,
shebang = file.shebang,
code = file.code,
inputMap = file.inputMap;
var results = [];
const {
opts,
ast,
code,
inputMap
} = file;
const results = [];
for (var _iterator = pluginPasses, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
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;
var generatorOverride = plugin.generatorOverride;
for (const plugins of pluginPasses) {
for (const plugin of plugins) {
const {
generatorOverride
} = plugin;
if (generatorOverride) {
var _result2 = generatorOverride(ast, opts.generatorOpts, code, _generator().default);
if (_result2 !== undefined) results.push(_result2);
const result = generatorOverride(ast, opts.generatorOpts, code, _generator().default);
if (result !== undefined) results.push(result);
}
}
}
var result;
let result;
if (results.length === 0) {
result = (0, _generator().default)(ast, opts.generatorOpts, code);
@@ -90,22 +59,19 @@ function generateCode(pluginPasses, file) {
result = results[0];
if (typeof result.then === "function") {
throw new Error("You appear to be using an async parser plugin, " + "which your current version of Babel does not support. " + "If you're using a published plugin, " + "you may need to upgrade your @babel/core version.");
throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`);
}
} else {
throw new Error("More than one plugin attempted to override codegen.");
}
var _result = result,
outputCode = _result.code,
outputMap = _result.map;
if (shebang) {
outputCode = shebang + "\n" + outputCode;
}
let {
code: outputCode,
map: outputMap
} = result;
if (outputMap && inputMap) {
outputMap = mergeSourceMap(inputMap.toObject(), outputMap);
outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap);
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
@@ -117,39 +83,7 @@ function generateCode(pluginPasses, file) {
}
return {
outputCode: outputCode,
outputMap: outputMap
outputCode,
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;
function _traverse() {
var data = _interopRequireDefault(require("@babel/traverse"));
const data = _interopRequireDefault(require("@babel/traverse"));
_traverse = function _traverse() {
_traverse = function () {
return data;
};
@@ -29,7 +29,7 @@ var _generate = _interopRequireDefault(require("./file/generate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function runAsync(config, code, ast, callback) {
var result;
let result;
try {
result = runSync(config, code, ast);
@@ -41,14 +41,13 @@ function runAsync(config, code, ast, callback) {
}
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);
var opts = file.opts;
var _ref = opts.code !== false ? (0, _generate.default)(config.passes, file) : {},
outputCode = _ref.outputCode,
outputMap = _ref.outputMap;
const opts = file.opts;
const {
outputCode,
outputMap
} = opts.code !== false ? (0, _generate.default)(config.passes, file) : {};
return {
metadata: file.metadata,
options: opts,
@@ -60,72 +59,42 @@ function runSync(config, code, ast) {
}
function transformFile(file, pluginPasses) {
for (var _iterator = pluginPasses, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref2;
for (const pluginPairs of pluginPasses) {
const passPairs = [];
const passes = [];
const visitors = [];
if (_isArray) {
if (_i >= _iterator.length) break;
_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);
for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) {
const pass = new _pluginPass.default(file, plugin.key, plugin.options);
passPairs.push([plugin, pass]);
passes.push(pass);
visitors.push(plugin.visitor);
}
for (var _i3 = 0; _i3 < passPairs.length; _i3++) {
var _passPairs$_i = passPairs[_i3],
_plugin = _passPairs$_i[0],
_pass = _passPairs$_i[1];
var fn = _plugin.pre;
for (const [plugin, pass] of passPairs) {
const fn = plugin.pre;
if (fn) {
var result = fn.call(_pass, file);
const result = fn.call(pass, file);
if (isThenable(result)) {
throw new Error("You appear to be using an plugin with an async .pre, " + "which your current version of Babel does not support." + "If you're using a published plugin, you may need to upgrade " + "your @babel/core version.");
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);
for (var _i4 = 0; _i4 < passPairs.length; _i4++) {
var _passPairs$_i2 = passPairs[_i4],
_plugin2 = _passPairs$_i2[0],
_pass2 = _passPairs$_i2[1];
var _fn = _plugin2.post;
for (const [plugin, pass] of passPairs) {
const fn = plugin.post;
if (_fn) {
var _result = _fn.call(_pass2, file);
if (fn) {
const result = fn.call(pass, file);
if (isThenable(_result)) {
throw new Error("You appear to be using an plugin with an async .post, " + "which your current version of Babel does not support." + "If you're using a published plugin, you may need to upgrade " + "your @babel/core version.");
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.`);
}
}
}
@@ -133,5 +102,5 @@ function transformFile(file, pluginPasses) {
}
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;
function t() {
var data = _interopRequireWildcard(require("@babel/types"));
function _path() {
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;
};
@@ -16,19 +46,19 @@ function t() {
}
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 _babylon() {
var data = require("babylon");
function _parser() {
const data = require("@babel/parser");
_babylon = function _babylon() {
_parser = function () {
return data;
};
@@ -36,9 +66,9 @@ function _babylon() {
}
function _codeFrame() {
var data = require("@babel/code-frame");
const data = require("@babel/code-frame");
_codeFrame = function _codeFrame() {
_codeFrame = function () {
return data;
};
@@ -49,32 +79,51 @@ var _file = _interopRequireDefault(require("./file/file"));
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; } }
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) {
code = "" + (code || "");
var shebang = null;
var inputMap = null;
code = `${code || ""}`;
let inputMap = null;
if (options.inputSourceMap !== false) {
inputMap = _convertSourceMap().default.fromSource(code);
if (inputMap) {
code = _convertSourceMap().default.removeComments(code);
} else if (typeof options.inputSourceMap === "object") {
if (typeof options.inputSourceMap === "object") {
inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap);
}
}
var shebangMatch = shebangRegex.exec(code);
if (!inputMap) {
try {
inputMap = _convertSourceMap().default.fromSource(code);
if (shebangMatch) {
shebang = shebangMatch[0];
code = code.replace(shebangRegex, "");
if (inputMap) {
code = _convertSourceMap().default.removeComments(code);
}
} catch (err) {
debug("discarding unknown inline input sourcemap", err);
code = _convertSourceMap().default.removeComments(code);
}
}
if (!inputMap) {
if (typeof options.filename === "string") {
try {
inputMap = _convertSourceMap().default.fromMapFileSource(code, _path().default.dirname(options.filename));
if (inputMap) {
code = _convertSourceMap().default.removeMapFileComments(code);
}
} catch (err) {
debug("discarding unknown file input sourcemap", err);
code = _convertSourceMap().default.removeMapFileComments(code);
}
} else {
debug("discarding un-loadable file input sourcemap");
code = _convertSourceMap().default.removeMapFileComments(code);
}
}
}
if (ast) {
@@ -83,64 +132,45 @@ function normalizeFile(pluginPasses, options, code, ast) {
} else if (ast.type !== "File") {
throw new Error("AST root must be a Program or File node");
}
ast = (0, _cloneDeep().default)(ast);
} else {
ast = parser(pluginPasses, options, code);
}
return new _file.default(options, {
code: code,
ast: ast,
shebang: shebang,
inputMap: inputMap
code,
ast,
inputMap
});
}
function parser(pluginPasses, options, code) {
function parser(pluginPasses, {
parserOpts,
highlightCode = true,
filename = "unknown"
}, code) {
try {
var results = [];
const results = [];
for (var _iterator = pluginPasses, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
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;
var parserOverride = plugin.parserOverride;
for (const plugins of pluginPasses) {
for (const plugin of plugins) {
const {
parserOverride
} = plugin;
if (parserOverride) {
var _ast = parserOverride(code, options.parserOpts, _babylon().parse);
if (_ast !== undefined) results.push(_ast);
const ast = parserOverride(code, parserOpts, _parser().parse);
if (ast !== undefined) results.push(ast);
}
}
}
if (results.length === 0) {
return (0, _babylon().parse)(code, options.parserOpts);
return (0, _parser().parse)(code, parserOpts);
} else if (results.length === 1) {
if (typeof results[0].then === "function") {
throw new Error("You appear to be using an async codegen plugin, " + "which your current version of Babel does not support. " + "If you're using a published plugin, you may need to upgrade " + "your @babel/core version.");
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];
@@ -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.";
}
var loc = err.loc,
missingPlugin = err.missingPlugin;
const {
loc,
missingPlugin
} = err;
if (loc) {
var codeFrame = (0, _codeFrame().codeFrameColumns)(code, {
const codeFrame = (0, _codeFrame().codeFrameColumns)(code, {
start: {
line: loc.line,
column: loc.column + 1
}
}, options);
}, {
highlightCode
});
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 {
err.message = (options.filename || "unknown") + ": " + err.message + "\n\n" + codeFrame;
err.message = `${filename}: ${err.message}\n\n` + codeFrame;
}
err.code = "BABEL_PARSE_ERROR";

View File

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

View File

@@ -5,42 +5,44 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = void 0;
var PluginPass = function () {
function PluginPass(file, key, options) {
class PluginPass {
constructor(file, key, options) {
this._map = new Map();
this.key = key;
this.file = file;
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;
_proto.set = function set(key, val) {
set(key, val) {
this._map.set(key, val);
};
}
_proto.get = function get(key) {
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);
};
}
_proto.addImport = function addImport() {
addImport() {
return this.file.addImport();
};
}
_proto.getModuleName = function getModuleName() {
getModuleName() {
return this.file.getModuleName();
};
}
_proto.buildCodeFrameError = function buildCodeFrameError(node, msg, Error) {
buildCodeFrameError(node, msg, Error) {
return this.file.buildCodeFrameError(node, msg, Error);
};
}
return PluginPass;
}();
}
exports.default = PluginPass;

View File

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

View File

@@ -0,0 +1,190 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration;
exports.ClassBody = ClassBody;
exports.ClassProperty = ClassProperty;
exports.ClassPrivateProperty = ClassPrivateProperty;
exports.ClassMethod = ClassMethod;
exports.ClassPrivateMethod = ClassPrivateMethod;
exports._classMethodHead = _classMethodHead;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function ClassDeclaration(node, parent) {
if (!this.format.decoratorsBeforeExport || !t().isExportDefaultDeclaration(parent) && !t().isExportNamedDeclaration(parent)) {
this.printJoin(node.decorators, node);
}
if (node.declare) {
this.word("declare");
this.space();
}
if (node.abstract) {
this.word("abstract");
this.space();
}
this.word("class");
if (node.id) {
this.space();
this.print(node.id, node);
}
this.print(node.typeParameters, node);
if (node.superClass) {
this.space();
this.word("extends");
this.space();
this.print(node.superClass, node);
this.print(node.superTypeParameters, node);
}
if (node.implements) {
this.space();
this.word("implements");
this.space();
this.printList(node.implements, node);
}
this.space();
this.print(node.body, node);
}
function ClassBody(node) {
this.token("{");
this.printInnerComments(node);
if (node.body.length === 0) {
this.token("}");
} else {
this.newline();
this.indent();
this.printSequence(node.body, node);
this.dedent();
if (!this.endsWith("\n")) this.newline();
this.rightBrace();
}
}
function ClassProperty(node) {
this.printJoin(node.decorators, node);
if (node.accessibility) {
this.word(node.accessibility);
this.space();
}
if (node.static) {
this.word("static");
this.space();
}
if (node.abstract) {
this.word("abstract");
this.space();
}
if (node.readonly) {
this.word("readonly");
this.space();
}
if (node.computed) {
this.token("[");
this.print(node.key, node);
this.token("]");
} else {
this._variance(node);
this.print(node.key, node);
}
if (node.optional) {
this.token("?");
}
if (node.definite) {
this.token("!");
}
this.print(node.typeAnnotation, node);
if (node.value) {
this.space();
this.token("=");
this.space();
this.print(node.value, node);
}
this.semicolon();
}
function ClassPrivateProperty(node) {
if (node.static) {
this.word("static");
this.space();
}
this.print(node.key, node);
this.print(node.typeAnnotation, node);
if (node.value) {
this.space();
this.token("=");
this.space();
this.print(node.value, node);
}
this.semicolon();
}
function ClassMethod(node) {
this._classMethodHead(node);
this.space();
this.print(node.body, node);
}
function ClassPrivateMethod(node) {
this._classMethodHead(node);
this.space();
this.print(node.body, node);
}
function _classMethodHead(node) {
this.printJoin(node.decorators, node);
if (node.accessibility) {
this.word(node.accessibility);
this.space();
}
if (node.abstract) {
this.word("abstract");
this.space();
}
if (node.static) {
this.word("static");
this.space();
}
this._methodHead(node);
}

View File

@@ -0,0 +1,292 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UnaryExpression = UnaryExpression;
exports.DoExpression = DoExpression;
exports.ParenthesizedExpression = ParenthesizedExpression;
exports.UpdateExpression = UpdateExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.NewExpression = NewExpression;
exports.SequenceExpression = SequenceExpression;
exports.ThisExpression = ThisExpression;
exports.Super = Super;
exports.Decorator = Decorator;
exports.OptionalMemberExpression = OptionalMemberExpression;
exports.OptionalCallExpression = OptionalCallExpression;
exports.CallExpression = CallExpression;
exports.Import = Import;
exports.EmptyStatement = EmptyStatement;
exports.ExpressionStatement = ExpressionStatement;
exports.AssignmentPattern = AssignmentPattern;
exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression;
exports.BindExpression = BindExpression;
exports.MemberExpression = MemberExpression;
exports.MetaProperty = MetaProperty;
exports.PrivateName = PrivateName;
exports.AwaitExpression = exports.YieldExpression = void 0;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
var n = _interopRequireWildcard(require("../node"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function UnaryExpression(node) {
if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof" || node.operator === "throw") {
this.word(node.operator);
this.space();
} else {
this.token(node.operator);
}
this.print(node.argument, node);
}
function DoExpression(node) {
this.word("do");
this.space();
this.print(node.body, node);
}
function ParenthesizedExpression(node) {
this.token("(");
this.print(node.expression, node);
this.token(")");
}
function UpdateExpression(node) {
if (node.prefix) {
this.token(node.operator);
this.print(node.argument, node);
} else {
this.startTerminatorless(true);
this.print(node.argument, node);
this.endTerminatorless();
this.token(node.operator);
}
}
function ConditionalExpression(node) {
this.print(node.test, node);
this.space();
this.token("?");
this.space();
this.print(node.consequent, node);
this.space();
this.token(":");
this.space();
this.print(node.alternate, node);
}
function NewExpression(node, parent) {
this.word("new");
this.space();
this.print(node.callee, node);
if (this.format.minified && node.arguments.length === 0 && !node.optional && !t().isCallExpression(parent, {
callee: node
}) && !t().isMemberExpression(parent) && !t().isNewExpression(parent)) {
return;
}
this.print(node.typeArguments, node);
this.print(node.typeParameters, node);
if (node.optional) {
this.token("?.");
}
this.token("(");
this.printList(node.arguments, node);
this.token(")");
}
function SequenceExpression(node) {
this.printList(node.expressions, node);
}
function ThisExpression() {
this.word("this");
}
function Super() {
this.word("super");
}
function Decorator(node) {
this.token("@");
this.print(node.expression, node);
this.newline();
}
function OptionalMemberExpression(node) {
this.print(node.object, node);
if (!node.computed && t().isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
let computed = node.computed;
if (t().isLiteral(node.property) && typeof node.property.value === "number") {
computed = true;
}
if (node.optional) {
this.token("?.");
}
if (computed) {
this.token("[");
this.print(node.property, node);
this.token("]");
} else {
if (!node.optional) {
this.token(".");
}
this.print(node.property, node);
}
}
function OptionalCallExpression(node) {
this.print(node.callee, node);
this.print(node.typeArguments, node);
this.print(node.typeParameters, node);
if (node.optional) {
this.token("?.");
}
this.token("(");
this.printList(node.arguments, node);
this.token(")");
}
function CallExpression(node) {
this.print(node.callee, node);
this.print(node.typeArguments, node);
this.print(node.typeParameters, node);
this.token("(");
this.printList(node.arguments, node);
this.token(")");
}
function Import() {
this.word("import");
}
function buildYieldAwait(keyword) {
return function (node) {
this.word(keyword);
if (node.delegate) {
this.token("*");
}
if (node.argument) {
this.space();
const terminatorState = this.startTerminatorless();
this.print(node.argument, node);
this.endTerminatorless(terminatorState);
}
};
}
const YieldExpression = buildYieldAwait("yield");
exports.YieldExpression = YieldExpression;
const AwaitExpression = buildYieldAwait("await");
exports.AwaitExpression = AwaitExpression;
function EmptyStatement() {
this.semicolon(true);
}
function ExpressionStatement(node) {
this.print(node.expression, node);
this.semicolon();
}
function AssignmentPattern(node) {
this.print(node.left, node);
if (node.left.optional) this.token("?");
this.print(node.left.typeAnnotation, node);
this.space();
this.token("=");
this.space();
this.print(node.right, node);
}
function AssignmentExpression(node, parent) {
const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent);
if (parens) {
this.token("(");
}
this.print(node.left, node);
this.space();
if (node.operator === "in" || node.operator === "instanceof") {
this.word(node.operator);
} else {
this.token(node.operator);
}
this.space();
this.print(node.right, node);
if (parens) {
this.token(")");
}
}
function BindExpression(node) {
this.print(node.object, node);
this.token("::");
this.print(node.callee, node);
}
function MemberExpression(node) {
this.print(node.object, node);
if (!node.computed && t().isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
let computed = node.computed;
if (t().isLiteral(node.property) && typeof node.property.value === "number") {
computed = true;
}
if (computed) {
this.token("[");
this.print(node.property, node);
this.token("]");
} else {
this.token(".");
this.print(node.property, node);
}
}
function MetaProperty(node) {
this.print(node.meta, node);
this.token(".");
this.print(node.property, node);
}
function PrivateName(node) {
this.token("#");
this.print(node.id, node);
}

View File

@@ -0,0 +1,628 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AnyTypeAnnotation = AnyTypeAnnotation;
exports.ArrayTypeAnnotation = ArrayTypeAnnotation;
exports.BooleanTypeAnnotation = BooleanTypeAnnotation;
exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation;
exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation;
exports.DeclareClass = DeclareClass;
exports.DeclareFunction = DeclareFunction;
exports.InferredPredicate = InferredPredicate;
exports.DeclaredPredicate = DeclaredPredicate;
exports.DeclareInterface = DeclareInterface;
exports.DeclareModule = DeclareModule;
exports.DeclareModuleExports = DeclareModuleExports;
exports.DeclareTypeAlias = DeclareTypeAlias;
exports.DeclareOpaqueType = DeclareOpaqueType;
exports.DeclareVariable = DeclareVariable;
exports.DeclareExportDeclaration = DeclareExportDeclaration;
exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration;
exports.ExistsTypeAnnotation = ExistsTypeAnnotation;
exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
exports.FunctionTypeParam = FunctionTypeParam;
exports.GenericTypeAnnotation = exports.ClassImplements = exports.InterfaceExtends = InterfaceExtends;
exports._interfaceish = _interfaceish;
exports._variance = _variance;
exports.InterfaceDeclaration = InterfaceDeclaration;
exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation;
exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation;
exports.MixedTypeAnnotation = MixedTypeAnnotation;
exports.EmptyTypeAnnotation = EmptyTypeAnnotation;
exports.NullableTypeAnnotation = NullableTypeAnnotation;
exports.NumberTypeAnnotation = NumberTypeAnnotation;
exports.StringTypeAnnotation = StringTypeAnnotation;
exports.ThisTypeAnnotation = ThisTypeAnnotation;
exports.TupleTypeAnnotation = TupleTypeAnnotation;
exports.TypeofTypeAnnotation = TypeofTypeAnnotation;
exports.TypeAlias = TypeAlias;
exports.TypeAnnotation = TypeAnnotation;
exports.TypeParameterDeclaration = exports.TypeParameterInstantiation = TypeParameterInstantiation;
exports.TypeParameter = TypeParameter;
exports.OpaqueType = OpaqueType;
exports.ObjectTypeAnnotation = ObjectTypeAnnotation;
exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot;
exports.ObjectTypeCallProperty = ObjectTypeCallProperty;
exports.ObjectTypeIndexer = ObjectTypeIndexer;
exports.ObjectTypeProperty = ObjectTypeProperty;
exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty;
exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier;
exports.UnionTypeAnnotation = UnionTypeAnnotation;
exports.TypeCastExpression = TypeCastExpression;
exports.Variance = Variance;
exports.VoidTypeAnnotation = VoidTypeAnnotation;
Object.defineProperty(exports, "NumberLiteralTypeAnnotation", {
enumerable: true,
get: function () {
return _types2.NumericLiteral;
}
});
Object.defineProperty(exports, "StringLiteralTypeAnnotation", {
enumerable: true,
get: function () {
return _types2.StringLiteral;
}
});
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
var _modules = require("./modules");
var _types2 = require("./types");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function AnyTypeAnnotation() {
this.word("any");
}
function ArrayTypeAnnotation(node) {
this.print(node.elementType, node);
this.token("[");
this.token("]");
}
function BooleanTypeAnnotation() {
this.word("boolean");
}
function BooleanLiteralTypeAnnotation(node) {
this.word(node.value ? "true" : "false");
}
function NullLiteralTypeAnnotation() {
this.word("null");
}
function DeclareClass(node, parent) {
if (!t().isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.word("class");
this.space();
this._interfaceish(node);
}
function DeclareFunction(node, parent) {
if (!t().isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.word("function");
this.space();
this.print(node.id, node);
this.print(node.id.typeAnnotation.typeAnnotation, node);
if (node.predicate) {
this.space();
this.print(node.predicate, node);
}
this.semicolon();
}
function InferredPredicate() {
this.token("%");
this.word("checks");
}
function DeclaredPredicate(node) {
this.token("%");
this.word("checks");
this.token("(");
this.print(node.value, node);
this.token(")");
}
function DeclareInterface(node) {
this.word("declare");
this.space();
this.InterfaceDeclaration(node);
}
function DeclareModule(node) {
this.word("declare");
this.space();
this.word("module");
this.space();
this.print(node.id, node);
this.space();
this.print(node.body, node);
}
function DeclareModuleExports(node) {
this.word("declare");
this.space();
this.word("module");
this.token(".");
this.word("exports");
this.print(node.typeAnnotation, node);
}
function DeclareTypeAlias(node) {
this.word("declare");
this.space();
this.TypeAlias(node);
}
function DeclareOpaqueType(node, parent) {
if (!t().isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.OpaqueType(node);
}
function DeclareVariable(node, parent) {
if (!t().isDeclareExportDeclaration(parent)) {
this.word("declare");
this.space();
}
this.word("var");
this.space();
this.print(node.id, node);
this.print(node.id.typeAnnotation, node);
this.semicolon();
}
function DeclareExportDeclaration(node) {
this.word("declare");
this.space();
this.word("export");
this.space();
if (node.default) {
this.word("default");
this.space();
}
FlowExportDeclaration.apply(this, arguments);
}
function DeclareExportAllDeclaration() {
this.word("declare");
this.space();
_modules.ExportAllDeclaration.apply(this, arguments);
}
function FlowExportDeclaration(node) {
if (node.declaration) {
const declar = node.declaration;
this.print(declar, node);
if (!t().isStatement(declar)) this.semicolon();
} else {
this.token("{");
if (node.specifiers.length) {
this.space();
this.printList(node.specifiers, node);
this.space();
}
this.token("}");
if (node.source) {
this.space();
this.word("from");
this.space();
this.print(node.source, node);
}
this.semicolon();
}
}
function ExistsTypeAnnotation() {
this.token("*");
}
function FunctionTypeAnnotation(node, parent) {
this.print(node.typeParameters, node);
this.token("(");
this.printList(node.params, node);
if (node.rest) {
if (node.params.length) {
this.token(",");
this.space();
}
this.token("...");
this.print(node.rest, node);
}
this.token(")");
if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction" || parent.type === "ObjectTypeProperty" && parent.method) {
this.token(":");
} else {
this.space();
this.token("=>");
}
this.space();
this.print(node.returnType, node);
}
function FunctionTypeParam(node) {
this.print(node.name, node);
if (node.optional) this.token("?");
if (node.name) {
this.token(":");
this.space();
}
this.print(node.typeAnnotation, node);
}
function InterfaceExtends(node) {
this.print(node.id, node);
this.print(node.typeParameters, node);
}
function _interfaceish(node) {
this.print(node.id, node);
this.print(node.typeParameters, node);
if (node.extends.length) {
this.space();
this.word("extends");
this.space();
this.printList(node.extends, node);
}
if (node.mixins && node.mixins.length) {
this.space();
this.word("mixins");
this.space();
this.printList(node.mixins, node);
}
if (node.implements && node.implements.length) {
this.space();
this.word("implements");
this.space();
this.printList(node.implements, node);
}
this.space();
this.print(node.body, node);
}
function _variance(node) {
if (node.variance) {
if (node.variance.kind === "plus") {
this.token("+");
} else if (node.variance.kind === "minus") {
this.token("-");
}
}
}
function InterfaceDeclaration(node) {
this.word("interface");
this.space();
this._interfaceish(node);
}
function andSeparator() {
this.space();
this.token("&");
this.space();
}
function InterfaceTypeAnnotation(node) {
this.word("interface");
if (node.extends && node.extends.length) {
this.space();
this.word("extends");
this.space();
this.printList(node.extends, node);
}
this.space();
this.print(node.body, node);
}
function IntersectionTypeAnnotation(node) {
this.printJoin(node.types, node, {
separator: andSeparator
});
}
function MixedTypeAnnotation() {
this.word("mixed");
}
function EmptyTypeAnnotation() {
this.word("empty");
}
function NullableTypeAnnotation(node) {
this.token("?");
this.print(node.typeAnnotation, node);
}
function NumberTypeAnnotation() {
this.word("number");
}
function StringTypeAnnotation() {
this.word("string");
}
function ThisTypeAnnotation() {
this.word("this");
}
function TupleTypeAnnotation(node) {
this.token("[");
this.printList(node.types, node);
this.token("]");
}
function TypeofTypeAnnotation(node) {
this.word("typeof");
this.space();
this.print(node.argument, node);
}
function TypeAlias(node) {
this.word("type");
this.space();
this.print(node.id, node);
this.print(node.typeParameters, node);
this.space();
this.token("=");
this.space();
this.print(node.right, node);
this.semicolon();
}
function TypeAnnotation(node) {
this.token(":");
this.space();
if (node.optional) this.token("?");
this.print(node.typeAnnotation, node);
}
function TypeParameterInstantiation(node) {
this.token("<");
this.printList(node.params, node, {});
this.token(">");
}
function TypeParameter(node) {
this._variance(node);
this.word(node.name);
if (node.bound) {
this.print(node.bound, node);
}
if (node.default) {
this.space();
this.token("=");
this.space();
this.print(node.default, node);
}
}
function OpaqueType(node) {
this.word("opaque");
this.space();
this.word("type");
this.space();
this.print(node.id, node);
this.print(node.typeParameters, node);
if (node.supertype) {
this.token(":");
this.space();
this.print(node.supertype, node);
}
if (node.impltype) {
this.space();
this.token("=");
this.space();
this.print(node.impltype, node);
}
this.semicolon();
}
function ObjectTypeAnnotation(node) {
if (node.exact) {
this.token("{|");
} else {
this.token("{");
}
const props = node.properties.concat(node.callProperties || [], node.indexers || [], node.internalSlots || []);
if (props.length) {
this.space();
this.printJoin(props, node, {
addNewlines(leading) {
if (leading && !props[0]) return 1;
},
indent: true,
statement: true,
iterator: () => {
if (props.length !== 1) {
this.token(",");
this.space();
}
}
});
this.space();
}
if (node.exact) {
this.token("|}");
} else {
this.token("}");
}
}
function ObjectTypeInternalSlot(node) {
if (node.static) {
this.word("static");
this.space();
}
this.token("[");
this.token("[");
this.print(node.id, node);
this.token("]");
this.token("]");
if (node.optional) this.token("?");
if (!node.method) {
this.token(":");
this.space();
}
this.print(node.value, node);
}
function ObjectTypeCallProperty(node) {
if (node.static) {
this.word("static");
this.space();
}
this.print(node.value, node);
}
function ObjectTypeIndexer(node) {
if (node.static) {
this.word("static");
this.space();
}
this._variance(node);
this.token("[");
if (node.id) {
this.print(node.id, node);
this.token(":");
this.space();
}
this.print(node.key, node);
this.token("]");
this.token(":");
this.space();
this.print(node.value, node);
}
function ObjectTypeProperty(node) {
if (node.proto) {
this.word("proto");
this.space();
}
if (node.static) {
this.word("static");
this.space();
}
this._variance(node);
this.print(node.key, node);
if (node.optional) this.token("?");
if (!node.method) {
this.token(":");
this.space();
}
this.print(node.value, node);
}
function ObjectTypeSpreadProperty(node) {
this.token("...");
this.print(node.argument, node);
}
function QualifiedTypeIdentifier(node) {
this.print(node.qualification, node);
this.token(".");
this.print(node.id, node);
}
function orSeparator() {
this.space();
this.token("|");
this.space();
}
function UnionTypeAnnotation(node) {
this.printJoin(node.types, node, {
separator: orSeparator
});
}
function TypeCastExpression(node) {
this.token("(");
this.print(node.expression, node);
this.print(node.typeAnnotation, node);
this.token(")");
}
function Variance(node) {
if (node.kind === "plus") {
this.token("+");
} else {
this.token("-");
}
}
function VoidTypeAnnotation() {
this.word("void");
}

View File

@@ -0,0 +1,137 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _templateLiterals = require("./template-literals");
Object.keys(_templateLiterals).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _templateLiterals[key];
}
});
});
var _expressions = require("./expressions");
Object.keys(_expressions).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _expressions[key];
}
});
});
var _statements = require("./statements");
Object.keys(_statements).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _statements[key];
}
});
});
var _classes = require("./classes");
Object.keys(_classes).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _classes[key];
}
});
});
var _methods = require("./methods");
Object.keys(_methods).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _methods[key];
}
});
});
var _modules = require("./modules");
Object.keys(_modules).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _modules[key];
}
});
});
var _types = require("./types");
Object.keys(_types).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _types[key];
}
});
});
var _flow = require("./flow");
Object.keys(_flow).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _flow[key];
}
});
});
var _base = require("./base");
Object.keys(_base).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _base[key];
}
});
});
var _jsx = require("./jsx");
Object.keys(_jsx).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _jsx[key];
}
});
});
var _typescript = require("./typescript");
Object.keys(_typescript).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _typescript[key];
}
});
});

View File

@@ -0,0 +1,145 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.JSXAttribute = JSXAttribute;
exports.JSXIdentifier = JSXIdentifier;
exports.JSXNamespacedName = JSXNamespacedName;
exports.JSXMemberExpression = JSXMemberExpression;
exports.JSXSpreadAttribute = JSXSpreadAttribute;
exports.JSXExpressionContainer = JSXExpressionContainer;
exports.JSXSpreadChild = JSXSpreadChild;
exports.JSXText = JSXText;
exports.JSXElement = JSXElement;
exports.JSXOpeningElement = JSXOpeningElement;
exports.JSXClosingElement = JSXClosingElement;
exports.JSXEmptyExpression = JSXEmptyExpression;
exports.JSXFragment = JSXFragment;
exports.JSXOpeningFragment = JSXOpeningFragment;
exports.JSXClosingFragment = JSXClosingFragment;
function JSXAttribute(node) {
this.print(node.name, node);
if (node.value) {
this.token("=");
this.print(node.value, node);
}
}
function JSXIdentifier(node) {
this.word(node.name);
}
function JSXNamespacedName(node) {
this.print(node.namespace, node);
this.token(":");
this.print(node.name, node);
}
function JSXMemberExpression(node) {
this.print(node.object, node);
this.token(".");
this.print(node.property, node);
}
function JSXSpreadAttribute(node) {
this.token("{");
this.token("...");
this.print(node.argument, node);
this.token("}");
}
function JSXExpressionContainer(node) {
this.token("{");
this.print(node.expression, node);
this.token("}");
}
function JSXSpreadChild(node) {
this.token("{");
this.token("...");
this.print(node.expression, node);
this.token("}");
}
function JSXText(node) {
const raw = this.getPossibleRaw(node);
if (raw != null) {
this.token(raw);
} else {
this.token(node.value);
}
}
function JSXElement(node) {
const open = node.openingElement;
this.print(open, node);
if (open.selfClosing) return;
this.indent();
for (const child of node.children) {
this.print(child, node);
}
this.dedent();
this.print(node.closingElement, node);
}
function spaceSeparator() {
this.space();
}
function JSXOpeningElement(node) {
this.token("<");
this.print(node.name, node);
this.print(node.typeParameters, node);
if (node.attributes.length > 0) {
this.space();
this.printJoin(node.attributes, node, {
separator: spaceSeparator
});
}
if (node.selfClosing) {
this.space();
this.token("/>");
} else {
this.token(">");
}
}
function JSXClosingElement(node) {
this.token("</");
this.print(node.name, node);
this.token(">");
}
function JSXEmptyExpression(node) {
this.printInnerComments(node);
}
function JSXFragment(node) {
this.print(node.openingFragment, node);
this.indent();
for (const child of node.children) {
this.print(child, node);
}
this.dedent();
this.print(node.closingFragment, node);
}
function JSXOpeningFragment() {
this.token("<");
this.token(">");
}
function JSXClosingFragment() {
this.token("</");
this.token(">");
}

View File

@@ -0,0 +1,167 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports._params = _params;
exports._parameters = _parameters;
exports._param = _param;
exports._methodHead = _methodHead;
exports._predicate = _predicate;
exports._functionHead = _functionHead;
exports.FunctionDeclaration = exports.FunctionExpression = FunctionExpression;
exports.ArrowFunctionExpression = ArrowFunctionExpression;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _params(node) {
this.print(node.typeParameters, node);
this.token("(");
this._parameters(node.params, node);
this.token(")");
this.print(node.returnType, node);
}
function _parameters(parameters, parent) {
for (let i = 0; i < parameters.length; i++) {
this._param(parameters[i], parent);
if (i < parameters.length - 1) {
this.token(",");
this.space();
}
}
}
function _param(parameter, parent) {
this.printJoin(parameter.decorators, parameter);
this.print(parameter, parent);
if (parameter.optional) this.token("?");
this.print(parameter.typeAnnotation, parameter);
}
function _methodHead(node) {
const kind = node.kind;
const key = node.key;
if (kind === "get" || kind === "set") {
this.word(kind);
this.space();
}
if (node.async) {
this.word("async");
this.space();
}
if (kind === "method" || kind === "init") {
if (node.generator) {
this.token("*");
}
}
if (node.computed) {
this.token("[");
this.print(key, node);
this.token("]");
} else {
this.print(key, node);
}
if (node.optional) {
this.token("?");
}
this._params(node);
}
function _predicate(node) {
if (node.predicate) {
if (!node.returnType) {
this.token(":");
}
this.space();
this.print(node.predicate, node);
}
}
function _functionHead(node) {
if (node.async) {
this.word("async");
this.space();
}
this.word("function");
if (node.generator) this.token("*");
this.space();
if (node.id) {
this.print(node.id, node);
}
this._params(node);
this._predicate(node);
}
function FunctionExpression(node) {
this._functionHead(node);
this.space();
this.print(node.body, node);
}
function ArrowFunctionExpression(node) {
if (node.async) {
this.word("async");
this.space();
}
const firstParam = node.params[0];
if (node.params.length === 1 && t().isIdentifier(firstParam) && !hasTypes(node, firstParam)) {
if (this.format.retainLines && node.loc && node.body.loc && node.loc.start.line < node.body.loc.start.line) {
this.token("(");
if (firstParam.loc && firstParam.loc.start.line > node.loc.start.line) {
this.indent();
this.print(firstParam, node);
this.dedent();
this._catchUp("start", node.body.loc);
} else {
this.print(firstParam, node);
}
this.token(")");
} else {
this.print(firstParam, node);
}
} else {
this._params(node);
}
this._predicate(node);
this.space();
this.token("=>");
this.space();
this.print(node.body, node);
}
function hasTypes(node, param) {
return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments;
}

View File

@@ -0,0 +1,214 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ImportSpecifier = ImportSpecifier;
exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
exports.ExportDefaultSpecifier = ExportDefaultSpecifier;
exports.ExportSpecifier = ExportSpecifier;
exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier;
exports.ExportAllDeclaration = ExportAllDeclaration;
exports.ExportNamedDeclaration = ExportNamedDeclaration;
exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
exports.ImportDeclaration = ImportDeclaration;
exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function ImportSpecifier(node) {
if (node.importKind === "type" || node.importKind === "typeof") {
this.word(node.importKind);
this.space();
}
this.print(node.imported, node);
if (node.local && node.local.name !== node.imported.name) {
this.space();
this.word("as");
this.space();
this.print(node.local, node);
}
}
function ImportDefaultSpecifier(node) {
this.print(node.local, node);
}
function ExportDefaultSpecifier(node) {
this.print(node.exported, node);
}
function ExportSpecifier(node) {
this.print(node.local, node);
if (node.exported && node.local.name !== node.exported.name) {
this.space();
this.word("as");
this.space();
this.print(node.exported, node);
}
}
function ExportNamespaceSpecifier(node) {
this.token("*");
this.space();
this.word("as");
this.space();
this.print(node.exported, node);
}
function ExportAllDeclaration(node) {
this.word("export");
this.space();
if (node.exportKind === "type") {
this.word("type");
this.space();
}
this.token("*");
this.space();
this.word("from");
this.space();
this.print(node.source, node);
this.semicolon();
}
function ExportNamedDeclaration(node) {
if (this.format.decoratorsBeforeExport && t().isClassDeclaration(node.declaration)) {
this.printJoin(node.declaration.decorators, node);
}
this.word("export");
this.space();
ExportDeclaration.apply(this, arguments);
}
function ExportDefaultDeclaration(node) {
if (this.format.decoratorsBeforeExport && t().isClassDeclaration(node.declaration)) {
this.printJoin(node.declaration.decorators, node);
}
this.word("export");
this.space();
this.word("default");
this.space();
ExportDeclaration.apply(this, arguments);
}
function ExportDeclaration(node) {
if (node.declaration) {
const declar = node.declaration;
this.print(declar, node);
if (!t().isStatement(declar)) this.semicolon();
} else {
if (node.exportKind === "type") {
this.word("type");
this.space();
}
const specifiers = node.specifiers.slice(0);
let hasSpecial = false;
while (true) {
const first = specifiers[0];
if (t().isExportDefaultSpecifier(first) || t().isExportNamespaceSpecifier(first)) {
hasSpecial = true;
this.print(specifiers.shift(), node);
if (specifiers.length) {
this.token(",");
this.space();
}
} else {
break;
}
}
if (specifiers.length || !specifiers.length && !hasSpecial) {
this.token("{");
if (specifiers.length) {
this.space();
this.printList(specifiers, node);
this.space();
}
this.token("}");
}
if (node.source) {
this.space();
this.word("from");
this.space();
this.print(node.source, node);
}
this.semicolon();
}
}
function ImportDeclaration(node) {
this.word("import");
this.space();
if (node.importKind === "type" || node.importKind === "typeof") {
this.word(node.importKind);
this.space();
}
const specifiers = node.specifiers.slice(0);
if (specifiers && specifiers.length) {
while (true) {
const first = specifiers[0];
if (t().isImportDefaultSpecifier(first) || t().isImportNamespaceSpecifier(first)) {
this.print(specifiers.shift(), node);
if (specifiers.length) {
this.token(",");
this.space();
}
} else {
break;
}
}
if (specifiers.length) {
this.token("{");
this.space();
this.printList(specifiers, node);
this.space();
this.token("}");
}
this.space();
this.word("from");
this.space();
}
this.print(node.source, node);
this.semicolon();
}
function ImportNamespaceSpecifier(node) {
this.token("*");
this.space();
this.word("as");
this.space();
this.print(node.local, node);
}

View File

@@ -0,0 +1,319 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WithStatement = WithStatement;
exports.IfStatement = IfStatement;
exports.ForStatement = ForStatement;
exports.WhileStatement = WhileStatement;
exports.DoWhileStatement = DoWhileStatement;
exports.LabeledStatement = LabeledStatement;
exports.TryStatement = TryStatement;
exports.CatchClause = CatchClause;
exports.SwitchStatement = SwitchStatement;
exports.SwitchCase = SwitchCase;
exports.DebuggerStatement = DebuggerStatement;
exports.VariableDeclaration = VariableDeclaration;
exports.VariableDeclarator = VariableDeclarator;
exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForOfStatement = exports.ForInStatement = void 0;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function WithStatement(node) {
this.word("with");
this.space();
this.token("(");
this.print(node.object, node);
this.token(")");
this.printBlock(node);
}
function IfStatement(node) {
this.word("if");
this.space();
this.token("(");
this.print(node.test, node);
this.token(")");
this.space();
const needsBlock = node.alternate && t().isIfStatement(getLastStatement(node.consequent));
if (needsBlock) {
this.token("{");
this.newline();
this.indent();
}
this.printAndIndentOnComments(node.consequent, node);
if (needsBlock) {
this.dedent();
this.newline();
this.token("}");
}
if (node.alternate) {
if (this.endsWith("}")) this.space();
this.word("else");
this.space();
this.printAndIndentOnComments(node.alternate, node);
}
}
function getLastStatement(statement) {
if (!t().isStatement(statement.body)) return statement;
return getLastStatement(statement.body);
}
function ForStatement(node) {
this.word("for");
this.space();
this.token("(");
this.inForStatementInitCounter++;
this.print(node.init, node);
this.inForStatementInitCounter--;
this.token(";");
if (node.test) {
this.space();
this.print(node.test, node);
}
this.token(";");
if (node.update) {
this.space();
this.print(node.update, node);
}
this.token(")");
this.printBlock(node);
}
function WhileStatement(node) {
this.word("while");
this.space();
this.token("(");
this.print(node.test, node);
this.token(")");
this.printBlock(node);
}
const buildForXStatement = function (op) {
return function (node) {
this.word("for");
this.space();
if (op === "of" && node.await) {
this.word("await");
this.space();
}
this.token("(");
this.print(node.left, node);
this.space();
this.word(op);
this.space();
this.print(node.right, node);
this.token(")");
this.printBlock(node);
};
};
const ForInStatement = buildForXStatement("in");
exports.ForInStatement = ForInStatement;
const ForOfStatement = buildForXStatement("of");
exports.ForOfStatement = ForOfStatement;
function DoWhileStatement(node) {
this.word("do");
this.space();
this.print(node.body, node);
this.space();
this.word("while");
this.space();
this.token("(");
this.print(node.test, node);
this.token(")");
this.semicolon();
}
function buildLabelStatement(prefix, key = "label") {
return function (node) {
this.word(prefix);
const label = node[key];
if (label) {
this.space();
const isLabel = key == "label";
const terminatorState = this.startTerminatorless(isLabel);
this.print(label, node);
this.endTerminatorless(terminatorState);
}
this.semicolon();
};
}
const ContinueStatement = buildLabelStatement("continue");
exports.ContinueStatement = ContinueStatement;
const ReturnStatement = buildLabelStatement("return", "argument");
exports.ReturnStatement = ReturnStatement;
const BreakStatement = buildLabelStatement("break");
exports.BreakStatement = BreakStatement;
const ThrowStatement = buildLabelStatement("throw", "argument");
exports.ThrowStatement = ThrowStatement;
function LabeledStatement(node) {
this.print(node.label, node);
this.token(":");
this.space();
this.print(node.body, node);
}
function TryStatement(node) {
this.word("try");
this.space();
this.print(node.block, node);
this.space();
if (node.handlers) {
this.print(node.handlers[0], node);
} else {
this.print(node.handler, node);
}
if (node.finalizer) {
this.space();
this.word("finally");
this.space();
this.print(node.finalizer, node);
}
}
function CatchClause(node) {
this.word("catch");
this.space();
if (node.param) {
this.token("(");
this.print(node.param, node);
this.token(")");
this.space();
}
this.print(node.body, node);
}
function SwitchStatement(node) {
this.word("switch");
this.space();
this.token("(");
this.print(node.discriminant, node);
this.token(")");
this.space();
this.token("{");
this.printSequence(node.cases, node, {
indent: true,
addNewlines(leading, cas) {
if (!leading && node.cases[node.cases.length - 1] === cas) return -1;
}
});
this.token("}");
}
function SwitchCase(node) {
if (node.test) {
this.word("case");
this.space();
this.print(node.test, node);
this.token(":");
} else {
this.word("default");
this.token(":");
}
if (node.consequent.length) {
this.newline();
this.printSequence(node.consequent, node, {
indent: true
});
}
}
function DebuggerStatement() {
this.word("debugger");
this.semicolon();
}
function variableDeclarationIndent() {
this.token(",");
this.newline();
if (this.endsWith("\n")) for (let i = 0; i < 4; i++) this.space(true);
}
function constDeclarationIndent() {
this.token(",");
this.newline();
if (this.endsWith("\n")) for (let i = 0; i < 6; i++) this.space(true);
}
function VariableDeclaration(node, parent) {
if (node.declare) {
this.word("declare");
this.space();
}
this.word(node.kind);
this.space();
let hasInits = false;
if (!t().isFor(parent)) {
for (const declar of node.declarations) {
if (declar.init) {
hasInits = true;
}
}
}
let separator;
if (hasInits) {
separator = node.kind === "const" ? constDeclarationIndent : variableDeclarationIndent;
}
this.printList(node.declarations, node, {
separator
});
if (t().isFor(parent)) {
if (parent.left === node || parent.init === node) return;
}
this.semicolon();
}
function VariableDeclarator(node) {
this.print(node.id, node);
if (node.definite) this.token("!");
this.print(node.id.typeAnnotation, node);
if (node.init) {
this.space();
this.token("=");
this.space();
this.print(node.init, node);
}
}

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TaggedTemplateExpression = TaggedTemplateExpression;
exports.TemplateElement = TemplateElement;
exports.TemplateLiteral = TemplateLiteral;
function TaggedTemplateExpression(node) {
this.print(node.tag, node);
this.print(node.typeParameters, node);
this.print(node.quasi, node);
}
function TemplateElement(node, parent) {
const isFirst = parent.quasis[0] === node;
const isLast = parent.quasis[parent.quasis.length - 1] === node;
const value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${");
this.token(value);
}
function TemplateLiteral(node) {
const quasis = node.quasis;
for (let i = 0; i < quasis.length; i++) {
this.print(quasis[i], node);
if (i + 1 < quasis.length) {
this.print(node.expressions[i], node);
}
}
}

View File

@@ -0,0 +1,198 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Identifier = Identifier;
exports.ArgumentPlaceholder = ArgumentPlaceholder;
exports.SpreadElement = exports.RestElement = RestElement;
exports.ObjectPattern = exports.ObjectExpression = ObjectExpression;
exports.ObjectMethod = ObjectMethod;
exports.ObjectProperty = ObjectProperty;
exports.ArrayPattern = exports.ArrayExpression = ArrayExpression;
exports.RegExpLiteral = RegExpLiteral;
exports.BooleanLiteral = BooleanLiteral;
exports.NullLiteral = NullLiteral;
exports.NumericLiteral = NumericLiteral;
exports.StringLiteral = StringLiteral;
exports.BigIntLiteral = BigIntLiteral;
exports.PipelineTopicExpression = PipelineTopicExpression;
exports.PipelineBareFunction = PipelineBareFunction;
exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _jsesc() {
const data = _interopRequireDefault(require("jsesc"));
_jsesc = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function Identifier(node) {
this.exactSource(node.loc, () => {
this.word(node.name);
});
}
function ArgumentPlaceholder() {
this.token("?");
}
function RestElement(node) {
this.token("...");
this.print(node.argument, node);
}
function ObjectExpression(node) {
const props = node.properties;
this.token("{");
this.printInnerComments(node);
if (props.length) {
this.space();
this.printList(props, node, {
indent: true,
statement: true
});
this.space();
}
this.token("}");
}
function ObjectMethod(node) {
this.printJoin(node.decorators, node);
this._methodHead(node);
this.space();
this.print(node.body, node);
}
function ObjectProperty(node) {
this.printJoin(node.decorators, node);
if (node.computed) {
this.token("[");
this.print(node.key, node);
this.token("]");
} else {
if (t().isAssignmentPattern(node.value) && t().isIdentifier(node.key) && node.key.name === node.value.left.name) {
this.print(node.value, node);
return;
}
this.print(node.key, node);
if (node.shorthand && t().isIdentifier(node.key) && t().isIdentifier(node.value) && node.key.name === node.value.name) {
return;
}
}
this.token(":");
this.space();
this.print(node.value, node);
}
function ArrayExpression(node) {
const elems = node.elements;
const len = elems.length;
this.token("[");
this.printInnerComments(node);
for (let i = 0; i < elems.length; i++) {
const elem = elems[i];
if (elem) {
if (i > 0) this.space();
this.print(elem, node);
if (i < len - 1) this.token(",");
} else {
this.token(",");
}
}
this.token("]");
}
function RegExpLiteral(node) {
this.word(`/${node.pattern}/${node.flags}`);
}
function BooleanLiteral(node) {
this.word(node.value ? "true" : "false");
}
function NullLiteral() {
this.word("null");
}
function NumericLiteral(node) {
const raw = this.getPossibleRaw(node);
const value = node.value + "";
if (raw == null) {
this.number(value);
} else if (this.format.minified) {
this.number(raw.length < value.length ? raw : value);
} else {
this.number(raw);
}
}
function StringLiteral(node) {
const raw = this.getPossibleRaw(node);
if (!this.format.minified && raw != null) {
this.token(raw);
return;
}
const opts = this.format.jsescOption;
if (this.format.jsonCompatibleStrings) {
opts.json = true;
}
const val = (0, _jsesc().default)(node.value, opts);
return this.token(val);
}
function BigIntLiteral(node) {
const raw = this.getPossibleRaw(node);
if (!this.format.minified && raw != null) {
this.token(raw);
return;
}
this.token(node.value);
}
function PipelineTopicExpression(node) {
this.print(node.expression, node);
}
function PipelineBareFunction(node) {
this.print(node.callee, node);
}
function PipelinePrimaryTopicReference() {
this.token("#");
}

View File

@@ -0,0 +1,715 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TSTypeAnnotation = TSTypeAnnotation;
exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation;
exports.TSTypeParameter = TSTypeParameter;
exports.TSParameterProperty = TSParameterProperty;
exports.TSDeclareFunction = TSDeclareFunction;
exports.TSDeclareMethod = TSDeclareMethod;
exports.TSQualifiedName = TSQualifiedName;
exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration;
exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration;
exports.TSPropertySignature = TSPropertySignature;
exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName;
exports.TSMethodSignature = TSMethodSignature;
exports.TSIndexSignature = TSIndexSignature;
exports.TSAnyKeyword = TSAnyKeyword;
exports.TSUnknownKeyword = TSUnknownKeyword;
exports.TSNumberKeyword = TSNumberKeyword;
exports.TSObjectKeyword = TSObjectKeyword;
exports.TSBooleanKeyword = TSBooleanKeyword;
exports.TSStringKeyword = TSStringKeyword;
exports.TSSymbolKeyword = TSSymbolKeyword;
exports.TSVoidKeyword = TSVoidKeyword;
exports.TSUndefinedKeyword = TSUndefinedKeyword;
exports.TSNullKeyword = TSNullKeyword;
exports.TSNeverKeyword = TSNeverKeyword;
exports.TSThisType = TSThisType;
exports.TSFunctionType = TSFunctionType;
exports.TSConstructorType = TSConstructorType;
exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType;
exports.TSTypeReference = TSTypeReference;
exports.TSTypePredicate = TSTypePredicate;
exports.TSTypeQuery = TSTypeQuery;
exports.TSTypeLiteral = TSTypeLiteral;
exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody;
exports.tsPrintBraced = tsPrintBraced;
exports.TSArrayType = TSArrayType;
exports.TSTupleType = TSTupleType;
exports.TSOptionalType = TSOptionalType;
exports.TSRestType = TSRestType;
exports.TSUnionType = TSUnionType;
exports.TSIntersectionType = TSIntersectionType;
exports.tsPrintUnionOrIntersectionType = tsPrintUnionOrIntersectionType;
exports.TSConditionalType = TSConditionalType;
exports.TSInferType = TSInferType;
exports.TSParenthesizedType = TSParenthesizedType;
exports.TSTypeOperator = TSTypeOperator;
exports.TSIndexedAccessType = TSIndexedAccessType;
exports.TSMappedType = TSMappedType;
exports.TSLiteralType = TSLiteralType;
exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments;
exports.TSInterfaceDeclaration = TSInterfaceDeclaration;
exports.TSInterfaceBody = TSInterfaceBody;
exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration;
exports.TSAsExpression = TSAsExpression;
exports.TSTypeAssertion = TSTypeAssertion;
exports.TSEnumDeclaration = TSEnumDeclaration;
exports.TSEnumMember = TSEnumMember;
exports.TSModuleDeclaration = TSModuleDeclaration;
exports.TSModuleBlock = TSModuleBlock;
exports.TSImportType = TSImportType;
exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration;
exports.TSExternalModuleReference = TSExternalModuleReference;
exports.TSNonNullExpression = TSNonNullExpression;
exports.TSExportAssignment = TSExportAssignment;
exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration;
exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase;
function TSTypeAnnotation(node) {
this.token(":");
this.space();
if (node.optional) this.token("?");
this.print(node.typeAnnotation, node);
}
function TSTypeParameterInstantiation(node) {
this.token("<");
this.printList(node.params, node, {});
this.token(">");
}
function TSTypeParameter(node) {
this.word(node.name);
if (node.constraint) {
this.space();
this.word("extends");
this.space();
this.print(node.constraint, node);
}
if (node.default) {
this.space();
this.token("=");
this.space();
this.print(node.default, node);
}
}
function TSParameterProperty(node) {
if (node.accessibility) {
this.word(node.accessibility);
this.space();
}
if (node.readonly) {
this.word("readonly");
this.space();
}
this._param(node.parameter);
}
function TSDeclareFunction(node) {
if (node.declare) {
this.word("declare");
this.space();
}
this._functionHead(node);
this.token(";");
}
function TSDeclareMethod(node) {
this._classMethodHead(node);
this.token(";");
}
function TSQualifiedName(node) {
this.print(node.left, node);
this.token(".");
this.print(node.right, node);
}
function TSCallSignatureDeclaration(node) {
this.tsPrintSignatureDeclarationBase(node);
}
function TSConstructSignatureDeclaration(node) {
this.word("new");
this.space();
this.tsPrintSignatureDeclarationBase(node);
}
function TSPropertySignature(node) {
const {
readonly,
initializer
} = node;
if (readonly) {
this.word("readonly");
this.space();
}
this.tsPrintPropertyOrMethodName(node);
this.print(node.typeAnnotation, node);
if (initializer) {
this.space();
this.token("=");
this.space();
this.print(initializer, node);
}
this.token(";");
}
function tsPrintPropertyOrMethodName(node) {
if (node.computed) {
this.token("[");
}
this.print(node.key, node);
if (node.computed) {
this.token("]");
}
if (node.optional) {
this.token("?");
}
}
function TSMethodSignature(node) {
this.tsPrintPropertyOrMethodName(node);
this.tsPrintSignatureDeclarationBase(node);
this.token(";");
}
function TSIndexSignature(node) {
const {
readonly
} = node;
if (readonly) {
this.word("readonly");
this.space();
}
this.token("[");
this._parameters(node.parameters, node);
this.token("]");
this.print(node.typeAnnotation, node);
this.token(";");
}
function TSAnyKeyword() {
this.word("any");
}
function TSUnknownKeyword() {
this.word("unknown");
}
function TSNumberKeyword() {
this.word("number");
}
function TSObjectKeyword() {
this.word("object");
}
function TSBooleanKeyword() {
this.word("boolean");
}
function TSStringKeyword() {
this.word("string");
}
function TSSymbolKeyword() {
this.word("symbol");
}
function TSVoidKeyword() {
this.word("void");
}
function TSUndefinedKeyword() {
this.word("undefined");
}
function TSNullKeyword() {
this.word("null");
}
function TSNeverKeyword() {
this.word("never");
}
function TSThisType() {
this.word("this");
}
function TSFunctionType(node) {
this.tsPrintFunctionOrConstructorType(node);
}
function TSConstructorType(node) {
this.word("new");
this.space();
this.tsPrintFunctionOrConstructorType(node);
}
function tsPrintFunctionOrConstructorType(node) {
const {
typeParameters,
parameters
} = node;
this.print(typeParameters, node);
this.token("(");
this._parameters(parameters, node);
this.token(")");
this.space();
this.token("=>");
this.space();
this.print(node.typeAnnotation.typeAnnotation, node);
}
function TSTypeReference(node) {
this.print(node.typeName, node);
this.print(node.typeParameters, node);
}
function TSTypePredicate(node) {
this.print(node.parameterName);
this.space();
this.word("is");
this.space();
this.print(node.typeAnnotation.typeAnnotation);
}
function TSTypeQuery(node) {
this.word("typeof");
this.space();
this.print(node.exprName);
}
function TSTypeLiteral(node) {
this.tsPrintTypeLiteralOrInterfaceBody(node.members, node);
}
function tsPrintTypeLiteralOrInterfaceBody(members, node) {
this.tsPrintBraced(members, node);
}
function tsPrintBraced(members, node) {
this.token("{");
if (members.length) {
this.indent();
this.newline();
for (const member of members) {
this.print(member, node);
this.newline();
}
this.dedent();
this.rightBrace();
} else {
this.token("}");
}
}
function TSArrayType(node) {
this.print(node.elementType, node);
this.token("[]");
}
function TSTupleType(node) {
this.token("[");
this.printList(node.elementTypes, node);
this.token("]");
}
function TSOptionalType(node) {
this.print(node.typeAnnotation, node);
this.token("?");
}
function TSRestType(node) {
this.token("...");
this.print(node.typeAnnotation, node);
}
function TSUnionType(node) {
this.tsPrintUnionOrIntersectionType(node, "|");
}
function TSIntersectionType(node) {
this.tsPrintUnionOrIntersectionType(node, "&");
}
function tsPrintUnionOrIntersectionType(node, sep) {
this.printJoin(node.types, node, {
separator() {
this.space();
this.token(sep);
this.space();
}
});
}
function TSConditionalType(node) {
this.print(node.checkType);
this.space();
this.word("extends");
this.space();
this.print(node.extendsType);
this.space();
this.token("?");
this.space();
this.print(node.trueType);
this.space();
this.token(":");
this.space();
this.print(node.falseType);
}
function TSInferType(node) {
this.token("infer");
this.space();
this.print(node.typeParameter);
}
function TSParenthesizedType(node) {
this.token("(");
this.print(node.typeAnnotation, node);
this.token(")");
}
function TSTypeOperator(node) {
this.token(node.operator);
this.space();
this.print(node.typeAnnotation, node);
}
function TSIndexedAccessType(node) {
this.print(node.objectType, node);
this.token("[");
this.print(node.indexType, node);
this.token("]");
}
function TSMappedType(node) {
const {
readonly,
typeParameter,
optional
} = node;
this.token("{");
this.space();
if (readonly) {
tokenIfPlusMinus(this, readonly);
this.word("readonly");
this.space();
}
this.token("[");
this.word(typeParameter.name);
this.space();
this.word("in");
this.space();
this.print(typeParameter.constraint, typeParameter);
this.token("]");
if (optional) {
tokenIfPlusMinus(this, optional);
this.token("?");
}
this.token(":");
this.space();
this.print(node.typeAnnotation, node);
this.space();
this.token("}");
}
function tokenIfPlusMinus(self, tok) {
if (tok !== true) {
self.token(tok);
}
}
function TSLiteralType(node) {
this.print(node.literal, node);
}
function TSExpressionWithTypeArguments(node) {
this.print(node.expression, node);
this.print(node.typeParameters, node);
}
function TSInterfaceDeclaration(node) {
const {
declare,
id,
typeParameters,
extends: extendz,
body
} = node;
if (declare) {
this.word("declare");
this.space();
}
this.word("interface");
this.space();
this.print(id, node);
this.print(typeParameters, node);
if (extendz) {
this.space();
this.word("extends");
this.space();
this.printList(extendz, node);
}
this.space();
this.print(body, node);
}
function TSInterfaceBody(node) {
this.tsPrintTypeLiteralOrInterfaceBody(node.body, node);
}
function TSTypeAliasDeclaration(node) {
const {
declare,
id,
typeParameters,
typeAnnotation
} = node;
if (declare) {
this.word("declare");
this.space();
}
this.word("type");
this.space();
this.print(id, node);
this.print(typeParameters, node);
this.space();
this.token("=");
this.space();
this.print(typeAnnotation, node);
this.token(";");
}
function TSAsExpression(node) {
const {
expression,
typeAnnotation
} = node;
this.print(expression, node);
this.space();
this.word("as");
this.space();
this.print(typeAnnotation, node);
}
function TSTypeAssertion(node) {
const {
typeAnnotation,
expression
} = node;
this.token("<");
this.print(typeAnnotation, node);
this.token(">");
this.space();
this.print(expression, node);
}
function TSEnumDeclaration(node) {
const {
declare,
const: isConst,
id,
members
} = node;
if (declare) {
this.word("declare");
this.space();
}
if (isConst) {
this.word("const");
this.space();
}
this.word("enum");
this.space();
this.print(id, node);
this.space();
this.tsPrintBraced(members, node);
}
function TSEnumMember(node) {
const {
id,
initializer
} = node;
this.print(id, node);
if (initializer) {
this.space();
this.token("=");
this.space();
this.print(initializer, node);
}
this.token(",");
}
function TSModuleDeclaration(node) {
const {
declare,
id
} = node;
if (declare) {
this.word("declare");
this.space();
}
if (!node.global) {
this.word(id.type === "Identifier" ? "namespace" : "module");
this.space();
}
this.print(id, node);
if (!node.body) {
this.token(";");
return;
}
let body = node.body;
while (body.type === "TSModuleDeclaration") {
this.token(".");
this.print(body.id, body);
body = body.body;
}
this.space();
this.print(body, node);
}
function TSModuleBlock(node) {
this.tsPrintBraced(node.body, node);
}
function TSImportType(node) {
const {
argument,
qualifier,
typeParameters
} = node;
this.word("import");
this.token("(");
this.print(argument, node);
this.token(")");
if (qualifier) {
this.token(".");
this.print(qualifier, node);
}
if (typeParameters) {
this.print(typeParameters, node);
}
}
function TSImportEqualsDeclaration(node) {
const {
isExport,
id,
moduleReference
} = node;
if (isExport) {
this.word("export");
this.space();
}
this.word("import");
this.space();
this.print(id, node);
this.space();
this.token("=");
this.space();
this.print(moduleReference, node);
this.token(";");
}
function TSExternalModuleReference(node) {
this.token("require(");
this.print(node.expression, node);
this.token(")");
}
function TSNonNullExpression(node) {
this.print(node.expression, node);
this.token("!");
}
function TSExportAssignment(node) {
this.word("export");
this.space();
this.token("=");
this.space();
this.print(node.expression, node);
this.token(";");
}
function TSNamespaceExportDeclaration(node) {
this.word("export");
this.space();
this.word("as");
this.space();
this.word("namespace");
this.space();
this.print(node.id, node);
}
function tsPrintSignatureDeclarationBase(node) {
const {
typeParameters,
parameters
} = node;
this.print(typeParameters, node);
this.token("(");
this._parameters(parameters, node);
this.token(")");
this.print(node.typeAnnotation, node);
}

View File

@@ -0,0 +1,92 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
exports.CodeGenerator = void 0;
var _sourceMap = _interopRequireDefault(require("./source-map"));
var _printer = _interopRequireDefault(require("./printer"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class Generator extends _printer.default {
constructor(ast, opts = {}, code) {
const format = normalizeOptions(code, opts);
const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null;
super(format, map);
this.ast = ast;
}
generate() {
return super.generate(this.ast);
}
}
function normalizeOptions(code, opts) {
const format = {
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
shouldPrintComment: opts.shouldPrintComment,
retainLines: opts.retainLines,
retainFunctionParens: opts.retainFunctionParens,
comments: opts.comments == null || opts.comments,
compact: opts.compact,
minified: opts.minified,
concise: opts.concise,
jsonCompatibleStrings: opts.jsonCompatibleStrings,
indent: {
adjustMultilineComment: true,
style: " ",
base: 0
},
decoratorsBeforeExport: !!opts.decoratorsBeforeExport,
jsescOption: Object.assign({
quotes: "double",
wrap: true
}, opts.jsescOption)
};
if (format.minified) {
format.compact = true;
format.shouldPrintComment = format.shouldPrintComment || (() => format.comments);
} else {
format.shouldPrintComment = format.shouldPrintComment || (value => format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0);
}
if (format.compact === "auto") {
format.compact = code.length > 500000;
if (format.compact) {
console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`);
}
}
if (format.compact) {
format.indent.adjustMultilineComment = false;
}
return format;
}
class CodeGenerator {
constructor(ast, opts, code) {
this._generator = new Generator(ast, opts, code);
}
generate() {
return this._generator.generate();
}
}
exports.CodeGenerator = CodeGenerator;
function _default(ast, opts, code) {
const gen = new Generator(ast, opts, code);
return gen.generate();
}

View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.needsWhitespace = needsWhitespace;
exports.needsWhitespaceBefore = needsWhitespaceBefore;
exports.needsWhitespaceAfter = needsWhitespaceAfter;
exports.needsParens = needsParens;
var whitespace = _interopRequireWildcard(require("./whitespace"));
var parens = _interopRequireWildcard(require("./parentheses"));
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function expandAliases(obj) {
const newObj = {};
function add(type, func) {
const fn = newObj[type];
newObj[type] = fn ? function (node, parent, stack) {
const result = fn(node, parent, stack);
return result == null ? func(node, parent, stack) : result;
} : func;
}
for (const type of Object.keys(obj)) {
const aliases = t().FLIPPED_ALIAS_KEYS[type];
if (aliases) {
for (const alias of aliases) {
add(alias, obj[type]);
}
} else {
add(type, obj[type]);
}
}
return newObj;
}
const expandedParens = expandAliases(parens);
const expandedWhitespaceNodes = expandAliases(whitespace.nodes);
const expandedWhitespaceList = expandAliases(whitespace.list);
function find(obj, node, parent, printStack) {
const fn = obj[node.type];
return fn ? fn(node, parent, printStack) : null;
}
function isOrHasCallExpression(node) {
if (t().isCallExpression(node)) {
return true;
}
if (t().isMemberExpression(node)) {
return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property);
} else {
return false;
}
}
function needsWhitespace(node, parent, type) {
if (!node) return 0;
if (t().isExpressionStatement(node)) {
node = node.expression;
}
let linesInfo = find(expandedWhitespaceNodes, node, parent);
if (!linesInfo) {
const items = find(expandedWhitespaceList, node, parent);
if (items) {
for (let i = 0; i < items.length; i++) {
linesInfo = needsWhitespace(items[i], node, type);
if (linesInfo) break;
}
}
}
if (typeof linesInfo === "object" && linesInfo !== null) {
return linesInfo[type] || 0;
}
return 0;
}
function needsWhitespaceBefore(node, parent) {
return needsWhitespace(node, parent, "before");
}
function needsWhitespaceAfter(node, parent) {
return needsWhitespace(node, parent, "after");
}
function needsParens(node, parent, printStack) {
if (!parent) return false;
if (t().isNewExpression(parent) && parent.callee === node) {
if (isOrHasCallExpression(node)) return true;
}
return find(expandedParens, node, parent, printStack);
}

View File

@@ -0,0 +1,253 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NullableTypeAnnotation = NullableTypeAnnotation;
exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
exports.UpdateExpression = UpdateExpression;
exports.ObjectExpression = ObjectExpression;
exports.DoExpression = DoExpression;
exports.Binary = Binary;
exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation;
exports.TSAsExpression = TSAsExpression;
exports.TSTypeAssertion = TSTypeAssertion;
exports.TSIntersectionType = exports.TSUnionType = TSUnionType;
exports.BinaryExpression = BinaryExpression;
exports.SequenceExpression = SequenceExpression;
exports.AwaitExpression = exports.YieldExpression = YieldExpression;
exports.ClassExpression = ClassExpression;
exports.UnaryLike = UnaryLike;
exports.FunctionExpression = FunctionExpression;
exports.ArrowFunctionExpression = ArrowFunctionExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.OptionalMemberExpression = OptionalMemberExpression;
exports.AssignmentExpression = AssignmentExpression;
exports.NewExpression = NewExpression;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
const PRECEDENCE = {
"||": 0,
"&&": 1,
"|": 2,
"^": 3,
"&": 4,
"==": 5,
"===": 5,
"!=": 5,
"!==": 5,
"<": 6,
">": 6,
"<=": 6,
">=": 6,
in: 6,
instanceof: 6,
">>": 7,
"<<": 7,
">>>": 7,
"+": 8,
"-": 8,
"*": 9,
"/": 9,
"%": 9,
"**": 10
};
const isClassExtendsClause = (node, parent) => (t().isClassDeclaration(parent) || t().isClassExpression(parent)) && parent.superClass === node;
function NullableTypeAnnotation(node, parent) {
return t().isArrayTypeAnnotation(parent);
}
function FunctionTypeAnnotation(node, parent) {
return t().isUnionTypeAnnotation(parent) || t().isIntersectionTypeAnnotation(parent) || t().isArrayTypeAnnotation(parent);
}
function UpdateExpression(node, parent) {
return t().isMemberExpression(parent, {
object: node
}) || t().isCallExpression(parent, {
callee: node
}) || t().isNewExpression(parent, {
callee: node
}) || isClassExtendsClause(node, parent);
}
function ObjectExpression(node, parent, printStack) {
return isFirstInStatement(printStack, {
considerArrow: true
});
}
function DoExpression(node, parent, printStack) {
return isFirstInStatement(printStack);
}
function Binary(node, parent) {
if (node.operator === "**" && t().isBinaryExpression(parent, {
operator: "**"
})) {
return parent.left === node;
}
if (isClassExtendsClause(node, parent)) {
return true;
}
if ((t().isCallExpression(parent) || t().isNewExpression(parent)) && parent.callee === node || t().isUnaryLike(parent) || t().isMemberExpression(parent) && parent.object === node || t().isAwaitExpression(parent)) {
return true;
}
if (t().isBinary(parent)) {
const parentOp = parent.operator;
const parentPos = PRECEDENCE[parentOp];
const nodeOp = node.operator;
const nodePos = PRECEDENCE[nodeOp];
if (parentPos === nodePos && parent.right === node && !t().isLogicalExpression(parent) || parentPos > nodePos) {
return true;
}
}
return false;
}
function UnionTypeAnnotation(node, parent) {
return t().isArrayTypeAnnotation(parent) || t().isNullableTypeAnnotation(parent) || t().isIntersectionTypeAnnotation(parent) || t().isUnionTypeAnnotation(parent);
}
function TSAsExpression() {
return true;
}
function TSTypeAssertion() {
return true;
}
function TSUnionType(node, parent) {
return t().isTSArrayType(parent) || t().isTSOptionalType(parent) || t().isTSIntersectionType(parent) || t().isTSUnionType(parent) || t().isTSRestType(parent);
}
function BinaryExpression(node, parent) {
return node.operator === "in" && (t().isVariableDeclarator(parent) || t().isFor(parent));
}
function SequenceExpression(node, parent) {
if (t().isForStatement(parent) || t().isThrowStatement(parent) || t().isReturnStatement(parent) || t().isIfStatement(parent) && parent.test === node || t().isWhileStatement(parent) && parent.test === node || t().isForInStatement(parent) && parent.right === node || t().isSwitchStatement(parent) && parent.discriminant === node || t().isExpressionStatement(parent) && parent.expression === node) {
return false;
}
return true;
}
function YieldExpression(node, parent) {
return t().isBinary(parent) || t().isUnaryLike(parent) || t().isCallExpression(parent) || t().isMemberExpression(parent) || t().isNewExpression(parent) || t().isAwaitExpression(parent) && t().isYieldExpression(node) || t().isConditionalExpression(parent) && node === parent.test || isClassExtendsClause(node, parent);
}
function ClassExpression(node, parent, printStack) {
return isFirstInStatement(printStack, {
considerDefaultExports: true
});
}
function UnaryLike(node, parent) {
return t().isMemberExpression(parent, {
object: node
}) || t().isCallExpression(parent, {
callee: node
}) || t().isNewExpression(parent, {
callee: node
}) || t().isBinaryExpression(parent, {
operator: "**",
left: node
}) || isClassExtendsClause(node, parent);
}
function FunctionExpression(node, parent, printStack) {
return isFirstInStatement(printStack, {
considerDefaultExports: true
});
}
function ArrowFunctionExpression(node, parent) {
return t().isExportDeclaration(parent) || ConditionalExpression(node, parent);
}
function ConditionalExpression(node, parent) {
if (t().isUnaryLike(parent) || t().isBinary(parent) || t().isConditionalExpression(parent, {
test: node
}) || t().isAwaitExpression(parent) || t().isOptionalMemberExpression(parent) || t().isTaggedTemplateExpression(parent) || t().isTSTypeAssertion(parent) || t().isTSAsExpression(parent)) {
return true;
}
return UnaryLike(node, parent);
}
function OptionalMemberExpression(node, parent) {
return t().isCallExpression(parent) || t().isMemberExpression(parent);
}
function AssignmentExpression(node) {
if (t().isObjectPattern(node.left)) {
return true;
} else {
return ConditionalExpression(...arguments);
}
}
function NewExpression(node, parent) {
return isClassExtendsClause(node, parent);
}
function isFirstInStatement(printStack, {
considerArrow = false,
considerDefaultExports = false
} = {}) {
let i = printStack.length - 1;
let node = printStack[i];
i--;
let parent = printStack[i];
while (i > 0) {
if (t().isExpressionStatement(parent, {
expression: node
}) || t().isTaggedTemplateExpression(parent) || considerDefaultExports && t().isExportDefaultDeclaration(parent, {
declaration: node
}) || considerArrow && t().isArrowFunctionExpression(parent, {
body: node
})) {
return true;
}
if (t().isCallExpression(parent, {
callee: node
}) || t().isSequenceExpression(parent) && parent.expressions[0] === node || t().isMemberExpression(parent, {
object: node
}) || t().isConditional(parent, {
test: node
}) || t().isBinary(parent, {
left: node
}) || t().isAssignmentExpression(parent, {
left: node
})) {
node = parent;
i--;
parent = printStack[i];
} else {
return false;
}
}
return false;
}

View File

@@ -0,0 +1,192 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.list = exports.nodes = void 0;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function crawl(node, state = {}) {
if (t().isMemberExpression(node)) {
crawl(node.object, state);
if (node.computed) crawl(node.property, state);
} else if (t().isBinary(node) || t().isAssignmentExpression(node)) {
crawl(node.left, state);
crawl(node.right, state);
} else if (t().isCallExpression(node)) {
state.hasCall = true;
crawl(node.callee, state);
} else if (t().isFunction(node)) {
state.hasFunction = true;
} else if (t().isIdentifier(node)) {
state.hasHelper = state.hasHelper || isHelper(node.callee);
}
return state;
}
function isHelper(node) {
if (t().isMemberExpression(node)) {
return isHelper(node.object) || isHelper(node.property);
} else if (t().isIdentifier(node)) {
return node.name === "require" || node.name[0] === "_";
} else if (t().isCallExpression(node)) {
return isHelper(node.callee);
} else if (t().isBinary(node) || t().isAssignmentExpression(node)) {
return t().isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right);
} else {
return false;
}
}
function isType(node) {
return t().isLiteral(node) || t().isObjectExpression(node) || t().isArrayExpression(node) || t().isIdentifier(node) || t().isMemberExpression(node);
}
const nodes = {
AssignmentExpression(node) {
const state = crawl(node.right);
if (state.hasCall && state.hasHelper || state.hasFunction) {
return {
before: state.hasFunction,
after: true
};
}
},
SwitchCase(node, parent) {
return {
before: node.consequent.length || parent.cases[0] === node,
after: !node.consequent.length && parent.cases[parent.cases.length - 1] === node
};
},
LogicalExpression(node) {
if (t().isFunction(node.left) || t().isFunction(node.right)) {
return {
after: true
};
}
},
Literal(node) {
if (node.value === "use strict") {
return {
after: true
};
}
},
CallExpression(node) {
if (t().isFunction(node.callee) || isHelper(node)) {
return {
before: true,
after: true
};
}
},
VariableDeclaration(node) {
for (let i = 0; i < node.declarations.length; i++) {
const declar = node.declarations[i];
let enabled = isHelper(declar.id) && !isType(declar.init);
if (!enabled) {
const state = crawl(declar.init);
enabled = isHelper(declar.init) && state.hasCall || state.hasFunction;
}
if (enabled) {
return {
before: true,
after: true
};
}
}
},
IfStatement(node) {
if (t().isBlockStatement(node.consequent)) {
return {
before: true,
after: true
};
}
}
};
exports.nodes = nodes;
nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) {
if (parent.properties[0] === node) {
return {
before: true
};
}
};
nodes.ObjectTypeCallProperty = function (node, parent) {
if (parent.callProperties[0] === node && (!parent.properties || !parent.properties.length)) {
return {
before: true
};
}
};
nodes.ObjectTypeIndexer = function (node, parent) {
if (parent.indexers[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length)) {
return {
before: true
};
}
};
nodes.ObjectTypeInternalSlot = function (node, parent) {
if (parent.internalSlots[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length) && (!parent.indexers || !parent.indexers.length)) {
return {
before: true
};
}
};
const list = {
VariableDeclaration(node) {
return node.declarations.map(decl => decl.init);
},
ArrayExpression(node) {
return node.elements;
},
ObjectExpression(node) {
return node.properties;
}
};
exports.list = list;
[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function ([type, amounts]) {
if (typeof amounts === "boolean") {
amounts = {
after: amounts,
before: amounts
};
}
[type].concat(t().FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) {
nodes[type] = function () {
return amounts;
};
});
});

View File

@@ -0,0 +1,501 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _isInteger() {
const data = _interopRequireDefault(require("lodash/isInteger"));
_isInteger = function () {
return data;
};
return data;
}
function _repeat() {
const data = _interopRequireDefault(require("lodash/repeat"));
_repeat = function () {
return data;
};
return data;
}
var _buffer = _interopRequireDefault(require("./buffer"));
var n = _interopRequireWildcard(require("./node"));
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
var generatorFunctions = _interopRequireWildcard(require("./generators"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const SCIENTIFIC_NOTATION = /e/i;
const ZERO_DECIMAL_INTEGER = /\.0+$/;
const NON_DECIMAL_LITERAL = /^0[box]/;
class Printer {
constructor(format, map) {
this.inForStatementInitCounter = 0;
this._printStack = [];
this._indent = 0;
this._insideAux = false;
this._printedCommentStarts = {};
this._parenPushNewlineState = null;
this._noLineTerminator = false;
this._printAuxAfterOnNextUserNode = false;
this._printedComments = new WeakSet();
this._endsWithInteger = false;
this._endsWithWord = false;
this.format = format || {};
this._buf = new _buffer.default(map);
}
generate(ast) {
this.print(ast);
this._maybeAddAuxComment();
return this._buf.get();
}
indent() {
if (this.format.compact || this.format.concise) return;
this._indent++;
}
dedent() {
if (this.format.compact || this.format.concise) return;
this._indent--;
}
semicolon(force = false) {
this._maybeAddAuxComment();
this._append(";", !force);
}
rightBrace() {
if (this.format.minified) {
this._buf.removeLastSemicolon();
}
this.token("}");
}
space(force = false) {
if (this.format.compact) return;
if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) {
this._space();
}
}
word(str) {
if (this._endsWithWord || this.endsWith("/") && str.indexOf("/") === 0) {
this._space();
}
this._maybeAddAuxComment();
this._append(str);
this._endsWithWord = true;
}
number(str) {
this.word(str);
this._endsWithInteger = (0, _isInteger().default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== ".";
}
token(str) {
if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) {
this._space();
}
this._maybeAddAuxComment();
this._append(str);
}
newline(i) {
if (this.format.retainLines || this.format.compact) return;
if (this.format.concise) {
this.space();
return;
}
if (this.endsWith("\n\n")) return;
if (typeof i !== "number") i = 1;
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
for (let j = 0; j < i; j++) {
this._newline();
}
}
endsWith(str) {
return this._buf.endsWith(str);
}
removeTrailingNewline() {
this._buf.removeTrailingNewline();
}
exactSource(loc, cb) {
this._catchUp("start", loc);
this._buf.exactSource(loc, cb);
}
source(prop, loc) {
this._catchUp(prop, loc);
this._buf.source(prop, loc);
}
withSource(prop, loc, cb) {
this._catchUp(prop, loc);
this._buf.withSource(prop, loc, cb);
}
_space() {
this._append(" ", true);
}
_newline() {
this._append("\n", true);
}
_append(str, queue = false) {
this._maybeAddParen(str);
this._maybeIndent(str);
if (queue) this._buf.queue(str);else this._buf.append(str);
this._endsWithWord = false;
this._endsWithInteger = false;
}
_maybeIndent(str) {
if (this._indent && this.endsWith("\n") && str[0] !== "\n") {
this._buf.queue(this._getIndent());
}
}
_maybeAddParen(str) {
const parenPushNewlineState = this._parenPushNewlineState;
if (!parenPushNewlineState) return;
this._parenPushNewlineState = null;
let i;
for (i = 0; i < str.length && str[i] === " "; i++) continue;
if (i === str.length) return;
const cha = str[i];
if (cha !== "\n") {
if (cha !== "/") return;
if (i + 1 === str.length) return;
const chaPost = str[i + 1];
if (chaPost !== "/" && chaPost !== "*") return;
}
this.token("(");
this.indent();
parenPushNewlineState.printed = true;
}
_catchUp(prop, loc) {
if (!this.format.retainLines) return;
const pos = loc ? loc[prop] : null;
if (pos && pos.line !== null) {
const count = pos.line - this._buf.getCurrentLine();
for (let i = 0; i < count; i++) {
this._newline();
}
}
}
_getIndent() {
return (0, _repeat().default)(this.format.indent.style, this._indent);
}
startTerminatorless(isLabel = false) {
if (isLabel) {
this._noLineTerminator = true;
return null;
} else {
return this._parenPushNewlineState = {
printed: false
};
}
}
endTerminatorless(state) {
this._noLineTerminator = false;
if (state && state.printed) {
this.dedent();
this.newline();
this.token(")");
}
}
print(node, parent) {
if (!node) return;
const oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
const printMethod = this[node.type];
if (!printMethod) {
throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`);
}
this._printStack.push(node);
const oldInAux = this._insideAux;
this._insideAux = !node.loc;
this._maybeAddAuxComment(this._insideAux && !oldInAux);
let needsParens = n.needsParens(node, parent, this._printStack);
if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) {
needsParens = true;
}
if (needsParens) this.token("(");
this._printLeadingComments(node);
const loc = t().isProgram(node) || t().isFile(node) ? null : node.loc;
this.withSource("start", loc, () => {
printMethod.call(this, node, parent);
});
this._printTrailingComments(node);
if (needsParens) this.token(")");
this._printStack.pop();
this.format.concise = oldConcise;
this._insideAux = oldInAux;
}
_maybeAddAuxComment(enteredPositionlessNode) {
if (enteredPositionlessNode) this._printAuxBeforeComment();
if (!this._insideAux) this._printAuxAfterComment();
}
_printAuxBeforeComment() {
if (this._printAuxAfterOnNextUserNode) return;
this._printAuxAfterOnNextUserNode = true;
const comment = this.format.auxiliaryCommentBefore;
if (comment) {
this._printComment({
type: "CommentBlock",
value: comment
});
}
}
_printAuxAfterComment() {
if (!this._printAuxAfterOnNextUserNode) return;
this._printAuxAfterOnNextUserNode = false;
const comment = this.format.auxiliaryCommentAfter;
if (comment) {
this._printComment({
type: "CommentBlock",
value: comment
});
}
}
getPossibleRaw(node) {
const extra = node.extra;
if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
return extra.raw;
}
}
printJoin(nodes, parent, opts = {}) {
if (!nodes || !nodes.length) return;
if (opts.indent) this.indent();
const newlineOpts = {
addNewlines: opts.addNewlines
};
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (!node) continue;
if (opts.statement) this._printNewline(true, node, parent, newlineOpts);
this.print(node, parent);
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && i < nodes.length - 1) {
opts.separator.call(this);
}
if (opts.statement) this._printNewline(false, node, parent, newlineOpts);
}
if (opts.indent) this.dedent();
}
printAndIndentOnComments(node, parent) {
const indent = node.leadingComments && node.leadingComments.length > 0;
if (indent) this.indent();
this.print(node, parent);
if (indent) this.dedent();
}
printBlock(parent) {
const node = parent.body;
if (!t().isEmptyStatement(node)) {
this.space();
}
this.print(node, parent);
}
_printTrailingComments(node) {
this._printComments(this._getComments(false, node));
}
_printLeadingComments(node) {
this._printComments(this._getComments(true, node));
}
printInnerComments(node, indent = true) {
if (!node.innerComments || !node.innerComments.length) return;
if (indent) this.indent();
this._printComments(node.innerComments);
if (indent) this.dedent();
}
printSequence(nodes, parent, opts = {}) {
opts.statement = true;
return this.printJoin(nodes, parent, opts);
}
printList(items, parent, opts = {}) {
if (opts.separator == null) {
opts.separator = commaSeparator;
}
return this.printJoin(items, parent, opts);
}
_printNewline(leading, node, parent, opts) {
if (this.format.retainLines || this.format.compact) return;
if (this.format.concise) {
this.space();
return;
}
let lines = 0;
if (this._buf.hasContent()) {
if (!leading) lines++;
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
const needs = leading ? n.needsWhitespaceBefore : n.needsWhitespaceAfter;
if (needs(node, parent)) lines++;
}
this.newline(lines);
}
_getComments(leading, node) {
return node && (leading ? node.leadingComments : node.trailingComments) || [];
}
_printComment(comment) {
if (!this.format.shouldPrintComment(comment.value)) return;
if (comment.ignore) return;
if (this._printedComments.has(comment)) return;
this._printedComments.add(comment);
if (comment.start != null) {
if (this._printedCommentStarts[comment.start]) return;
this._printedCommentStarts[comment.start] = true;
}
const isBlockComment = comment.type === "CommentBlock";
this.newline(this._buf.hasContent() && !this._noLineTerminator && isBlockComment ? 1 : 0);
if (!this.endsWith("[") && !this.endsWith("{")) this.space();
let val = !isBlockComment && !this._noLineTerminator ? `//${comment.value}\n` : `/*${comment.value}*/`;
if (isBlockComment && this.format.indent.adjustMultilineComment) {
const offset = comment.loc && comment.loc.start.column;
if (offset) {
const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
const indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn());
val = val.replace(/\n(?!$)/g, `\n${(0, _repeat().default)(" ", indentSize)}`);
}
if (this.endsWith("/")) this._space();
this.withSource("start", comment.loc, () => {
this._append(val);
});
this.newline(isBlockComment && !this._noLineTerminator ? 1 : 0);
}
_printComments(comments) {
if (!comments || !comments.length) return;
for (const comment of comments) {
this._printComment(comment);
}
}
}
exports.default = Printer;
Object.assign(Printer.prototype, generatorFunctions);
function commaSeparator() {
this.token(",");
this.space();
}

View File

@@ -0,0 +1,81 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _sourceMap() {
const data = _interopRequireDefault(require("source-map"));
_sourceMap = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class SourceMap {
constructor(opts, code) {
this._cachedMap = null;
this._code = code;
this._opts = opts;
this._rawMappings = [];
}
get() {
if (!this._cachedMap) {
const map = this._cachedMap = new (_sourceMap().default.SourceMapGenerator)({
sourceRoot: this._opts.sourceRoot
});
const code = this._code;
if (typeof code === "string") {
map.setSourceContent(this._opts.sourceFileName, code);
} else if (typeof code === "object") {
Object.keys(code).forEach(sourceFileName => {
map.setSourceContent(sourceFileName, code[sourceFileName]);
});
}
this._rawMappings.forEach(map.addMapping, map);
}
return this._cachedMap.toJSON();
}
getRawMappings() {
return this._rawMappings.slice();
}
mark(generatedLine, generatedColumn, line, column, identifierName, filename, force) {
if (this._lastGenLine !== generatedLine && line === null) return;
if (!force && this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) {
return;
}
this._cachedMap = null;
this._lastGenLine = generatedLine;
this._lastSourceLine = line;
this._lastSourceColumn = column;
this._rawMappings.push({
name: identifierName || undefined,
generated: {
line: generatedLine,
column: generatedColumn
},
source: line == null ? undefined : filename || this._opts.sourceFileName,
original: line == null ? undefined : {
line: line,
column: column
}
});
}
}
exports.default = SourceMap;

View File

@@ -0,0 +1,61 @@
{
"_from": "@babel/generator@^7.4.0",
"_id": "@babel/generator@7.4.0",
"_inBundle": false,
"_integrity": "sha512-/v5I+a1jhGSKLgZDcmAUZ4K/VePi43eRkUs3yePW1HB1iANOD5tqJXwGSG4BZhSksP8J9ejSlwGeTiiOFZOrXQ==",
"_location": "/@babel/core/@babel/generator",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/generator@^7.4.0",
"name": "@babel/generator",
"escapedName": "@babel%2fgenerator",
"scope": "@babel",
"rawSpec": "^7.4.0",
"saveSpec": null,
"fetchSpec": "^7.4.0"
},
"_requiredBy": [
"/@babel/core",
"/@babel/core/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.4.0.tgz",
"_shasum": "c230e79589ae7a729fd4631b9ded4dc220418196",
"_spec": "@babel/generator@^7.4.0",
"_where": "E:\\projects\\p\\minifyfromhtml\\node_modules\\@babel\\core",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/types": "^7.4.0",
"jsesc": "^2.5.1",
"lodash": "^4.17.11",
"source-map": "^0.5.0",
"trim-right": "^1.0.1"
},
"deprecated": false,
"description": "Turns an AST into code.",
"devDependencies": {
"@babel/helper-fixtures": "^7.2.0",
"@babel/parser": "^7.4.0"
},
"files": [
"lib"
],
"gitHead": "f1328fb913b5a93d54dfc6e3728b1f56c8f4a804",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/generator",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-generator"
},
"version": "7.4.0"
}

View File

@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-2018 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/helper-function-name
> Helper function to change the property 'name' of every function
See our website [@babel/helper-function-name](https://babeljs.io/docs/en/next/babel-helper-function-name.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/helper-function-name
```
or using yarn:
```sh
yarn add @babel/helper-function-name --dev
```

View File

@@ -0,0 +1,198 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function _helperGetFunctionArity() {
const data = _interopRequireDefault(require("@babel/helper-get-function-arity"));
_helperGetFunctionArity = function () {
return data;
};
return data;
}
function _template() {
const data = _interopRequireDefault(require("@babel/template"));
_template = function () {
return data;
};
return data;
}
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const buildPropertyMethodAssignmentWrapper = (0, _template().default)(`
(function (FUNCTION_KEY) {
function FUNCTION_ID() {
return FUNCTION_KEY.apply(this, arguments);
}
FUNCTION_ID.toString = function () {
return FUNCTION_KEY.toString();
}
return FUNCTION_ID;
})(FUNCTION)
`);
const buildGeneratorPropertyMethodAssignmentWrapper = (0, _template().default)(`
(function (FUNCTION_KEY) {
function* FUNCTION_ID() {
return yield* FUNCTION_KEY.apply(this, arguments);
}
FUNCTION_ID.toString = function () {
return FUNCTION_KEY.toString();
};
return FUNCTION_ID;
})(FUNCTION)
`);
const visitor = {
"ReferencedIdentifier|BindingIdentifier"(path, state) {
if (path.node.name !== state.name) return;
const localDeclar = path.scope.getBindingIdentifier(state.name);
if (localDeclar !== state.outerDeclar) return;
state.selfReference = true;
path.stop();
}
};
function getNameFromLiteralId(id) {
if (t().isNullLiteral(id)) {
return "null";
}
if (t().isRegExpLiteral(id)) {
return `_${id.pattern}_${id.flags}`;
}
if (t().isTemplateLiteral(id)) {
return id.quasis.map(quasi => quasi.value.raw).join("");
}
if (id.value !== undefined) {
return id.value + "";
}
return "";
}
function wrap(state, method, id, scope) {
if (state.selfReference) {
if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
scope.rename(id.name);
} else {
if (!t().isFunction(method)) return;
let build = buildPropertyMethodAssignmentWrapper;
if (method.generator) {
build = buildGeneratorPropertyMethodAssignmentWrapper;
}
const template = build({
FUNCTION: method,
FUNCTION_ID: id,
FUNCTION_KEY: scope.generateUidIdentifier(id.name)
}).expression;
const params = template.callee.body.body[0].params;
for (let i = 0, len = (0, _helperGetFunctionArity().default)(method); i < len; i++) {
params.push(scope.generateUidIdentifier("x"));
}
return template;
}
}
method.id = id;
scope.getProgramParent().references[id.name] = true;
}
function visit(node, name, scope) {
const state = {
selfAssignment: false,
selfReference: false,
outerDeclar: scope.getBindingIdentifier(name),
references: [],
name: name
};
const binding = scope.getOwnBinding(name);
if (binding) {
if (binding.kind === "param") {
state.selfReference = true;
} else {}
} else if (state.outerDeclar || scope.hasGlobal(name)) {
scope.traverse(node, visitor, state);
}
return state;
}
function _default({
node,
parent,
scope,
id
}, localBinding = false) {
if (node.id) return;
if ((t().isObjectProperty(parent) || t().isObjectMethod(parent, {
kind: "method"
})) && (!parent.computed || t().isLiteral(parent.key))) {
id = parent.key;
} else if (t().isVariableDeclarator(parent)) {
id = parent.id;
if (t().isIdentifier(id) && !localBinding) {
const binding = scope.parent.getBinding(id.name);
if (binding && binding.constant && scope.getBinding(id.name) === binding) {
node.id = t().cloneNode(id);
node.id[t().NOT_LOCAL_BINDING] = true;
return;
}
}
} else if (t().isAssignmentExpression(parent)) {
id = parent.left;
} else if (!id) {
return;
}
let name;
if (id && t().isLiteral(id)) {
name = getNameFromLiteralId(id);
} else if (id && t().isIdentifier(id)) {
name = id.name;
}
if (name === undefined) {
return;
}
name = t().toBindingIdentifierName(name);
id = t().identifier(name);
id[t().NOT_LOCAL_BINDING] = true;
const state = visit(node, name, scope);
return wrap(state, node, id, scope) || node;
}

View File

@@ -0,0 +1,45 @@
{
"_from": "@babel/helper-function-name@^7.1.0",
"_id": "@babel/helper-function-name@7.1.0",
"_inBundle": false,
"_integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==",
"_location": "/@babel/core/@babel/helper-function-name",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/helper-function-name@^7.1.0",
"name": "@babel/helper-function-name",
"escapedName": "@babel%2fhelper-function-name",
"scope": "@babel",
"rawSpec": "^7.1.0",
"saveSpec": null,
"fetchSpec": "^7.1.0"
},
"_requiredBy": [
"/@babel/core/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz",
"_shasum": "a0ceb01685f73355d4360c1247f582bfafc8ff53",
"_spec": "@babel/helper-function-name@^7.1.0",
"_where": "E:\\projects\\p\\minifyfromhtml\\node_modules\\@babel\\core\\node_modules\\@babel\\traverse",
"bundleDependencies": false,
"dependencies": {
"@babel/helper-get-function-arity": "^7.0.0",
"@babel/template": "^7.1.0",
"@babel/types": "^7.0.0"
},
"deprecated": false,
"description": "Helper function to change the property 'name' of every function",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/helper-function-name",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-function-name"
},
"version": "7.1.0"
}

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/helper-get-function-arity
> Helper function to get function arity
See our website [@babel/helper-get-function-arity](https://babeljs.io/docs/en/next/babel-helper-get-function-arity.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/helper-get-function-arity
```
or using yarn:
```sh
yarn add @babel/helper-get-function-arity --dev
```

View File

@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _default(node) {
const params = node.params;
for (let i = 0; i < params.length; i++) {
const param = params[i];
if (t().isAssignmentPattern(param) || t().isRestElement(param)) {
return i;
}
}
return params.length;
}

View File

@@ -0,0 +1,40 @@
{
"_from": "@babel/helper-get-function-arity@^7.0.0",
"_id": "@babel/helper-get-function-arity@7.0.0",
"_inBundle": false,
"_integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==",
"_location": "/@babel/core/@babel/helper-get-function-arity",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/helper-get-function-arity@^7.0.0",
"name": "@babel/helper-get-function-arity",
"escapedName": "@babel%2fhelper-get-function-arity",
"scope": "@babel",
"rawSpec": "^7.0.0",
"saveSpec": null,
"fetchSpec": "^7.0.0"
},
"_requiredBy": [
"/@babel/core/@babel/helper-function-name"
],
"_resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz",
"_shasum": "83572d4320e2a4657263734113c42868b64e49c3",
"_spec": "@babel/helper-get-function-arity@^7.0.0",
"_where": "E:\\projects\\p\\minifyfromhtml\\node_modules\\@babel\\core\\node_modules\\@babel\\helper-function-name",
"bundleDependencies": false,
"dependencies": {
"@babel/types": "^7.0.0"
},
"deprecated": false,
"description": "Helper function to get function arity",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/helper-get-function-arity",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-get-function-arity"
},
"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/helper-split-export-declaration
>
See our website [@babel/helper-split-export-declaration](https://babeljs.io/docs/en/next/babel-helper-split-export-declaration.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/helper-split-export-declaration
```
or using yarn:
```sh
yarn add @babel/helper-split-export-declaration --dev
```

View File

@@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = splitExportDeclaration;
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function splitExportDeclaration(exportDeclaration) {
if (!exportDeclaration.isExportDeclaration()) {
throw new Error("Only export declarations can be splitted.");
}
const isDefault = exportDeclaration.isExportDefaultDeclaration();
const declaration = exportDeclaration.get("declaration");
const isClassDeclaration = declaration.isClassDeclaration();
if (isDefault) {
const standaloneDeclaration = declaration.isFunctionDeclaration() || isClassDeclaration;
const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
let id = declaration.node.id;
let needBindingRegistration = false;
if (!id) {
needBindingRegistration = true;
id = scope.generateUidIdentifier("default");
if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) {
declaration.node.id = t().cloneNode(id);
}
}
const updatedDeclaration = standaloneDeclaration ? declaration : t().variableDeclaration("var", [t().variableDeclarator(t().cloneNode(id), declaration.node)]);
const updatedExportDeclaration = t().exportNamedDeclaration(null, [t().exportSpecifier(t().cloneNode(id), t().identifier("default"))]);
exportDeclaration.insertAfter(updatedExportDeclaration);
exportDeclaration.replaceWith(updatedDeclaration);
if (needBindingRegistration) {
scope.registerDeclaration(exportDeclaration);
}
return exportDeclaration;
}
if (exportDeclaration.get("specifiers").length > 0) {
throw new Error("It doesn't make sense to split exported specifiers.");
}
const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
const specifiers = Object.keys(bindingIdentifiers).map(name => {
return t().exportSpecifier(t().identifier(name), t().identifier(name));
});
const aliasDeclar = t().exportNamedDeclaration(null, specifiers);
exportDeclaration.insertAfter(aliasDeclar);
exportDeclaration.replaceWith(declaration.node);
return exportDeclaration;
}

View File

@@ -0,0 +1,44 @@
{
"_from": "@babel/helper-split-export-declaration@^7.4.0",
"_id": "@babel/helper-split-export-declaration@7.4.0",
"_inBundle": false,
"_integrity": "sha512-7Cuc6JZiYShaZnybDmfwhY4UYHzI6rlqhWjaIqbsJGsIqPimEYy5uh3akSRLMg65LSdSEnJ8a8/bWQN6u2oMGw==",
"_location": "/@babel/core/@babel/helper-split-export-declaration",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/helper-split-export-declaration@^7.4.0",
"name": "@babel/helper-split-export-declaration",
"escapedName": "@babel%2fhelper-split-export-declaration",
"scope": "@babel",
"rawSpec": "^7.4.0",
"saveSpec": null,
"fetchSpec": "^7.4.0"
},
"_requiredBy": [
"/@babel/core/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.0.tgz",
"_shasum": "571bfd52701f492920d63b7f735030e9a3e10b55",
"_spec": "@babel/helper-split-export-declaration@^7.4.0",
"_where": "E:\\projects\\p\\minifyfromhtml\\node_modules\\@babel\\core\\node_modules\\@babel\\traverse",
"bundleDependencies": false,
"dependencies": {
"@babel/types": "^7.4.0"
},
"deprecated": false,
"description": ">",
"gitHead": "f1328fb913b5a93d54dfc6e3728b1f56c8f4a804",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/helper-split-export-declaration",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-split-export-declaration"
},
"version": "7.4.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/helpers
> Collection of helper functions used by Babel transforms.
See our website [@babel/helpers](https://babeljs.io/docs/en/next/babel-helpers.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/helpers
```
or using yarn:
```sh
yarn add @babel/helpers --dev
```

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,285 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.get = get;
exports.minVersion = minVersion;
exports.getDependencies = getDependencies;
exports.default = exports.list = void 0;
function _traverse() {
const data = _interopRequireDefault(require("@babel/traverse"));
_traverse = function () {
return data;
};
return data;
}
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
var _helpers = _interopRequireDefault(require("./helpers"));
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 makePath(path) {
const parts = [];
for (; path.parentPath; path = path.parentPath) {
parts.push(path.key);
if (path.inList) parts.push(path.listKey);
}
return parts.reverse().join(".");
}
function getHelperMetadata(file) {
const globals = new Set();
const localBindingNames = new Set();
const dependencies = new Map();
let exportName;
let exportPath;
const exportBindingAssignments = [];
const importPaths = [];
const importBindingsReferences = [];
(0, _traverse().default)(file, {
ImportDeclaration(child) {
const name = child.node.source.value;
if (!_helpers.default[name]) {
throw child.buildCodeFrameError(`Unknown helper ${name}`);
}
if (child.get("specifiers").length !== 1 || !child.get("specifiers.0").isImportDefaultSpecifier()) {
throw child.buildCodeFrameError("Helpers can only import a default value");
}
const bindingIdentifier = child.node.specifiers[0].local;
dependencies.set(bindingIdentifier, name);
importPaths.push(makePath(child));
},
ExportDefaultDeclaration(child) {
const decl = child.get("declaration");
if (decl.isFunctionDeclaration()) {
if (!decl.node.id) {
throw decl.buildCodeFrameError("Helpers should give names to their exported func declaration");
}
exportName = decl.node.id.name;
}
exportPath = makePath(child);
},
ExportAllDeclaration(child) {
throw child.buildCodeFrameError("Helpers can only export default");
},
ExportNamedDeclaration(child) {
throw child.buildCodeFrameError("Helpers can only export default");
},
Statement(child) {
if (child.isModuleDeclaration()) return;
child.skip();
}
});
(0, _traverse().default)(file, {
Program(path) {
const bindings = path.scope.getAllBindings();
Object.keys(bindings).forEach(name => {
if (name === exportName) return;
if (dependencies.has(bindings[name].identifier)) return;
localBindingNames.add(name);
});
},
ReferencedIdentifier(child) {
const name = child.node.name;
const binding = child.scope.getBinding(name, true);
if (!binding) {
globals.add(name);
} else if (dependencies.has(binding.identifier)) {
importBindingsReferences.push(makePath(child));
}
},
AssignmentExpression(child) {
const left = child.get("left");
if (!(exportName in left.getBindingIdentifiers())) return;
if (!left.isIdentifier()) {
throw left.buildCodeFrameError("Only simple assignments to exports are allowed in helpers");
}
const binding = child.scope.getBinding(exportName);
if (binding && binding.scope.path.isProgram()) {
exportBindingAssignments.push(makePath(child));
}
}
});
if (!exportPath) throw new Error("Helpers must default-export something.");
exportBindingAssignments.reverse();
return {
globals: Array.from(globals),
localBindingNames: Array.from(localBindingNames),
dependencies,
exportBindingAssignments,
exportPath,
exportName,
importBindingsReferences,
importPaths
};
}
function permuteHelperAST(file, metadata, id, localBindings, getDependency) {
if (localBindings && !id) {
throw new Error("Unexpected local bindings for module-based helpers.");
}
if (!id) return;
const {
localBindingNames,
dependencies,
exportBindingAssignments,
exportPath,
exportName,
importBindingsReferences,
importPaths
} = metadata;
const dependenciesRefs = {};
dependencies.forEach((name, id) => {
dependenciesRefs[id.name] = typeof getDependency === "function" && getDependency(name) || id;
});
const toRename = {};
const bindings = new Set(localBindings || []);
localBindingNames.forEach(name => {
let newName = name;
while (bindings.has(newName)) newName = "_" + newName;
if (newName !== name) toRename[name] = newName;
});
if (id.type === "Identifier" && exportName !== id.name) {
toRename[exportName] = id.name;
}
(0, _traverse().default)(file, {
Program(path) {
const exp = path.get(exportPath);
const imps = importPaths.map(p => path.get(p));
const impsBindingRefs = importBindingsReferences.map(p => path.get(p));
const decl = exp.get("declaration");
if (id.type === "Identifier") {
if (decl.isFunctionDeclaration()) {
exp.replaceWith(decl);
} else {
exp.replaceWith(t().variableDeclaration("var", [t().variableDeclarator(id, decl.node)]));
}
} else if (id.type === "MemberExpression") {
if (decl.isFunctionDeclaration()) {
exportBindingAssignments.forEach(assignPath => {
const assign = path.get(assignPath);
assign.replaceWith(t().assignmentExpression("=", id, assign.node));
});
exp.replaceWith(decl);
path.pushContainer("body", t().expressionStatement(t().assignmentExpression("=", id, t().identifier(exportName))));
} else {
exp.replaceWith(t().expressionStatement(t().assignmentExpression("=", id, decl.node)));
}
} else {
throw new Error("Unexpected helper format.");
}
Object.keys(toRename).forEach(name => {
path.scope.rename(name, toRename[name]);
});
for (const path of imps) path.remove();
for (const path of impsBindingRefs) {
const node = t().cloneNode(dependenciesRefs[path.node.name]);
path.replaceWith(node);
}
path.stop();
}
});
}
const helperData = Object.create(null);
function loadHelper(name) {
if (!helperData[name]) {
const helper = _helpers.default[name];
if (!helper) {
throw Object.assign(new ReferenceError(`Unknown helper ${name}`), {
code: "BABEL_HELPER_UNKNOWN",
helper: name
});
}
const fn = () => {
return t().file(helper.ast());
};
const metadata = getHelperMetadata(fn());
helperData[name] = {
build(getDependency, id, localBindings) {
const file = fn();
permuteHelperAST(file, metadata, id, localBindings, getDependency);
return {
nodes: file.program.body,
globals: metadata.globals
};
},
minVersion() {
return helper.minVersion;
},
dependencies: metadata.dependencies
};
}
return helperData[name];
}
function get(name, getDependency, id, localBindings) {
return loadHelper(name).build(getDependency, id, localBindings);
}
function minVersion(name) {
return loadHelper(name).minVersion();
}
function getDependencies(name) {
return Array.from(loadHelper(name).dependencies.values());
}
const list = Object.keys(_helpers.default).map(name => name.replace(/^_/, "")).filter(name => name !== "__esModule");
exports.list = list;
var _default = get;
exports.default = _default;

View File

@@ -0,0 +1,54 @@
{
"_from": "@babel/helpers@^7.4.0",
"_id": "@babel/helpers@7.4.2",
"_inBundle": false,
"_integrity": "sha512-gQR1eQeroDzFBikhrCccm5Gs2xBjZ57DNjGbqTaHo911IpmSxflOQWMAHPw/TXk8L3isv7s9lYzUkexOeTQUYg==",
"_location": "/@babel/core/@babel/helpers",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/helpers@^7.4.0",
"name": "@babel/helpers",
"escapedName": "@babel%2fhelpers",
"scope": "@babel",
"rawSpec": "^7.4.0",
"saveSpec": null,
"fetchSpec": "^7.4.0"
},
"_requiredBy": [
"/@babel/core"
],
"_resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.4.2.tgz",
"_shasum": "3bdfa46a552ca77ef5a0f8551be5f0845ae989be",
"_spec": "@babel/helpers@^7.4.0",
"_where": "E:\\projects\\p\\minifyfromhtml\\node_modules\\@babel\\core",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/template": "^7.4.0",
"@babel/traverse": "^7.4.0",
"@babel/types": "^7.4.0"
},
"deprecated": false,
"description": "Collection of helper functions used by Babel transforms.",
"devDependencies": {
"@babel/helper-plugin-test-runner": "^7.0.0"
},
"gitHead": "7dea0f23de51af336a2fab0286a73af30cddf3be",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/helpers",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helpers"
},
"version": "7.4.2"
}

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/highlight
> Syntax highlight JavaScript strings for output in terminals.
See our website [@babel/highlight](https://babeljs.io/docs/en/next/babel-highlight.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/highlight
```
or using yarn:
```sh
yarn add @babel/highlight --dev
```

View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.shouldHighlight = shouldHighlight;
exports.getChalk = getChalk;
exports.default = highlight;
function _jsTokens() {
const data = _interopRequireWildcard(require("js-tokens"));
_jsTokens = function () {
return data;
};
return data;
}
function _esutils() {
const data = _interopRequireDefault(require("esutils"));
_esutils = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require("chalk"));
_chalk = 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 getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold
};
}
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
const JSX_TAG = /^[a-z][\w-]*$/i;
const BRACKET = /^[()[\]{}]$/;
function getTokenType(match) {
const [offset, text] = match.slice(-2);
const token = (0, _jsTokens().matchToToken)(match);
if (token.type === "name") {
if (_esutils().default.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
return "jsx_tag";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
}
function highlightTokens(defs, text) {
return text.replace(_jsTokens().default, function (...args) {
const type = getTokenType(args);
const colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
} else {
return args[0];
}
});
}
function shouldHighlight(options) {
return _chalk().default.supportsColor || options.forceColor;
}
function getChalk(options) {
let chalk = _chalk().default;
if (options.forceColor) {
chalk = new (_chalk().default.constructor)({
enabled: true,
level: 1
});
}
return chalk;
}
function highlight(code, options = {}) {
if (shouldHighlight(options)) {
const chalk = getChalk(options);
const defs = getDefs(chalk);
return highlightTokens(defs, code);
} else {
return code;
}
}

View File

@@ -0,0 +1,50 @@
{
"_from": "@babel/highlight@^7.0.0",
"_id": "@babel/highlight@7.0.0",
"_inBundle": false,
"_integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==",
"_location": "/@babel/core/@babel/highlight",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/highlight@^7.0.0",
"name": "@babel/highlight",
"escapedName": "@babel%2fhighlight",
"scope": "@babel",
"rawSpec": "^7.0.0",
"saveSpec": null,
"fetchSpec": "^7.0.0"
},
"_requiredBy": [
"/@babel/core/@babel/code-frame"
],
"_resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz",
"_shasum": "f710c38c8d458e6dd9a201afb637fcb781ce99e4",
"_spec": "@babel/highlight@^7.0.0",
"_where": "E:\\projects\\p\\minifyfromhtml\\node_modules\\@babel\\core\\node_modules\\@babel\\code-frame",
"author": {
"name": "suchipi",
"email": "me@suchipi.com"
},
"bundleDependencies": false,
"dependencies": {
"chalk": "^2.0.0",
"esutils": "^2.0.2",
"js-tokens": "^4.0.0"
},
"deprecated": false,
"description": "Syntax highlight JavaScript strings for output in terminals.",
"devDependencies": {
"strip-ansi": "^4.0.0"
},
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/highlight",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-highlight"
},
"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/template
> Generate an AST from a string template.
See our website [@babel/template](https://babeljs.io/docs/en/next/babel-template.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20template%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/template
```
or using yarn:
```sh
yarn add @babel/template --dev
```

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = createTemplateBuilder;
var _options = require("./options");
var _string = _interopRequireDefault(require("./string"));
var _literal = _interopRequireDefault(require("./literal"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const NO_PLACEHOLDER = (0, _options.validate)({
placeholderPattern: false
});
function createTemplateBuilder(formatter, defaultOpts) {
const templateFnCache = new WeakMap();
const templateAstCache = new WeakMap();
const cachedOpts = defaultOpts || (0, _options.validate)(null);
return Object.assign((tpl, ...args) => {
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return extendedTrace((0, _string.default)(formatter, tpl, (0, _options.merge)(cachedOpts, (0, _options.validate)(args[0]))));
} else if (Array.isArray(tpl)) {
let builder = templateFnCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, cachedOpts);
templateFnCache.set(tpl, builder);
}
return extendedTrace(builder(args));
} else if (typeof tpl === "object" && tpl) {
if (args.length > 0) throw new Error("Unexpected extra params.");
return createTemplateBuilder(formatter, (0, _options.merge)(cachedOpts, (0, _options.validate)(tpl)));
}
throw new Error(`Unexpected template param ${typeof tpl}`);
}, {
ast: (tpl, ...args) => {
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return (0, _string.default)(formatter, tpl, (0, _options.merge)((0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])), NO_PLACEHOLDER))();
} else if (Array.isArray(tpl)) {
let builder = templateAstCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, (0, _options.merge)(cachedOpts, NO_PLACEHOLDER));
templateAstCache.set(tpl, builder);
}
return builder(args)();
}
throw new Error(`Unexpected template param ${typeof tpl}`);
}
});
}
function extendedTrace(fn) {
let rootStack = "";
try {
throw new Error();
} catch (error) {
if (error.stack) {
rootStack = error.stack.split("\n").slice(3).join("\n");
}
}
return arg => {
try {
return fn(arg);
} catch (err) {
err.stack += `\n =============\n${rootStack}`;
throw err;
}
};
}

View File

@@ -0,0 +1,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.program = exports.expression = exports.statement = exports.statements = exports.smart = void 0;
function makeStatementFormatter(fn) {
return {
code: str => `/* @babel/template */;\n${str}`,
validate: () => {},
unwrap: ast => {
return fn(ast.program.body.slice(1));
}
};
}
const smart = makeStatementFormatter(body => {
if (body.length > 1) {
return body;
} else {
return body[0];
}
});
exports.smart = smart;
const statements = makeStatementFormatter(body => body);
exports.statements = statements;
const statement = makeStatementFormatter(body => {
if (body.length === 0) {
throw new Error("Found nothing to return.");
}
if (body.length > 1) {
throw new Error("Found multiple statements but wanted one");
}
return body[0];
});
exports.statement = statement;
const expression = {
code: str => `(\n${str}\n)`,
validate: ({
program
}) => {
if (program.body.length > 1) {
throw new Error("Found multiple statements but wanted one");
}
const expression = program.body[0].expression;
if (expression.start === 0) {
throw new Error("Parse result included parens.");
}
},
unwrap: ast => ast.program.body[0].expression
};
exports.expression = expression;
const program = {
code: str => str,
validate: () => {},
unwrap: ast => ast.program
};
exports.program = program;

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