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

update node modules

This commit is contained in:
s2
2021-05-07 15:56:33 +02:00
parent d81e8e9fb8
commit 3ec373077c
550 changed files with 84712 additions and 15991 deletions

118
node_modules/terser/CHANGELOG.md generated vendored
View File

@@ -1,5 +1,123 @@
# Changelog
## v5.7.0
- Several compile-time evaluation and inlining fixes
- Allow `reduce_funcs` to be disabled again.
- Add `spidermonkey` options to parse and format (#974)
- Accept `{get = "default val"}` and `{set = "default val"}` in destructuring arguments.
- Change package.json export map to help require.resolve (#971)
- Improve docs
- Fix `export default` of an anonymous class with `extends`
## v5.6.1
- Mark assignments to the `.prototype` of a class as pure
- Parenthesize `await` on the left of `**` (while accepting legacy non-parenthesised input)
- Avoided outputting NUL bytes in optimized RegExps, to stop the output from breaking other tools
- Added `exports` to domprops (#939)
- Fixed a crash when spreading `...this`
- Fixed the computed size of arrow functions, which improves their inlining
## v5.6.0
- Added top-level await
- Beautify option has been removed in #895
- Private properties, getters and setters have been added in #913 and some more commits
- Docs improvements: #896, #903, #916
## v5.5.1
- Fixed object properties with unicode surrogates on safari.
## v5.5.0
- Fixed crash when inlining uninitialized variable into template string.
- The sourcemap for dist was removed for being too large.
## v5.4.0
- Logical assignment
- Change `let x = undefined` to just `let x`
- Removed some optimizations for template strings, placing them behind `unsafe` options. Reason: adding strings is not equivalent to template strings, due to valueOf differences.
- The AST_Token class was slimmed down in order to use less memory.
## v5.3.8
- Restore node 13 support
## v5.3.7
Hotfix release, fixes package.json "engines" syntax
## v5.3.6
- Fixed parentheses when outputting `??` mixed with `||` and `&&`
- Improved hygiene of the symbol generator
## v5.3.5
- Avoid moving named functions into default exports.
- Enabled transform() for chain expressions. This allows AST transformers to reach inside chain expressions.
## v5.3.4
- Fixed a crash when hoisting (with `hoist_vars`) a destructuring variable declaration
## v5.3.3
- `source-map` library has been updated, bringing memory usage and CPU time improvements when reading input source maps (the SourceMapConsumer is now WASM based).
- The `wrap_func_args` option now also wraps arrow functions, as opposed to only function expressions.
## v5.3.2
- Prevented spread operations from being expanded when the expanded array/object contains getters, setters, or array holes.
- Fixed _very_ slow self-recursion in some cases of removing extraneous parentheses from `+` operations.
## v5.3.1
- An issue with destructuring declarations when `pure_getters` is enabled has been fixed
- Fixed a crash when chain expressions need to be shallowly compared
- Made inlining functions more conservative to make sure a function that contains a reference to itself isn't moved into a place that can create multiple instances of itself.
## v5.3.0
- Fixed a crash when compressing object spreads in some cases
- Fixed compiletime evaluation of optional chains (caused typeof a?.b to always return "object")
- domprops has been updated to contain every single possible prop
## v5.2.1
- The parse step now doesn't accept an `ecma` option, so that all ES code is accepted.
- Optional dotted chains now accept keywords, just like dotted expressions (`foo?.default`)
## v5.2.0
- Optional chaining syntax is now supported.
- Consecutive await expressions don't have unnecessary parens
- Taking the variable name's length (after mangling) into consideration when deciding to inline
## v5.1.0
- `import.meta` is now supported
- Typescript typings have been improved
## v5.0.0
- `in` operator now taken into account during property mangle.
- Fixed infinite loop in face of a reference loop in some situations.
- Kept exports and imports around even if there's something which will throw before them.
- The main exported bundle for commonjs, dist/bundle.min.js is no longer minified.
## v5.0.0-beta.0
- BREAKING: `minify()` is now async and rejects a promise instead of returning an error.
- BREAKING: Internal AST is no longer exposed, so that it can be improved without releasing breaking changes.
- BREAKING: Lowest supported node version is 10
- BREAKING: There are no more warnings being emitted
- Module is now distributed as a dual package - You can `import` and `require()` too.
- Inline improvements were made
## v4.8.0
- Support for numeric separators (`million = 1_000_000`) was added.

2
node_modules/terser/LICENSE generated vendored
View File

@@ -1,4 +1,4 @@
UglifyJS is released under the BSD license:
Terser is released under the BSD license:
Copyright 2012-2018 (c) Mihai Bazon <mihai.bazon@gmail.com>

257
node_modules/terser/README.md generated vendored
View File

@@ -21,8 +21,8 @@ Find the changelog in [CHANGELOG.md](https://github.com/terser/terser/blob/maste
[npm-url]: https://npmjs.org/package/terser
[downloads-image]: https://img.shields.io/npm/dm/terser.svg
[downloads-url]: https://npmjs.org/package/terser
[travis-image]: https://img.shields.io/travis/terser/terser/master.svg
[travis-url]: https://travis-ci.org/terser/terser
[travis-image]: https://travis-ci.com/terser/terser.svg?branch=master
[travis-url]: https://travis-ci.com/terser/terser
[opencollective-contributors]: https://opencollective.com/terser/tiers/badge.svg
[opencollective-url]: https://opencollective.com/terser
@@ -50,6 +50,8 @@ From NPM for programmatic use:
# Command line usage
<!-- CLI_USAGE:START -->
terser [input files] [options]
Terser can take multiple input files. It's recommended that you pass the
@@ -99,7 +101,7 @@ a double dash to prevent input files being used as option arguments:
being automatically reserved.
`regex` Only mangle matched property names.
`reserved` List of names that should not be mangled.
-b, --beautify [options] Specify output options:
-f, --format [options] Specify format options.
`preamble` Preamble to prepend to the output. You
can use this to insert a comment, for
example for licensing information.
@@ -137,7 +139,7 @@ a double dash to prevent input files being used as option arguments:
arguments and values.
--ie8 Support non-standard Internet Explorer 8.
Equivalent to setting `ie8: true` in `minify()`
for `compress`, `mangle` and `output` options.
for `compress`, `mangle` and `format` options.
By default Terser will not try to be IE-proof.
--keep-classnames Do not mangle/drop class names.
--keep-fnames Do not mangle/drop function names. Useful for
@@ -147,7 +149,7 @@ a double dash to prevent input files being used as option arguments:
--name-cache <file> File to hold mangled name mappings.
--safari10 Support non-standard Safari 10/11.
Equivalent to setting `safari10: true` in `minify()`
for `mangle` and `output` options.
for `mangle` and `format` options.
By default `terser` will not work around
Safari 10/11 bugs.
--source-map [options] Enable source map/specify source map options:
@@ -166,8 +168,6 @@ a double dash to prevent input files being used as option arguments:
`//# sourceMappingURL`.
--timings Display operations run time on STDERR.
--toplevel Compress and/or mangle variables in top level scope.
--verbose Print diagnostic messages.
--warn Print warning messages.
--wrap <name> Embed everything in a big function, making the
“exports” and “global” variables available. You
need to pass an argument to this option to
@@ -389,29 +389,40 @@ random number on every compile to simulate mangling changing with different
inputs (e.g. as you update the input script with new properties), and to help
identify mistakes like writing mangled keys to storage.
<!-- CLI_USAGE:END -->
# API Reference
<!-- API_REFERENCE:START -->
Assuming installation via NPM, you can load Terser in your application
like this:
```javascript
var Terser = require("terser");
```
Browser loading is also supported:
```html
<script src="node_modules/source-map/dist/source-map.min.js"></script>
<script src="dist/bundle.min.js"></script>
const { minify } = require("terser");
```
There is a single high level function, **`minify(code, options)`**,
Or,
```javascript
import { minify } from "terser";
```
Browser loading is also supported:
```html
<script src="https://cdn.jsdelivr.net/npm/source-map@0.7.3/dist/source-map.js"></script>
<script src="https://cdn.jsdelivr.net/npm/terser/dist/bundle.min.js"></script>
```
There is a single async high level function, **`async minify(code, options)`**,
which will perform all minification [phases](#minify-options) in a configurable
manner. By default `minify()` will enable the options [`compress`](#compress-options)
manner. By default `minify()` will enable [`compress`](#compress-options)
and [`mangle`](#mangle-options). Example:
```javascript
var code = "function add(first, second) { return first + second; }";
var result = Terser.minify(code);
console.log(result.error); // runtime error, or `undefined` if no error
var result = await minify(code, { sourceMap: true });
console.log(result.code); // minified output: function add(n,d){return n+d}
console.log(result.map); // source map
```
You can `minify` more than one JavaScript file at a time by using an object
@@ -422,7 +433,7 @@ var code = {
"file1.js": "function add(first, second) { return first + second; }",
"file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var result = Terser.minify(code);
var result = await minify(code);
console.log(result.code);
// function add(d,n){return d+n}console.log(add(3,7));
```
@@ -434,7 +445,7 @@ var code = {
"file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var options = { toplevel: true };
var result = Terser.minify(code, options);
var result = await minify(code, options);
console.log(result.code);
// console.log(3+7);
```
@@ -447,10 +458,10 @@ var options = {
},
nameCache: {}
};
var result1 = Terser.minify({
var result1 = await minify({
"file1.js": "function add(first, second) { return first + second; }"
}, options);
var result2 = Terser.minify({
var result2 = await minify({
"file2.js": "console.log(add(1 + 2, 3 + 4));"
}, options);
console.log(result1.code);
@@ -468,11 +479,11 @@ var options = {
},
nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8"))
};
fs.writeFileSync("part1.js", Terser.minify({
fs.writeFileSync("part1.js", await minify({
"file1.js": fs.readFileSync("file1.js", "utf8"),
"file2.js": fs.readFileSync("file2.js", "utf8")
}, options).code, "utf8");
fs.writeFileSync("part2.js", Terser.minify({
fs.writeFileSync("part2.js", await minify({
"file3.js": fs.readFileSync("file3.js", "utf8"),
"file4.js": fs.readFileSync("file4.js", "utf8")
}, options).code, "utf8");
@@ -493,47 +504,31 @@ var options = {
},
passes: 2
},
output: {
beautify: false,
format: {
preamble: "/* minified */"
}
};
var result = Terser.minify(code, options);
var result = await minify(code, options);
console.log(result.code);
// /* minified */
// alert(10);"
```
To produce warnings:
```javascript
var code = "function f(){ var u; return 2 + 3; }";
var options = { warnings: true };
var result = Terser.minify(code, options);
console.log(result.error); // runtime error, `undefined` in this case
console.log(result.warnings); // [ 'Dropping unused variable u [0:1,18]' ]
console.log(result.code); // function f(){return 5}
```
An error example:
```javascript
var result = Terser.minify({"foo.js" : "if (0) else console.log(1);"});
console.log(JSON.stringify(result.error));
// {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7}
```
Note: unlike `uglify-js@2.x`, the Terser API does not throw errors.
To achieve a similar effect one could do the following:
```javascript
var result = Terser.minify(code, options);
if (result.error) throw result.error;
try {
const result = await minify({"foo.js" : "if (0) else console.log(1);"});
// Do something with result
} catch (error) {
const { message, filename, line, col, pos } = error;
// Do something with error
}
```
## Minify options
- `ecma` (default `undefined`) - pass `5`, `2015`, `2016`, etc to override `parse`,
`compress` and `output`'s `ecma` options.
- `warnings` (default `false`) — pass `true` to return compressor warnings
in `result.warnings`. Use the value `"verbose"` for more detailed warnings.
- `ecma` (default `undefined`) - pass `5`, `2015`, `2016`, etc to override
`compress` and `format`'s `ecma` options.
- `parse` (default `{}`) — pass an object if you wish to specify some
additional [parse options](#parse-options).
@@ -551,8 +546,8 @@ if (result.error) throw result.error;
is implied and names can be mangled on the top scope. If `compress` or
`mangle` is enabled then the `toplevel` option will be enabled.
- `output` (default `null`) — pass an object if you wish to specify
additional [output options](#output-options). The defaults are optimized
- `format` or `output` (default `null`) — pass an object if you wish to specify
additional [format options](#format-options). The defaults are optimized
for best compression.
- `sourceMap` (default `false`) - pass an object if you wish to specify
@@ -581,7 +576,7 @@ if (result.error) throw result.error;
- `safari10` (default: `false`) - pass `true` to work around Safari 10/11 bugs in
loop scoping and `await`. See `safari10` options in [`mangle`](#mangle-options)
and [`output`](#output-options) for details.
and [`format`](#format-options) for details.
## Minify options structure
@@ -600,8 +595,8 @@ if (result.error) throw result.error;
// mangle property options
}
},
output: {
// output options
format: {
// format options (can also use `output` for backwards compatibility)
},
sourceMap: {
// source map options
@@ -613,8 +608,7 @@ if (result.error) throw result.error;
module: false,
nameCache: null, // or specify a name cache object
safari10: false,
toplevel: false,
warnings: false,
toplevel: false
}
```
@@ -622,7 +616,7 @@ if (result.error) throw result.error;
To generate a source map:
```javascript
var result = Terser.minify({"file1.js": "var a = function() {};"}, {
var result = await minify({"file1.js": "var a = function() {};"}, {
sourceMap: {
filename: "out.js",
url: "out.js.map"
@@ -643,7 +637,7 @@ be appended to code.
You can also specify sourceRoot property to be included in source map:
```javascript
var result = Terser.minify({"file1.js": "var a = function() {};"}, {
var result = await minify({"file1.js": "var a = function() {};"}, {
sourceMap: {
root: "http://example.com/src",
url: "out.js.map"
@@ -654,7 +648,7 @@ var result = Terser.minify({"file1.js": "var a = function() {};"}, {
If you're compressing compiled JavaScript and have a source map for it, you
can use `sourceMap.content`:
```javascript
var result = Terser.minify({"compiled.js": "compiled code"}, {
var result = await minify({"compiled.js": "compiled code"}, {
sourceMap: {
content: "content from compiled.js.map",
url: "minified.js.map"
@@ -671,14 +665,12 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
- `bare_returns` (default `false`) -- support top level `return` statements
- `ecma` (default: `2017`) -- specify one of `5`, `2015`, `2016` or `2017`. Note: this setting
is not presently enforced except for ES8 optional trailing commas in function
parameter lists and calls with `ecma` `2017`.
- `html5_comments` (default `true`)
- `shebang` (default `true`) -- support `#!command` as the first line
- `spidermonkey` (default `false`) -- accept a Spidermonkey (Mozilla) AST
## Compress options
- `defaults` (default: `true`) -- Pass `false` to disable most default
@@ -758,7 +750,7 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
- `keep_classnames` (default: `false`) -- Pass `true` to prevent the compressor from
discarding class names. Pass a regular expression to only keep class names matching
that regex. See also: the `keep_classnames` [mangle option](#mangle).
that regex. See also: the `keep_classnames` [mangle option](#mangle-options).
- `keep_fargs` (default: `true`) -- Prevents the compressor from discarding unused
function arguments. You need this for code which relies on `Function.length`.
@@ -766,7 +758,7 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
- `keep_fnames` (default: `false`) -- Pass `true` to prevent the
compressor from discarding function names. Pass a regular expression to only keep
function names matching that regex. Useful for code relying on `Function.prototype.name`.
See also: the `keep_fnames` [mangle option](#mangle).
See also: the `keep_fnames` [mangle option](#mangle-options).
- `keep_infinity` (default: `false`) -- Pass `true` to prevent `Infinity` from
being compressed into `1/0`, which may cause performance issues on Chrome.
@@ -805,11 +797,13 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
Specify `"strict"` to treat `foo.bar` as side-effect-free only when
`foo` is certain to not throw, i.e. not `null` or `undefined`.
- `reduce_funcs` (legacy option, safely ignored for backwards compatibility).
- `reduce_vars` (default: `true`) -- Improve optimization on variables assigned with and
used as constant values.
- `reduce_funcs` (default: `true`) -- Inline single-use functions when
possible. Depends on `reduce_vars` being enabled. Disabling this option
sometimes improves performance of the output code.
- `sequences` (default: `true`) -- join consecutive simple statements using the
comma operator. May be set to a positive integer to specify the maximum number
of consecutive comma sequences that will be generated. If this option is set to
@@ -819,10 +813,8 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
occasions the default sequences limit leads to very slow compress times in which
case a value of `20` or less is recommended.
- `side_effects` (default: `true`) -- Pass `false` to disable potentially dropping
function calls marked as "pure". A function call is marked as "pure" if a comment
annotation `/*@__PURE__*/` or `/*#__PURE__*/` immediately precedes the call. For
example: `/*@__PURE__*/foo();`
- `side_effects` (default: `true`) -- Remove expressions which have no side effects
and whose results aren't used.
- `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches
@@ -860,7 +852,7 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
- `unsafe_math` (default: `false`) -- optimize numerical expressions like
`2 * x * 3` into `6 * x`, which may give imprecise floating point results.
- `unsafe_symbols` (default: `false`) -- removes keys from native Symbol
- `unsafe_symbols` (default: `false`) -- removes keys from native Symbol
declarations, e.g `Symbol("kDog")` becomes `Symbol()`.
- `unsafe_methods` (default: false) -- Converts `{ m: function(){} }` to
@@ -883,9 +875,6 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
- `unused` (default: `true`) -- drop unreferenced functions and variables (simple
direct variable assignments do not count as references unless set to `"keep_assign"`)
- `warnings` (default: `false`) -- display warnings when dropping unreachable
code or unused declarations etc.
## Mangle options
- `eval` (default `false`) -- Pass `true` to mangle names visible in scopes
@@ -912,7 +901,7 @@ If you happen to need the source map as a raw object, set `sourceMap.asObject` t
- `safari10` (default `false`) -- Pass `true` to work around the Safari 10 loop
iterator [bug](https://bugs.webkit.org/show_bug.cgi?id=171041)
"Cannot declare a let variable twice".
See also: the `safari10` [output option](#output-options).
See also: the `safari10` [format option](#format-options).
Examples:
@@ -926,13 +915,13 @@ function funcName(firstLongName, anotherLongName) {
```javascript
var code = fs.readFileSync("test.js", "utf8");
Terser.minify(code).code;
await minify(code).code;
// 'function funcName(a,n){}var globalVar;'
Terser.minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
await minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
// 'function funcName(firstLongName,a){}var globalVar;'
Terser.minify(code, { mangle: { toplevel: true } }).code;
await minify(code, { mangle: { toplevel: true } }).code;
// 'function n(n,a){}var a;'
```
@@ -944,11 +933,10 @@ Terser.minify(code, { mangle: { toplevel: true } }).code;
- `debug` (default: `false`) — Mangle names with the original name still present.
Pass an empty string `""` to enable, or a non-empty string to set the debug suffix.
- `keep_quoted` (default: `false`) — Only mangle unquoted property names.
- `true` -- Quoted property names are automatically reserved and any unquoted
property names will not be mangled.
- `"strict"` -- Advanced, all unquoted property names are mangled unless
explicitly reserved.
- `keep_quoted` (default: `false`) — How quoting properties (`{"prop": ...}` and `obj["prop"]`) controls what gets mangled.
- `"strict"` (recommended) -- `obj.prop` is mangled.
- `false` -- `obj["prop"]` is mangled.
- `true` -- `obj.prop` is mangled unless there is `obj["prop"]` elsewhere in the code.
- `regex` (default: `null`) — Pass a [RegExp literal or pattern string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to only mangle property matching the regular expression.
@@ -960,35 +948,33 @@ Terser.minify(code, { mangle: { toplevel: true } }).code;
found in input code. May be useful when only minifying parts of a project.
See [#397](https://github.com/terser/terser/issues/397) for more details.
## Output options
The code generator tries to output shortest code possible by default. In
case you want beautified output, pass `--beautify` (`-b`). Optionally you
can pass additional arguments that control the code output:
## Format options
These options control the format of Terser's output code. Previously known
as "output options".
- `ascii_only` (default `false`) -- escape Unicode characters in strings and
regexps (affects directives with non-ascii characters becoming invalid)
- `beautify` (default `true`) -- whether to actually beautify the output.
Passing `-b` will set this to true, but you might need to pass `-b` even
when you want to generate minified code, in order to specify additional
arguments, so you can use `-b beautify=false` to override it.
- `beautify` (default `false`) -- (DEPRECATED) whether to beautify the output.
When using the legacy `-b` CLI flag, this is set to true by default.
- `braces` (default `false`) -- always insert braces in `if`, `for`,
`do`, `while` or `with` statements, even if their body is a single
statement.
- `comments` (default `"some"`) -- by default it keeps JSDoc-style comments
that contain "@license" or "@preserve", pass `true` or `"all"` to preserve all
comments, `false` to omit comments in the output, a regular expression string
(e.g. `/^!/`) or a function.
that contain "@license", "@preserve" or start with `!`, pass `true` or
`"all"` to preserve all comments, `false` to omit comments in the output,
a regular expression string (e.g. `/^!/`) or a function.
- `ecma` (default `5`) -- set output printing mode. Set `ecma` to `2015` or
greater to emit shorthand object properties - i.e.: `{a}` instead of `{a: a}`.
The `ecma` option will only change the output in direct control of the
beautifier. Non-compatible features in the abstract syntax tree will still
be output as is. For example: an `ecma` setting of `5` will **not** convert
ES6+ code to ES5.
- `ecma` (default `5`) -- set desired EcmaScript standard version for output.
Set `ecma` to `2015` or greater to emit shorthand object properties - i.e.:
`{a}` instead of `{a: a}`. The `ecma` option will only change the output in
direct control of the beautifier. Non-compatible features in your input will
still be output as is. For example: an `ecma` setting of `5` will **not**
convert modern code to ES5.
- `indent_level` (default `4`)
@@ -1034,6 +1020,8 @@ can pass additional arguments that control the code output:
- `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts)
- `spidermonkey` (default `false`) -- produce a Spidermonkey (Mozilla) AST
- `webkit` (default `false`) -- enable workarounds for WebKit bugs.
PhantomJS users should set this option to `true`.
@@ -1103,10 +1091,6 @@ if (DEBUG) {
You can specify nested constants in the form of `--define env.DEBUG=false`.
Terser will warn about the condition being always false and about dropping
unreachable code; for now there is no option to turn off only this specific
warning, you can pass `warnings=false` to turn off *all* warnings.
Another way of doing that is to declare your globals as constants in a
separate file and include it into the build. For example you can have a
`build/defines.js` file with the following:
@@ -1132,7 +1116,7 @@ You can also use conditional compilation via the programmatic API. With the diff
property name is `global_defs` and is a compressor property:
```javascript
var result = Terser.minify(fs.readFileSync("input.js", "utf8"), {
var result = await minify(fs.readFileSync("input.js", "utf8"), {
compress: {
dead_code: true,
global_defs: {
@@ -1146,7 +1130,7 @@ To replace an identifier with an arbitrary non-constant expression it is
necessary to prefix the `global_defs` key with `"@"` to instruct Terser
to parse the value as an expression:
```javascript
Terser.minify("alert('hello');", {
await minify("alert('hello');", {
compress: {
global_defs: {
"@alert": "console.log"
@@ -1158,7 +1142,7 @@ Terser.minify("alert('hello');", {
Otherwise it would be replaced as string literal:
```javascript
Terser.minify("alert('hello');", {
await minify("alert('hello');", {
compress: {
global_defs: {
"alert": "console.log"
@@ -1168,40 +1152,6 @@ Terser.minify("alert('hello');", {
// returns: '"console.log"("hello");'
```
### Using native Terser AST with `minify()`
```javascript
// example: parse only, produce native Terser AST
var result = Terser.minify(code, {
parse: {},
compress: false,
mangle: false,
output: {
ast: true,
code: false // optional - faster if false
}
});
// result.ast contains native Terser AST
```
```javascript
// example: accept native Terser AST input and then compress and mangle
// to produce both code and native AST.
var result = Terser.minify(ast, {
compress: {},
mangle: {},
output: {
ast: true,
code: true // optional - faster if false
}
});
// result.ast contains native Terser AST
// result.code contains the minified code in string form.
```
### Annotations
Annotations in Terser are a way to tell it to treat a certain function call differently. The following annotations are available:
@@ -1224,18 +1174,6 @@ function_cant_be_inlined_into_here()
const x = /*#__PURE__*/i_am_dropped_if_x_is_not_used()
```
### Working with Terser AST
Traversal and transformation of the native AST can be performed through
[`TreeWalker`](https://github.com/fabiosantoscode/terser/blob/master/lib/ast.js) and
[`TreeTransformer`](https://github.com/fabiosantoscode/terser/blob/master/lib/transform.js)
respectively.
Largely compatible native AST examples can be found in the original UglifyJS
documentation. See: [tree walker](http://lisperator.net/uglifyjs/walk) and
[tree transform](http://lisperator.net/uglifyjs/transform).
### ESTree / SpiderMonkey AST
Terser has its own abstract syntax tree format; for
@@ -1255,6 +1193,9 @@ JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we
don't use our own parser in this case, but just transform that AST into our
internal AST.
`spidermonkey` is also available in `minify` as `parse` and `format` options to
accept and/or produce a spidermonkey AST.
### Use Acorn for parsing
More for fun, I added the `-p acorn` option which will use Acorn to do all
@@ -1290,7 +1231,7 @@ terser file.js -m
```
To enable fast minify mode with the API use:
```js
Terser.minify(code, { compress: false, mangle: true });
await minify(code, { compress: false, mangle: true });
```
#### Source maps and debugging
@@ -1346,9 +1287,11 @@ $ rm -rf node_modules yarn.lock
$ yarn
```
<!-- API_REFERENCE:END -->
# Reporting issues
In the terser CLI we use [source-map-support](https://npmjs.com/source-map-support) to produce good error stacks. In your own app, you're expected to enable source-map-support (read their docs) to have nice stack traces that will make good issues.
In the terser CLI we use [source-map-support](https://npmjs.com/source-map-support) to produce good error stacks. In your own app, you're expected to enable source-map-support (read their docs) to have nice stack traces that will help you write good issues.
# README.md Patrons:

10
node_modules/terser/bin/package.json generated vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"name": "bin",
"private": true,
"version": "1.0.0",
"main": "terser",
"type": "commonjs",
"author": "",
"license": "BSD-2-Clause",
"description": "A package to hold the Terser bin bundle as commonjs while keeping the rest of it ESM."
}

478
node_modules/terser/bin/terser generated vendored
View File

@@ -1,477 +1,21 @@
#!/usr/bin/env node
// -*- js -*-
/* eslint-env node */
"use strict";
require("../tools/exit.js");
require("../tools/exit.cjs");
var fs = require("fs");
var info = require("../package.json");
var path = require("path");
var program = require("commander");
var Terser = require("..");
try {
require("source-map-support").install();
} catch (err) {}
const skip_keys = new Set([ "cname", "parent_scope", "scope", "uses_eval", "uses_with", "_var_name_cache" ]);
var files = {};
var options = {
compress: false,
mangle: false
};
program.version(info.name + " " + info.version);
program.parseArgv = program.parse;
program.parse = undefined;
if (process.argv.includes("ast")) program.helpInformation = describe_ast;
else if (process.argv.includes("options")) program.helpInformation = function() {
var text = [];
var options = Terser.default_options();
for (var option in options) {
text.push("--" + (option === "output" ? "beautify" : option === "sourceMap" ? "source-map" : option) + " options:");
text.push(format_object(options[option]));
text.push("");
}
return text.join("\n");
};
program.option("-p, --parse <options>", "Specify parser options.", parse_js());
program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js());
program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js());
program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js());
program.option("-b, --beautify [options]", "Beautify output/specify output options.", parse_js());
program.option("-o, --output <file>", "Output file (default STDOUT).");
program.option("--comments [filter]", "Preserve copyright comments in the output.");
program.option("--config-file <file>", "Read minify() options from JSON file.");
program.option("-d, --define <expr>[=value]", "Global definitions.", parse_js("define"));
program.option("--ecma <version>", "Specify ECMAScript release: 5, 2015, 2016 or 2017...");
program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values.");
program.option("--ie8", "Support non-standard Internet Explorer 8.");
program.option("--keep-classnames", "Do not mangle/drop class names.");
program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");
program.option("--module", "Input is an ES6 module");
program.option("--name-cache <file>", "File to hold mangled name mappings.");
program.option("--rename", "Force symbol expansion.");
program.option("--no-rename", "Disable symbol expansion.");
program.option("--safari10", "Support non-standard Safari 10.");
program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js());
program.option("--timings", "Display operations run time on STDERR.");
program.option("--toplevel", "Compress and/or mangle variables in toplevel scope.");
program.option("--verbose", "Print diagnostic messages.");
program.option("--warn", "Print warning messages.");
program.option("--wrap <name>", "Embed everything as a function with “exports” corresponding to “name” globally.");
program.arguments("[files...]").parseArgv(process.argv);
if (program.configFile) {
options = JSON.parse(read_file(program.configFile));
}
if (!program.output && program.sourceMap && program.sourceMap.url != "inline") {
fatal("ERROR: cannot write source map to STDOUT");
}
[
"compress",
"enclose",
"ie8",
"mangle",
"module",
"safari10",
"sourceMap",
"toplevel",
"wrap"
].forEach(function(name) {
if (name in program) {
options[name] = program[name];
}
const fs = require("fs");
const path = require("path");
const program = require("commander");
const packageJson = require("../package.json");
const { _run_cli: run_cli } = require("..");
run_cli({ program, packageJson, fs, path }).catch((error) => {
console.error(error);
process.exitCode = 1;
});
if ("ecma" in program) {
if (program.ecma != (program.ecma | 0)) fatal("ERROR: ecma must be an integer");
const ecma = program.ecma | 0;
if (ecma > 5 && ecma < 2015)
options.ecma = ecma + 2009;
else
options.ecma = ecma;
}
if (program.beautify) {
options.output = typeof program.beautify == "object" ? program.beautify : {};
if (!("beautify" in options.output)) {
options.output.beautify = true;
}
}
if (program.comments) {
if (typeof options.output != "object") options.output = {};
options.output.comments = typeof program.comments == "string" ? (program.comments == "false" ? false : program.comments) : "some";
}
if (program.define) {
if (typeof options.compress != "object") options.compress = {};
if (typeof options.compress.global_defs != "object") options.compress.global_defs = {};
for (var expr in program.define) {
options.compress.global_defs[expr] = program.define[expr];
}
}
if (program.keepClassnames) {
options.keep_classnames = true;
}
if (program.keepFnames) {
options.keep_fnames = true;
}
if (program.mangleProps) {
if (program.mangleProps.domprops) {
delete program.mangleProps.domprops;
} else {
if (typeof program.mangleProps != "object") program.mangleProps = {};
if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = [];
}
if (typeof options.mangle != "object") options.mangle = {};
options.mangle.properties = program.mangleProps;
}
if (program.nameCache) {
options.nameCache = JSON.parse(read_file(program.nameCache, "{}"));
}
if (program.output == "ast") {
options.output = {
ast: true,
code: false
};
}
if (program.parse) {
if (!program.parse.acorn && !program.parse.spidermonkey) {
options.parse = program.parse;
} else if (program.sourceMap && program.sourceMap.content == "inline") {
fatal("ERROR: inline source map only works with built-in parser");
}
}
if (~program.rawArgs.indexOf("--rename")) {
options.rename = true;
} else if (!program.rename) {
options.rename = false;
}
var convert_path = function(name) {
return name;
};
if (typeof program.sourceMap == "object" && "base" in program.sourceMap) {
convert_path = function() {
var base = program.sourceMap.base;
delete options.sourceMap.base;
return function(name) {
return path.relative(base, name);
};
}();
}
if (program.verbose) {
options.warnings = "verbose";
} else if (program.warn) {
options.warnings = true;
}
let filesList;
if (options.files && options.files.length) {
filesList = options.files;
delete options.files;
} else if (program.args.length) {
filesList = program.args;
}
if (filesList) {
simple_glob(filesList).forEach(function(name) {
files[convert_path(name)] = read_file(name);
});
run();
} else {
var chunks = [];
process.stdin.setEncoding("utf8");
process.stdin.on("data", function(chunk) {
chunks.push(chunk);
}).on("end", function() {
files = [ chunks.join("") ];
run();
});
process.stdin.resume();
}
function convert_ast(fn) {
return Terser.AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
}
function run() {
Terser.AST_Node.warn_function = function(msg) {
print_error("WARN: " + msg);
};
var content = program.sourceMap && program.sourceMap.content;
if (content && content !== "inline") {
options.sourceMap.content = read_file(content, content);
}
if (program.timings) options.timings = true;
try {
if (program.parse) {
if (program.parse.acorn) {
files = convert_ast(function(toplevel, name) {
return require("acorn").parse(files[name], {
ecmaVersion: 2018,
locations: true,
program: toplevel,
sourceFile: name,
sourceType: options.module || program.parse.module ? "module" : "script"
});
});
} else if (program.parse.spidermonkey) {
files = convert_ast(function(toplevel, name) {
var obj = JSON.parse(files[name]);
if (!toplevel) return obj;
toplevel.body = toplevel.body.concat(obj.body);
return toplevel;
});
}
}
} catch (ex) {
fatal(ex);
}
var result = Terser.minify(files, options);
if (result.error) {
var ex = result.error;
if (ex.name == "SyntaxError") {
print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
var col = ex.col;
var lines = files[ex.filename].split(/\r?\n/);
var line = lines[ex.line - 1];
if (!line && !col) {
line = lines[ex.line - 2];
col = line.length;
}
if (line) {
var limit = 70;
if (col > limit) {
line = line.slice(col - limit);
col = limit;
}
print_error(line.slice(0, 80));
print_error(line.slice(0, col).replace(/\S/g, " ") + "^");
}
}
if (ex.defs) {
print_error("Supported options:");
print_error(format_object(ex.defs));
}
fatal(ex);
} else if (program.output == "ast") {
if (!options.compress && !options.mangle) {
result.ast.figure_out_scope({});
}
print(JSON.stringify(result.ast, function(key, value) {
if (value) switch (key) {
case "thedef":
return symdef(value);
case "enclosed":
return value.length ? value.map(symdef) : undefined;
case "variables":
case "functions":
case "globals":
return value.size ? collect_from_map(value, symdef) : undefined;
}
if (skip_keys.has(key)) return;
if (value instanceof Terser.AST_Token) return;
if (value instanceof Map) return;
if (value instanceof Terser.AST_Node) {
var result = {
_class: "AST_" + value.TYPE
};
if (value.block_scope) {
result.variables = value.block_scope.variables;
result.functions = value.block_scope.functions;
result.enclosed = value.block_scope.enclosed;
}
value.CTOR.PROPS.forEach(function(prop) {
if (prop === "block_scope") return;
result[prop] = value[prop];
});
return result;
}
return value;
}, 2));
} else if (program.output == "spidermonkey") {
print(JSON.stringify(Terser.minify(result.code, {
compress: false,
mangle: false,
output: {
ast: true,
code: false
}
}).ast.to_mozilla_ast(), null, 2));
} else if (program.output) {
fs.writeFileSync(program.output, result.code);
if (options.sourceMap.url !== "inline" && result.map) {
fs.writeFileSync(program.output + ".map", result.map);
}
} else {
print(result.code);
}
if (program.nameCache) {
fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache));
}
if (result.timings) for (var phase in result.timings) {
print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s");
}
}
function fatal(message) {
if (message instanceof Error) message = message.stack.replace(/^\S*?Error:/, "ERROR:");
print_error(message);
process.exit(1);
}
// A file glob function that only supports "*" and "?" wildcards in the basename.
// Example: "foo/bar/*baz??.*.js"
// Argument `glob` may be a string or an array of strings.
// Returns an array of strings. Garbage in, garbage out.
function simple_glob(glob) {
if (Array.isArray(glob)) {
return [].concat.apply([], glob.map(simple_glob));
}
if (glob && glob.match(/[*?]/)) {
var dir = path.dirname(glob);
try {
var entries = fs.readdirSync(dir);
} catch (ex) {}
if (entries) {
var pattern = "^" + path.basename(glob)
.replace(/[.+^$[\]\\(){}]/g, "\\$&")
.replace(/\*/g, "[^/\\\\]*")
.replace(/\?/g, "[^/\\\\]") + "$";
var mod = process.platform === "win32" ? "i" : "";
var rx = new RegExp(pattern, mod);
var results = entries.filter(function(name) {
return rx.test(name);
}).map(function(name) {
return path.join(dir, name);
});
if (results.length) return results;
}
}
return [ glob ];
}
function read_file(path, default_value) {
try {
return fs.readFileSync(path, "utf8");
} catch (ex) {
if ((ex.code == "ENOENT" || ex.code == "ENAMETOOLONG") && default_value != null) return default_value;
fatal(ex);
}
}
function parse_js(flag) {
return function(value, options) {
options = options || {};
try {
Terser.parse(value, {
expression: true
}).walk(new Terser.TreeWalker(function(node) {
if (node instanceof Terser.AST_Assign) {
var name = node.left.print_to_string();
var value = node.right;
if (flag) {
options[name] = value;
} else if (value instanceof Terser.AST_Array) {
options[name] = value.elements.map(to_string);
} else if (value instanceof Terser.AST_RegExp) {
value = value.value;
options[name] = new RegExp(value.source, value.flags);
} else {
options[name] = to_string(value);
}
return true;
}
if (node instanceof Terser.AST_Symbol || node instanceof Terser.AST_PropAccess) {
var name = node.print_to_string();
options[name] = true;
return true;
}
if (!(node instanceof Terser.AST_Sequence)) throw node;
function to_string(value) {
return value instanceof Terser.AST_Constant ? value.getValue() : value.print_to_string({
quote_keys: true
});
}
}));
} catch(ex) {
if (flag) {
fatal("Error parsing arguments for '" + flag + "': " + value);
} else {
options[value] = null;
}
}
return options;
};
}
function symdef(def) {
var ret = (1e6 + def.id) + " " + def.name;
if (def.mangled_name) ret += " " + def.mangled_name;
return ret;
}
function collect_from_map(map, callback) {
var result = [];
map.forEach(function (def) {
result.push(callback(def));
});
return result;
}
function format_object(obj) {
var lines = [];
var padding = "";
Object.keys(obj).map(function(name) {
if (padding.length < name.length) padding = Array(name.length + 1).join(" ");
return [ name, JSON.stringify(obj[name]) ];
}).forEach(function(tokens) {
lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
});
return lines.join("\n");
}
function print_error(msg) {
process.stderr.write(msg);
process.stderr.write("\n");
}
function print(txt) {
process.stdout.write(txt);
process.stdout.write("\n");
}
function describe_ast() {
var out = Terser.OutputStream({ beautify: true });
function doitem(ctor) {
out.print("AST_" + ctor.TYPE);
var props = ctor.SELF_PROPS.filter(function(prop) {
return !/^\$/.test(prop);
});
if (props.length > 0) {
out.space();
out.with_parens(function() {
props.forEach(function(prop, i) {
if (i) out.space();
out.print(prop);
});
});
}
if (ctor.documentation) {
out.space();
out.print_string(ctor.documentation);
}
if (ctor.SUBCLASSES.length > 0) {
out.space();
out.with_block(function() {
ctor.SUBCLASSES.forEach(function(ctor, i) {
out.indent();
doitem(ctor);
out.newline();
});
});
}
}
doitem(Terser.AST_Node);
return out + "\n";
}

21
node_modules/terser/bin/terser.mjs generated vendored Normal file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env node
"use strict";
import "../tools/exit.cjs";
import fs from "fs"
import path from "path"
import program from "commander"
import { run_cli } from "../lib/cli.js"
const packageJson = {
name: "terser",
version: "experimental module CLI"
}
run_cli({ program, packageJson, fs, path }).catch((error) => {
console.error(error);
process.exitCode = 1;
});

27144
node_modules/terser/dist/bundle.min.js generated vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

10
node_modules/terser/dist/package.json generated vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"name": "dist",
"private": true,
"version": "1.0.0",
"main": "bundle.min.js",
"type": "commonjs",
"author": "",
"license": "BSD-2-Clause",
"description": "A package to hold the Terser dist bundle as commonjs while keeping the rest of it ESM. Nothing to see here."
}

1862
node_modules/terser/lib/ast.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

477
node_modules/terser/lib/cli.js generated vendored Normal file
View File

@@ -0,0 +1,477 @@
import { minify, _default_options } from "../main.js";
import { parse } from "./parse.js";
import {
AST_Assign,
AST_Array,
AST_Constant,
AST_Node,
AST_PropAccess,
AST_RegExp,
AST_Sequence,
AST_Symbol,
AST_Token,
walk
} from "./ast.js";
import { OutputStream } from "./output.js";
export async function run_cli({ program, packageJson, fs, path }) {
const skip_keys = new Set([ "cname", "parent_scope", "scope", "uses_eval", "uses_with" ]);
var files = {};
var options = {
compress: false,
mangle: false
};
const default_options = await _default_options();
program.version(packageJson.name + " " + packageJson.version);
program.parseArgv = program.parse;
program.parse = undefined;
if (process.argv.includes("ast")) program.helpInformation = describe_ast;
else if (process.argv.includes("options")) program.helpInformation = function() {
var text = [];
for (var option in default_options) {
text.push("--" + (option === "sourceMap" ? "source-map" : option) + " options:");
text.push(format_object(default_options[option]));
text.push("");
}
return text.join("\n");
};
program.option("-p, --parse <options>", "Specify parser options.", parse_js());
program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js());
program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js());
program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js());
program.option("-f, --format [options]", "Format options.", parse_js());
program.option("-b, --beautify [options]", "Alias for --format.", parse_js());
program.option("-o, --output <file>", "Output file (default STDOUT).");
program.option("--comments [filter]", "Preserve copyright comments in the output.");
program.option("--config-file <file>", "Read minify() options from JSON file.");
program.option("-d, --define <expr>[=value]", "Global definitions.", parse_js("define"));
program.option("--ecma <version>", "Specify ECMAScript release: 5, 2015, 2016 or 2017...");
program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values.");
program.option("--ie8", "Support non-standard Internet Explorer 8.");
program.option("--keep-classnames", "Do not mangle/drop class names.");
program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");
program.option("--module", "Input is an ES6 module");
program.option("--name-cache <file>", "File to hold mangled name mappings.");
program.option("--rename", "Force symbol expansion.");
program.option("--no-rename", "Disable symbol expansion.");
program.option("--safari10", "Support non-standard Safari 10.");
program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js());
program.option("--timings", "Display operations run time on STDERR.");
program.option("--toplevel", "Compress and/or mangle variables in toplevel scope.");
program.option("--wrap <name>", "Embed everything as a function with “exports” corresponding to “name” globally.");
program.arguments("[files...]").parseArgv(process.argv);
if (program.configFile) {
options = JSON.parse(read_file(program.configFile));
}
if (!program.output && program.sourceMap && program.sourceMap.url != "inline") {
fatal("ERROR: cannot write source map to STDOUT");
}
[
"compress",
"enclose",
"ie8",
"mangle",
"module",
"safari10",
"sourceMap",
"toplevel",
"wrap"
].forEach(function(name) {
if (name in program) {
options[name] = program[name];
}
});
if ("ecma" in program) {
if (program.ecma != (program.ecma | 0)) fatal("ERROR: ecma must be an integer");
const ecma = program.ecma | 0;
if (ecma > 5 && ecma < 2015)
options.ecma = ecma + 2009;
else
options.ecma = ecma;
}
if (program.format || program.beautify) {
const chosenOption = program.format || program.beautify;
options.format = typeof chosenOption === "object" ? chosenOption : {};
}
if (program.comments) {
if (typeof options.format != "object") options.format = {};
options.format.comments = typeof program.comments == "string" ? (program.comments == "false" ? false : program.comments) : "some";
}
if (program.define) {
if (typeof options.compress != "object") options.compress = {};
if (typeof options.compress.global_defs != "object") options.compress.global_defs = {};
for (var expr in program.define) {
options.compress.global_defs[expr] = program.define[expr];
}
}
if (program.keepClassnames) {
options.keep_classnames = true;
}
if (program.keepFnames) {
options.keep_fnames = true;
}
if (program.mangleProps) {
if (program.mangleProps.domprops) {
delete program.mangleProps.domprops;
} else {
if (typeof program.mangleProps != "object") program.mangleProps = {};
if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = [];
}
if (typeof options.mangle != "object") options.mangle = {};
options.mangle.properties = program.mangleProps;
}
if (program.nameCache) {
options.nameCache = JSON.parse(read_file(program.nameCache, "{}"));
}
if (program.output == "ast") {
options.format = {
ast: true,
code: false
};
}
if (program.parse) {
if (!program.parse.acorn && !program.parse.spidermonkey) {
options.parse = program.parse;
} else if (program.sourceMap && program.sourceMap.content == "inline") {
fatal("ERROR: inline source map only works with built-in parser");
}
}
if (~program.rawArgs.indexOf("--rename")) {
options.rename = true;
} else if (!program.rename) {
options.rename = false;
}
let convert_path = name => name;
if (typeof program.sourceMap == "object" && "base" in program.sourceMap) {
convert_path = function() {
var base = program.sourceMap.base;
delete options.sourceMap.base;
return function(name) {
return path.relative(base, name);
};
}();
}
let filesList;
if (options.files && options.files.length) {
filesList = options.files;
delete options.files;
} else if (program.args.length) {
filesList = program.args;
}
if (filesList) {
simple_glob(filesList).forEach(function(name) {
files[convert_path(name)] = read_file(name);
});
} else {
await new Promise((resolve) => {
var chunks = [];
process.stdin.setEncoding("utf8");
process.stdin.on("data", function(chunk) {
chunks.push(chunk);
}).on("end", function() {
files = [ chunks.join("") ];
resolve();
});
process.stdin.resume();
});
}
await run_cli();
function convert_ast(fn) {
return AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
}
async function run_cli() {
var content = program.sourceMap && program.sourceMap.content;
if (content && content !== "inline") {
options.sourceMap.content = read_file(content, content);
}
if (program.timings) options.timings = true;
try {
if (program.parse) {
if (program.parse.acorn) {
files = convert_ast(function(toplevel, name) {
return require("acorn").parse(files[name], {
ecmaVersion: 2018,
locations: true,
program: toplevel,
sourceFile: name,
sourceType: options.module || program.parse.module ? "module" : "script"
});
});
} else if (program.parse.spidermonkey) {
files = convert_ast(function(toplevel, name) {
var obj = JSON.parse(files[name]);
if (!toplevel) return obj;
toplevel.body = toplevel.body.concat(obj.body);
return toplevel;
});
}
}
} catch (ex) {
fatal(ex);
}
let result;
try {
result = await minify(files, options);
} catch (ex) {
if (ex.name == "SyntaxError") {
print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
var col = ex.col;
var lines = files[ex.filename].split(/\r?\n/);
var line = lines[ex.line - 1];
if (!line && !col) {
line = lines[ex.line - 2];
col = line.length;
}
if (line) {
var limit = 70;
if (col > limit) {
line = line.slice(col - limit);
col = limit;
}
print_error(line.slice(0, 80));
print_error(line.slice(0, col).replace(/\S/g, " ") + "^");
}
}
if (ex.defs) {
print_error("Supported options:");
print_error(format_object(ex.defs));
}
fatal(ex);
return;
}
if (program.output == "ast") {
if (!options.compress && !options.mangle) {
result.ast.figure_out_scope({});
}
console.log(JSON.stringify(result.ast, function(key, value) {
if (value) switch (key) {
case "thedef":
return symdef(value);
case "enclosed":
return value.length ? value.map(symdef) : undefined;
case "variables":
case "functions":
case "globals":
return value.size ? collect_from_map(value, symdef) : undefined;
}
if (skip_keys.has(key)) return;
if (value instanceof AST_Token) return;
if (value instanceof Map) return;
if (value instanceof AST_Node) {
var result = {
_class: "AST_" + value.TYPE
};
if (value.block_scope) {
result.variables = value.block_scope.variables;
result.functions = value.block_scope.functions;
result.enclosed = value.block_scope.enclosed;
}
value.CTOR.PROPS.forEach(function(prop) {
result[prop] = value[prop];
});
return result;
}
return value;
}, 2));
} else if (program.output == "spidermonkey") {
try {
const minified = await minify(result.code, {
compress: false,
mangle: false,
format: {
ast: true,
code: false
}
});
console.log(JSON.stringify(minified.ast.to_mozilla_ast(), null, 2));
} catch (ex) {
fatal(ex);
return;
}
} else if (program.output) {
fs.writeFileSync(program.output, result.code);
if (options.sourceMap && options.sourceMap.url !== "inline" && result.map) {
fs.writeFileSync(program.output + ".map", result.map);
}
} else {
console.log(result.code);
}
if (program.nameCache) {
fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache));
}
if (result.timings) for (var phase in result.timings) {
print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s");
}
}
function fatal(message) {
if (message instanceof Error) message = message.stack.replace(/^\S*?Error:/, "ERROR:");
print_error(message);
process.exit(1);
}
// A file glob function that only supports "*" and "?" wildcards in the basename.
// Example: "foo/bar/*baz??.*.js"
// Argument `glob` may be a string or an array of strings.
// Returns an array of strings. Garbage in, garbage out.
function simple_glob(glob) {
if (Array.isArray(glob)) {
return [].concat.apply([], glob.map(simple_glob));
}
if (glob && glob.match(/[*?]/)) {
var dir = path.dirname(glob);
try {
var entries = fs.readdirSync(dir);
} catch (ex) {}
if (entries) {
var pattern = "^" + path.basename(glob)
.replace(/[.+^$[\]\\(){}]/g, "\\$&")
.replace(/\*/g, "[^/\\\\]*")
.replace(/\?/g, "[^/\\\\]") + "$";
var mod = process.platform === "win32" ? "i" : "";
var rx = new RegExp(pattern, mod);
var results = entries.filter(function(name) {
return rx.test(name);
}).map(function(name) {
return path.join(dir, name);
});
if (results.length) return results;
}
}
return [ glob ];
}
function read_file(path, default_value) {
try {
return fs.readFileSync(path, "utf8");
} catch (ex) {
if ((ex.code == "ENOENT" || ex.code == "ENAMETOOLONG") && default_value != null) return default_value;
fatal(ex);
}
}
function parse_js(flag) {
return function(value, options) {
options = options || {};
try {
walk(parse(value, { expression: true }), node => {
if (node instanceof AST_Assign) {
var name = node.left.print_to_string();
var value = node.right;
if (flag) {
options[name] = value;
} else if (value instanceof AST_Array) {
options[name] = value.elements.map(to_string);
} else if (value instanceof AST_RegExp) {
value = value.value;
options[name] = new RegExp(value.source, value.flags);
} else {
options[name] = to_string(value);
}
return true;
}
if (node instanceof AST_Symbol || node instanceof AST_PropAccess) {
var name = node.print_to_string();
options[name] = true;
return true;
}
if (!(node instanceof AST_Sequence)) throw node;
function to_string(value) {
return value instanceof AST_Constant ? value.getValue() : value.print_to_string({
quote_keys: true
});
}
});
} catch(ex) {
if (flag) {
fatal("Error parsing arguments for '" + flag + "': " + value);
} else {
options[value] = null;
}
}
return options;
};
}
function symdef(def) {
var ret = (1e6 + def.id) + " " + def.name;
if (def.mangled_name) ret += " " + def.mangled_name;
return ret;
}
function collect_from_map(map, callback) {
var result = [];
map.forEach(function (def) {
result.push(callback(def));
});
return result;
}
function format_object(obj) {
var lines = [];
var padding = "";
Object.keys(obj).map(function(name) {
if (padding.length < name.length) padding = Array(name.length + 1).join(" ");
return [ name, JSON.stringify(obj[name]) ];
}).forEach(function(tokens) {
lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
});
return lines.join("\n");
}
function print_error(msg) {
process.stderr.write(msg);
process.stderr.write("\n");
}
function describe_ast() {
var out = OutputStream({ beautify: true });
function doitem(ctor) {
out.print("AST_" + ctor.TYPE);
const props = ctor.SELF_PROPS.filter(prop => !/^\$/.test(prop));
if (props.length > 0) {
out.space();
out.with_parens(function() {
props.forEach(function(prop, i) {
if (i) out.space();
out.print(prop);
});
});
}
if (ctor.documentation) {
out.space();
out.print_string(ctor.documentation);
}
if (ctor.SUBCLASSES.length > 0) {
out.space();
out.with_block(function() {
ctor.SUBCLASSES.forEach(function(ctor) {
out.indent();
doitem(ctor);
out.newline();
});
});
}
}
doitem(AST_Node);
return out + "\n";
}
}

7760
node_modules/terser/lib/compress/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

308
node_modules/terser/lib/equivalent-to.js generated vendored Normal file
View File

@@ -0,0 +1,308 @@
import {
AST_Array,
AST_Atom,
AST_Await,
AST_BigInt,
AST_Binary,
AST_Block,
AST_Call,
AST_Catch,
AST_Chain,
AST_Class,
AST_ClassProperty,
AST_ConciseMethod,
AST_Conditional,
AST_Debugger,
AST_Definitions,
AST_Destructuring,
AST_Directive,
AST_Do,
AST_Dot,
AST_EmptyStatement,
AST_Expansion,
AST_Export,
AST_Finally,
AST_For,
AST_ForIn,
AST_ForOf,
AST_If,
AST_Import,
AST_ImportMeta,
AST_Jump,
AST_LabeledStatement,
AST_Lambda,
AST_LoopControl,
AST_NameMapping,
AST_NewTarget,
AST_Node,
AST_Number,
AST_Object,
AST_ObjectGetter,
AST_ObjectKeyVal,
AST_ObjectProperty,
AST_ObjectSetter,
AST_PrefixedTemplateString,
AST_PropAccess,
AST_RegExp,
AST_Sequence,
AST_SimpleStatement,
AST_String,
AST_Super,
AST_Switch,
AST_SwitchBranch,
AST_Symbol,
AST_TemplateSegment,
AST_TemplateString,
AST_This,
AST_Toplevel,
AST_Try,
AST_Unary,
AST_VarDef,
AST_While,
AST_With,
AST_Yield
} from "./ast.js";
const shallow_cmp = (node1, node2) => {
return (
node1 === null && node2 === null
|| node1.TYPE === node2.TYPE && node1.shallow_cmp(node2)
);
};
export const equivalent_to = (tree1, tree2) => {
if (!shallow_cmp(tree1, tree2)) return false;
const walk_1_state = [tree1];
const walk_2_state = [tree2];
const walk_1_push = walk_1_state.push.bind(walk_1_state);
const walk_2_push = walk_2_state.push.bind(walk_2_state);
while (walk_1_state.length && walk_2_state.length) {
const node_1 = walk_1_state.pop();
const node_2 = walk_2_state.pop();
if (!shallow_cmp(node_1, node_2)) return false;
node_1._children_backwards(walk_1_push);
node_2._children_backwards(walk_2_push);
if (walk_1_state.length !== walk_2_state.length) {
// Different number of children
return false;
}
}
return walk_1_state.length == 0 && walk_2_state.length == 0;
};
// Creates a shallow compare function
const mkshallow = (props) => {
const comparisons = Object
.keys(props)
.map(key => {
if (props[key] === "eq") {
return `this.${key} === other.${key}`;
} else if (props[key] === "exist") {
return `(this.${key} == null ? other.${key} == null : this.${key} === other.${key})`;
} else {
throw new Error(`mkshallow: Unexpected instruction: ${props[key]}`);
}
})
.join(" && ");
return new Function("other", "return " + comparisons);
};
const pass_through = () => true;
AST_Node.prototype.shallow_cmp = function () {
throw new Error("did not find a shallow_cmp function for " + this.constructor.name);
};
AST_Debugger.prototype.shallow_cmp = pass_through;
AST_Directive.prototype.shallow_cmp = mkshallow({ value: "eq" });
AST_SimpleStatement.prototype.shallow_cmp = pass_through;
AST_Block.prototype.shallow_cmp = pass_through;
AST_EmptyStatement.prototype.shallow_cmp = pass_through;
AST_LabeledStatement.prototype.shallow_cmp = mkshallow({ "label.name": "eq" });
AST_Do.prototype.shallow_cmp = pass_through;
AST_While.prototype.shallow_cmp = pass_through;
AST_For.prototype.shallow_cmp = mkshallow({
init: "exist",
condition: "exist",
step: "exist"
});
AST_ForIn.prototype.shallow_cmp = pass_through;
AST_ForOf.prototype.shallow_cmp = pass_through;
AST_With.prototype.shallow_cmp = pass_through;
AST_Toplevel.prototype.shallow_cmp = pass_through;
AST_Expansion.prototype.shallow_cmp = pass_through;
AST_Lambda.prototype.shallow_cmp = mkshallow({
is_generator: "eq",
async: "eq"
});
AST_Destructuring.prototype.shallow_cmp = mkshallow({
is_array: "eq"
});
AST_PrefixedTemplateString.prototype.shallow_cmp = pass_through;
AST_TemplateString.prototype.shallow_cmp = pass_through;
AST_TemplateSegment.prototype.shallow_cmp = mkshallow({
"value": "eq"
});
AST_Jump.prototype.shallow_cmp = pass_through;
AST_LoopControl.prototype.shallow_cmp = pass_through;
AST_Await.prototype.shallow_cmp = pass_through;
AST_Yield.prototype.shallow_cmp = mkshallow({
is_star: "eq"
});
AST_If.prototype.shallow_cmp = mkshallow({
alternative: "exist"
});
AST_Switch.prototype.shallow_cmp = pass_through;
AST_SwitchBranch.prototype.shallow_cmp = pass_through;
AST_Try.prototype.shallow_cmp = mkshallow({
bcatch: "exist",
bfinally: "exist"
});
AST_Catch.prototype.shallow_cmp = mkshallow({
argname: "exist"
});
AST_Finally.prototype.shallow_cmp = pass_through;
AST_Definitions.prototype.shallow_cmp = pass_through;
AST_VarDef.prototype.shallow_cmp = mkshallow({
value: "exist"
});
AST_NameMapping.prototype.shallow_cmp = pass_through;
AST_Import.prototype.shallow_cmp = mkshallow({
imported_name: "exist",
imported_names: "exist"
});
AST_ImportMeta.prototype.shallow_cmp = pass_through;
AST_Export.prototype.shallow_cmp = mkshallow({
exported_definition: "exist",
exported_value: "exist",
exported_names: "exist",
module_name: "eq",
is_default: "eq",
});
AST_Call.prototype.shallow_cmp = pass_through;
AST_Sequence.prototype.shallow_cmp = pass_through;
AST_PropAccess.prototype.shallow_cmp = pass_through;
AST_Chain.prototype.shallow_cmp = pass_through;
AST_Dot.prototype.shallow_cmp = mkshallow({
property: "eq"
});
AST_Unary.prototype.shallow_cmp = mkshallow({
operator: "eq"
});
AST_Binary.prototype.shallow_cmp = mkshallow({
operator: "eq"
});
AST_Conditional.prototype.shallow_cmp = pass_through;
AST_Array.prototype.shallow_cmp = pass_through;
AST_Object.prototype.shallow_cmp = pass_through;
AST_ObjectProperty.prototype.shallow_cmp = pass_through;
AST_ObjectKeyVal.prototype.shallow_cmp = mkshallow({
key: "eq"
});
AST_ObjectSetter.prototype.shallow_cmp = mkshallow({
static: "eq"
});
AST_ObjectGetter.prototype.shallow_cmp = mkshallow({
static: "eq"
});
AST_ConciseMethod.prototype.shallow_cmp = mkshallow({
static: "eq",
is_generator: "eq",
async: "eq",
});
AST_Class.prototype.shallow_cmp = mkshallow({
name: "exist",
extends: "exist",
});
AST_ClassProperty.prototype.shallow_cmp = mkshallow({
static: "eq"
});
AST_Symbol.prototype.shallow_cmp = mkshallow({
name: "eq"
});
AST_NewTarget.prototype.shallow_cmp = pass_through;
AST_This.prototype.shallow_cmp = pass_through;
AST_Super.prototype.shallow_cmp = pass_through;
AST_String.prototype.shallow_cmp = mkshallow({
value: "eq"
});
AST_Number.prototype.shallow_cmp = mkshallow({
value: "eq"
});
AST_BigInt.prototype.shallow_cmp = mkshallow({
value: "eq"
});
AST_RegExp.prototype.shallow_cmp = function (other) {
return (
this.value.flags === other.value.flags
&& this.value.source === other.value.source
);
};
AST_Atom.prototype.shallow_cmp = pass_through;

285
node_modules/terser/lib/minify.js generated vendored Normal file
View File

@@ -0,0 +1,285 @@
"use strict";
/* eslint-env browser, es6, node */
import {
defaults,
map_from_object,
map_to_object,
HOP,
} from "./utils/index.js";
import { AST_Toplevel, AST_Node } from "./ast.js";
import { parse } from "./parse.js";
import { OutputStream } from "./output.js";
import { Compressor } from "./compress/index.js";
import { base54 } from "./scope.js";
import { SourceMap } from "./sourcemap.js";
import {
mangle_properties,
reserve_quoted_keys,
} from "./propmangle.js";
var to_ascii = typeof atob == "undefined" ? function(b64) {
return Buffer.from(b64, "base64").toString();
} : atob;
var to_base64 = typeof btoa == "undefined" ? function(str) {
return Buffer.from(str).toString("base64");
} : btoa;
function read_source_map(code) {
var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code);
if (!match) {
console.warn("inline source map not found");
return null;
}
return to_ascii(match[2]);
}
function set_shorthand(name, options, keys) {
if (options[name]) {
keys.forEach(function(key) {
if (options[key]) {
if (typeof options[key] != "object") options[key] = {};
if (!(name in options[key])) options[key][name] = options[name];
}
});
}
}
function init_cache(cache) {
if (!cache) return;
if (!("props" in cache)) {
cache.props = new Map();
} else if (!(cache.props instanceof Map)) {
cache.props = map_from_object(cache.props);
}
}
function cache_to_json(cache) {
return {
props: map_to_object(cache.props)
};
}
async function minify(files, options) {
options = defaults(options, {
compress: {},
ecma: undefined,
enclose: false,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
mangle: {},
module: false,
nameCache: null,
output: null,
format: null,
parse: {},
rename: undefined,
safari10: false,
sourceMap: false,
spidermonkey: false,
timings: false,
toplevel: false,
warnings: false,
wrap: false,
}, true);
var timings = options.timings && {
start: Date.now()
};
if (options.keep_classnames === undefined) {
options.keep_classnames = options.keep_fnames;
}
if (options.rename === undefined) {
options.rename = options.compress && options.mangle;
}
if (options.output && options.format) {
throw new Error("Please only specify either output or format option, preferrably format.");
}
options.format = options.format || options.output || {};
set_shorthand("ecma", options, [ "parse", "compress", "format" ]);
set_shorthand("ie8", options, [ "compress", "mangle", "format" ]);
set_shorthand("keep_classnames", options, [ "compress", "mangle" ]);
set_shorthand("keep_fnames", options, [ "compress", "mangle" ]);
set_shorthand("module", options, [ "parse", "compress", "mangle" ]);
set_shorthand("safari10", options, [ "mangle", "format" ]);
set_shorthand("toplevel", options, [ "compress", "mangle" ]);
set_shorthand("warnings", options, [ "compress" ]); // legacy
var quoted_props;
if (options.mangle) {
options.mangle = defaults(options.mangle, {
cache: options.nameCache && (options.nameCache.vars || {}),
eval: false,
ie8: false,
keep_classnames: false,
keep_fnames: false,
module: false,
properties: false,
reserved: [],
safari10: false,
toplevel: false,
}, true);
if (options.mangle.properties) {
if (typeof options.mangle.properties != "object") {
options.mangle.properties = {};
}
if (options.mangle.properties.keep_quoted) {
quoted_props = options.mangle.properties.reserved;
if (!Array.isArray(quoted_props)) quoted_props = [];
options.mangle.properties.reserved = quoted_props;
}
if (options.nameCache && !("cache" in options.mangle.properties)) {
options.mangle.properties.cache = options.nameCache.props || {};
}
}
init_cache(options.mangle.cache);
init_cache(options.mangle.properties.cache);
}
if (options.sourceMap) {
options.sourceMap = defaults(options.sourceMap, {
asObject: false,
content: null,
filename: null,
includeSources: false,
root: null,
url: null,
}, true);
}
if (timings) timings.parse = Date.now();
var toplevel;
if (files instanceof AST_Toplevel) {
toplevel = files;
} else {
if (typeof files == "string" || (options.parse.spidermonkey && !Array.isArray(files))) {
files = [ files ];
}
options.parse = options.parse || {};
options.parse.toplevel = null;
if (options.parse.spidermonkey) {
options.parse.toplevel = AST_Node.from_mozilla_ast(Object.keys(files).reduce(function(toplevel, name) {
if (!toplevel) return files[name];
toplevel.body = toplevel.body.concat(files[name].body);
return toplevel;
}, null));
} else {
delete options.parse.spidermonkey;
for (var name in files) if (HOP(files, name)) {
options.parse.filename = name;
options.parse.toplevel = parse(files[name], options.parse);
if (options.sourceMap && options.sourceMap.content == "inline") {
if (Object.keys(files).length > 1)
throw new Error("inline source map only works with singular input");
options.sourceMap.content = read_source_map(files[name]);
}
}
}
toplevel = options.parse.toplevel;
}
if (quoted_props && options.mangle.properties.keep_quoted !== "strict") {
reserve_quoted_keys(toplevel, quoted_props);
}
if (options.wrap) {
toplevel = toplevel.wrap_commonjs(options.wrap);
}
if (options.enclose) {
toplevel = toplevel.wrap_enclose(options.enclose);
}
if (timings) timings.rename = Date.now();
// disable rename on harmony due to expand_names bug in for-of loops
// https://github.com/mishoo/UglifyJS2/issues/2794
if (0 && options.rename) {
toplevel.figure_out_scope(options.mangle);
toplevel.expand_names(options.mangle);
}
if (timings) timings.compress = Date.now();
if (options.compress) {
toplevel = new Compressor(options.compress, {
mangle_options: options.mangle
}).compress(toplevel);
}
if (timings) timings.scope = Date.now();
if (options.mangle) toplevel.figure_out_scope(options.mangle);
if (timings) timings.mangle = Date.now();
if (options.mangle) {
base54.reset();
toplevel.compute_char_frequency(options.mangle);
toplevel.mangle_names(options.mangle);
}
if (timings) timings.properties = Date.now();
if (options.mangle && options.mangle.properties) {
toplevel = mangle_properties(toplevel, options.mangle.properties);
}
if (timings) timings.format = Date.now();
var result = {};
if (options.format.ast) {
result.ast = toplevel;
}
if (options.format.spidermonkey) {
result.ast = toplevel.to_mozilla_ast();
}
if (!HOP(options.format, "code") || options.format.code) {
if (options.sourceMap) {
options.format.source_map = await SourceMap({
file: options.sourceMap.filename,
orig: options.sourceMap.content,
root: options.sourceMap.root
});
if (options.sourceMap.includeSources) {
if (files instanceof AST_Toplevel) {
throw new Error("original source content unavailable");
} else for (var name in files) if (HOP(files, name)) {
options.format.source_map.get().setSourceContent(name, files[name]);
}
}
}
delete options.format.ast;
delete options.format.code;
delete options.format.spidermonkey;
var stream = OutputStream(options.format);
toplevel.print(stream);
result.code = stream.get();
if (options.sourceMap) {
if(options.sourceMap.asObject) {
result.map = options.format.source_map.get().toJSON();
} else {
result.map = options.format.source_map.toString();
}
if (options.sourceMap.url == "inline") {
var sourceMap = typeof result.map === "object" ? JSON.stringify(result.map) : result.map;
result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap);
} else if (options.sourceMap.url) {
result.code += "\n//# sourceMappingURL=" + options.sourceMap.url;
}
}
}
if (options.nameCache && options.mangle) {
if (options.mangle.cache) options.nameCache.vars = cache_to_json(options.mangle.cache);
if (options.mangle.properties && options.mangle.properties.cache) {
options.nameCache.props = cache_to_json(options.mangle.properties.cache);
}
}
if (options.format && options.format.source_map) {
options.format.source_map.destroy();
}
if (timings) {
timings.end = Date.now();
result.timings = {
parse: 1e-3 * (timings.rename - timings.parse),
rename: 1e-3 * (timings.compress - timings.rename),
compress: 1e-3 * (timings.scope - timings.compress),
scope: 1e-3 * (timings.mangle - timings.scope),
mangle: 1e-3 * (timings.properties - timings.mangle),
properties: 1e-3 * (timings.format - timings.properties),
format: 1e-3 * (timings.end - timings.format),
total: 1e-3 * (timings.end - timings.start)
};
}
return result;
}
export {
minify,
to_ascii,
};

1334
node_modules/terser/lib/mozilla-ast.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

2283
node_modules/terser/lib/output.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

3344
node_modules/terser/lib/parse.js generated vendored Normal file

File diff suppressed because one or more lines are too long

353
node_modules/terser/lib/propmangle.js generated vendored Normal file
View File

@@ -0,0 +1,353 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/
"use strict";
/* global global, self */
import {
defaults,
push_uniq,
} from "./utils/index.js";
import { base54 } from "./scope.js";
import {
AST_Binary,
AST_Call,
AST_ClassPrivateProperty,
AST_Conditional,
AST_Dot,
AST_DotHash,
AST_ObjectKeyVal,
AST_ObjectProperty,
AST_PrivateMethod,
AST_Sequence,
AST_String,
AST_Sub,
TreeTransformer,
TreeWalker,
} from "./ast.js";
import { domprops } from "../tools/domprops.js";
function find_builtins(reserved) {
domprops.forEach(add);
// Compatibility fix for some standard defined globals not defined on every js environment
var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"];
var objects = {};
var global_ref = typeof global === "object" ? global : self;
new_globals.forEach(function (new_global) {
objects[new_global] = global_ref[new_global] || new Function();
});
[
"null",
"true",
"false",
"NaN",
"Infinity",
"-Infinity",
"undefined",
].forEach(add);
[ Object, Array, Function, Number,
String, Boolean, Error, Math,
Date, RegExp, objects.Symbol, ArrayBuffer,
DataView, decodeURI, decodeURIComponent,
encodeURI, encodeURIComponent, eval, EvalError,
Float32Array, Float64Array, Int8Array, Int16Array,
Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat,
parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError,
objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array,
Uint8ClampedArray, Uint16Array, Uint32Array, URIError,
objects.WeakMap, objects.WeakSet
].forEach(function(ctor) {
Object.getOwnPropertyNames(ctor).map(add);
if (ctor.prototype) {
Object.getOwnPropertyNames(ctor.prototype).map(add);
}
});
function add(name) {
reserved.add(name);
}
}
function reserve_quoted_keys(ast, reserved) {
function add(name) {
push_uniq(reserved, name);
}
ast.walk(new TreeWalker(function(node) {
if (node instanceof AST_ObjectKeyVal && node.quote) {
add(node.key);
} else if (node instanceof AST_ObjectProperty && node.quote) {
add(node.key.name);
} else if (node instanceof AST_Sub) {
addStrings(node.property, add);
}
}));
}
function addStrings(node, add) {
node.walk(new TreeWalker(function(node) {
if (node instanceof AST_Sequence) {
addStrings(node.tail_node(), add);
} else if (node instanceof AST_String) {
add(node.value);
} else if (node instanceof AST_Conditional) {
addStrings(node.consequent, add);
addStrings(node.alternative, add);
}
return true;
}));
}
function mangle_properties(ast, options) {
options = defaults(options, {
builtins: false,
cache: null,
debug: false,
keep_quoted: false,
only_cache: false,
regex: null,
reserved: null,
undeclared: false,
}, true);
var reserved_option = options.reserved;
if (!Array.isArray(reserved_option)) reserved_option = [reserved_option];
var reserved = new Set(reserved_option);
if (!options.builtins) find_builtins(reserved);
var cname = -1;
var cprivate = -1;
var cache;
var private_cache = new Map();
if (options.cache) {
cache = options.cache.props;
cache.forEach(function(mangled_name) {
reserved.add(mangled_name);
});
} else {
cache = new Map();
}
var regex = options.regex && new RegExp(options.regex);
// note debug is either false (disabled), or a string of the debug suffix to use (enabled).
// note debug may be enabled as an empty string, which is falsey. Also treat passing 'true'
// the same as passing an empty string.
var debug = options.debug !== false;
var debug_name_suffix;
if (debug) {
debug_name_suffix = (options.debug === true ? "" : options.debug);
}
var names_to_mangle = new Set();
var unmangleable = new Set();
var private_properties = new Set();
var keep_quoted_strict = options.keep_quoted === "strict";
// step 1: find candidates to mangle
ast.walk(new TreeWalker(function(node) {
if (
node instanceof AST_ClassPrivateProperty
|| node instanceof AST_PrivateMethod
) {
private_properties.add(node.key.name);
} else if (node instanceof AST_DotHash) {
private_properties.add(node.property);
} else if (node instanceof AST_ObjectKeyVal) {
if (typeof node.key == "string" &&
(!keep_quoted_strict || !node.quote)) {
add(node.key);
}
} else if (node instanceof AST_ObjectProperty) {
// setter or getter, since KeyVal is handled above
if (!keep_quoted_strict || !node.key.end.quote) {
add(node.key.name);
}
} else if (node instanceof AST_Dot) {
var declared = !!options.undeclared;
if (!declared) {
var root = node;
while (root.expression) {
root = root.expression;
}
declared = !(root.thedef && root.thedef.undeclared);
}
if (declared &&
(!keep_quoted_strict || !node.quote)) {
add(node.property);
}
} else if (node instanceof AST_Sub) {
if (!keep_quoted_strict) {
addStrings(node.property, add);
}
} else if (node instanceof AST_Call
&& node.expression.print_to_string() == "Object.defineProperty") {
addStrings(node.args[1], add);
} else if (node instanceof AST_Binary && node.operator === "in") {
addStrings(node.left, add);
}
}));
// step 2: transform the tree, renaming properties
return ast.transform(new TreeTransformer(function(node) {
if (
node instanceof AST_ClassPrivateProperty
|| node instanceof AST_PrivateMethod
) {
node.key.name = mangle_private(node.key.name);
} else if (node instanceof AST_DotHash) {
node.property = mangle_private(node.property);
} else if (node instanceof AST_ObjectKeyVal) {
if (typeof node.key == "string" &&
(!keep_quoted_strict || !node.quote)) {
node.key = mangle(node.key);
}
} else if (node instanceof AST_ObjectProperty) {
// setter, getter, method or class field
if (!keep_quoted_strict || !node.key.end.quote) {
node.key.name = mangle(node.key.name);
}
} else if (node instanceof AST_Dot) {
if (!keep_quoted_strict || !node.quote) {
node.property = mangle(node.property);
}
} else if (!options.keep_quoted && node instanceof AST_Sub) {
node.property = mangleStrings(node.property);
} else if (node instanceof AST_Call
&& node.expression.print_to_string() == "Object.defineProperty") {
node.args[1] = mangleStrings(node.args[1]);
} else if (node instanceof AST_Binary && node.operator === "in") {
node.left = mangleStrings(node.left);
}
}));
// only function declarations after this line
function can_mangle(name) {
if (unmangleable.has(name)) return false;
if (reserved.has(name)) return false;
if (options.only_cache) {
return cache.has(name);
}
if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false;
return true;
}
function should_mangle(name) {
if (regex && !regex.test(name)) return false;
if (reserved.has(name)) return false;
return cache.has(name)
|| names_to_mangle.has(name);
}
function add(name) {
if (can_mangle(name))
names_to_mangle.add(name);
if (!should_mangle(name)) {
unmangleable.add(name);
}
}
function mangle(name) {
if (!should_mangle(name)) {
return name;
}
var mangled = cache.get(name);
if (!mangled) {
if (debug) {
// debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_.
var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_";
if (can_mangle(debug_mangled)) {
mangled = debug_mangled;
}
}
// either debug mode is off, or it is on and we could not use the mangled name
if (!mangled) {
do {
mangled = base54(++cname);
} while (!can_mangle(mangled));
}
cache.set(name, mangled);
}
return mangled;
}
function mangle_private(name) {
let mangled = private_cache.get(name);
if (!mangled) {
mangled = base54(++cprivate);
private_cache.set(name, mangled);
}
return mangled;
}
function mangleStrings(node) {
return node.transform(new TreeTransformer(function(node) {
if (node instanceof AST_Sequence) {
var last = node.expressions.length - 1;
node.expressions[last] = mangleStrings(node.expressions[last]);
} else if (node instanceof AST_String) {
node.value = mangle(node.value);
} else if (node instanceof AST_Conditional) {
node.consequent = mangleStrings(node.consequent);
node.alternative = mangleStrings(node.alternative);
}
return node;
}));
}
}
export {
reserve_quoted_keys,
mangle_properties,
};

994
node_modules/terser/lib/scope.js generated vendored Normal file
View File

@@ -0,0 +1,994 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/
"use strict";
import {
defaults,
keep_name,
mergeSort,
push_uniq,
make_node,
return_false,
return_this,
return_true,
string_template,
} from "./utils/index.js";
import {
AST_Arrow,
AST_Block,
AST_Call,
AST_Catch,
AST_Class,
AST_Conditional,
AST_DefClass,
AST_Defun,
AST_Destructuring,
AST_Dot,
AST_DotHash,
AST_Export,
AST_For,
AST_ForIn,
AST_Function,
AST_Import,
AST_IterationStatement,
AST_Label,
AST_LabeledStatement,
AST_LabelRef,
AST_Lambda,
AST_LoopControl,
AST_NameMapping,
AST_Node,
AST_Scope,
AST_Sequence,
AST_String,
AST_Sub,
AST_Switch,
AST_SwitchBranch,
AST_Symbol,
AST_SymbolBlockDeclaration,
AST_SymbolCatch,
AST_SymbolClass,
AST_SymbolConst,
AST_SymbolDefClass,
AST_SymbolDefun,
AST_SymbolExport,
AST_SymbolFunarg,
AST_SymbolImport,
AST_SymbolLambda,
AST_SymbolLet,
AST_SymbolMethod,
AST_SymbolRef,
AST_SymbolVar,
AST_Toplevel,
AST_VarDef,
AST_With,
TreeWalker,
walk
} from "./ast.js";
import {
RESERVED_WORDS,
js_error,
} from "./parse.js";
const MASK_EXPORT_DONT_MANGLE = 1 << 0;
const MASK_EXPORT_WANT_MANGLE = 1 << 1;
let function_defs = null;
let unmangleable_names = null;
class SymbolDef {
constructor(scope, orig, init) {
this.name = orig.name;
this.orig = [ orig ];
this.init = init;
this.eliminated = 0;
this.assignments = 0;
this.scope = scope;
this.replaced = 0;
this.global = false;
this.export = 0;
this.mangled_name = null;
this.undeclared = false;
this.id = SymbolDef.next_id++;
this.chained = false;
this.direct_access = false;
this.escaped = 0;
this.recursive_refs = 0;
this.references = [];
this.should_replace = undefined;
this.single_use = false;
this.fixed = false;
Object.seal(this);
}
fixed_value() {
if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed;
return this.fixed();
}
unmangleable(options) {
if (!options) options = {};
if (
function_defs &&
function_defs.has(this.id) &&
keep_name(options.keep_fnames, this.orig[0].name)
) return true;
return this.global && !options.toplevel
|| (this.export & MASK_EXPORT_DONT_MANGLE)
|| this.undeclared
|| !options.eval && this.scope.pinned()
|| (this.orig[0] instanceof AST_SymbolLambda
|| this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name)
|| this.orig[0] instanceof AST_SymbolMethod
|| (this.orig[0] instanceof AST_SymbolClass
|| this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name);
}
mangle(options) {
const cache = options.cache && options.cache.props;
if (this.global && cache && cache.has(this.name)) {
this.mangled_name = cache.get(this.name);
} else if (!this.mangled_name && !this.unmangleable(options)) {
var s = this.scope;
var sym = this.orig[0];
if (options.ie8 && sym instanceof AST_SymbolLambda)
s = s.parent_scope;
const redefinition = redefined_catch_def(this);
this.mangled_name = redefinition
? redefinition.mangled_name || redefinition.name
: s.next_mangled(options, this);
if (this.global && cache) {
cache.set(this.name, this.mangled_name);
}
}
}
}
SymbolDef.next_id = 1;
function redefined_catch_def(def) {
if (def.orig[0] instanceof AST_SymbolCatch
&& def.scope.is_block_scope()
) {
return def.scope.get_defun_scope().variables.get(def.name);
}
}
AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) {
options = defaults(options, {
cache: null,
ie8: false,
safari10: false,
});
if (!(toplevel instanceof AST_Toplevel)) {
throw new Error("Invalid toplevel scope");
}
// pass 1: setup scope chaining and handle definitions
var scope = this.parent_scope = parent_scope;
var labels = new Map();
var defun = null;
var in_destructuring = null;
var for_scopes = [];
var tw = new TreeWalker((node, descend) => {
if (node.is_block_scope()) {
const save_scope = scope;
node.block_scope = scope = new AST_Scope(node);
scope._block_scope = true;
// AST_Try in the AST sadly *is* (not has) a body itself,
// and its catch and finally branches are children of the AST_Try itself
const parent_scope = node instanceof AST_Catch
? save_scope.parent_scope
: save_scope;
scope.init_scope_vars(parent_scope);
scope.uses_with = save_scope.uses_with;
scope.uses_eval = save_scope.uses_eval;
if (options.safari10) {
if (node instanceof AST_For || node instanceof AST_ForIn) {
for_scopes.push(scope);
}
}
if (node instanceof AST_Switch) {
// XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope
// AST_Switch has a scope within the body, but it itself "is a block scope"
// This means the switched expression has to belong to the outer scope
// while the body inside belongs to the switch itself.
// This is pretty nasty and warrants an AST change similar to AST_Try (read above)
const the_block_scope = scope;
scope = save_scope;
node.expression.walk(tw);
scope = the_block_scope;
for (let i = 0; i < node.body.length; i++) {
node.body[i].walk(tw);
}
} else {
descend();
}
scope = save_scope;
return true;
}
if (node instanceof AST_Destructuring) {
const save_destructuring = in_destructuring;
in_destructuring = node;
descend();
in_destructuring = save_destructuring;
return true;
}
if (node instanceof AST_Scope) {
node.init_scope_vars(scope);
var save_scope = scope;
var save_defun = defun;
var save_labels = labels;
defun = scope = node;
labels = new Map();
descend();
scope = save_scope;
defun = save_defun;
labels = save_labels;
return true; // don't descend again in TreeWalker
}
if (node instanceof AST_LabeledStatement) {
var l = node.label;
if (labels.has(l.name)) {
throw new Error(string_template("Label {name} defined twice", l));
}
labels.set(l.name, l);
descend();
labels.delete(l.name);
return true; // no descend again
}
if (node instanceof AST_With) {
for (var s = scope; s; s = s.parent_scope)
s.uses_with = true;
return;
}
if (node instanceof AST_Symbol) {
node.scope = scope;
}
if (node instanceof AST_Label) {
node.thedef = node;
node.references = [];
}
if (node instanceof AST_SymbolLambda) {
defun.def_function(node, node.name == "arguments" ? undefined : defun);
} else if (node instanceof AST_SymbolDefun) {
// Careful here, the scope where this should be defined is
// the parent scope. The reason is that we enter a new
// scope when we encounter the AST_Defun node (which is
// instanceof AST_Scope) but we get to the symbol a bit
// later.
mark_export((node.scope = defun.parent_scope.get_defun_scope()).def_function(node, defun), 1);
} else if (node instanceof AST_SymbolClass) {
mark_export(defun.def_variable(node, defun), 1);
} else if (node instanceof AST_SymbolImport) {
scope.def_variable(node);
} else if (node instanceof AST_SymbolDefClass) {
// This deals with the name of the class being available
// inside the class.
mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1);
} else if (
node instanceof AST_SymbolVar
|| node instanceof AST_SymbolLet
|| node instanceof AST_SymbolConst
|| node instanceof AST_SymbolCatch
) {
var def;
if (node instanceof AST_SymbolBlockDeclaration) {
def = scope.def_variable(node, null);
} else {
def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined);
}
if (!def.orig.every((sym) => {
if (sym === node) return true;
if (node instanceof AST_SymbolBlockDeclaration) {
return sym instanceof AST_SymbolLambda;
}
return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst);
})) {
js_error(
`"${node.name}" is redeclared`,
node.start.file,
node.start.line,
node.start.col,
node.start.pos
);
}
if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2);
if (defun !== scope) {
node.mark_enclosed();
var def = scope.find_variable(node);
if (node.thedef !== def) {
node.thedef = def;
node.reference();
}
}
} else if (node instanceof AST_LabelRef) {
var sym = labels.get(node.name);
if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
name: node.name,
line: node.start.line,
col: node.start.col
}));
node.thedef = sym;
}
if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) {
js_error(
`"${node.TYPE}" statement may only appear at the top level`,
node.start.file,
node.start.line,
node.start.col,
node.start.pos
);
}
});
this.walk(tw);
function mark_export(def, level) {
if (in_destructuring) {
var i = 0;
do {
level++;
} while (tw.parent(i++) !== in_destructuring);
}
var node = tw.parent(level);
if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) {
var exported = node.exported_definition;
if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) {
def.export = MASK_EXPORT_WANT_MANGLE;
}
}
}
// pass 2: find back references and eval
const is_toplevel = this instanceof AST_Toplevel;
if (is_toplevel) {
this.globals = new Map();
}
var tw = new TreeWalker(node => {
if (node instanceof AST_LoopControl && node.label) {
node.label.thedef.references.push(node);
return true;
}
if (node instanceof AST_SymbolRef) {
var name = node.name;
if (name == "eval" && tw.parent() instanceof AST_Call) {
for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
s.uses_eval = true;
}
}
var sym;
if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name
|| !(sym = node.scope.find_variable(name))) {
sym = toplevel.def_global(node);
if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE;
} else if (sym.scope instanceof AST_Lambda && name == "arguments") {
sym.scope.uses_arguments = true;
}
node.thedef = sym;
node.reference();
if (node.scope.is_block_scope()
&& !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) {
node.scope = node.scope.get_defun_scope();
}
return true;
}
// ensure mangling works if catch reuses a scope variable
var def;
if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) {
var s = node.scope;
while (s) {
push_uniq(s.enclosed, def);
if (s === def.scope) break;
s = s.parent_scope;
}
}
});
this.walk(tw);
// pass 3: work around IE8 and Safari catch scope bugs
if (options.ie8 || options.safari10) {
walk(this, node => {
if (node instanceof AST_SymbolCatch) {
var name = node.name;
var refs = node.thedef.references;
var scope = node.scope.get_defun_scope();
var def = scope.find_variable(name)
|| toplevel.globals.get(name)
|| scope.def_variable(node);
refs.forEach(function(ref) {
ref.thedef = def;
ref.reference();
});
node.thedef = def;
node.reference();
return true;
}
});
}
// pass 4: add symbol definitions to loop scopes
// Safari/Webkit bug workaround - loop init let variable shadowing argument.
// https://github.com/mishoo/UglifyJS2/issues/1753
// https://bugs.webkit.org/show_bug.cgi?id=171041
if (options.safari10) {
for (const scope of for_scopes) {
scope.parent_scope.variables.forEach(function(def) {
push_uniq(scope.enclosed, def);
});
}
}
});
AST_Toplevel.DEFMETHOD("def_global", function(node) {
var globals = this.globals, name = node.name;
if (globals.has(name)) {
return globals.get(name);
} else {
var g = new SymbolDef(this, node);
g.undeclared = true;
g.global = true;
globals.set(name, g);
return g;
}
});
AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) {
this.variables = new Map(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
this.functions = new Map(); // map name to AST_SymbolDefun (functions defined in this scope)
this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
this.parent_scope = parent_scope; // the parent scope
this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
this.cname = -1; // the current index for mangling functions/variables
});
AST_Scope.DEFMETHOD("conflicting_def", function (name) {
return (
this.enclosed.find(def => def.name === name)
|| this.variables.has(name)
|| (this.parent_scope && this.parent_scope.conflicting_def(name))
);
});
AST_Scope.DEFMETHOD("conflicting_def_shallow", function (name) {
return (
this.enclosed.find(def => def.name === name)
|| this.variables.has(name)
);
});
AST_Scope.DEFMETHOD("add_child_scope", function (scope) {
// `scope` is going to be moved into `this` right now.
// Update the required scopes' information
if (scope.parent_scope === this) return;
scope.parent_scope = this;
// TODO uses_with, uses_eval, etc
const scope_ancestry = (() => {
const ancestry = [];
let cur = this;
do {
ancestry.push(cur);
} while ((cur = cur.parent_scope));
ancestry.reverse();
return ancestry;
})();
const new_scope_enclosed_set = new Set(scope.enclosed);
const to_enclose = [];
for (const scope_topdown of scope_ancestry) {
to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e));
for (const def of scope_topdown.variables.values()) {
if (new_scope_enclosed_set.has(def)) {
push_uniq(to_enclose, def);
push_uniq(scope_topdown.enclosed, def);
}
}
}
});
function find_scopes_visible_from(scopes) {
const found_scopes = new Set();
for (const scope of new Set(scopes)) {
(function bubble_up(scope) {
if (scope == null || found_scopes.has(scope)) return;
found_scopes.add(scope);
bubble_up(scope.parent_scope);
})(scope);
}
return [...found_scopes];
}
// Creates a symbol during compression
AST_Scope.DEFMETHOD("create_symbol", function(SymClass, {
source,
tentative_name,
scope,
conflict_scopes = [scope],
init = null
} = {}) {
let symbol_name;
conflict_scopes = find_scopes_visible_from(conflict_scopes);
if (tentative_name) {
// Implement hygiene (no new names are conflicting with existing names)
tentative_name =
symbol_name =
tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");
let i = 0;
while (conflict_scopes.find(s => s.conflicting_def_shallow(symbol_name))) {
symbol_name = tentative_name + "$" + i++;
}
}
if (!symbol_name) {
throw new Error("No symbol name could be generated in create_symbol()");
}
const symbol = make_node(SymClass, source, {
name: symbol_name,
scope
});
this.def_variable(symbol, init || null);
symbol.mark_enclosed();
return symbol;
});
AST_Node.DEFMETHOD("is_block_scope", return_false);
AST_Class.DEFMETHOD("is_block_scope", return_false);
AST_Lambda.DEFMETHOD("is_block_scope", return_false);
AST_Toplevel.DEFMETHOD("is_block_scope", return_false);
AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false);
AST_Block.DEFMETHOD("is_block_scope", return_true);
AST_Scope.DEFMETHOD("is_block_scope", function () {
return this._block_scope || false;
});
AST_IterationStatement.DEFMETHOD("is_block_scope", return_true);
AST_Lambda.DEFMETHOD("init_scope_vars", function() {
AST_Scope.prototype.init_scope_vars.apply(this, arguments);
this.uses_arguments = false;
this.def_variable(new AST_SymbolFunarg({
name: "arguments",
start: this.start,
end: this.end
}));
});
AST_Arrow.DEFMETHOD("init_scope_vars", function() {
AST_Scope.prototype.init_scope_vars.apply(this, arguments);
this.uses_arguments = false;
});
AST_Symbol.DEFMETHOD("mark_enclosed", function() {
var def = this.definition();
var s = this.scope;
while (s) {
push_uniq(s.enclosed, def);
if (s === def.scope) break;
s = s.parent_scope;
}
});
AST_Symbol.DEFMETHOD("reference", function() {
this.definition().references.push(this);
this.mark_enclosed();
});
AST_Scope.DEFMETHOD("find_variable", function(name) {
if (name instanceof AST_Symbol) name = name.name;
return this.variables.get(name)
|| (this.parent_scope && this.parent_scope.find_variable(name));
});
AST_Scope.DEFMETHOD("def_function", function(symbol, init) {
var def = this.def_variable(symbol, init);
if (!def.init || def.init instanceof AST_Defun) def.init = init;
this.functions.set(symbol.name, def);
return def;
});
AST_Scope.DEFMETHOD("def_variable", function(symbol, init) {
var def = this.variables.get(symbol.name);
if (def) {
def.orig.push(symbol);
if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) {
def.init = init;
}
} else {
def = new SymbolDef(this, symbol, init);
this.variables.set(symbol.name, def);
def.global = !this.parent_scope;
}
return symbol.thedef = def;
});
function next_mangled(scope, options) {
var ext = scope.enclosed;
out: while (true) {
var m = base54(++scope.cname);
if (RESERVED_WORDS.has(m)) continue; // skip over "do"
// https://github.com/mishoo/UglifyJS2/issues/242 -- do not
// shadow a name reserved from mangling.
if (options.reserved.has(m)) continue;
// Functions with short names might collide with base54 output
// and therefore cause collisions when keep_fnames is true.
if (unmangleable_names && unmangleable_names.has(m)) continue out;
// we must ensure that the mangled name does not shadow a name
// from some parent scope that is referenced in this or in
// inner scopes.
for (let i = ext.length; --i >= 0;) {
const def = ext[i];
const name = def.mangled_name || (def.unmangleable(options) && def.name);
if (m == name) continue out;
}
return m;
}
}
AST_Scope.DEFMETHOD("next_mangled", function(options) {
return next_mangled(this, options);
});
AST_Toplevel.DEFMETHOD("next_mangled", function(options) {
let name;
const mangled_names = this.mangled_names;
do {
name = next_mangled(this, options);
} while (mangled_names.has(name));
return name;
});
AST_Function.DEFMETHOD("next_mangled", function(options, def) {
// #179, #326
// in Safari strict mode, something like (function x(x){...}) is a syntax error;
// a function expression's argument cannot shadow the function expression's name
var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
// the function's mangled_name is null when keep_fnames is true
var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;
while (true) {
var name = next_mangled(this, options);
if (!tricky_name || tricky_name != name)
return name;
}
});
AST_Symbol.DEFMETHOD("unmangleable", function(options) {
var def = this.definition();
return !def || def.unmangleable(options);
});
// labels are always mangleable
AST_Label.DEFMETHOD("unmangleable", return_false);
AST_Symbol.DEFMETHOD("unreferenced", function() {
return !this.definition().references.length && !this.scope.pinned();
});
AST_Symbol.DEFMETHOD("definition", function() {
return this.thedef;
});
AST_Symbol.DEFMETHOD("global", function() {
return this.thedef.global;
});
AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) {
options = defaults(options, {
eval : false,
ie8 : false,
keep_classnames: false,
keep_fnames : false,
module : false,
reserved : [],
toplevel : false,
});
if (options.module) options.toplevel = true;
if (!Array.isArray(options.reserved)
&& !(options.reserved instanceof Set)
) {
options.reserved = [];
}
options.reserved = new Set(options.reserved);
// Never mangle arguments
options.reserved.add("arguments");
return options;
});
AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
options = this._default_mangler_options(options);
// We only need to mangle declaration nodes. Special logic wired
// into the code generator will display the mangled name if it's
// present (and for AST_SymbolRef-s it'll use the mangled name of
// the AST_SymbolDeclaration that it points to).
var lname = -1;
var to_mangle = [];
if (options.keep_fnames) {
function_defs = new Set();
}
const mangled_names = this.mangled_names = new Set();
if (options.cache) {
this.globals.forEach(collect);
if (options.cache.props) {
options.cache.props.forEach(function(mangled_name) {
mangled_names.add(mangled_name);
});
}
}
var tw = new TreeWalker(function(node, descend) {
if (node instanceof AST_LabeledStatement) {
// lname is incremented when we get to the AST_Label
var save_nesting = lname;
descend();
lname = save_nesting;
return true; // don't descend again in TreeWalker
}
if (node instanceof AST_Scope) {
node.variables.forEach(collect);
return;
}
if (node.is_block_scope()) {
node.block_scope.variables.forEach(collect);
return;
}
if (
function_defs
&& node instanceof AST_VarDef
&& node.value instanceof AST_Lambda
&& !node.value.name
&& keep_name(options.keep_fnames, node.name.name)
) {
function_defs.add(node.name.definition().id);
return;
}
if (node instanceof AST_Label) {
let name;
do {
name = base54(++lname);
} while (RESERVED_WORDS.has(name));
node.mangled_name = name;
return true;
}
if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) {
to_mangle.push(node.definition());
return;
}
});
this.walk(tw);
if (options.keep_fnames || options.keep_classnames) {
unmangleable_names = new Set();
// Collect a set of short names which are unmangleable,
// for use in avoiding collisions in next_mangled.
to_mangle.forEach(def => {
if (def.name.length < 6 && def.unmangleable(options)) {
unmangleable_names.add(def.name);
}
});
}
to_mangle.forEach(def => { def.mangle(options); });
function_defs = null;
unmangleable_names = null;
function collect(symbol) {
const should_mangle = !options.reserved.has(symbol.name)
&& !(symbol.export & MASK_EXPORT_DONT_MANGLE);
if (should_mangle) {
to_mangle.push(symbol);
}
}
});
AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
const cache = options.cache && options.cache.props;
const avoid = new Set();
options.reserved.forEach(to_avoid);
this.globals.forEach(add_def);
this.walk(new TreeWalker(function(node) {
if (node instanceof AST_Scope) node.variables.forEach(add_def);
if (node instanceof AST_SymbolCatch) add_def(node.definition());
}));
return avoid;
function to_avoid(name) {
avoid.add(name);
}
function add_def(def) {
var name = def.name;
if (def.global && cache && cache.has(name)) name = cache.get(name);
else if (!def.unmangleable(options)) return;
to_avoid(name);
}
});
AST_Toplevel.DEFMETHOD("expand_names", function(options) {
base54.reset();
base54.sort();
options = this._default_mangler_options(options);
var avoid = this.find_colliding_names(options);
var cname = 0;
this.globals.forEach(rename);
this.walk(new TreeWalker(function(node) {
if (node instanceof AST_Scope) node.variables.forEach(rename);
if (node instanceof AST_SymbolCatch) rename(node.definition());
}));
function next_name() {
var name;
do {
name = base54(cname++);
} while (avoid.has(name) || RESERVED_WORDS.has(name));
return name;
}
function rename(def) {
if (def.global && options.cache) return;
if (def.unmangleable(options)) return;
if (options.reserved.has(def.name)) return;
const redefinition = redefined_catch_def(def);
const name = def.name = redefinition ? redefinition.name : next_name();
def.orig.forEach(function(sym) {
sym.name = name;
});
def.references.forEach(function(sym) {
sym.name = name;
});
}
});
AST_Node.DEFMETHOD("tail_node", return_this);
AST_Sequence.DEFMETHOD("tail_node", function() {
return this.expressions[this.expressions.length - 1];
});
AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) {
options = this._default_mangler_options(options);
try {
AST_Node.prototype.print = function(stream, force_parens) {
this._print(stream, force_parens);
if (this instanceof AST_Symbol && !this.unmangleable(options)) {
base54.consider(this.name, -1);
} else if (options.properties) {
if (this instanceof AST_DotHash) {
base54.consider("#" + this.property, -1);
} else if (this instanceof AST_Dot) {
base54.consider(this.property, -1);
} else if (this instanceof AST_Sub) {
skip_string(this.property);
}
}
};
base54.consider(this.print_to_string(), 1);
} finally {
AST_Node.prototype.print = AST_Node.prototype._print;
}
base54.sort();
function skip_string(node) {
if (node instanceof AST_String) {
base54.consider(node.value, -1);
} else if (node instanceof AST_Conditional) {
skip_string(node.consequent);
skip_string(node.alternative);
} else if (node instanceof AST_Sequence) {
skip_string(node.tail_node());
}
}
});
const base54 = (() => {
const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");
const digits = "0123456789".split("");
let chars;
let frequency;
function reset() {
frequency = new Map();
leading.forEach(function(ch) {
frequency.set(ch, 0);
});
digits.forEach(function(ch) {
frequency.set(ch, 0);
});
}
base54.consider = function(str, delta) {
for (var i = str.length; --i >= 0;) {
frequency.set(str[i], frequency.get(str[i]) + delta);
}
};
function compare(a, b) {
return frequency.get(b) - frequency.get(a);
}
base54.sort = function() {
chars = mergeSort(leading, compare).concat(mergeSort(digits, compare));
};
base54.reset = reset;
reset();
function base54(num) {
var ret = "", base = 54;
num++;
do {
num--;
ret += chars[num % base];
num = Math.floor(num / base);
base = 64;
} while (num > 0);
return ret;
}
return base54;
})();
export {
base54,
SymbolDef,
};

490
node_modules/terser/lib/size.js generated vendored Normal file
View File

@@ -0,0 +1,490 @@
import {
AST_Accessor,
AST_Array,
AST_Arrow,
AST_Await,
AST_BigInt,
AST_Binary,
AST_Block,
AST_Break,
AST_Call,
AST_Case,
AST_Class,
AST_ClassPrivateProperty,
AST_ClassProperty,
AST_ConciseMethod,
AST_Conditional,
AST_Const,
AST_Continue,
AST_Debugger,
AST_Default,
AST_Defun,
AST_Destructuring,
AST_Directive,
AST_Do,
AST_Dot,
AST_DotHash,
AST_EmptyStatement,
AST_Expansion,
AST_Export,
AST_False,
AST_For,
AST_ForIn,
AST_Function,
AST_Hole,
AST_If,
AST_Import,
AST_ImportMeta,
AST_Infinity,
AST_LabeledStatement,
AST_Let,
AST_NameMapping,
AST_NaN,
AST_New,
AST_NewTarget,
AST_Node,
AST_Null,
AST_Number,
AST_Object,
AST_ObjectKeyVal,
AST_ObjectGetter,
AST_ObjectSetter,
AST_PrivateGetter,
AST_PrivateMethod,
AST_PrivateSetter,
AST_RegExp,
AST_Return,
AST_Sequence,
AST_String,
AST_Sub,
AST_Super,
AST_Switch,
AST_Symbol,
AST_SymbolClassProperty,
AST_SymbolExportForeign,
AST_SymbolImportForeign,
AST_SymbolRef,
AST_SymbolDeclaration,
AST_TemplateSegment,
AST_TemplateString,
AST_This,
AST_Throw,
AST_Toplevel,
AST_True,
AST_Try,
AST_Catch,
AST_Finally,
AST_Unary,
AST_Undefined,
AST_Var,
AST_VarDef,
AST_While,
AST_With,
AST_Yield,
walk_parent
} from "./ast.js";
import { first_in_statement } from "./utils/first_in_statement.js";
let mangle_options = undefined;
AST_Node.prototype.size = function (compressor, stack) {
mangle_options = compressor && compressor.mangle_options;
let size = 0;
walk_parent(this, (node, info) => {
size += node._size(info);
// Braceless arrow functions have fake "return" statements
if (node instanceof AST_Arrow && node.is_braceless()) {
size += node.body[0].value._size(info);
return true;
}
}, stack || (compressor && compressor.stack));
// just to save a bit of memory
mangle_options = undefined;
return size;
};
AST_Node.prototype._size = () => 0;
AST_Debugger.prototype._size = () => 8;
AST_Directive.prototype._size = function () {
// TODO string encoding stuff
return 2 + this.value.length;
};
const list_overhead = (array) => array.length && array.length - 1;
AST_Block.prototype._size = function () {
return 2 + list_overhead(this.body);
};
AST_Toplevel.prototype._size = function() {
return list_overhead(this.body);
};
AST_EmptyStatement.prototype._size = () => 1;
AST_LabeledStatement.prototype._size = () => 2; // x:
AST_Do.prototype._size = () => 9;
AST_While.prototype._size = () => 7;
AST_For.prototype._size = () => 8;
AST_ForIn.prototype._size = () => 8;
// AST_ForOf inherits ^
AST_With.prototype._size = () => 6;
AST_Expansion.prototype._size = () => 3;
const lambda_modifiers = func =>
(func.is_generator ? 1 : 0) + (func.async ? 6 : 0);
AST_Accessor.prototype._size = function () {
return lambda_modifiers(this) + 4 + list_overhead(this.argnames) + list_overhead(this.body);
};
AST_Function.prototype._size = function (info) {
const first = !!first_in_statement(info);
return (first * 2) + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body);
};
AST_Defun.prototype._size = function () {
return lambda_modifiers(this) + 13 + list_overhead(this.argnames) + list_overhead(this.body);
};
AST_Arrow.prototype._size = function () {
let args_and_arrow = 2 + list_overhead(this.argnames);
if (
!(
this.argnames.length === 1
&& this.argnames[0] instanceof AST_Symbol
)
) {
args_and_arrow += 2;
}
const body_overhead = this.is_braceless() ? 0 : list_overhead(this.body) + 2;
return lambda_modifiers(this) + args_and_arrow + body_overhead;
};
AST_Destructuring.prototype._size = () => 2;
AST_TemplateString.prototype._size = function () {
return 2 + (Math.floor(this.segments.length / 2) * 3); /* "${}" */
};
AST_TemplateSegment.prototype._size = function () {
return this.value.length;
};
AST_Return.prototype._size = function () {
return this.value ? 7 : 6;
};
AST_Throw.prototype._size = () => 6;
AST_Break.prototype._size = function () {
return this.label ? 6 : 5;
};
AST_Continue.prototype._size = function () {
return this.label ? 9 : 8;
};
AST_If.prototype._size = () => 4;
AST_Switch.prototype._size = function () {
return 8 + list_overhead(this.body);
};
AST_Case.prototype._size = function () {
return 5 + list_overhead(this.body);
};
AST_Default.prototype._size = function () {
return 8 + list_overhead(this.body);
};
AST_Try.prototype._size = function () {
return 3 + list_overhead(this.body);
};
AST_Catch.prototype._size = function () {
let size = 7 + list_overhead(this.body);
if (this.argname) {
size += 2;
}
return size;
};
AST_Finally.prototype._size = function () {
return 7 + list_overhead(this.body);
};
/*#__INLINE__*/
const def_size = (size, def) => size + list_overhead(def.definitions);
AST_Var.prototype._size = function () {
return def_size(4, this);
};
AST_Let.prototype._size = function () {
return def_size(4, this);
};
AST_Const.prototype._size = function () {
return def_size(6, this);
};
AST_VarDef.prototype._size = function () {
return this.value ? 1 : 0;
};
AST_NameMapping.prototype._size = function () {
// foreign name isn't mangled
return this.name ? 4 : 0;
};
AST_Import.prototype._size = function () {
// import
let size = 6;
if (this.imported_name) size += 1;
// from
if (this.imported_name || this.imported_names) size += 5;
// braces, and the commas
if (this.imported_names) {
size += 2 + list_overhead(this.imported_names);
}
return size;
};
AST_ImportMeta.prototype._size = () => 11;
AST_Export.prototype._size = function () {
let size = 7 + (this.is_default ? 8 : 0);
if (this.exported_value) {
size += this.exported_value._size();
}
if (this.exported_names) {
// Braces and commas
size += 2 + list_overhead(this.exported_names);
}
if (this.module_name) {
// "from "
size += 5;
}
return size;
};
AST_Call.prototype._size = function () {
if (this.optional) {
return 4 + list_overhead(this.args);
}
return 2 + list_overhead(this.args);
};
AST_New.prototype._size = function () {
return 6 + list_overhead(this.args);
};
AST_Sequence.prototype._size = function () {
return list_overhead(this.expressions);
};
AST_Dot.prototype._size = function () {
if (this.optional) {
return this.property.length + 2;
}
return this.property.length + 1;
};
AST_DotHash.prototype._size = function () {
if (this.optional) {
return this.property.length + 3;
}
return this.property.length + 2;
};
AST_Sub.prototype._size = function () {
return this.optional ? 4 : 2;
};
AST_Unary.prototype._size = function () {
if (this.operator === "typeof") return 7;
if (this.operator === "void") return 5;
return this.operator.length;
};
AST_Binary.prototype._size = function (info) {
if (this.operator === "in") return 4;
let size = this.operator.length;
if (
(this.operator === "+" || this.operator === "-")
&& this.right instanceof AST_Unary && this.right.operator === this.operator
) {
// 1+ +a > needs space between the +
size += 1;
}
if (this.needs_parens(info)) {
size += 2;
}
return size;
};
AST_Conditional.prototype._size = () => 3;
AST_Array.prototype._size = function () {
return 2 + list_overhead(this.elements);
};
AST_Object.prototype._size = function (info) {
let base = 2;
if (first_in_statement(info)) {
base += 2; // parens
}
return base + list_overhead(this.properties);
};
/*#__INLINE__*/
const key_size = key =>
typeof key === "string" ? key.length : 0;
AST_ObjectKeyVal.prototype._size = function () {
return key_size(this.key) + 1;
};
/*#__INLINE__*/
const static_size = is_static => is_static ? 7 : 0;
AST_ObjectGetter.prototype._size = function () {
return 5 + static_size(this.static) + key_size(this.key);
};
AST_ObjectSetter.prototype._size = function () {
return 5 + static_size(this.static) + key_size(this.key);
};
AST_ConciseMethod.prototype._size = function () {
return static_size(this.static) + key_size(this.key) + lambda_modifiers(this);
};
AST_PrivateMethod.prototype._size = function () {
return AST_ConciseMethod.prototype._size.call(this) + 1;
};
AST_PrivateGetter.prototype._size = AST_PrivateSetter.prototype._size = function () {
return AST_ConciseMethod.prototype._size.call(this) + 4;
};
AST_Class.prototype._size = function () {
return (
(this.name ? 8 : 7)
+ (this.extends ? 8 : 0)
);
};
AST_ClassProperty.prototype._size = function () {
return (
static_size(this.static)
+ (typeof this.key === "string" ? this.key.length + 2 : 0)
+ (this.value ? 1 : 0)
);
};
AST_ClassPrivateProperty.prototype._size = function () {
return AST_ClassProperty.prototype._size.call(this) + 1;
};
AST_Symbol.prototype._size = function () {
return !mangle_options || this.definition().unmangleable(mangle_options)
? this.name.length
: 1;
};
// TODO take propmangle into account
AST_SymbolClassProperty.prototype._size = function () {
return this.name.length;
};
AST_SymbolRef.prototype._size = AST_SymbolDeclaration.prototype._size = function () {
const { name, thedef } = this;
if (thedef && thedef.global) return name.length;
if (name === "arguments") return 9;
return AST_Symbol.prototype._size.call(this);
};
AST_NewTarget.prototype._size = () => 10;
AST_SymbolImportForeign.prototype._size = function () {
return this.name.length;
};
AST_SymbolExportForeign.prototype._size = function () {
return this.name.length;
};
AST_This.prototype._size = () => 4;
AST_Super.prototype._size = () => 5;
AST_String.prototype._size = function () {
return this.value.length + 2;
};
AST_Number.prototype._size = function () {
const { value } = this;
if (value === 0) return 1;
if (value > 0 && Math.floor(value) === value) {
return Math.floor(Math.log10(value) + 1);
}
return value.toString().length;
};
AST_BigInt.prototype._size = function () {
return this.value.length;
};
AST_RegExp.prototype._size = function () {
return this.value.toString().length;
};
AST_Null.prototype._size = () => 4;
AST_NaN.prototype._size = () => 3;
AST_Undefined.prototype._size = () => 6; // "void 0"
AST_Hole.prototype._size = () => 0; // comma is taken into account
AST_Infinity.prototype._size = () => 8;
AST_True.prototype._size = () => 4;
AST_False.prototype._size = () => 5;
AST_Await.prototype._size = () => 6;
AST_Yield.prototype._size = () => 6;

114
node_modules/terser/lib/sourcemap.js generated vendored Normal file
View File

@@ -0,0 +1,114 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/
"use strict";
import MOZ_SourceMap from "source-map";
import {
defaults,
} from "./utils/index.js";
// a small wrapper around fitzgen's source-map library
async function SourceMap(options) {
options = defaults(options, {
file : null,
root : null,
orig : null,
orig_line_diff : 0,
dest_line_diff : 0,
});
var orig_map;
var generator = new MOZ_SourceMap.SourceMapGenerator({
file : options.file,
sourceRoot : options.root
});
if (options.orig) {
orig_map = await new MOZ_SourceMap.SourceMapConsumer(options.orig);
orig_map.sources.forEach(function(source) {
var sourceContent = orig_map.sourceContentFor(source, true);
if (sourceContent) {
generator.setSourceContent(source, sourceContent);
}
});
}
function add(source, gen_line, gen_col, orig_line, orig_col, name) {
if (orig_map) {
var info = orig_map.originalPositionFor({
line: orig_line,
column: orig_col
});
if (info.source === null) {
return;
}
source = info.source;
orig_line = info.line;
orig_col = info.column;
name = info.name || name;
}
generator.addMapping({
generated : { line: gen_line + options.dest_line_diff, column: gen_col },
original : { line: orig_line + options.orig_line_diff, column: orig_col },
source : source,
name : name
});
}
return {
add : add,
get : function() { return generator; },
toString : function() { return generator.toString(); },
destroy : function () {
if (orig_map && orig_map.destroy) {
orig_map.destroy();
}
}
};
}
export {
SourceMap,
};

318
node_modules/terser/lib/transform.js generated vendored Normal file
View File

@@ -0,0 +1,318 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/
"use strict";
import {
AST_Array,
AST_Await,
AST_Binary,
AST_Block,
AST_Call,
AST_Case,
AST_Catch,
AST_Chain,
AST_Class,
AST_Conditional,
AST_Definitions,
AST_Destructuring,
AST_Do,
AST_Dot,
AST_Exit,
AST_Expansion,
AST_Export,
AST_For,
AST_ForIn,
AST_If,
AST_Import,
AST_LabeledStatement,
AST_Lambda,
AST_LoopControl,
AST_NameMapping,
AST_Node,
AST_Number,
AST_Object,
AST_ObjectProperty,
AST_PrefixedTemplateString,
AST_Sequence,
AST_SimpleStatement,
AST_Sub,
AST_Switch,
AST_TemplateString,
AST_Try,
AST_Unary,
AST_VarDef,
AST_While,
AST_With,
AST_Yield,
} from "./ast.js";
import {
MAP,
noop,
} from "./utils/index.js";
function def_transform(node, descend) {
node.DEFMETHOD("transform", function(tw, in_list) {
let transformed = undefined;
tw.push(this);
if (tw.before) transformed = tw.before(this, descend, in_list);
if (transformed === undefined) {
transformed = this;
descend(transformed, tw);
if (tw.after) {
const after_ret = tw.after(transformed, in_list);
if (after_ret !== undefined) transformed = after_ret;
}
}
tw.pop();
return transformed;
});
}
function do_list(list, tw) {
return MAP(list, function(node) {
return node.transform(tw, true);
});
}
def_transform(AST_Node, noop);
def_transform(AST_LabeledStatement, function(self, tw) {
self.label = self.label.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_SimpleStatement, function(self, tw) {
self.body = self.body.transform(tw);
});
def_transform(AST_Block, function(self, tw) {
self.body = do_list(self.body, tw);
});
def_transform(AST_Do, function(self, tw) {
self.body = self.body.transform(tw);
self.condition = self.condition.transform(tw);
});
def_transform(AST_While, function(self, tw) {
self.condition = self.condition.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_For, function(self, tw) {
if (self.init) self.init = self.init.transform(tw);
if (self.condition) self.condition = self.condition.transform(tw);
if (self.step) self.step = self.step.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_ForIn, function(self, tw) {
self.init = self.init.transform(tw);
self.object = self.object.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_With, function(self, tw) {
self.expression = self.expression.transform(tw);
self.body = self.body.transform(tw);
});
def_transform(AST_Exit, function(self, tw) {
if (self.value) self.value = self.value.transform(tw);
});
def_transform(AST_LoopControl, function(self, tw) {
if (self.label) self.label = self.label.transform(tw);
});
def_transform(AST_If, function(self, tw) {
self.condition = self.condition.transform(tw);
self.body = self.body.transform(tw);
if (self.alternative) self.alternative = self.alternative.transform(tw);
});
def_transform(AST_Switch, function(self, tw) {
self.expression = self.expression.transform(tw);
self.body = do_list(self.body, tw);
});
def_transform(AST_Case, function(self, tw) {
self.expression = self.expression.transform(tw);
self.body = do_list(self.body, tw);
});
def_transform(AST_Try, function(self, tw) {
self.body = do_list(self.body, tw);
if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
});
def_transform(AST_Catch, function(self, tw) {
if (self.argname) self.argname = self.argname.transform(tw);
self.body = do_list(self.body, tw);
});
def_transform(AST_Definitions, function(self, tw) {
self.definitions = do_list(self.definitions, tw);
});
def_transform(AST_VarDef, function(self, tw) {
self.name = self.name.transform(tw);
if (self.value) self.value = self.value.transform(tw);
});
def_transform(AST_Destructuring, function(self, tw) {
self.names = do_list(self.names, tw);
});
def_transform(AST_Lambda, function(self, tw) {
if (self.name) self.name = self.name.transform(tw);
self.argnames = do_list(self.argnames, tw);
if (self.body instanceof AST_Node) {
self.body = self.body.transform(tw);
} else {
self.body = do_list(self.body, tw);
}
});
def_transform(AST_Call, function(self, tw) {
self.expression = self.expression.transform(tw);
self.args = do_list(self.args, tw);
});
def_transform(AST_Sequence, function(self, tw) {
const result = do_list(self.expressions, tw);
self.expressions = result.length
? result
: [new AST_Number({ value: 0 })];
});
def_transform(AST_Dot, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Sub, function(self, tw) {
self.expression = self.expression.transform(tw);
self.property = self.property.transform(tw);
});
def_transform(AST_Chain, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Yield, function(self, tw) {
if (self.expression) self.expression = self.expression.transform(tw);
});
def_transform(AST_Await, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Unary, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_Binary, function(self, tw) {
self.left = self.left.transform(tw);
self.right = self.right.transform(tw);
});
def_transform(AST_Conditional, function(self, tw) {
self.condition = self.condition.transform(tw);
self.consequent = self.consequent.transform(tw);
self.alternative = self.alternative.transform(tw);
});
def_transform(AST_Array, function(self, tw) {
self.elements = do_list(self.elements, tw);
});
def_transform(AST_Object, function(self, tw) {
self.properties = do_list(self.properties, tw);
});
def_transform(AST_ObjectProperty, function(self, tw) {
if (self.key instanceof AST_Node) {
self.key = self.key.transform(tw);
}
if (self.value) self.value = self.value.transform(tw);
});
def_transform(AST_Class, function(self, tw) {
if (self.name) self.name = self.name.transform(tw);
if (self.extends) self.extends = self.extends.transform(tw);
self.properties = do_list(self.properties, tw);
});
def_transform(AST_Expansion, function(self, tw) {
self.expression = self.expression.transform(tw);
});
def_transform(AST_NameMapping, function(self, tw) {
self.foreign_name = self.foreign_name.transform(tw);
self.name = self.name.transform(tw);
});
def_transform(AST_Import, function(self, tw) {
if (self.imported_name) self.imported_name = self.imported_name.transform(tw);
if (self.imported_names) do_list(self.imported_names, tw);
self.module_name = self.module_name.transform(tw);
});
def_transform(AST_Export, function(self, tw) {
if (self.exported_definition) self.exported_definition = self.exported_definition.transform(tw);
if (self.exported_value) self.exported_value = self.exported_value.transform(tw);
if (self.exported_names) do_list(self.exported_names, tw);
if (self.module_name) self.module_name = self.module_name.transform(tw);
});
def_transform(AST_TemplateString, function(self, tw) {
self.segments = do_list(self.segments, tw);
});
def_transform(AST_PrefixedTemplateString, function(self, tw) {
self.prefix = self.prefix.transform(tw);
self.template_string = self.template_string.transform(tw);
});

50
node_modules/terser/lib/utils/first_in_statement.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
import {
AST_Binary,
AST_Conditional,
AST_Dot,
AST_Object,
AST_Sequence,
AST_Statement,
AST_Sub,
AST_UnaryPostfix,
AST_PrefixedTemplateString
} from "../ast.js";
// return true if the node at the top of the stack (that means the
// innermost node in the current output) is lexically the first in
// a statement.
function first_in_statement(stack) {
let node = stack.parent(-1);
for (let i = 0, p; p = stack.parent(i); i++) {
if (p instanceof AST_Statement && p.body === node)
return true;
if ((p instanceof AST_Sequence && p.expressions[0] === node) ||
(p.TYPE === "Call" && p.expression === node) ||
(p instanceof AST_PrefixedTemplateString && p.prefix === node) ||
(p instanceof AST_Dot && p.expression === node) ||
(p instanceof AST_Sub && p.expression === node) ||
(p instanceof AST_Conditional && p.condition === node) ||
(p instanceof AST_Binary && p.left === node) ||
(p instanceof AST_UnaryPostfix && p.expression === node)
) {
node = p;
} else {
return false;
}
}
}
// Returns whether the leftmost item in the expression is an object
function left_is_object(node) {
if (node instanceof AST_Object) return true;
if (node instanceof AST_Sequence) return left_is_object(node.expressions[0]);
if (node.TYPE === "Call") return left_is_object(node.expression);
if (node instanceof AST_PrefixedTemplateString) return left_is_object(node.prefix);
if (node instanceof AST_Dot || node instanceof AST_Sub) return left_is_object(node.expression);
if (node instanceof AST_Conditional) return left_is_object(node.condition);
if (node instanceof AST_Binary) return left_is_object(node.left);
if (node instanceof AST_UnaryPostfix) return left_is_object(node.expression);
return false;
}
export { first_in_statement, left_is_object };

304
node_modules/terser/lib/utils/index.js generated vendored Normal file
View File

@@ -0,0 +1,304 @@
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/
"use strict";
function characters(str) {
return str.split("");
}
function member(name, array) {
return array.includes(name);
}
class DefaultsError extends Error {
constructor(msg, defs) {
super();
this.name = "DefaultsError";
this.message = msg;
this.defs = defs;
}
}
function defaults(args, defs, croak) {
if (args === true) {
args = {};
}
if (args != null && typeof args === "object") {
args = Object.assign({}, args);
}
const ret = args || {};
if (croak) for (const i in ret) if (HOP(ret, i) && !HOP(defs, i)) {
throw new DefaultsError("`" + i + "` is not a supported option", defs);
}
for (const i in defs) if (HOP(defs, i)) {
if (!args || !HOP(args, i)) {
ret[i] = defs[i];
} else if (i === "ecma") {
let ecma = args[i] | 0;
if (ecma > 5 && ecma < 2015) ecma += 2009;
ret[i] = ecma;
} else {
ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
}
}
return ret;
}
function noop() {}
function return_false() { return false; }
function return_true() { return true; }
function return_this() { return this; }
function return_null() { return null; }
var MAP = (function() {
function MAP(a, f, backwards) {
var ret = [], top = [], i;
function doit() {
var val = f(a[i], i);
var is_last = val instanceof Last;
if (is_last) val = val.v;
if (val instanceof AtTop) {
val = val.v;
if (val instanceof Splice) {
top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
} else {
top.push(val);
}
} else if (val !== skip) {
if (val instanceof Splice) {
ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
} else {
ret.push(val);
}
}
return is_last;
}
if (Array.isArray(a)) {
if (backwards) {
for (i = a.length; --i >= 0;) if (doit()) break;
ret.reverse();
top.reverse();
} else {
for (i = 0; i < a.length; ++i) if (doit()) break;
}
} else {
for (i in a) if (HOP(a, i)) if (doit()) break;
}
return top.concat(ret);
}
MAP.at_top = function(val) { return new AtTop(val); };
MAP.splice = function(val) { return new Splice(val); };
MAP.last = function(val) { return new Last(val); };
var skip = MAP.skip = {};
function AtTop(val) { this.v = val; }
function Splice(val) { this.v = val; }
function Last(val) { this.v = val; }
return MAP;
})();
function make_node(ctor, orig, props) {
if (!props) props = {};
if (orig) {
if (!props.start) props.start = orig.start;
if (!props.end) props.end = orig.end;
}
return new ctor(props);
}
function push_uniq(array, el) {
if (!array.includes(el))
array.push(el);
}
function string_template(text, props) {
return text.replace(/{(.+?)}/g, function(str, p) {
return props && props[p];
});
}
function remove(array, el) {
for (var i = array.length; --i >= 0;) {
if (array[i] === el) array.splice(i, 1);
}
}
function mergeSort(array, cmp) {
if (array.length < 2) return array.slice();
function merge(a, b) {
var r = [], ai = 0, bi = 0, i = 0;
while (ai < a.length && bi < b.length) {
cmp(a[ai], b[bi]) <= 0
? r[i++] = a[ai++]
: r[i++] = b[bi++];
}
if (ai < a.length) r.push.apply(r, a.slice(ai));
if (bi < b.length) r.push.apply(r, b.slice(bi));
return r;
}
function _ms(a) {
if (a.length <= 1)
return a;
var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
left = _ms(left);
right = _ms(right);
return merge(left, right);
}
return _ms(array);
}
function makePredicate(words) {
if (!Array.isArray(words)) words = words.split(" ");
return new Set(words.sort());
}
function map_add(map, key, value) {
if (map.has(key)) {
map.get(key).push(value);
} else {
map.set(key, [ value ]);
}
}
function map_from_object(obj) {
var map = new Map();
for (var key in obj) {
if (HOP(obj, key) && key.charAt(0) === "$") {
map.set(key.substr(1), obj[key]);
}
}
return map;
}
function map_to_object(map) {
var obj = Object.create(null);
map.forEach(function (value, key) {
obj["$" + key] = value;
});
return obj;
}
function HOP(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function keep_name(keep_setting, name) {
return keep_setting === true
|| (keep_setting instanceof RegExp && keep_setting.test(name));
}
var lineTerminatorEscape = {
"\0": "0",
"\n": "n",
"\r": "r",
"\u2028": "u2028",
"\u2029": "u2029",
};
function regexp_source_fix(source) {
// V8 does not escape line terminators in regexp patterns in node 12
// We'll also remove literal \0
return source.replace(/[\0\n\r\u2028\u2029]/g, function (match, offset) {
var escaped = source[offset - 1] == "\\"
&& (source[offset - 2] != "\\"
|| /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1)));
return (escaped ? "" : "\\") + lineTerminatorEscape[match];
});
}
const all_flags = "gimuy";
function sort_regexp_flags(flags) {
const existing_flags = new Set(flags.split(""));
let out = "";
for (const flag of all_flags) {
if (existing_flags.has(flag)) {
out += flag;
existing_flags.delete(flag);
}
}
if (existing_flags.size) {
// Flags Terser doesn't know about
existing_flags.forEach(flag => { out += flag; });
}
return out;
}
function has_annotation(node, annotation) {
return node._annotations & annotation;
}
function set_annotation(node, annotation) {
node._annotations |= annotation;
}
export {
characters,
defaults,
HOP,
keep_name,
make_node,
makePredicate,
map_add,
map_from_object,
map_to_object,
MAP,
member,
mergeSort,
noop,
push_uniq,
regexp_source_fix,
remove,
return_false,
return_null,
return_this,
return_true,
sort_regexp_flags,
string_template,
has_annotation,
set_annotation
};

27
node_modules/terser/main.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import "./lib/transform.js";
import "./lib/mozilla-ast.js";
import { minify } from "./lib/minify.js";
export { minify } from "./lib/minify.js";
export { run_cli as _run_cli } from "./lib/cli.js";
export async function _default_options() {
const defs = {};
Object.keys(infer_options({ 0: 0 })).forEach((component) => {
const options = infer_options({
[component]: {0: 0}
});
if (options) defs[component] = options;
});
return defs;
}
async function infer_options(options) {
try {
await minify("", options);
} catch (error) {
return error.defs;
}
}

View File

@@ -0,0 +1,344 @@
# Change Log
## 0.7.3
* Fix a bug where nested uses of `SourceMapConsumer` could result in a
`TypeError`. [#338](https://github.com/mozilla/source-map/issues/338)
[#330](https://github.com/mozilla/source-map/issues/330)
[#319](https://github.com/mozilla/source-map/issues/319)
## 0.7.2
* Another 3x speed up in `SourceMapConsumer`. Read about it here:
http://fitzgeraldnick.com/2018/02/26/speed-without-wizardry.html
## 0.7.1
* Updated TypeScript typings. [#321][]
[#321]: https://github.com/mozilla/source-map/pull/321
## 0.7.0
* `SourceMapConsumer` now uses WebAssembly, and is **much** faster! Read about
it here:
https://hacks.mozilla.org/2018/01/oxidizing-source-maps-with-rust-and-webassembly/
* **Breaking change:** `new SourceMapConsumer` now returns a `Promise` object
that resolves to the newly constructed `SourceMapConsumer` instance, rather
than returning the new instance immediately.
* **Breaking change:** when you're done using a `SourceMapConsumer` instance,
you must call `SourceMapConsumer.prototype.destroy` on it. After calling
`destroy`, you must not use the instance again.
* **Breaking change:** `SourceMapConsumer` used to be able to handle lines,
columns numbers and source and name indices up to `2^53 - 1` (aka
`Number.MAX_SAFE_INTEGER`). It can now only handle them up to `2^32 - 1`.
* **Breaking change:** The `source-map` library now uses modern ECMAScript-isms:
`let`, arrow functions, `async`, etc. Use Babel to compile it down to
ECMAScript 5 if you need to support older JavaScript environments.
* **Breaking change:** Drop support for Node < 8. If you want to support older
versions of node, please use v0.6 or below.
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.

28
node_modules/terser/node_modules/source-map/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

822
node_modules/terser/node_modules/source-map/README.md generated vendored Normal file
View File

@@ -0,0 +1,822 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![Coverage Status](https://coveralls.io/repos/github/mozilla/source-map/badge.svg)](https://coveralls.io/github/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://unpkg.com/source-map@0.7.3/dist/source-map.js"></script>
<script>
sourceMap.SourceMapConsumer.initialize({
"lib/mappings.wasm": "https://unpkg.com/source-map@0.7.3/lib/mappings.wasm"
});
</script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [SourceMapConsumer.initialize(options)](#sourcemapconsumerinitializeoptions)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.with](#sourcemapconsumerwith)
- [SourceMapConsumer.prototype.destroy()](#sourcemapconsumerprototypedestroy)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
const rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
const whatever = await SourceMapConsumer.with(rawSourceMap, null, consumer => {
console.log(consumer.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(consumer.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(consumer.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
consumer.eachMapping(function (m) {
// ...
});
return computeWhatever();
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A `SourceMapConsumer` instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### SourceMapConsumer.initialize(options)
When using `SourceMapConsumer` outside of node.js, for example on the Web, it
needs to know from what URL to load `lib/mappings.wasm`. You must inform it by
calling `initialize` before constructing any `SourceMapConsumer`s.
The options object has the following properties:
* `"lib/mappings.wasm"`: A `String` containing the URL of the
`lib/mappings.wasm` file.
```js
sourceMap.SourceMapConsumer.initialize({
"lib/mappings.wasm": "https://example.com/source-map/lib/mappings.wasm"
});
```
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
The promise of the constructed souce map consumer is returned.
When the `SourceMapConsumer` will no longer be used anymore, you must call its
`destroy` method.
```js
const consumer = await new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
doStuffWith(consumer);
consumer.destroy();
```
Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember
to call `destroy`.
#### SourceMapConsumer.with
Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
(see the `SourceMapConsumer` constructor for details. Then, invoke the `async
function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
for `f` to complete, call `destroy` on the consumer, and return `f`'s return
value.
You must not use the consumer after `f` completes!
By using `with`, you do not have to remember to manually call `destroy` on
the consumer, since it will be called automatically once `f` completes.
```js
const xSquared = await SourceMapConsumer.with(
myRawSourceMap,
null,
async function (consumer) {
// Use `consumer` inside here and don't worry about remembering
// to call `destroy`.
const x = await whatever(consumer);
return x * x;
}
);
// You may not use that `consumer` anymore out here; it has
// been destroyed. But you can use `xSquared`.
console.log(xSquared);
```
#### SourceMapConsumer.prototype.destroy()
Free this source map consumer's associated wasm data that is manually-managed.
```js
consumer.destroy();
```
Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember
to call `destroy`.
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source. Line numbers in
this library are 1-based (note that the underlying source map
specification uses 0-based line numbers -- this library handles the
translation).
* `column`: The column number in the generated source. Column numbers
in this library are 0-based.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available. The line number is 1-based.
* `column`: The column number in the original source, or null if this
information is not available. The column number is 0-based.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: Optional. The column number in the original source. The
column number is 0-based.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line. The line number is 1-based.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column. The column number
is 0-based.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
const consumer = await new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
const node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,100 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
class ArraySet {
constructor() {
this._array = [];
this._set = new Map();
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
static fromArray(aArray, aAllowDuplicates) {
const set = new ArraySet();
for (let i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
}
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
size() {
return this._set.size;
}
/**
* Add the given string to this set.
*
* @param String aStr
*/
add(aStr, aAllowDuplicates) {
const isDuplicate = this.has(aStr);
const idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set.set(aStr, idx);
}
}
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
has(aStr) {
return this._set.has(aStr);
}
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
indexOf(aStr) {
const idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
throw new Error('"' + aStr + '" is not in the set.');
}
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error("No element indexed by " + aIdx);
}
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
toArray() {
return this._array.slice();
}
}
exports.ArraySet = ArraySet;

View File

@@ -0,0 +1,111 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
const base64 = require("./base64");
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
const VLQ_BASE_SHIFT = 5;
// binary: 100000
const VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
const VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
const VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
// eslint-disable-next-line no-unused-vars
function fromVLQSigned(aValue) {
const isNegative = (aValue & 1) === 1;
const shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
let encoded = "";
let digit;
let vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};

View File

@@ -0,0 +1,18 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
const intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function(number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};

View File

@@ -0,0 +1,107 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
const mid = Math.floor((aHigh - aLow) / 2) + aLow;
const cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
} else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
}
return mid;
}
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
}
return aLow < 0 ? -1 : aLow;
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};

View File

@@ -0,0 +1,80 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
const util = require("./util");
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
const lineA = mappingA.generatedLine;
const lineB = mappingB.generatedLine;
const columnA = mappingA.generatedColumn;
const columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a negligible overhead in general
* case for a large speedup in case of mappings being added in order.
*/
class MappingList {
constructor() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
unsortedForEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
}
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
}
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
}
}
exports.MappingList = MappingList;

Binary file not shown.

View File

@@ -0,0 +1,40 @@
if (typeof fetch === "function") {
// Web version of reading a wasm file into an array buffer.
let mappingsWasmUrl = null;
module.exports = function readWasm() {
if (typeof mappingsWasmUrl !== "string") {
throw new Error("You must provide the URL of lib/mappings.wasm by calling " +
"SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) " +
"before using SourceMapConsumer");
}
return fetch(mappingsWasmUrl)
.then(response => response.arrayBuffer());
};
module.exports.initialize = url => mappingsWasmUrl = url;
} else {
// Node version of reading a wasm file into an array buffer.
const fs = require("fs");
const path = require("path");
module.exports = function readWasm() {
return new Promise((resolve, reject) => {
const wasmPath = path.join(__dirname, "mappings.wasm");
fs.readFile(wasmPath, null, (error, data) => {
if (error) {
reject(error);
return;
}
resolve(data.buffer);
});
});
};
module.exports.initialize = _ => {
console.debug("SourceMapConsumer.initialize is a no-op when running in node.js");
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,413 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
const base64VLQ = require("./base64-vlq");
const util = require("./util");
const ArraySet = require("./array-set").ArraySet;
const MappingList = require("./mapping-list").MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
class SourceMapGenerator {
constructor(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, "file", null);
this._sourceRoot = util.getArg(aArgs, "sourceRoot", null);
this._skipValidation = util.getArg(aArgs, "skipValidation", false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
static fromSourceMap(aSourceMapConsumer) {
const sourceRoot = aSourceMapConsumer.sourceRoot;
const generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot
});
aSourceMapConsumer.eachMapping(function(mapping) {
const newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function(sourceFile) {
let sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util.relative(sourceRoot, sourceFile);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
const content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
}
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
addMapping(aArgs) {
const generated = util.getArg(aArgs, "generated");
const original = util.getArg(aArgs, "original", null);
let source = util.getArg(aArgs, "source", null);
let name = util.getArg(aArgs, "name", null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source,
name
});
}
/**
* Set the source content for a source file.
*/
setSourceContent(aSourceFile, aSourceContent) {
let source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
}
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
let sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(
"SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, " +
'or the source map\'s "file" property. Both were omitted.'
);
}
sourceFile = aSourceMapConsumer.file;
}
const sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
const newSources = this._mappings.toArray().length > 0
? new ArraySet()
: this._sources;
const newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function(mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
const original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source);
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
const source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
const name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function(srcFile) {
const content = aSourceMapConsumer.sourceContentFor(srcFile);
if (content != null) {
if (aSourceMapPath != null) {
srcFile = util.join(aSourceMapPath, srcFile);
}
if (sourceRoot != null) {
srcFile = util.relative(sourceRoot, srcFile);
}
this.setSourceContent(srcFile, content);
}
}, this);
}
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
_validateMapping(aGenerated, aOriginal, aSource, aName) {
// When aOriginal is truthy but has empty values for .line and .column,
// it is most likely a programmer error. In this case we throw a very
// specific error message to try to guide them the right way.
// For example: https://github.com/Polymer/polymer-bundler/pull/519
if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
throw new Error(
"original.line and original.column are not numbers -- you probably meant to omit " +
"the original mapping entirely and only map the generated position. If so, pass " +
"null for the original mapping instead of an object with empty or null values."
);
}
if (aGenerated && "line" in aGenerated && "column" in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
} else if (aGenerated && "line" in aGenerated && "column" in aGenerated
&& aOriginal && "line" in aOriginal && "column" in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
} else {
throw new Error("Invalid mapping: " + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
}
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
_serializeMappings() {
let previousGeneratedColumn = 0;
let previousGeneratedLine = 1;
let previousOriginalColumn = 0;
let previousOriginalLine = 0;
let previousName = 0;
let previousSource = 0;
let result = "";
let next;
let mapping;
let nameIdx;
let sourceIdx;
const mappings = this._mappings.toArray();
for (let i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = "";
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ";";
previousGeneratedLine++;
}
} else if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ",";
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
}
_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function(source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
const key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
}
/**
* Externalize the source map.
*/
toJSON() {
const map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
}
/**
* Render the source map being generated to a string.
*/
toString() {
return JSON.stringify(this.toJSON());
}
}
SourceMapGenerator.prototype._version = 3;
exports.SourceMapGenerator = SourceMapGenerator;

View File

@@ -0,0 +1,404 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
const SourceMapGenerator = require("./source-map-generator").SourceMapGenerator;
const util = require("./util");
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
const REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
const NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
const isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
class SourceNode {
constructor(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
static fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
const node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are accessed by calling `shiftNextLine`.
const remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
let remainingLinesIndex = 0;
const shiftNextLine = function() {
const lineContents = getNextLine();
// The last line of a file might not have a newline.
const newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
};
// We need to remember the position of "remainingLines"
let lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
let lastMapping = null;
let nextLine;
aSourceMapConsumer.eachMapping(function(mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
nextLine = remainingLines[remainingLinesIndex] || "";
const code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
nextLine = remainingLines[remainingLinesIndex] || "";
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLinesIndex < remainingLines.length) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.splice(remainingLinesIndex).join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function(sourceFile) {
const content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
const source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
}
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function(chunk) {
this.add(chunk);
}, this);
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
} else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
}
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (let i = aChunk.length - 1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
} else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
}
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
walk(aFn) {
let chunk;
for (let i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
} else if (chunk !== "") {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
join(aSep) {
let newChildren;
let i;
const len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len - 1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
}
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
replaceRight(aPattern, aReplacement) {
const lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
} else if (typeof lastChild === "string") {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
} else {
this.children.push("".replace(aPattern, aReplacement));
}
return this;
}
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
}
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
walkSourceContents(aFn) {
for (let i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
const sources = Object.keys(this.sourceContents);
for (let i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
}
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
toString() {
let str = "";
this.walk(function(chunk) {
str += chunk;
});
return str;
}
/**
* Returns the string representation of this source node along with a source
* map.
*/
toStringWithSourceMap(aArgs) {
const generated = {
code: "",
line: 1,
column: 0
};
const map = new SourceMapGenerator(aArgs);
let sourceMappingActive = false;
let lastOriginalSource = null;
let lastOriginalLine = null;
let lastOriginalColumn = null;
let lastOriginalName = null;
this.walk(function(chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if (lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (let idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function(sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map };
}
}
exports.SourceNode = SourceNode;

546
node_modules/terser/node_modules/source-map/lib/util.js generated vendored Normal file
View File

@@ -0,0 +1,546 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
}
throw new Error('"' + aName + '" is a required argument.');
}
exports.getArg = getArg;
const urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
const dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
const match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
let url = "";
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ":";
}
url += "//";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@";
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port;
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
const MAX_CACHED_INPUTS = 32;
/**
* Takes some function `f(input) -> result` and returns a memoized version of
* `f`.
*
* We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
* memoization is a dumb-simple, linear least-recently-used cache.
*/
function lruMemoize(f) {
const cache = [];
return function(input) {
for (let i = 0; i < cache.length; i++) {
if (cache[i].input === input) {
const temp = cache[0];
cache[0] = cache[i];
cache[i] = temp;
return cache[0].result;
}
}
const result = f(input);
cache.unshift({
input,
result,
});
if (cache.length > MAX_CACHED_INPUTS) {
cache.pop();
}
return result;
};
}
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
const normalize = lruMemoize(function normalize(aPath) {
let path = aPath;
const url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
const isAbsolute = exports.isAbsolute(path);
// Split the path into parts between `/` characters. This is much faster than
// using `.split(/\/+/g)`.
const parts = [];
let start = 0;
let i = 0;
while (true) {
start = i;
i = path.indexOf("/", start);
if (i === -1) {
parts.push(path.slice(start));
break;
} else {
parts.push(path.slice(start, i));
while (i < path.length && path[i] === "/") {
i++;
}
}
}
let up = 0;
for (i = parts.length - 1; i >= 0; i--) {
const part = parts[i];
if (part === ".") {
parts.splice(i, 1);
} else if (part === "..") {
up++;
} else if (up > 0) {
if (part === "") {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join("/");
if (path === "") {
path = isAbsolute ? "/" : ".";
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
});
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
const aPathUrl = urlParse(aPath);
const aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || "/";
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
const joined = aPath.charAt(0) === "/"
? aPath
: normalize(aRoot.replace(/\/+$/, "") + "/" + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function(aPath) {
return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, "");
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
let level = 0;
while (aPath.indexOf(aRoot + "/") !== 0) {
const index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
const supportsNullProto = (function() {
const obj = Object.create(null);
return !("__proto__" in obj);
}());
function identity(s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return "$" + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
const length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
/* eslint-disable no-multi-spaces */
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
/* eslint-enable no-multi-spaces */
for (let i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
let cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
let cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 === null) {
return 1; // aStr2 !== null
}
if (aStr2 === null) {
return -1; // aStr1 !== null
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
let cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
/**
* Strip any JSON XSSI avoidance prefix from the string (as documented
* in the source maps specification), and then parse the string as
* JSON.
*/
function parseSourceMapInput(str) {
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
}
exports.parseSourceMapInput = parseSourceMapInput;
/**
* Compute the URL of a source given the the source root, the source's
* URL, and the source map's URL.
*/
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
sourceURL = sourceURL || "";
if (sourceRoot) {
// This follows what Chrome does.
if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
sourceRoot += "/";
}
// The spec says:
// Line 4: An optional source root, useful for relocating source
// files on a server or removing repeated values in the
// “sources” entry. This value is prepended to the individual
// entries in the “source” field.
sourceURL = sourceRoot + sourceURL;
}
// Historically, SourceMapConsumer did not take the sourceMapURL as
// a parameter. This mode is still somewhat supported, which is why
// this code block is conditional. However, it's preferable to pass
// the source map URL to SourceMapConsumer, so that this function
// can implement the source URL resolution algorithm as outlined in
// the spec. This block is basically the equivalent of:
// new URL(sourceURL, sourceMapURL).toString()
// ... except it avoids using URL, which wasn't available in the
// older releases of node still supported by this library.
//
// The spec says:
// If the sources are not absolute URLs after prepending of the
// “sourceRoot”, the sources are resolved relative to the
// SourceMap (like resolving script src in a html document).
if (sourceMapURL) {
const parsed = urlParse(sourceMapURL);
if (!parsed) {
throw new Error("sourceMapURL could not be parsed");
}
if (parsed.path) {
// Strip the last path component, but keep the "/".
const index = parsed.path.lastIndexOf("/");
if (index >= 0) {
parsed.path = parsed.path.substring(0, index + 1);
}
}
sourceURL = join(urlGenerate(parsed), sourceURL);
}
return normalize(sourceURL);
}
exports.computeSourceURL = computeSourceURL;

107
node_modules/terser/node_modules/source-map/lib/wasm.js generated vendored Normal file
View File

@@ -0,0 +1,107 @@
const readWasm = require("../lib/read-wasm");
/**
* Provide the JIT with a nice shape / hidden class.
*/
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.lastGeneratedColumn = null;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
let cachedWasm = null;
module.exports = function wasm() {
if (cachedWasm) {
return cachedWasm;
}
const callbackStack = [];
cachedWasm = readWasm().then(buffer => {
return WebAssembly.instantiate(buffer, {
env: {
mapping_callback(
generatedLine,
generatedColumn,
hasLastGeneratedColumn,
lastGeneratedColumn,
hasOriginal,
source,
originalLine,
originalColumn,
hasName,
name
) {
const mapping = new Mapping();
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.generatedLine = generatedLine + 1;
mapping.generatedColumn = generatedColumn;
if (hasLastGeneratedColumn) {
// JS uses inclusive last generated column, wasm uses exclusive.
mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
}
if (hasOriginal) {
mapping.source = source;
// JS uses 1-based line numbers, wasm uses 0-based.
mapping.originalLine = originalLine + 1;
mapping.originalColumn = originalColumn;
if (hasName) {
mapping.name = name;
}
}
callbackStack[callbackStack.length - 1](mapping);
},
start_all_generated_locations_for() { console.time("all_generated_locations_for"); },
end_all_generated_locations_for() { console.timeEnd("all_generated_locations_for"); },
start_compute_column_spans() { console.time("compute_column_spans"); },
end_compute_column_spans() { console.timeEnd("compute_column_spans"); },
start_generated_location_for() { console.time("generated_location_for"); },
end_generated_location_for() { console.timeEnd("generated_location_for"); },
start_original_location_for() { console.time("original_location_for"); },
end_original_location_for() { console.timeEnd("original_location_for"); },
start_parse_mappings() { console.time("parse_mappings"); },
end_parse_mappings() { console.timeEnd("parse_mappings"); },
start_sort_by_generated_location() { console.time("sort_by_generated_location"); },
end_sort_by_generated_location() { console.timeEnd("sort_by_generated_location"); },
start_sort_by_original_location() { console.time("sort_by_original_location"); },
end_sort_by_original_location() { console.timeEnd("sort_by_original_location"); },
}
});
}).then(Wasm => {
return {
exports: Wasm.instance.exports,
withMappingCallback: (mappingCallback, f) => {
callbackStack.push(mappingCallback);
try {
f();
} finally {
callbackStack.pop();
}
}
};
}).then(null, e => {
cachedWasm = null;
throw e;
});
return cachedWasm;
};

View File

@@ -0,0 +1,229 @@
{
"_from": "source-map@~0.7.2",
"_id": "source-map@0.7.3",
"_inBundle": false,
"_integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==",
"_location": "/terser/source-map",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "source-map@~0.7.2",
"name": "source-map",
"escapedName": "source-map",
"rawSpec": "~0.7.2",
"saveSpec": null,
"fetchSpec": "~0.7.2"
},
"_requiredBy": [
"/terser"
],
"_resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz",
"_shasum": "5302f8169031735226544092e64981f751750383",
"_spec": "source-map@~0.7.2",
"_where": "D:\\Projects\\minifyfromhtml\\node_modules\\terser",
"author": {
"name": "Nick Fitzgerald",
"email": "nfitzgerald@mozilla.com"
},
"bugs": {
"url": "https://github.com/mozilla/source-map/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Tobias Koppers",
"email": "tobias.koppers@googlemail.com"
},
{
"name": "Duncan Beevers",
"email": "duncan@dweebd.com"
},
{
"name": "Stephen Crane",
"email": "scrane@mozilla.com"
},
{
"name": "Ryan Seddon",
"email": "seddon.ryan@gmail.com"
},
{
"name": "Miles Elam",
"email": "miles.elam@deem.com"
},
{
"name": "Mihai Bazon",
"email": "mihai.bazon@gmail.com"
},
{
"name": "Michael Ficarra",
"email": "github.public.email@michael.ficarra.me"
},
{
"name": "Todd Wolfson",
"email": "todd@twolfson.com"
},
{
"name": "Alexander Solovyov",
"email": "alexander@solovyov.net"
},
{
"name": "Felix Gnass",
"email": "fgnass@gmail.com"
},
{
"name": "Conrad Irwin",
"email": "conrad.irwin@gmail.com"
},
{
"name": "usrbincc",
"email": "usrbincc@yahoo.com"
},
{
"name": "David Glasser",
"email": "glasser@davidglasser.net"
},
{
"name": "Chase Douglas",
"email": "chase@newrelic.com"
},
{
"name": "Evan Wallace",
"email": "evan.exe@gmail.com"
},
{
"name": "Heather Arthur",
"email": "fayearthur@gmail.com"
},
{
"name": "Hugh Kennedy",
"email": "hughskennedy@gmail.com"
},
{
"name": "David Glasser",
"email": "glasser@davidglasser.net"
},
{
"name": "Simon Lydell",
"email": "simon.lydell@gmail.com"
},
{
"name": "Jmeas Smith",
"email": "jellyes2@gmail.com"
},
{
"name": "Michael Z Goddard",
"email": "mzgoddard@gmail.com"
},
{
"name": "azu",
"email": "azu@users.noreply.github.com"
},
{
"name": "John Gozde",
"email": "john@gozde.ca"
},
{
"name": "Adam Kirkton",
"email": "akirkton@truefitinnovation.com"
},
{
"name": "Chris Montgomery",
"email": "christopher.montgomery@dowjones.com"
},
{
"name": "J. Ryan Stinnett",
"email": "jryans@gmail.com"
},
{
"name": "Jack Herrington",
"email": "jherrington@walmartlabs.com"
},
{
"name": "Chris Truter",
"email": "jeffpalentine@gmail.com"
},
{
"name": "Daniel Espeset",
"email": "daniel@danielespeset.com"
},
{
"name": "Jamie Wong",
"email": "jamie.lf.wong@gmail.com"
},
{
"name": "Eddy Bruël",
"email": "ejpbruel@mozilla.com"
},
{
"name": "Hawken Rives",
"email": "hawkrives@gmail.com"
},
{
"name": "Gilad Peleg",
"email": "giladp007@gmail.com"
},
{
"name": "djchie",
"email": "djchie.dev@gmail.com"
},
{
"name": "Gary Ye",
"email": "garysye@gmail.com"
},
{
"name": "Nicolas Lalevée",
"email": "nicolas.lalevee@hibnet.org"
}
],
"deprecated": false,
"description": "Generates and consumes source maps",
"devDependencies": {
"doctoc": "^0.15.0",
"eslint": "^4.19.1",
"live-server": "^1.2.0",
"npm-run-all": "^4.1.2",
"nyc": "^11.7.1",
"watch": "^1.0.2",
"webpack": "^3.10"
},
"engines": {
"node": ">= 8"
},
"files": [
"source-map.js",
"source-map.d.ts",
"lib/",
"dist/source-map.js"
],
"homepage": "https://github.com/mozilla/source-map",
"license": "BSD-3-Clause",
"main": "./source-map.js",
"name": "source-map",
"nyc": {
"reporter": "html"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/mozilla/source-map.git"
},
"scripts": {
"build": "webpack --color",
"clean": "rm -rf coverage .nyc_output",
"coverage": "nyc node test/run-tests.js",
"dev": "npm-run-all -p --silent dev:*",
"dev:live": "live-server --port=4103 --ignorePattern='(js|css|png)$' coverage",
"dev:watch": "watch 'npm run coverage' lib/ test/",
"lint": "eslint *.js lib/ test/",
"prebuild": "npm run lint",
"precoverage": "npm run build",
"predev": "npm run setup",
"pretest": "npm run build",
"setup": "mkdir -p coverage && cp -n .waiting.html coverage/index.html || true",
"test": "node test/run-tests.js",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"types": "./source-map.d.ts",
"typings": "source-map",
"version": "0.7.3"
}

View File

@@ -0,0 +1,369 @@
// Type definitions for source-map 0.7
// Project: https://github.com/mozilla/source-map
// Definitions by: Morten Houston Ludvigsen <https://github.com/MortenHoustonLudvigsen>,
// Ron Buckton <https://github.com/rbuckton>,
// John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/mozilla/source-map
export type SourceMapUrl = string;
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
skipValidation?: boolean;
}
export interface RawSourceMap {
version: number;
sources: string[];
names: string[];
sourceRoot?: string;
sourcesContent?: string[];
mappings: string;
file: string;
}
export interface RawIndexMap extends StartOfSourceMap {
version: number;
sections: RawSection[];
}
export interface RawSection {
offset: Position;
map: RawSourceMap;
}
export interface Position {
line: number;
column: number;
}
export interface NullablePosition {
line: number | null;
column: number | null;
lastColumn: number | null;
}
export interface MappedPosition {
source: string;
line: number;
column: number;
name?: string;
}
export interface NullableMappedPosition {
source: string | null;
line: number | null;
column: number | null;
name: string | null;
}
export interface MappingItem {
source: string;
generatedLine: number;
generatedColumn: number;
originalLine: number;
originalColumn: number;
name: string;
}
export interface Mapping {
generated: Position;
original: Position;
source: string;
name?: string;
}
export interface CodeWithSourceMap {
code: string;
map: SourceMapGenerator;
}
export interface SourceMapConsumer {
/**
* Compute the last column for each generated mapping. The last column is
* inclusive.
*/
computeColumnSpans(): void;
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
originalPositionFor(generatedPosition: Position & { bias?: number }): NullableMappedPosition;
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
generatedPositionFor(originalPosition: MappedPosition & { bias?: number }): NullablePosition;
/**
* Returns all generated line and column information for the original source,
* line, and column provided. If no column is provided, returns all mappings
* corresponding to a either the line we are searching for or the next
* closest line that has any mappings. Otherwise, returns all mappings
* corresponding to the given line and either the column we are searching for
* or the next closest column that has any offsets.
*
* The only argument is an object with the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: Optional. the column number in the original source.
*
* and an array of objects is returned, each with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
allGeneratedPositionsFor(originalPosition: MappedPosition): NullablePosition[];
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
hasContentsOfAllSources(): boolean;
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param callback
* The function that is called with each mapping.
* @param context
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param order
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
/**
* Free this source map consumer's associated wasm data that is manually-managed.
* Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy.
*/
destroy(): void;
}
export interface SourceMapConsumerConstructor {
prototype: SourceMapConsumer;
GENERATED_ORDER: number;
ORIGINAL_ORDER: number;
GREATEST_LOWER_BOUND: number;
LEAST_UPPER_BOUND: number;
new (rawSourceMap: RawSourceMap, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer>;
new (rawSourceMap: RawIndexMap, sourceMapUrl?: SourceMapUrl): Promise<IndexedSourceMapConsumer>;
new (rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer | IndexedSourceMapConsumer>;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param sourceMap
* The source map that will be consumed.
*/
fromSourceMap(sourceMap: SourceMapGenerator, sourceMapUrl?: SourceMapUrl): Promise<BasicSourceMapConsumer>;
/**
* Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
* (see the `SourceMapConsumer` constructor for details. Then, invoke the `async
* function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
* for `f` to complete, call `destroy` on the consumer, and return `f`'s return
* value.
*
* You must not use the consumer after `f` completes!
*
* By using `with`, you do not have to remember to manually call `destroy` on
* the consumer, since it will be called automatically once `f` completes.
*
* ```js
* const xSquared = await SourceMapConsumer.with(
* myRawSourceMap,
* null,
* async function (consumer) {
* // Use `consumer` inside here and don't worry about remembering
* // to call `destroy`.
*
* const x = await whatever(consumer);
* return x * x;
* }
* );
*
* // You may not use that `consumer` anymore out here; it has
* // been destroyed. But you can use `xSquared`.
* console.log(xSquared);
* ```
*/
with<T>(rawSourceMap: RawSourceMap | RawIndexMap | string, sourceMapUrl: SourceMapUrl | null | undefined, callback: (consumer: BasicSourceMapConsumer | IndexedSourceMapConsumer) => Promise<T> | T): Promise<T>;
}
export const SourceMapConsumer: SourceMapConsumerConstructor;
export interface BasicSourceMapConsumer extends SourceMapConsumer {
file: string;
sourceRoot: string;
sources: string[];
sourcesContent: string[];
}
export interface BasicSourceMapConsumerConstructor {
prototype: BasicSourceMapConsumer;
new (rawSourceMap: RawSourceMap | string): Promise<BasicSourceMapConsumer>;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param sourceMap
* The source map that will be consumed.
*/
fromSourceMap(sourceMap: SourceMapGenerator): Promise<BasicSourceMapConsumer>;
}
export const BasicSourceMapConsumer: BasicSourceMapConsumerConstructor;
export interface IndexedSourceMapConsumer extends SourceMapConsumer {
sources: string[];
}
export interface IndexedSourceMapConsumerConstructor {
prototype: IndexedSourceMapConsumer;
new (rawSourceMap: RawIndexMap | string): Promise<IndexedSourceMapConsumer>;
}
export const IndexedSourceMapConsumer: IndexedSourceMapConsumerConstructor;
export class SourceMapGenerator {
constructor(startOfSourceMap?: StartOfSourceMap);
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param sourceMapConsumer The SourceMap.
*/
static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator;
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
addMapping(mapping: Mapping): void;
/**
* Set the source content for a source file.
*/
setSourceContent(sourceFile: string, sourceContent: string): void;
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param sourceMapConsumer The source map to be applied.
* @param sourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param sourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
toString(): string;
toJSON(): RawSourceMap;
}
export class SourceNode {
children: SourceNode[];
sourceContents: any;
line: number;
column: number;
source: string;
name: string;
constructor();
constructor(
line: number | null,
column: number | null,
source: string | null,
chunks?: Array<(string | SourceNode)> | SourceNode | string,
name?: string
);
static fromStringWithSourceMap(
code: string,
sourceMapConsumer: SourceMapConsumer,
relativePath?: string
): SourceNode;
add(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode;
prepend(chunk: Array<(string | SourceNode)> | SourceNode | string): SourceNode;
setSourceContent(sourceFile: string, sourceContent: string): void;
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
walkSourceContents(fn: (file: string, content: string) => void): void;
join(sep: string): SourceNode;
replaceRight(pattern: string, replacement: string): SourceNode;
toString(): string;
toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
}

View File

@@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require("./lib/source-map-generator").SourceMapGenerator;
exports.SourceMapConsumer = require("./lib/source-map-consumer").SourceMapConsumer;
exports.SourceNode = require("./lib/source-node").SourceNode;

85
node_modules/terser/package.json generated vendored
View File

@@ -1,26 +1,27 @@
{
"_from": "terser@^4.8.0",
"_id": "terser@4.8.0",
"_from": "terser@5.7.0",
"_id": "terser@5.7.0",
"_inBundle": false,
"_integrity": "sha512-EAPipTNeWsb/3wLPeup1tVPaXfIaU68xMnVdPafIL1TV05OhASArYyIfFvnvJCNrR2NIOvDVNNTFRa+Re2MWyw==",
"_integrity": "sha512-HP5/9hp2UaZt5fYkuhNBR8YyRcT8juw8+uFbAme53iN9hblvKnLUTKkmwJG6ocWpIKf8UK4DoeWG4ty0J6S6/g==",
"_location": "/terser",
"_phantomChildren": {},
"_requested": {
"type": "range",
"type": "version",
"registry": true,
"raw": "terser@^4.8.0",
"raw": "terser@5.7.0",
"name": "terser",
"escapedName": "terser",
"rawSpec": "^4.8.0",
"rawSpec": "5.7.0",
"saveSpec": null,
"fetchSpec": "^4.8.0"
"fetchSpec": "5.7.0"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/terser/-/terser-4.8.0.tgz",
"_shasum": "63056343d7c70bb29f3af665865a46fe03a0df17",
"_spec": "terser@^4.8.0",
"_resolved": "https://registry.npmjs.org/terser/-/terser-5.7.0.tgz",
"_shasum": "a761eeec206bc87b605ab13029876ead938ae693",
"_spec": "terser@5.7.0",
"_where": "D:\\Projects\\minifyfromhtml",
"author": {
"name": "Mihai Bazon",
@@ -36,33 +37,36 @@
"bundleDependencies": false,
"dependencies": {
"commander": "^2.20.0",
"source-map": "~0.6.1",
"source-map-support": "~0.5.12"
"source-map": "~0.7.2",
"source-map-support": "~0.5.19"
},
"deprecated": false,
"description": "JavaScript parser, mangler/compressor and beautifier toolkit for ES6+",
"devDependencies": {
"acorn": "^7.1.1",
"astring": "^1.4.1",
"eslint": "^6.3.0",
"@ls-lint/ls-lint": "^1.9.2",
"acorn": "^8.0.5",
"astring": "^1.6.2",
"eslint": "^7.19.0",
"eslump": "^2.0.0",
"mocha": "^7.1.2",
"mochallel": "^2.0.0",
"esm": "^3.2.25",
"mocha": "^8.2.1",
"pre-commit": "^1.2.2",
"rimraf": "^3.0.0",
"rollup": "2.0.6",
"rollup-plugin-terser": "5.3.0",
"semver": "^7.1.3"
"rimraf": "^3.0.2",
"rollup": "2.38.4",
"semver": "^7.3.4"
},
"engines": {
"node": ">=6.0.0"
"node": ">=10"
},
"eslintConfig": {
"parserOptions": {
"sourceType": "module"
"sourceType": "module",
"ecmaVersion": "2020"
},
"env": {
"es6": true
"node": true,
"browser": true,
"es2020": true
},
"globals": {
"describe": false,
@@ -89,7 +93,7 @@
"no-unused-vars": [
"error",
{
"varsIgnorePattern": "^_$"
"varsIgnorePattern": "^_"
}
],
"no-tabs": "error",
@@ -105,14 +109,28 @@
]
}
},
"exports": {
".": [
{
"import": "./main.js",
"require": "./dist/bundle.min.js"
},
"./dist/bundle.min.js"
],
"./package": "./package.json",
"./package.json": "./package.json",
"./bin/terser": "./bin/terser"
},
"files": [
"bin",
"dist",
"lib",
"tools",
"LICENSE",
"README.md",
"CHANGELOG.md",
"PATRONS.md"
"PATRONS.md",
"main.js"
],
"homepage": "https://terser.org",
"keywords": [
@@ -142,9 +160,12 @@
"email": "fabiosantosart@gmail.com"
}
],
"module": "./main.js",
"name": "terser",
"pre-commit": [
"build",
"lint-fix",
"ls-lint",
"test"
],
"repository": {
@@ -152,15 +173,17 @@
"url": "git+https://github.com/terser/terser.git"
},
"scripts": {
"build": "rimraf dist/* && rollup --config --silent",
"build": "rimraf dist/bundle* && rollup --config --silent",
"lint": "eslint lib",
"lint-fix": "eslint --fix lib",
"ls-lint": "ls-lint",
"postversion": "echo 'Remember to update the changelog!'",
"prepare": "npm run build",
"test": "npm run build -- --configTest && node test/run-tests.js",
"test:compress": "npm run build -- --configTest && node test/compress.js",
"test:mocha": "npm run build -- --configTest && node test/mocha.js"
"test": "node test/compress.js && mocha test/mocha",
"test:compress": "node test/compress.js",
"test:mocha": "mocha test/mocha"
},
"type": "module",
"types": "tools/terser.d.ts",
"version": "4.8.0"
"version": "5.7.0"
}

View File

@@ -1,11 +0,0 @@
"use strict"
if (Number((/([0-9]+)\./.exec(process.version) || [])[1]) >= 10) {
var Console = require("console").Console;
global.console = new Console({
stdout: process.stdout,
stderr: process.stderr,
colorMode: false
});
}

2154
node_modules/terser/tools/domprops.js generated vendored

File diff suppressed because it is too large Load Diff

7
node_modules/terser/tools/exit.cjs generated vendored Normal file
View File

@@ -0,0 +1,7 @@
// workaround for tty output truncation upon process.exit()
// https://github.com/nodejs/node/issues/6456
[process.stdout, process.stderr].forEach((s) => {
s && s.isTTY && s._handle && s._handle.setBlocking &&
s._handle.setBlocking(true)
});

15
node_modules/terser/tools/exit.js generated vendored
View File

@@ -1,15 +0,0 @@
// workaround for tty output truncation upon process.exit()
var exit = process.exit;
process.exit = function() {
var args = [].slice.call(arguments);
process.once("uncaughtException", function() {
(function callback() {
if (process.stdout.bufferSize || process.stderr.bufferSize) {
setImmediate(callback);
} else {
exit.apply(process, args);
}
})();
});
throw exit;
};

19
node_modules/terser/tools/node.js generated vendored
View File

@@ -1,19 +0,0 @@
import { minify } from "../lib/minify";
export function default_options() {
const defs = {};
Object.keys(infer_options({ 0: 0 })).forEach((component) => {
const options = infer_options({
[component]: {0: 0}
});
if (options) defs[component] = options;
});
return defs;
}
function infer_options(options) {
var result = minify("", options);
return result.error && result.error.defs;
}

640
node_modules/terser/tools/terser.d.ts generated vendored
View File

@@ -2,10 +2,7 @@
import { RawSourceMap } from 'source-map';
/** @deprecated since this versions basically do not exist */
type ECMA_UNOFFICIAL = 6 | 7 | 8 | 9 | 10 | 11;
export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | ECMA_UNOFFICIAL;
export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020;
export interface ParseOptions {
bare_returns?: boolean;
@@ -69,7 +66,6 @@ export interface CompressOptions {
unsafe_regexp?: boolean;
unsafe_undefined?: boolean;
unused?: boolean;
warnings?: boolean;
}
export enum InlineFunctions {
@@ -98,11 +94,12 @@ export interface ManglePropertiesOptions {
reserved?: string[];
}
export interface OutputOptions {
export interface FormatOptions {
ascii_only?: boolean;
/** @deprecated Not implemented anymore */
beautify?: boolean;
braces?: boolean;
comments?: boolean | 'all' | 'some' | RegExp | ( (node: AST_Node, comment: {
comments?: boolean | 'all' | 'some' | RegExp | ( (node: any, comment: {
value: string,
type: 'comment1' | 'comment2' | 'comment3' | 'comment4',
pos: number,
@@ -147,20 +144,18 @@ export interface MinifyOptions {
mangle?: boolean | MangleOptions;
module?: boolean;
nameCache?: object;
output?: OutputOptions;
format?: FormatOptions;
/** @deprecated */
output?: FormatOptions;
parse?: ParseOptions;
safari10?: boolean;
sourceMap?: boolean | SourceMapOptions;
toplevel?: boolean;
warnings?: boolean | 'verbose';
}
export interface MinifyOutput {
ast?: AST_Node;
code?: string;
error?: Error;
map?: RawSourceMap | string;
warnings?: string[];
}
export interface SourceMapOptions {
@@ -172,623 +167,4 @@ export interface SourceMapOptions {
url?: string | 'inline';
}
declare function parse(text: string, options?: ParseOptions): AST_Node;
export class TreeWalker {
constructor(callback: (node: AST_Node, descend?: (node: AST_Node) => void) => boolean | undefined);
directives: object;
find_parent(type: AST_Node): AST_Node | undefined;
has_directive(type: string): boolean;
loopcontrol_target(node: AST_Node): AST_Node | undefined;
parent(n: number): AST_Node | undefined;
pop(): void;
push(node: AST_Node): void;
self(): AST_Node | undefined;
stack: AST_Node[];
visit: (node: AST_Node, descend: boolean) => any;
}
export class TreeTransformer extends TreeWalker {
constructor(
before: (node: AST_Node, descend?: (node: AST_Node, tw: TreeWalker) => void, in_list?: boolean) => AST_Node | undefined,
after?: (node: AST_Node, in_list?: boolean) => AST_Node | undefined
);
before: (node: AST_Node) => AST_Node;
after?: (node: AST_Node) => AST_Node;
}
export function push_uniq<T>(array: T[], el: T): void;
export function minify(files: string | string[] | { [file: string]: string } | AST_Node, options?: MinifyOptions): MinifyOutput;
export class AST_Node {
constructor(props?: object);
static BASE?: AST_Node;
static PROPS: string[];
static SELF_PROPS: string[];
static SUBCLASSES: AST_Node[];
static documentation: string;
static propdoc?: Record<string, string>;
static expressions?: AST_Node[];
static warn?: (text: string, props: any) => void;
static from_mozilla_ast?: (node: AST_Node) => any;
walk: (visitor: TreeWalker) => void;
print_to_string: (options?: OutputOptions) => string;
transform: (tt: TreeTransformer, in_list?: boolean) => AST_Node;
TYPE: string;
CTOR: typeof AST_Node;
}
declare class SymbolDef {
constructor(scope?: AST_Scope, orig?: object, init?: object);
name: string;
orig: AST_SymbolRef[];
init: AST_SymbolRef;
eliminated: number;
scope: AST_Scope;
references: AST_SymbolRef[];
replaced: number;
global: boolean;
export: boolean;
mangled_name: null | string;
undeclared: boolean;
id: number;
}
type ArgType = AST_SymbolFunarg | AST_DefaultAssign | AST_Destructuring | AST_Expansion;
declare class AST_Statement extends AST_Node {
constructor(props?: object);
}
declare class AST_Debugger extends AST_Statement {
constructor(props?: object);
}
declare class AST_Directive extends AST_Statement {
constructor(props?: object);
value: string;
quote: string;
}
declare class AST_SimpleStatement extends AST_Statement {
constructor(props?: object);
body: AST_Node[];
}
declare class AST_Block extends AST_Statement {
constructor(props?: object);
body: AST_Node[];
block_scope: AST_Scope | null;
}
declare class AST_BlockStatement extends AST_Block {
constructor(props?: object);
}
declare class AST_Scope extends AST_Block {
constructor(props?: object);
variables: any;
functions: any;
uses_with: boolean;
uses_eval: boolean;
parent_scope: AST_Scope | null;
enclosed: any;
cname: any;
}
declare class AST_Toplevel extends AST_Scope {
constructor(props?: object);
globals: any;
}
declare class AST_Lambda extends AST_Scope {
constructor(props?: object);
name: AST_SymbolDeclaration | null;
argnames: ArgType[];
uses_arguments: boolean;
is_generator: boolean;
async: boolean;
}
declare class AST_Accessor extends AST_Lambda {
constructor(props?: object);
}
declare class AST_Function extends AST_Lambda {
constructor(props?: object);
}
declare class AST_Arrow extends AST_Lambda {
constructor(props?: object);
}
declare class AST_Defun extends AST_Lambda {
constructor(props?: object);
}
declare class AST_Class extends AST_Scope {
constructor(props?: object);
name: AST_SymbolClass | AST_SymbolDefClass | null;
extends: AST_Node | null;
properties: AST_ObjectProperty[];
}
declare class AST_DefClass extends AST_Class {
constructor(props?: object);
}
declare class AST_ClassExpression extends AST_Class {
constructor(props?: object);
}
declare class AST_Switch extends AST_Block {
constructor(props?: object);
expression: AST_Node;
}
declare class AST_SwitchBranch extends AST_Block {
constructor(props?: object);
}
declare class AST_Default extends AST_SwitchBranch {
constructor(props?: object);
}
declare class AST_Case extends AST_SwitchBranch {
constructor(props?: object);
expression: AST_Node;
}
declare class AST_Try extends AST_Block {
constructor(props?: object);
bcatch: AST_Catch;
bfinally: null | AST_Finally;
}
declare class AST_Catch extends AST_Block {
constructor(props?: object);
argname: ArgType;
}
declare class AST_Finally extends AST_Block {
constructor(props?: object);
}
declare class AST_EmptyStatement extends AST_Statement {
constructor(props?: object);
}
declare class AST_StatementWithBody extends AST_Statement {
constructor(props?: object);
body: AST_Node[];
}
declare class AST_LabeledStatement extends AST_StatementWithBody {
constructor(props?: object);
label: AST_Label;
}
declare class AST_IterationStatement extends AST_StatementWithBody {
constructor(props?: object);
block_scope: AST_Scope | null;
}
declare class AST_DWLoop extends AST_IterationStatement {
constructor(props?: object);
condition: AST_Node;
}
declare class AST_Do extends AST_DWLoop {
constructor(props?: object);
}
declare class AST_While extends AST_DWLoop {
constructor(props?: object);
}
declare class AST_For extends AST_IterationStatement {
constructor(props?: object);
init: AST_Node | null;
condition: AST_Node | null;
step: AST_Node | null;
}
declare class AST_ForIn extends AST_IterationStatement {
constructor(props?: object);
init: AST_Node | null;
object: AST_Node;
}
declare class AST_ForOf extends AST_ForIn {
constructor(props?: object);
await: boolean;
}
declare class AST_With extends AST_StatementWithBody {
constructor(props?: object);
expression: AST_Node;
}
declare class AST_If extends AST_StatementWithBody {
constructor(props?: object);
condition: AST_Node;
alternative: AST_Node | null;
}
declare class AST_Jump extends AST_Statement {
constructor(props?: object);
}
declare class AST_Exit extends AST_Jump {
constructor(props?: object);
value: AST_Node | null;
}
declare class AST_Return extends AST_Exit {
constructor(props?: object);
}
declare class AST_Throw extends AST_Exit {
constructor(props?: object);
}
declare class AST_LoopControl extends AST_Jump {
constructor(props?: object);
label: null | AST_LabelRef;
}
declare class AST_Break extends AST_LoopControl {
constructor(props?: object);
}
declare class AST_Continue extends AST_LoopControl {
constructor(props?: object);
}
declare class AST_Definitions extends AST_Statement {
constructor(props?: object);
definitions: AST_VarDef[];
}
declare class AST_Var extends AST_Definitions {
constructor(props?: object);
}
declare class AST_Let extends AST_Definitions {
constructor(props?: object);
}
declare class AST_Const extends AST_Definitions {
constructor(props?: object);
}
declare class AST_Export extends AST_Statement {
constructor(props?: object);
exported_definition: AST_Definitions | AST_Lambda | AST_DefClass | null;
exported_value: AST_Node | null;
is_default: boolean;
exported_names: AST_NameMapping[];
module_name: AST_String;
}
declare class AST_Expansion extends AST_Node {
constructor(props?: object);
expression: AST_Node;
}
declare class AST_Destructuring extends AST_Node {
constructor(props?: object);
names: AST_Node[];
is_array: boolean;
}
declare class AST_PrefixedTemplateString extends AST_Node {
constructor(props?: object);
template_string: AST_TemplateString;
prefix: AST_Node;
}
declare class AST_TemplateString extends AST_Node {
constructor(props?: object);
segments: AST_Node[];
}
declare class AST_TemplateSegment extends AST_Node {
constructor(props?: object);
value: string;
raw: string;
}
declare class AST_NameMapping extends AST_Node {
constructor(props?: object);
foreign_name: AST_Symbol;
name: AST_SymbolExport | AST_SymbolImport;
}
declare class AST_Import extends AST_Node {
constructor(props?: object);
imported_name: null | AST_SymbolImport;
imported_names: AST_NameMapping[];
module_name: AST_String;
}
declare class AST_VarDef extends AST_Node {
constructor(props?: object);
name: AST_Destructuring | AST_SymbolConst | AST_SymbolLet | AST_SymbolVar;
value: AST_Node | null;
}
declare class AST_Call extends AST_Node {
constructor(props?: object);
expression: AST_Node;
args: AST_Node[];
}
declare class AST_New extends AST_Call {
constructor(props?: object);
}
declare class AST_Sequence extends AST_Node {
constructor(props?: object);
expressions: AST_Node[];
}
declare class AST_PropAccess extends AST_Node {
constructor(props?: object);
expression: AST_Node;
property: AST_Node | string;
}
declare class AST_Dot extends AST_PropAccess {
constructor(props?: object);
}
declare class AST_Sub extends AST_PropAccess {
constructor(props?: object);
}
declare class AST_Unary extends AST_Node {
constructor(props?: object);
operator: string;
expression: AST_Node;
}
declare class AST_UnaryPrefix extends AST_Unary {
constructor(props?: object);
}
declare class AST_UnaryPostfix extends AST_Unary {
constructor(props?: object);
}
declare class AST_Binary extends AST_Node {
constructor(props?: object);
operator: string;
left: AST_Node;
right: AST_Node;
}
declare class AST_Assign extends AST_Binary {
constructor(props?: object);
}
declare class AST_DefaultAssign extends AST_Binary {
constructor(props?: object);
}
declare class AST_Conditional extends AST_Node {
constructor(props?: object);
condition: AST_Node;
consequent: AST_Node;
alternative: AST_Node;
}
declare class AST_Array extends AST_Node {
constructor(props?: object);
elements: AST_Node[];
}
declare class AST_Object extends AST_Node {
constructor(props?: object);
properties: AST_ObjectProperty[];
}
declare class AST_ObjectProperty extends AST_Node {
constructor(props?: object);
key: string | number | AST_Node;
value: AST_Node;
}
declare class AST_ObjectKeyVal extends AST_ObjectProperty {
constructor(props?: object);
quote: string;
}
declare class AST_ObjectSetter extends AST_ObjectProperty {
constructor(props?: object);
quote: string;
static: boolean;
}
declare class AST_ObjectGetter extends AST_ObjectProperty {
constructor(props?: object);
quote: string;
static: boolean;
}
declare class AST_ConciseMethod extends AST_ObjectProperty {
constructor(props?: object);
quote: string;
static: boolean;
is_generator: boolean;
async: boolean;
}
declare class AST_Symbol extends AST_Node {
constructor(props?: object);
scope: AST_Scope;
name: string;
thedef: SymbolDef;
}
declare class AST_SymbolDeclaration extends AST_Symbol {
constructor(props?: object);
init: AST_Node | null;
}
declare class AST_SymbolVar extends AST_SymbolDeclaration {
constructor(props?: object);
}
declare class AST_SymbolFunarg extends AST_SymbolVar {
constructor(props?: object);
}
declare class AST_SymbolBlockDeclaration extends AST_SymbolDeclaration {
constructor(props?: object);
}
declare class AST_SymbolConst extends AST_SymbolBlockDeclaration {
constructor(props?: object);
}
declare class AST_SymbolLet extends AST_SymbolBlockDeclaration {
constructor(props?: object);
}
declare class AST_SymbolDefClass extends AST_SymbolBlockDeclaration {
constructor(props?: object);
}
declare class AST_SymbolCatch extends AST_SymbolBlockDeclaration {
constructor(props?: object);
}
declare class AST_SymbolImport extends AST_SymbolBlockDeclaration {
constructor(props?: object);
}
declare class AST_SymbolDefun extends AST_SymbolDeclaration {
constructor(props?: object);
}
declare class AST_SymbolLambda extends AST_SymbolDeclaration {
constructor(props?: object);
}
declare class AST_SymbolClass extends AST_SymbolDeclaration {
constructor(props?: object);
}
declare class AST_SymbolMethod extends AST_Symbol {
constructor(props?: object);
}
declare class AST_SymbolImportForeign extends AST_Symbol {
constructor(props?: object);
}
declare class AST_Label extends AST_Symbol {
constructor(props?: object);
references: AST_LoopControl | null;
}
declare class AST_SymbolRef extends AST_Symbol {
constructor(props?: object);
}
declare class AST_SymbolExport extends AST_SymbolRef {
constructor(props?: object);
}
declare class AST_SymbolExportForeign extends AST_Symbol {
constructor(props?: object);
}
declare class AST_LabelRef extends AST_Symbol {
constructor(props?: object);
}
declare class AST_This extends AST_Symbol {
constructor(props?: object);
}
declare class AST_Super extends AST_This {
constructor(props?: object);
}
declare class AST_NewTarget extends AST_Node {
constructor(props?: object);
}
declare class AST_Constant extends AST_Node {
constructor(props?: object);
}
declare class AST_String extends AST_Constant {
constructor(props?: object);
value: string;
quote: string;
}
declare class AST_Number extends AST_Constant {
constructor(props?: object);
value: number;
literal: string;
}
declare class AST_RegExp extends AST_Constant {
constructor(props?: object);
value: {
source: string,
flags: string
};
}
declare class AST_Atom extends AST_Constant {
constructor(props?: object);
}
declare class AST_Null extends AST_Atom {
constructor(props?: object);
}
declare class AST_NaN extends AST_Atom {
constructor(props?: object);
}
declare class AST_Undefined extends AST_Atom {
constructor(props?: object);
}
declare class AST_Hole extends AST_Atom {
constructor(props?: object);
}
declare class AST_Infinity extends AST_Atom {
constructor(props?: object);
}
declare class AST_Boolean extends AST_Atom {
constructor(props?: object);
}
declare class AST_False extends AST_Boolean {
constructor(props?: object);
}
declare class AST_True extends AST_Boolean {
constructor(props?: object);
}
declare class AST_Await extends AST_Node {
constructor(props?: object);
expression: AST_Node;
}
declare class AST_Yield extends AST_Node {
constructor(props?: object);
expression: AST_Node;
is_star: boolean;
}
export function minify(files: string | string[] | { [file: string]: string }, options?: MinifyOptions): Promise<MinifyOutput>;