Compare commits

..

77 Commits

Author SHA1 Message Date
Mihai Bazon
a8e67d157e v2.5.0 2015-10-11 18:24:38 +03:00
kzc
e870c7db45 have minify() call figure_out_scope() if needed to produce well formed "use asm" code 2015-10-07 16:31:57 -04:00
kzc
6500f8c52c get rid of SCOPE_IS_NEEDED as it was always true 2015-10-07 15:33:24 -04:00
kzc
4d2f7d83af Fix handling of "use asm" when no command line flags are passed to uglifyjs. SCOPE_IS_NEEDED is unconditionally true now. Refactored floating point literal parsing to be more in keeping with the AST class design. 2015-10-07 13:10:53 -04:00
SpainTrain
99945fcd04 Pin dependencies with npm shrinkwrap
* Use `npm run shrinkwrap` to create a shrinkwrap file with all dependencies pinned
* Update dependency `source-map` to latest (Closes #738)
2015-10-07 13:52:49 +02:00
kzc
0d952ae43d add asm.js test 2015-10-07 10:00:28 +02:00
kzc
593677d2ff Add proper support for "use asm"; blocks. Disable -c optimization within "use asm"; sections and preserve floating point literals in their original form. Non-asm.js sections are optimized as before. Asm.js sections can still be mangled and minified of whitespace. No special command line flags are required. 2015-10-07 10:00:28 +02:00
Anthony Van de Gejuchte
c69294c449 Implement shebang support 2015-10-06 22:35:45 +02:00
Mihai Bazon
2a06c7758e Merge pull request #808 from avdg/travis
Add node 4.x in Travis
2015-09-24 19:27:54 +03:00
Anthony Van de Gejuchte
7ee1ec91a2 Add node 4.x in Travis 2015-09-24 17:41:52 +02:00
Mihai Bazon
233fb62bd8 Disable node 0.8 in Travis 2015-09-24 18:26:23 +03:00
Mihai Bazon
6637c267a5 Fix mozilla-ast after module loading changes
Need to explicitly qualify stuff now, since it's not evaluated in some
global scope.

Ref #636
2015-09-24 18:13:21 +03:00
Mihai Bazon
99233c44cc No longer use vm to load code.
Improves performance 2x on node > 0.10.

Ref #636
2015-09-24 17:58:51 +03:00
Mihai Bazon
33528002b4 Fix wrap_commonjs to include code first
(code could have directives, i.e. "use strict")
2015-09-24 17:58:51 +03:00
Kyle Mitchell
20542a37a8 use a valid SPDX license identifier 2015-09-14 19:44:49 +02:00
Ville Lautanala
5fd12451f9 Control keeping function arguments with a single option 2015-09-14 19:38:45 +02:00
Richard van Velzen
ba939ccd6c Merge pull request #786 from istr/anonymous-source-map
Allow for anonymous map generation using string type check
2015-09-06 17:06:14 +02:00
Ingo Struck
3a5f354846 allow for anonymous map generation using string type check 2015-08-27 19:38:33 +02:00
Richard van Velzen
fcde6109b0 Fix bad parsing of new new x()() constructs
Fixes #739
2015-08-27 12:29:36 +03:00
Richard van Velzen
e3bd223dac Don't change sequences that influence lexical binding in calls
Fixes #782
2015-08-25 10:53:35 +02:00
Richard van Velzen
6c8db6eae1 Merge pull request #767 from vjeux/208
[Fix] --define replaces SymbolRefs in LHS of assignments
2015-08-10 20:29:37 +02:00
Christopher Chedeau
3ff0b9e0c9 [Fix] --define replaces SymbolRefs in LHS of assignments
See #208 for context
2015-08-10 11:22:36 -07:00
Richard van Velzen
464a942a95 Merge pull request #736 from AlbertoGP/master
fromString option, use index from argument array for filename instead of "?"
2015-08-07 14:12:41 +02:00
Richard van Velzen
d7a4a4a462 Merge pull request #729 from DrewML/keep_fnames_docs
Add keep_fnames compressor option to README.md
2015-08-07 14:11:50 +02:00
Richard van Velzen
759b3f7d6d Fix mangling of property names which overwrite unmangleable properties
Fixes #747.
2015-08-05 21:18:39 +02:00
Richard van Velzen
958b6c2e57 Merge pull request #753 from Surgo/master
Support wrap and exportAll options for node.js tools.
2015-08-05 21:17:42 +02:00
Mihai Bazon
ab15d676d7 Merge pull request #757 from rvanvelzen/semicolon-fix
Fix semicolon printing when restricting max line length
2015-07-30 17:25:13 +03:00
Richard van Velzen
66761d7ecf Fix semicolon printing when restricting max line length
Fixes #755
2015-07-30 16:13:32 +02:00
Richard van Velzen
3afad58a93 Revert "Fix semicolon printing when restricting max line length"
This reverts commit 170e8b519e.
2015-07-30 15:57:18 +02:00
Richard van Velzen
170e8b519e Fix semicolon printing when restricting max line length
Fixes #755
2015-07-29 17:57:18 +02:00
Richard van Velzen
f8684f418a Replace util.puts in run-tests with console.log
See d2dda34b2a
2015-07-29 15:24:45 +02:00
XhmikosR
881bda7f59 Make node.js 0.8 the minimum supported version.
Node.js 0.4 and 0.6 are ancient; things don't work there.
Update Travis CI configuration accordingly.

Note, that the npm update in Travis is needed for 0.8 only at the moment.
2015-07-29 15:21:01 +02:00
Chris Cowan
9854deb626 Re-use the caught exception's error message in the parse error call. 2015-07-29 15:06:52 +02:00
Chris Cowan
d6814050dd Give a good error message if an invalid regular expression is found. 2015-07-29 15:05:59 +02:00
thorn0
252fc65558 Advanced way to specify if a function call might have side effects. #400 2015-07-29 14:36:42 +02:00
Kosei Kitahara
8108c7ffaf Support wrap and exportAll options. 2015-07-28 21:36:22 +09:00
Mihai Bazon
ba9936a572 v2.4.24 2015-07-22 16:58:09 +03:00
Mihai Bazon
905b601178 Don't attempt to negate non-boolean AST_Binary
Fix #751
2015-07-22 16:55:55 +03:00
Mihai Bazon
63fb2d5a44 Merge pull request #735 from kzc/master
optimizations for && and || where left side is constant expression
2015-07-20 09:58:01 +03:00
Mihai Bazon
85a5fc0aeb Don't drop parens in a * (b * c). Close #744 2015-06-30 10:10:29 +03:00
Alberto González Palomo
4fba3e0b80 fromString option, use index from argument array for filename instead of "?"
The index allows the caller to map things like parse errors back to the
code chunk where they appeared.
2015-06-15 18:03:06 +02:00
kzc
9d398d999c spacing 2015-06-14 17:45:19 -04:00
kzc
f47b2b52a5 operator && and || optimization: add "else" before "if" as intended 2015-06-14 17:44:26 -04:00
kzc
fedb6191a1 optimizations for && and || where left side is constant expression 2015-06-11 23:22:38 -04:00
Mihai Bazon
5bf617ebde Merge pull request #733 from jcxplorer/add-mangle-regex-option
Add --mangle-regex option
2015-06-09 16:33:21 +03:00
Joao Carlos
0b82e1cd5b Change --mangle-regex to accept a full regex 2015-06-09 15:14:41 +03:00
Joao Carlos
9aef34a816 Show descriptive error when --mangle-regex is invalid 2015-06-09 14:31:49 +03:00
Joao Carlos
0ac6918a41 Add --mangle-regex option 2015-06-09 14:16:50 +03:00
Andrew Levine
65ee5af78c Add keep_fnames compressor option to README.md 2015-06-02 15:32:10 -05:00
Mihai Bazon
c6fa291571 v2.4.23 2015-05-20 17:48:30 +03:00
Mihai Bazon
bce4307e9e Treat \uFEFF as whitespace.
Fix #714
2015-05-20 16:17:46 +03:00
Mihai Bazon
96ad94ab41 v2.4.22 2015-05-18 13:58:25 +03:00
Mihai Bazon
a5b60217ce Fix compressing conditionals
Only transform foo() ? EXP(x) : EXP(y) into EXP(foo() ? x : y) if EXP has no
side effects.

Fix #710
2015-05-18 13:56:04 +03:00
Mihai Bazon
44fd6694eb fix again reserved props 2015-05-13 22:03:00 +03:00
Mihai Bazon
e48db3a8b6 Make reserved names take priority over the name cache 2015-05-07 15:01:16 +03:00
Mihai Bazon
e637bdaf4e Only drop the BOM when it's the first character.
Close #704
2015-05-05 10:11:38 +03:00
Mihai Bazon
d558abbdb7 v2.4.21 2015-05-04 19:14:42 +03:00
Mihai Bazon
4aed0830e5 Fix blank lines in the output.
The issue was more obvious when max_line_len has a small value, rather than
the default 32K characters.  A blank line showed up after most statements.
2015-05-04 17:55:42 +03:00
Mihai Bazon
d2dda34b2a Remove deprecated calls to utils.print/utils.error
Close #542, #641, #647
2015-05-04 15:07:16 +03:00
Mihai Bazon
c3a10c135e Avoid spurious brackets when dropping unused vars
Fix #702
2015-05-04 14:49:17 +03:00
Mihai Bazon
92e4340732 Fix parsing strings with literal DOS newlines
(should not set newline_before)

Fix #693
2015-04-23 12:08:19 +03:00
Mihai Bazon
7b22f2031f If name_cache is specified, do rename cached properties
(even if --mangle-props is not there)
2015-04-22 17:34:49 +03:00
Mihai Bazon
3b14582d6b Fix tests 2015-04-17 11:28:59 +03:00
Mihai Bazon
274e1b3dc7 Drop NaN -> 0/0 transformation.
Fix #687
2015-04-17 11:26:36 +03:00
Fábio Santos
de58b0289d Added expect_exact for testing the OutputStream
This works almost exactly like `expect`, except that you pass a literal string
of which the result is compared with the generated output.
2015-04-14 20:26:47 +02:00
XhmikosR
efea52a4f4 Normalize package.json.
* Specify the files to install in package.json
* Add missing properties
* Follow `npm init`'s scheme
2015-04-14 20:17:03 +02:00
Jordan Harband
763bd36b60 Test on latest node and io.js
Per 0262b4244c - if you're going to stop testing on 0.8, you should be testing on 0.12.

Also allow failures on unstable nodes and "older than two latest" `io.js` versions, and enable "sudo: false" which makes tests run faster.
2015-04-14 20:06:09 +02:00
Mihai Bazon
0552dbd93c v2.4.20 2015-04-13 18:59:21 +03:00
Mihai Bazon
18c63ff3d8 Fix compression of conditionals
Don't move the condition on the right side of an assignment when
the left side may have side effects.

Fix #677
2015-04-13 17:29:48 +03:00
Mihai Bazon
e04ef56243 Use the before visitor in mangle props
(works around a bug in our tree walker which, while cloning nodes, breaks
references between labeled statements and break/continue labels)
2015-04-10 11:33:29 +03:00
Mihai Bazon
5d60484553 More fixes for the breaking changes in yargs
Close #670
2015-04-05 13:20:22 +03:00
Mihai Bazon
3c846e6f7b Merge pull request #669 from galvanix/documentation-inSourceMap
Document passing source maps directly to minify() using inSourceMap
2015-04-04 15:29:03 +03:00
David Caldwell
2850dc69fd Document passing source maps directly to minify() using inSourceMap 2015-04-03 17:27:28 -07:00
Mihai Bazon
94205c3a37 v2.4.19 2015-03-29 14:02:37 +03:00
Mihai Bazon
2ada34b229 Merge pull request #660 from ntkme/fix-long-options
Fix long options
2015-03-29 14:01:21 +03:00
なつき
db396da734 Fix long options 2015-03-29 04:00:42 -07:00
Mihai Bazon
0262b4244c Disable testing with Node 0.8 2015-03-29 13:19:07 +03:00
27 changed files with 959 additions and 259 deletions

3
.gitignore vendored
View File

@@ -1,2 +1,3 @@
/node_modules/
/npm-debug.log
tmp/
node_modules/

View File

@@ -1,2 +0,0 @@
test
.travis.yml

View File

@@ -1,6 +1,10 @@
language: node_js
before_install: "npm install -g npm"
node_js:
- "0.8"
- "iojs"
- "0.12"
- "0.10"
- "0.11"
- "4"
matrix:
fast_finish: true
sudo: false

View File

@@ -132,6 +132,7 @@ The available options are:
--reserve-domprops Make (most?) DOM properties reserved for
--mangle-props
--mangle-props Mangle property names
--mangle-regex Only mangle property names matching the regex
--name-cache File to hold mangled names mappings
```
@@ -251,6 +252,10 @@ A default exclusion file is provided in `tools/domprops.json` which should
cover most standard JS and DOM properties defined in various browsers. Pass
`--reserve-domprops` to read that in.
You can also use a regular expression to define which property names should be
mangled. For example, `--mangle-regex="/^_/"` will only mangle property names
that start with an underscore.
When you compress multiple files using this option, in order for them to
work together in the end we need to ensure somehow that one property gets
mangled to the same name in all of them. For this, pass `--name-cache
@@ -345,6 +350,11 @@ to set `true`; it's effectively a shortcut for `foo=true`).
compressor from discarding unused function arguments. You need this
for code which relies on `Function.length`.
- `keep_fnames` -- default `false`. Pass `true` to prevent the
compressor from mangling/discarding function names. Useful for code relying on
`Function.prototype.name`.
### The `unsafe` option
It enables some transformations that *might* break code logic in certain
@@ -591,6 +601,16 @@ var result = UglifyJS.minify("compiled.js", {
// same as before, it returns `code` and `map`
```
If your input source map is not in a file, you can pass it in as an object
using the `inSourceMap` argument:
```javascript
var result = UglifyJS.minify("compiled.js", {
inSourceMap: JSON.parse(my_source_map_string),
outSourceMap: "minified.js.map"
});
```
The `inSourceMap` is only used if you also request `outSourceMap` (it makes
no sense otherwise).

View File

@@ -70,6 +70,7 @@ You need to pass an argument to this option to specify the name that your module
.describe("reserved-file", "File containing reserved names")
.describe("reserve-domprops", "Make (most?) DOM properties reserved for --mangle-props")
.describe("mangle-props", "Mangle property names")
.describe("mangle-regex", "Only mangle property names matching the regex")
.describe("name-cache", "File to hold mangled names mappings")
.alias("p", "prefix")
@@ -88,13 +89,19 @@ You need to pass an argument to this option to specify the name that your module
.string("source-map-root")
.string("source-map-url")
.string("b")
.string("beautify")
.string("m")
.string("mangle")
.string("c")
.string("compress")
.string("d")
.string("define")
.string("e")
.string("enclose")
.string("comments")
.string("wrap")
.string("p")
.string("prefix")
.string("name-cache")
.array("reserved-file")
@@ -104,11 +111,13 @@ You need to pass an argument to this option to specify the name that your module
.boolean("export-all")
.boolean("self")
.boolean("v")
.boolean("verbose")
.boolean("stats")
.boolean("acorn")
.boolean("spidermonkey")
.boolean("lint")
.boolean("V")
.boolean("version")
.boolean("noerr")
.boolean("bare-returns")
.boolean("keep-fnames")
@@ -124,24 +133,24 @@ normalize(ARGS);
if (ARGS.noerr) {
UglifyJS.DefaultsError.croak = function(msg, defs) {
sys.error("WARN: " + msg);
print_error("WARN: " + msg);
};
}
if (ARGS.version || ARGS.V) {
var json = require("../package.json");
sys.puts(json.name + ' ' + json.version);
print(json.name + ' ' + json.version);
process.exit(0);
}
if (ARGS.ast_help) {
var desc = UglifyJS.describe_ast();
sys.puts(typeof desc == "string" ? desc : JSON.stringify(desc, null, 2));
print(typeof desc == "string" ? desc : JSON.stringify(desc, null, 2));
process.exit(0);
}
if (ARGS.h || ARGS.help) {
sys.puts(yargs.help());
print(yargs.help());
process.exit(0);
}
@@ -183,6 +192,15 @@ function writeNameCache(key, cache) {
return UglifyJS.writeNameCache(ARGS.name_cache, key, cache);
}
function extractRegex(str) {
if (/^\/.*\/[a-zA-Z]*$/.test(str)) {
var regex_pos = str.lastIndexOf("/");
return new RegExp(str.substr(1, regex_pos - 1), str.substr(regex_pos + 1));
} else {
throw new Error("Invalid regular expression: " + str);
}
}
if (ARGS.quotes === true) {
ARGS.quotes = 3;
}
@@ -207,13 +225,12 @@ if (ARGS.keep_fnames) {
if (BEAUTIFY)
UglifyJS.merge(OUTPUT_OPTIONS, BEAUTIFY);
if (ARGS.comments) {
if (ARGS.comments != null) {
if (/^\/.*\/[a-zA-Z]*$/.test(ARGS.comments)) {
var regex_pos = ARGS.comments.lastIndexOf("/");
try {
OUTPUT_OPTIONS.comments = new RegExp(ARGS.comments.substr(1, regex_pos - 1), ARGS.comments.substr(regex_pos + 1));
OUTPUT_OPTIONS.comments = extractRegex(ARGS.comments);
} catch (e) {
sys.error("ERROR: Invalid --comments: " + e.message);
print_error("ERROR: Invalid --comments: " + e.message);
}
} else if (ARGS.comments == "all") {
OUTPUT_OPTIONS.comments = true;
@@ -233,11 +250,10 @@ var files = ARGS._.slice();
if (ARGS.self) {
if (files.length > 0) {
sys.error("WARN: Ignoring input files since --self was passed");
print_error("WARN: Ignoring input files since --self was passed");
}
files = UglifyJS.FILES;
if (!ARGS.wrap) ARGS.wrap = "UglifyJS";
ARGS.export_all = true;
}
var ORIG_MAP = ARGS.in_source_map;
@@ -245,7 +261,7 @@ var ORIG_MAP = ARGS.in_source_map;
if (ORIG_MAP) {
ORIG_MAP = JSON.parse(fs.readFileSync(ORIG_MAP));
if (files.length == 0) {
sys.error("INFO: Using file from the input source map: " + ORIG_MAP.file);
print_error("INFO: Using file from the input source map: " + ORIG_MAP.file);
files = [ ORIG_MAP.file ];
}
if (ARGS.source_map_root == null) {
@@ -258,12 +274,12 @@ if (files.length == 0) {
}
if (files.indexOf("-") >= 0 && ARGS.source_map) {
sys.error("ERROR: Source map doesn't work with input from STDIN");
print_error("ERROR: Source map doesn't work with input from STDIN");
process.exit(1);
}
if (files.filter(function(el){ return el == "-" }).length > 1) {
sys.error("ERROR: Can read a single file from STDIN (two or more dashes specified)");
print_error("ERROR: Can read a single file from STDIN (two or more dashes specified)");
process.exit(1);
}
@@ -286,9 +302,9 @@ try {
var compressor = COMPRESS && UglifyJS.Compressor(COMPRESS);
} catch(ex) {
if (ex instanceof UglifyJS.DefaultsError) {
sys.error(ex.msg);
sys.error("Supported options:");
sys.error(sys.inspect(ex.defs));
print_error(ex.msg);
print_error("Supported options:");
print_error(sys.inspect(ex.defs));
process.exit(1);
}
}
@@ -296,7 +312,7 @@ try {
async.eachLimit(files, 1, function (file, cb) {
read_whole_file(file, function (err, code) {
if (err) {
sys.error("ERROR: can't read file: " + file);
print_error("ERROR: can't read file: " + file);
process.exit(1);
}
if (ARGS.p != null) {
@@ -333,9 +349,9 @@ async.eachLimit(files, 1, function (file, cb) {
});
} catch(ex) {
if (ex instanceof UglifyJS.JS_Parse_Error) {
sys.error("Parse error at " + file + ":" + ex.line + "," + ex.col);
sys.error(ex.message);
sys.error(ex.stack);
print_error("Parse error at " + file + ":" + ex.line + "," + ex.col);
print_error(ex.message);
print_error(ex.stack);
process.exit(1);
}
throw ex;
@@ -349,11 +365,11 @@ async.eachLimit(files, 1, function (file, cb) {
TOPLEVEL = UglifyJS.AST_Node.from_mozilla_ast(TOPLEVEL);
});
if (ARGS.wrap) {
if (ARGS.wrap != null) {
TOPLEVEL = TOPLEVEL.wrap_commonjs(ARGS.wrap, ARGS.export_all);
}
if (ARGS.enclose) {
if (ARGS.enclose != null) {
var arg_parameter_list = ARGS.enclose;
if (arg_parameter_list === true) {
arg_parameter_list = [];
@@ -364,27 +380,35 @@ async.eachLimit(files, 1, function (file, cb) {
TOPLEVEL = TOPLEVEL.wrap_enclose(arg_parameter_list);
}
if (ARGS.mangle_props) (function(){
if (ARGS.mangle_props || ARGS.name_cache) (function(){
var reserved = RESERVED ? RESERVED.props : null;
var cache = readNameCache("props");
var regex;
try {
regex = ARGS.mangle_regex ? extractRegex(ARGS.mangle_regex) : null;
} catch (e) {
print_error("ERROR: Invalid --mangle-regex: " + e.message);
process.exit(1);
}
TOPLEVEL = UglifyJS.mangle_properties(TOPLEVEL, {
reserved : reserved,
cache: cache
cache : cache,
only_cache : !ARGS.mangle_props,
regex : regex
});
writeNameCache("props", cache);
})();
var SCOPE_IS_NEEDED = COMPRESS || MANGLE || ARGS.lint;
var TL_CACHE = readNameCache("vars");
if (SCOPE_IS_NEEDED) {
time_it("scope", function(){
TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8, cache: TL_CACHE });
if (ARGS.lint) {
TOPLEVEL.scope_warnings();
}
});
}
if (COMPRESS) {
time_it("squeeze", function(){
@@ -392,14 +416,12 @@ async.eachLimit(files, 1, function (file, cb) {
});
}
if (SCOPE_IS_NEEDED) {
time_it("scope", function(){
TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8, cache: TL_CACHE });
if (MANGLE && !TL_CACHE) {
TOPLEVEL.compute_char_frequency(MANGLE);
}
});
}
if (MANGLE) time_it("mangle", function(){
MANGLE.cache = TL_CACHE;
@@ -435,15 +457,15 @@ async.eachLimit(files, 1, function (file, cb) {
if (OUTPUT_FILE) {
fs.writeFileSync(OUTPUT_FILE, output, "utf8");
} else {
sys.print(output);
print(output);
}
if (ARGS.stats) {
sys.error(UglifyJS.string_template("Timing information (compressed {count} files):", {
print_error(UglifyJS.string_template("Timing information (compressed {count} files):", {
count: files.length
}));
for (var i in STATS) if (STATS.hasOwnProperty(i)) {
sys.error(UglifyJS.string_template("- {name}: {time}s", {
print_error(UglifyJS.string_template("- {name}: {time}s", {
name: i,
time: (STATS[i] / 1000).toFixed(3)
}));
@@ -470,7 +492,7 @@ function getOptions(x, constants) {
ast = UglifyJS.parse(x, { expression: true });
} catch(ex) {
if (ex instanceof UglifyJS.JS_Parse_Error) {
sys.error("Error parsing arguments in: " + x);
print_error("Error parsing arguments in: " + x);
process.exit(1);
}
}
@@ -489,8 +511,8 @@ function getOptions(x, constants) {
ret[name] = true;
return true; // no descend
}
sys.error(node.TYPE)
sys.error("Error parsing arguments in: " + x);
print_error(node.TYPE)
print_error("Error parsing arguments in: " + x);
process.exit(1);
}));
}
@@ -522,3 +544,11 @@ function time_it(name, cont) {
}
return ret;
}
function print_error(msg) {
console.error("%s", msg);
}
function print(txt) {
console.log("%s", txt);
}

View File

@@ -81,6 +81,7 @@ function DEFNODE(type, props, methods, base) {
ctor.DEFMETHOD = function(name, method) {
this.prototype[name] = method;
};
exports["AST_" + type] = ctor;
return ctor;
};
@@ -329,12 +330,11 @@ var AST_Toplevel = DEFNODE("Toplevel", "globals", {
}
}));
}
var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))";
wrapped_tl = parse(wrapped_tl);
wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
if (node instanceof AST_SimpleStatement) {
node = node.body;
if (node instanceof AST_String) switch (node.getValue()) {
if (node instanceof AST_Directive) {
switch (node.value) {
case "$ORIG":
return MAP.splice(self.body);
case "$EXPORTS":
@@ -864,10 +864,11 @@ var AST_String = DEFNODE("String", "value quote", {
}
}, AST_Constant);
var AST_Number = DEFNODE("Number", "value", {
var AST_Number = DEFNODE("Number", "value literal", {
$documentation: "A number literal",
$propdoc: {
value: "[number] the numeric value"
value: "[number] the numeric value",
literal: "[string] numeric value as string (optional)"
}
}, AST_Constant);

View File

@@ -61,7 +61,7 @@ function Compressor(options, false_by_default) {
loops : !false_by_default,
unused : !false_by_default,
hoist_funs : !false_by_default,
keep_fargs : false,
keep_fargs : true,
keep_fnames : false,
hoist_vars : false,
if_return : !false_by_default,
@@ -111,6 +111,7 @@ merge(Compressor.prototype, {
node.DEFMETHOD("optimize", function(compressor){
var self = this;
if (self._optimized) return self;
if (compressor.has_directive("use asm")) return self;
var opt = optimizer(self, compressor);
opt._optimized = true;
if (opt === self) return opt;
@@ -896,6 +897,7 @@ merge(Compressor.prototype, {
def(AST_Call, function(compressor){
var pure = compressor.option("pure_funcs");
if (!pure) return true;
if (typeof pure == "function") return pure(this);
return pure.indexOf(this.expression.print_to_string()) < 0;
});
@@ -1025,6 +1027,7 @@ merge(Compressor.prototype, {
AST_Scope.DEFMETHOD("drop_unused", function(compressor){
var self = this;
if (compressor.has_directive("use asm")) return self;
if (compressor.option("unused")
&& !(self instanceof AST_Toplevel)
&& !self.uses_eval
@@ -1086,7 +1089,7 @@ merge(Compressor.prototype, {
var tt = new TreeTransformer(
function before(node, descend, in_list) {
if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
if (compressor.option("unsafe") && !compressor.option("keep_fargs")) {
if (!compressor.option("keep_fargs")) {
for (var a = node.argnames, i = a.length; --i >= 0;) {
var sym = a[i];
if (sym.unreferenced()) {
@@ -1168,12 +1171,12 @@ merge(Compressor.prototype, {
return make_node(AST_EmptyStatement, node);
}
if (def.length == 0) {
return side_effects;
return in_list ? MAP.splice(side_effects.body) : side_effects;
}
node.definitions = def;
if (side_effects) {
side_effects.body.unshift(node);
node = side_effects;
return in_list ? MAP.splice(side_effects.body) : side_effects;
}
return node;
}
@@ -1204,9 +1207,10 @@ merge(Compressor.prototype, {
});
AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
var self = this;
if (compressor.has_directive("use asm")) return self;
var hoist_funs = compressor.option("hoist_funs");
var hoist_vars = compressor.option("hoist_vars");
var self = this;
if (hoist_funs || hoist_vars) {
var dirs = [];
var hoisted = [];
@@ -1909,15 +1913,11 @@ merge(Compressor.prototype, {
if (!compressor.option("side_effects"))
return self;
if (!self.car.has_side_effects(compressor)) {
// we shouldn't compress (1,eval)(something) to
// eval(something) because that changes the meaning of
// eval (becomes lexical instead of global).
var p;
if (!(self.cdr instanceof AST_SymbolRef
&& self.cdr.name == "eval"
&& self.cdr.undeclared()
&& (p = compressor.parent()) instanceof AST_Call
&& p.expression === self)) {
// we shouldn't compress (1,func)(something) to
// func(something) because that changes the meaning of
// the func (becomes lexical instead of global).
var p = compressor.parent();
if (!(p instanceof AST_Call && p.expression === self)) {
return self.cdr;
}
}
@@ -2031,15 +2031,14 @@ merge(Compressor.prototype, {
var commutativeOperators = makePredicate("== === != !== * & | ^");
OPT(AST_Binary, function(self, compressor){
var reverse = compressor.has_directive("use asm") ? noop
: function(op, force) {
function reverse(op, force) {
if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
if (op) self.operator = op;
var tmp = self.left;
self.left = self.right;
self.right = tmp;
}
};
}
if (commutativeOperators(self.operator)) {
if (self.right instanceof AST_Constant
&& !(self.left instanceof AST_Constant)) {
@@ -2104,6 +2103,34 @@ merge(Compressor.prototype, {
}
break;
}
if (compressor.option("conditionals")) {
if (self.operator == "&&") {
var ll = self.left.evaluate(compressor);
if (ll.length > 1) {
if (ll[1]) {
compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start);
var rr = self.right.evaluate(compressor);
return rr[0];
} else {
compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start);
return ll[0];
}
}
}
else if (self.operator == "||") {
var ll = self.left.evaluate(compressor);
if (ll.length > 1) {
if (ll[1]) {
compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start);
return ll[0];
} else {
compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start);
var rr = self.right.evaluate(compressor);
return rr[0];
}
}
}
}
if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
case "&&":
var ll = self.left.evaluate(compressor);
@@ -2155,7 +2182,7 @@ merge(Compressor.prototype, {
}
break;
}
if (compressor.option("comparisons")) {
if (compressor.option("comparisons") && self.is_boolean()) {
if (!(compressor.parent() instanceof AST_Binary)
|| compressor.parent() instanceof AST_Assign) {
var negated = make_node(AST_UnaryPrefix, self, {
@@ -2230,10 +2257,11 @@ merge(Compressor.prototype, {
}
}
}
// x * (y * z) ==> x * y * z
// x && (y && z) ==> x && y && z
// x || (y || z) ==> x || y || z
if (self.right instanceof AST_Binary
&& self.right.operator == self.operator
&& (self.operator == "*" || self.operator == "&&" || self.operator == "||"))
&& (self.operator == "&&" || self.operator == "||"))
{
self.left = make_node(AST_Binary, self.left, {
operator : self.operator,
@@ -2247,7 +2275,15 @@ merge(Compressor.prototype, {
});
OPT(AST_SymbolRef, function(self, compressor){
if (self.undeclared()) {
function isLHS(symbol, parent) {
return (
parent instanceof AST_Binary &&
parent.operator === '=' &&
parent.left === symbol
);
}
if (self.undeclared() && !isLHS(self, compressor.parent())) {
var defines = compressor.option("global_defs");
if (defines && defines.hasOwnProperty(self.name)) {
return make_node_from_constant(compressor, defines[self.name], self);
@@ -2272,14 +2308,6 @@ merge(Compressor.prototype, {
});
});
OPT(AST_NaN, function (self, compressor) {
return make_node(AST_Binary, self, {
operator : '/',
left : make_node(AST_Number, self, {value: 0}),
right : make_node(AST_Number, self, {value: 0})
});
});
OPT(AST_Undefined, function(self, compressor){
if (compressor.option("unsafe")) {
var scope = compressor.find_parent(AST_Scope);
@@ -2343,6 +2371,7 @@ merge(Compressor.prototype, {
&& alternative instanceof AST_Assign
&& consequent.operator == alternative.operator
&& consequent.left.equivalent_to(alternative.left)
&& !consequent.left.has_side_effects(compressor)
) {
/*
* Stuff like this:
@@ -2363,6 +2392,7 @@ merge(Compressor.prototype, {
if (consequent instanceof AST_Call
&& alternative.TYPE === consequent.TYPE
&& consequent.args.length == alternative.args.length
&& !consequent.expression.has_side_effects(compressor)
&& consequent.expression.equivalent_to(alternative.expression)) {
if (consequent.args.length == 0) {
return make_node(AST_Seq, self, {

View File

@@ -399,7 +399,7 @@
function map(moztype, mytype, propmap) {
var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
moz_to_me += "return new " + mytype.name + "({\n" +
moz_to_me += "return new U2." + mytype.name + "({\n" +
"start: my_start_token(M),\n" +
"end: my_end_token(M)";
@@ -442,8 +442,8 @@
//me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
//console.log(moz_to_me);
moz_to_me = new Function("my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
my_start_token, my_end_token, from_moz
moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
exports, my_start_token, my_end_token, from_moz
);
me_to_moz = new Function("to_moz", "to_moz_block", "return(" + me_to_moz + ")")(
to_moz, to_moz_block

View File

@@ -60,6 +60,7 @@ function OutputStream(options) {
bracketize : false,
semicolons : true,
comments : false,
shebang : true,
preserve_line : false,
screw_ie8 : false,
preamble : null,
@@ -161,6 +162,8 @@ function OutputStream(options) {
str = String(str);
var ch = str.charAt(0);
if (might_need_semicolon) {
might_need_semicolon = false;
if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
if (options.semicolons || requireSemicolonChars(ch)) {
OUTPUT += ";";
@@ -171,12 +174,17 @@ function OutputStream(options) {
current_pos++;
current_line++;
current_col = 0;
if (/^\s+$/.test(str)) {
// reset the semicolon flag, since we didn't print one
// now and might still have to later
might_need_semicolon = true;
}
}
if (!options.beautify)
might_need_space = false;
}
might_need_semicolon = false;
maybe_newline();
}
if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
@@ -396,7 +404,6 @@ function OutputStream(options) {
AST_Node.DEFMETHOD("add_comments", function(output){
var c = output.option("comments"), self = this;
if (c) {
var start = self.start;
if (start && !start._comments_dumped) {
start._comments_dumped = true;
@@ -419,13 +426,17 @@ function OutputStream(options) {
}));
}
if (c.test) {
if (!c) {
comments = comments.filter(function(comment) {
return c.test(comment.value);
return comment.type == "comment5";
});
} else if (c.test) {
comments = comments.filter(function(comment){
return c.test(comment.value) || comment.type == "comment5";
});
} else if (typeof c == "function") {
comments = comments.filter(function(comment){
return c(self, comment);
return c(self, comment) || comment.type == "comment5";
});
}
@@ -451,8 +462,11 @@ function OutputStream(options) {
output.space();
}
}
});
else if (output.pos() === 0 && c.type == "comment5" && output.option("shebang")) {
output.print("#!" + c.value + "\n");
output.indent();
}
});
}
});
@@ -1144,7 +1158,13 @@ function OutputStream(options) {
output.print_string(self.getValue(), self.quote);
});
DEFPRINT(AST_Number, function(self, output){
if (self.literal !== undefined
&& +self.literal === self.value /* paranoid check */
&& self.scope && self.scope.has_directive('use asm')) {
output.print(self.literal);
} else {
output.print(make_num(self.getValue()));
}
});
function regexp_safe_literal(code) {

View File

@@ -108,7 +108,7 @@ var OPERATORS = makePredicate([
"||"
]);
var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF"));
var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
@@ -210,10 +210,10 @@ function is_token(token, type, val) {
var EX_EOF = {};
function tokenizer($TEXT, filename, html5_comments) {
function tokenizer($TEXT, filename, html5_comments, shebang) {
var S = {
text : $TEXT.replace(/\uFEFF/g, ''),
text : $TEXT,
filename : filename,
pos : 0,
tokpos : 0,
@@ -335,7 +335,11 @@ function tokenizer($TEXT, filename, html5_comments) {
if (prefix) num = prefix + num;
var valid = parse_js_number(num);
if (!isNaN(valid)) {
return token("num", valid);
var tok = token("num", valid);
if (num.indexOf('.') >= 0) {
tok.literal = num;
}
return tok;
} else {
parse_error("Invalid syntax: " + num);
}
@@ -354,8 +358,13 @@ function tokenizer($TEXT, filename, html5_comments) {
case 120 : return String.fromCharCode(hex_bytes(2)); // \x
case 117 : return String.fromCharCode(hex_bytes(4)); // \u
case 10 : return ""; // newline
default : return ch;
case 13 : // \r
if (peek() == "\n") { // DOS newline
next(true, in_string);
return "";
}
}
return ch;
};
function hex_bytes(n) {
@@ -372,7 +381,7 @@ function tokenizer($TEXT, filename, html5_comments) {
var read_string = with_eof_error("Unterminated string constant", function(quote_char){
var quote = next(), ret = "";
for (;;) {
var ch = next(true);
var ch = next(true, true);
if (ch == "\\") {
// read OctalEscapeSequence (XXX: deprecated if "strict mode")
// https://github.com/mishoo/UglifyJS/issues/178
@@ -475,7 +484,11 @@ function tokenizer($TEXT, filename, html5_comments) {
regexp += ch;
}
var mods = read_name();
try {
return token("regexp", new RegExp(regexp, mods));
} catch(e) {
parse_error(e.message);
}
});
function read_operator(prefix) {
@@ -559,6 +572,13 @@ function tokenizer($TEXT, filename, html5_comments) {
if (PUNC_CHARS(ch)) return token("punc", next());
if (OPERATOR_CHARS(ch)) return read_operator();
if (code == 92 || is_identifier_start(code)) return read_word();
if (shebang) {
if (S.pos == 0 && looking_at("#!")) {
forward(2);
return skip_line_comment("comment5");
}
}
parse_error("Unexpected character '" + ch + "'");
};
@@ -628,12 +648,13 @@ function parse($TEXT, options) {
expression : false,
html5_comments : true,
bare_returns : false,
shebang : true,
});
var S = {
input : (typeof $TEXT == "string"
? tokenizer($TEXT, options.filename,
options.html5_comments)
options.html5_comments, options.shebang)
: $TEXT),
token : null,
prev : null,
@@ -1105,7 +1126,7 @@ function parse($TEXT, options) {
});
};
var new_ = function() {
var new_ = function(allow_calls) {
var start = S.token;
expect_token("operator", "new");
var newexp = expr_atom(false), args;
@@ -1120,7 +1141,7 @@ function parse($TEXT, options) {
expression : newexp,
args : args,
end : prev()
}), true);
}), allow_calls);
};
function as_atom_node() {
@@ -1131,7 +1152,7 @@ function parse($TEXT, options) {
ret = _make_symbol(AST_SymbolRef);
break;
case "num":
ret = new AST_Number({ start: tok, end: tok, value: tok.value });
ret = new AST_Number({ start: tok, end: tok, value: tok.value, literal: tok.literal });
break;
case "string":
ret = new AST_String({
@@ -1164,7 +1185,7 @@ function parse($TEXT, options) {
var expr_atom = function(allow_calls) {
if (is("operator", "new")) {
return new_();
return new_(allow_calls);
}
var start = S.token;
if (is("punc")) {

View File

@@ -63,7 +63,9 @@ function find_builtins() {
function mangle_properties(ast, options) {
options = defaults(options, {
reserved : null,
cache : null
cache : null,
only_cache : false,
regex : null
});
var reserved = options.reserved;
@@ -78,7 +80,10 @@ function mangle_properties(ast, options) {
};
}
var regex = options.regex;
var names_to_mangle = [];
var unmangleable = [];
// step 1: find candidates to mangle
ast.walk(new TreeWalker(function(node){
@@ -102,23 +107,17 @@ function mangle_properties(ast, options) {
}));
// step 2: transform the tree, renaming properties
return ast.transform(new TreeTransformer(null, function(node){
return ast.transform(new TreeTransformer(function(node){
if (node instanceof AST_ObjectKeyVal) {
if (should_mangle(node.key)) {
node.key = mangle(node.key);
}
}
else if (node instanceof AST_ObjectProperty) {
// setter or getter
if (should_mangle(node.key.name)) {
node.key.name = mangle(node.key.name);
}
}
else if (node instanceof AST_Dot) {
if (should_mangle(node.property)) {
node.property = mangle(node.property);
}
}
else if (node instanceof AST_Sub) {
node.property = mangleStrings(node.property);
}
@@ -139,12 +138,18 @@ function mangle_properties(ast, options) {
// only function declarations after this line
function can_mangle(name) {
if (unmangleable.indexOf(name) >= 0) return false;
if (reserved.indexOf(name) >= 0) return false;
if (options.only_cache) {
return cache.props.has(name);
}
if (/^[0-9.]+$/.test(name)) return false;
return true;
}
function should_mangle(name) {
if (regex && !regex.test(name)) return false;
if (reserved.indexOf(name) >= 0) return false;
return cache.props.has(name)
|| names_to_mangle.indexOf(name) >= 0;
}
@@ -152,9 +157,17 @@ function mangle_properties(ast, options) {
function add(name) {
if (can_mangle(name))
push_uniq(names_to_mangle, name);
if (!should_mangle(name)) {
push_uniq(unmangleable, name);
}
}
function mangle(name) {
if (!should_mangle(name)) {
return name;
}
var mangled = cache.props.get(name);
if (!mangled) {
do {
@@ -197,10 +210,8 @@ function mangle_properties(ast, options) {
node.cdr = mangleStrings(node.cdr);
}
else if (node instanceof AST_String) {
if (should_mangle(node.value)) {
node.value = mangle(node.value);
}
}
else if (node instanceof AST_Conditional) {
node.consequent = mangleStrings(node.consequent);
node.alternative = mangleStrings(node.alternative);

View File

@@ -119,6 +119,10 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
push_uniq(scope.directives, node.value);
return true;
}
if (node instanceof AST_Number) {
node.scope = scope;
return true;
}
if (node instanceof AST_With) {
for (var s = scope; s; s = s.parent_scope)
s.uses_with = true;

128
npm-shrinkwrap.json generated Normal file
View File

@@ -0,0 +1,128 @@
{
"name": "uglify-js",
"version": "2.4.24",
"dependencies": {
"abbrev": {
"version": "1.0.7",
"from": "abbrev@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.7.tgz"
},
"amdefine": {
"version": "1.0.0",
"from": "amdefine@>=0.0.4",
"resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.0.tgz"
},
"async": {
"version": "0.2.10",
"from": "async@>=0.2.6 <0.3.0",
"resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz"
},
"camelcase": {
"version": "1.2.1",
"from": "camelcase@>=1.0.2 <2.0.0",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz"
},
"decamelize": {
"version": "1.0.0",
"from": "decamelize@>=1.0.0 <2.0.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.0.0.tgz"
},
"deep-is": {
"version": "0.1.3",
"from": "deep-is@>=0.1.2 <0.2.0",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz"
},
"esprima": {
"version": "1.1.1",
"from": "esprima@>=1.1.1 <1.2.0",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-1.1.1.tgz"
},
"estraverse": {
"version": "1.5.1",
"from": "estraverse@>=1.5.1 <1.6.0",
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-1.5.1.tgz"
},
"esutils": {
"version": "1.0.0",
"from": "esutils@>=1.0.0 <1.1.0",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-1.0.0.tgz"
},
"fast-levenshtein": {
"version": "1.0.7",
"from": "fast-levenshtein@>=1.0.0 <1.1.0",
"resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-1.0.7.tgz"
},
"levn": {
"version": "0.2.5",
"from": "levn@>=0.2.5 <0.3.0",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.2.5.tgz"
},
"nopt": {
"version": "2.1.2",
"from": "nopt@>=2.1.2 <2.2.0",
"resolved": "https://registry.npmjs.org/nopt/-/nopt-2.1.2.tgz"
},
"optionator": {
"version": "0.5.0",
"from": "optionator@>=0.5.0 <0.6.0",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.5.0.tgz"
},
"prelude-ls": {
"version": "1.1.2",
"from": "prelude-ls@>=1.1.1 <1.2.0",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz"
},
"reflect": {
"version": "0.1.3",
"from": "git://github.com/zaach/reflect.js.git",
"resolved": "git://github.com/zaach/reflect.js.git#286bcd79661c96ecc404357d3c0e35fdb54a6967"
},
"source-map": {
"version": "0.5.1",
"from": "source-map@>=0.5.1 <0.6.0",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.1.tgz"
},
"type-check": {
"version": "0.3.1",
"from": "type-check@>=0.3.1 <0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.1.tgz"
},
"uglify-js": {
"version": "2.4.24",
"from": "git://github.com/mishoo/UglifyJS2.git",
"resolved": "git://github.com/mishoo/UglifyJS2.git#2a06c7758e24a64740473c8031eafbb7fefa213f",
"dependencies": {
"source-map": {
"version": "0.1.34",
"from": "source-map@0.1.34",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.1.34.tgz"
}
}
},
"uglify-to-browserify": {
"version": "1.0.2",
"from": "uglify-to-browserify@>=1.0.0 <1.1.0",
"resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz"
},
"window-size": {
"version": "0.1.0",
"from": "window-size@0.1.0",
"resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz"
},
"wordwrap": {
"version": "0.0.2",
"from": "wordwrap@0.0.2",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz"
},
"yargs": {
"version": "3.5.4",
"from": "yargs@>=3.5.4 <3.6.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-3.5.4.tgz"
},
"zeparser": {
"version": "0.0.7",
"from": "git://github.com/qfox/ZeParser.git",
"resolved": "git://github.com/qfox/ZeParser.git#c99240c5ba7054c467733800ff38265958a2dda9"
}
}
}

View File

@@ -2,23 +2,37 @@
"name": "uglify-js",
"description": "JavaScript parser, mangler/compressor and beautifier toolkit",
"homepage": "http://lisperator.net/uglifyjs",
"main": "tools/node.js",
"version": "2.4.18",
"engines": { "node" : ">=0.4.0" },
"maintainers": [{
"name": "Mihai Bazon",
"email": "mihai.bazon@gmail.com",
"web": "http://lisperator.net/"
}],
"author": "Mihai Bazon <mihai.bazon@gmail.com> (http://lisperator.net/)",
"license": "BSD-2-Clause",
"version": "2.5.0",
"engines": {
"node": ">=0.8.0"
},
"maintainers": [
"Mihai Bazon <mihai.bazon@gmail.com> (http://lisperator.net/)"
],
"repository": {
"type": "git",
"url": "https://github.com/mishoo/UglifyJS2.git"
},
"bugs": {
"url": "https://github.com/mishoo/UglifyJS2/issues"
},
"main": "tools/node.js",
"bin": {
"uglifyjs": "bin/uglifyjs"
},
"files": [
"bin",
"lib",
"tools",
"LICENSE"
],
"dependencies": {
"async": "~0.2.6",
"source-map" : "0.1.34",
"yargs": "~3.5.4",
"uglify-to-browserify": "~1.0.0"
"source-map": "~0.5.1",
"uglify-to-browserify": "~1.0.0",
"yargs": "~3.5.4"
},
"devDependencies": {
"acorn": "~0.6.0",
@@ -27,11 +41,12 @@
"estraverse": "~1.5.1"
},
"browserify": {
"transform": [ "uglify-to-browserify" ]
"transform": [
"uglify-to-browserify"
]
},
"bin": {
"uglifyjs" : "bin/uglifyjs"
},
"license": "BSD",
"scripts": {"test": "node test/run-tests.js"}
"scripts": {
"shrinkwrap": "rm ./npm-shrinkwrap.json; rm -rf ./node_modules; npm i && npm shrinkwrap && npm outdated",
"test": "node test/run-tests.js"
}
}

106
test/compress/asm.js Normal file
View File

@@ -0,0 +1,106 @@
asm_mixed: {
options = {
sequences : true,
properties : true,
dead_code : true,
drop_debugger : true,
conditionals : true,
comparisons : true,
evaluate : true,
booleans : true,
loops : true,
unused : true,
hoist_funs : true,
keep_fargs : true,
keep_fnames : false,
hoist_vars : true,
if_return : true,
join_vars : true,
cascade : true,
side_effects : true,
negate_iife : true
};
input: {
// adapted from http://asmjs.org/spec/latest/
function asm_GeometricMean(stdlib, foreign, buffer) {
"use asm";
var exp = stdlib.Math.exp;
var log = stdlib.Math.log;
var values = new stdlib.Float64Array(buffer);
function logSum(start, end) {
start = start|0;
end = end|0;
var sum = 0.0, p = 0, q = 0;
// asm.js forces byte addressing of the heap by requiring shifting by 3
for (p = start << 3, q = end << 3; (p|0) < (q|0); p = (p + 8)|0) {
sum = sum + +log(values[p>>3]);
}
return +sum;
}
function geometricMean(start, end) {
start = start|0;
end = end|0;
return +exp(+logSum(start, end) / +((end - start)|0));
}
return { geometricMean: geometricMean };
}
function no_asm_GeometricMean(stdlib, foreign, buffer) {
var exp = stdlib.Math.exp;
var log = stdlib.Math.log;
var values = new stdlib.Float64Array(buffer);
function logSum(start, end) {
start = start|0;
end = end|0;
var sum = 0.0, p = 0, q = 0;
// asm.js forces byte addressing of the heap by requiring shifting by 3
for (p = start << 3, q = end << 3; (p|0) < (q|0); p = (p + 8)|0) {
sum = sum + +log(values[p>>3]);
}
return +sum;
}
function geometricMean(start, end) {
start = start|0;
end = end|0;
return +exp(+logSum(start, end) / +((end - start)|0));
}
return { geometricMean: geometricMean };
}
}
expect: {
function asm_GeometricMean(stdlib, foreign, buffer) {
"use asm";
var exp = stdlib.Math.exp;
var log = stdlib.Math.log;
var values = new stdlib.Float64Array(buffer);
function logSum(start, end) {
start = start | 0;
end = end | 0;
var sum = 0.0, p = 0, q = 0;
for (p = start << 3, q = end << 3; (p | 0) < (q | 0); p = p + 8 | 0) {
sum = sum + +log(values[p >> 3]);
}
return +sum;
}
function geometricMean(start, end) {
start = start | 0;
end = end | 0;
return +exp(+logSum(start, end) / +(end - start | 0));
}
return { geometricMean: geometricMean };
}
function no_asm_GeometricMean(stdlib, foreign, buffer) {
function logSum(start, end) {
start = 0 | start, end = 0 | end;
var sum = 0, p = 0, q = 0;
for (p = start << 3, q = end << 3; (0 | q) > (0 | p); p = p + 8 | 0) sum += +log(values[p >> 3]);
return +sum;
}
function geometricMean(start, end) {
return start = 0 | start, end = 0 | end, +exp(+logSum(start, end) / +(end - start | 0));
}
var exp = stdlib.Math.exp, log = stdlib.Math.log, values = new stdlib.Float64Array(buffer);
return { geometricMean: geometricMean };
}
}
}

View File

@@ -86,7 +86,9 @@ ifs_4: {
x(foo)[10].bar.baz = something_else();
}
expect: {
x(foo)[10].bar.baz = (foo && bar) ? something() : something_else();
foo && bar
? x(foo)[10].bar.baz = something()
: x(foo)[10].bar.baz = something_else();
}
}
@@ -133,6 +135,7 @@ ifs_6: {
comparisons: true
};
input: {
var x;
if (!foo && !bar && !baz && !boo) {
x = 10;
} else {
@@ -140,6 +143,7 @@ ifs_6: {
}
}
expect: {
var x;
x = foo || bar || baz || boo ? 20 : 10;
}
}
@@ -149,6 +153,7 @@ cond_1: {
conditionals: true
};
input: {
var do_something; // if undeclared it's assumed to have side-effects
if (some_condition()) {
do_something(x);
} else {
@@ -156,6 +161,7 @@ cond_1: {
}
}
expect: {
var do_something;
do_something(some_condition() ? x : y);
}
}
@@ -165,6 +171,7 @@ cond_2: {
conditionals: true
};
input: {
var x, FooBar;
if (some_condition()) {
x = new FooBar(1);
} else {
@@ -172,6 +179,7 @@ cond_2: {
}
}
expect: {
var x, FooBar;
x = new FooBar(some_condition() ? 1 : 2);
}
}
@@ -181,6 +189,7 @@ cond_3: {
conditionals: true
};
input: {
var FooBar;
if (some_condition()) {
new FooBar(1);
} else {
@@ -188,6 +197,7 @@ cond_3: {
}
}
expect: {
var FooBar;
some_condition() ? new FooBar(1) : FooBar(2);
}
}
@@ -197,6 +207,7 @@ cond_4: {
conditionals: true
};
input: {
var do_something;
if (some_condition()) {
do_something();
} else {
@@ -204,6 +215,7 @@ cond_4: {
}
}
expect: {
var do_something;
some_condition(), do_something();
}
}
@@ -303,6 +315,7 @@ cond_7_1: {
evaluate : true
};
input: {
var x;
// access to global should be assumed to have side effects
if (y) {
x = 1+1;
@@ -311,6 +324,7 @@ cond_7_1: {
}
}
expect: {
var x;
x = (y, 2);
}
}
@@ -321,6 +335,7 @@ cond_8: {
evaluate : true
};
input: {
var a;
// compress these
a = condition ? true : false;
@@ -355,6 +370,7 @@ cond_8: {
}
expect: {
var a;
a = !!condition;
a = !condition;
a = !!condition();
@@ -368,3 +384,163 @@ cond_8: {
a = condition ? 1 : 0;
}
}
conditional_and: {
options = {
conditionals: true,
evaluate : true
};
input: {
var a;
// compress these
a = true && condition;
a = 1 && console.log("a");
a = 2 * 3 && 2 * condition;
a = 5 == 5 && condition + 3;
a = "string" && 4 - condition;
a = 5 + "" && condition / 5;
a = -4.5 && 6 << condition;
a = 6 && 7;
a = false && condition;
a = NaN && console.log("b");
a = 0 && console.log("c");
a = undefined && 2 * condition;
a = null && condition + 3;
a = 2 * 3 - 6 && 4 - condition;
a = 10 == 7 && condition / 5;
a = !"string" && 6 % condition;
a = 0 && 7;
// don't compress these
a = condition && true;
a = console.log("a") && 2;
a = 4 - condition && "string";
a = 6 << condition && -4.5;
a = condition && false;
a = console.log("b") && NaN;
a = console.log("c") && 0;
a = 2 * condition && undefined;
a = condition + 3 && null;
}
expect: {
var a;
a = condition;
a = console.log("a");
a = 2 * condition;
a = condition + 3;
a = 4 - condition;
a = condition / 5;
a = 6 << condition;
a = 7;
a = false;
a = NaN;
a = 0;
a = void 0;
a = null;
a = 0;
a = false;
a = false;
a = 0;
a = condition && true;
a = console.log("a") && 2;
a = 4 - condition && "string";
a = 6 << condition && -4.5;
a = condition && false;
a = console.log("b") && NaN;
a = console.log("c") && 0;
a = 2 * condition && void 0;
a = condition + 3 && null;
}
}
conditional_or: {
options = {
conditionals: true,
evaluate : true
};
input: {
var a;
// compress these
a = true || condition;
a = 1 || console.log("a");
a = 2 * 3 || 2 * condition;
a = 5 == 5 || condition + 3;
a = "string" || 4 - condition;
a = 5 + "" || condition / 5;
a = -4.5 || 6 << condition;
a = 6 || 7;
a = false || condition;
a = 0 || console.log("b");
a = NaN || console.log("c");
a = undefined || 2 * condition;
a = null || condition + 3;
a = 2 * 3 - 6 || 4 - condition;
a = 10 == 7 || condition / 5;
a = !"string" || 6 % condition;
a = null || 7;
a = console.log(undefined && condition || null);
a = console.log(undefined || condition && null);
// don't compress these
a = condition || true;
a = console.log("a") || 2;
a = 4 - condition || "string";
a = 6 << condition || -4.5;
a = condition || false;
a = console.log("b") || NaN;
a = console.log("c") || 0;
a = 2 * condition || undefined;
a = condition + 3 || null;
}
expect: {
var a;
a = true;
a = 1;
a = 6;
a = true;
a = "string";
a = "5";
a = -4.5;
a = 6;
a = condition;
a = console.log("b");
a = console.log("c");
a = 2 * condition;
a = condition + 3;
a = 4 - condition;
a = condition / 5;
a = 6 % condition;
a = 7;
a = console.log(null);
a = console.log(condition && null);
a = condition || true;
a = console.log("a") || 2;
a = 4 - condition || "string";
a = 6 << condition || -4.5;
a = condition || false;
a = console.log("b") || NaN;
a = console.log("c") || 0;
a = 2 * condition || void 0;
a = condition + 3 || null;
}
}

View File

@@ -1,5 +1,5 @@
unused_funarg_1: {
options = { unused: true, unsafe: true };
options = { unused: true, keep_fargs: false };
input: {
function f(a, b, c, d, e) {
return a + b;
@@ -13,7 +13,7 @@ unused_funarg_1: {
}
unused_funarg_2: {
options = { unused: true, unsafe: true };
options = { unused: true, keep_fargs: false };
input: {
function f(a, b, c, d, e) {
return a + c;
@@ -173,7 +173,7 @@ keep_fnames: {
}
expect: {
function foo() {
return function bar() {};
return function bar(baz) {};
}
}
}

View File

@@ -0,0 +1,11 @@
do_not_update_lhs: {
options = { global_defs: { DEBUG: false } };
input: { DEBUG = false; }
expect: { DEBUG = false; }
}
do_update_rhs: {
options = { global_defs: { DEBUG: false } };
input: { MY_DEBUG = DEBUG; }
expect: { MY_DEBUG = false; }
}

View File

@@ -6,7 +6,7 @@ NaN_and_Infinity_must_have_parens: {
}
expect: {
(1/0).toString();
(0/0).toString();
NaN.toString(); // transformation to 0/0 dropped
}
}

View File

@@ -0,0 +1,37 @@
dont_reuse_prop: {
mangle_props = {
regex: /asd/
};
input: {
var obj = {};
obj.a = 123;
obj.asd = 256;
console.log(obj.a);
}
expect: {
var obj = {};
obj.a = 123;
obj.b = 256;
console.log(obj.a);
}
}
unmangleable_props_should_always_be_reserved: {
mangle_props = {
regex: /asd/
};
input: {
var obj = {};
obj.asd = 256;
obj.a = 123;
console.log(obj.a);
}
expect: {
var obj = {};
obj.b = 256;
obj.a = 123;
console.log(obj.a);
}
}

View File

@@ -0,0 +1,29 @@
negate_booleans_1: {
options = {
comparisons: true
};
input: {
var a = !a || !b || !c || !d || !e || !f;
}
expect: {
var a = !(a && b && c && d && e && f);
}
}
negate_booleans_2: {
options = {
comparisons: true
};
input: {
var match = !x && // should not touch this one
(!z || c) &&
(!k || d) &&
the_stuff();
}
expect: {
var match = !x &&
(!z || c) &&
(!k || d) &&
the_stuff();
}
}

View File

@@ -0,0 +1,23 @@
remove_redundant_sequence_items: {
options = { side_effects: true };
input: {
(0, 1, logThis)();
(0, 1, _decorators.logThis)();
}
expect: {
(0, logThis)();
(0, _decorators.logThis)();
}
}
dont_remove_lexical_binding_sequence: {
options = { side_effects: true };
input: {
(0, logThis)();
(0, _decorators.logThis)();
}
expect: {
(0, logThis)();
(0, _decorators.logThis)();
}
}

12
test/compress/new.js Normal file
View File

@@ -0,0 +1,12 @@
new_statement: {
input: {
new x(1);
new x(1)(2);
new x(1)(2)(3);
new new x(1);
new new x(1)(2);
new (new x(1))(2);
(new new x(1))(2);
}
expect_exact: "new x(1);new x(1)(2);new x(1)(2)(3);new new x(1);new new x(1)(2);new new x(1)(2);(new new x(1))(2);"
}

View File

@@ -31,7 +31,7 @@ function tmpl() {
function log() {
var txt = tmpl.apply(this, arguments);
sys.puts(txt);
console.log("%s", txt);
}
function log_directory(dir) {
@@ -84,9 +84,17 @@ function run_compress_tests() {
warnings: false
});
var cmp = new U.Compressor(options, true);
var expect = make_code(as_toplevel(test.expect), false);
var expect;
if (test.expect) {
expect = make_code(as_toplevel(test.expect), false);
} else {
expect = test.expect_exact;
}
var input = as_toplevel(test.input);
var input_code = make_code(test.input);
if (test.mangle_props) {
input = U.mangle_properties(input, test.mangle_props);
}
var output = input.transform(cmp);
output.figure_out_scope();
output = make_code(output, false);
@@ -150,7 +158,7 @@ function parse_test(file) {
}
if (node instanceof U.AST_LabeledStatement) {
assert.ok(
node.label.name == "input" || node.label.name == "expect",
node.label.name == "input" || node.label.name == "expect" || node.label.name == "expect_exact",
tmpl("Unsupported label {name} [{line},{col}]", {
name: node.label.name,
line: node.label.start.line,
@@ -162,7 +170,16 @@ function parse_test(file) {
if (stat.body.length == 1) stat = stat.body[0];
else if (stat.body.length == 0) stat = new U.AST_EmptyStatement();
}
if (node.label.name === "expect_exact") {
if (!(stat.TYPE === "SimpleStatement" && stat.body.TYPE === "String")) {
throw new Error(
"The value of the expect_exact clause should be a string, " +
"like `expect_exact: \"some.exact.javascript;\"`");
}
test[node.label.name] = stat.body.start.value
} else {
test[node.label.name] = stat;
}
return true;
}
});

17
tools/exports.js Normal file
View File

@@ -0,0 +1,17 @@
exports["Compressor"] = Compressor;
exports["DefaultsError"] = DefaultsError;
exports["Dictionary"] = Dictionary;
exports["JS_Parse_Error"] = JS_Parse_Error;
exports["MAP"] = MAP;
exports["OutputStream"] = OutputStream;
exports["SourceMap"] = SourceMap;
exports["TreeTransformer"] = TreeTransformer;
exports["TreeWalker"] = TreeWalker;
exports["base54"] = base54;
exports["defaults"] = defaults;
exports["mangle_properties"] = mangle_properties;
exports["merge"] = merge;
exports["parse"] = parse;
exports["push_uniq"] = push_uniq;
exports["string_template"] = string_template;
exports["is_identifier"] = is_identifier;

View File

@@ -1,28 +1,5 @@
var path = require("path");
var fs = require("fs");
var vm = require("vm");
var sys = require("util");
var UglifyJS = vm.createContext({
sys : sys,
console : console,
process : process,
Buffer : Buffer,
MOZ_SourceMap : require("source-map")
});
function load_global(file) {
file = path.resolve(path.dirname(module.filename), file);
try {
var code = fs.readFileSync(file, "utf8");
return vm.runInContext(code, UglifyJS, file);
} catch(ex) {
// XXX: in case of a syntax error, the message is kinda
// useless. (no location information).
sys.debug("ERROR in file: " + file + " / " + ex);
process.exit(1);
}
};
var FILES = exports.FILES = [
"../lib/utils.js",
@@ -34,24 +11,25 @@ var FILES = exports.FILES = [
"../lib/compress.js",
"../lib/sourcemap.js",
"../lib/mozilla-ast.js",
"../lib/propmangle.js"
"../lib/propmangle.js",
"./exports.js",
].map(function(file){
return fs.realpathSync(path.join(path.dirname(__filename), file));
});
FILES.forEach(load_global);
var UglifyJS = exports;
new Function("MOZ_SourceMap", "exports", FILES.map(function(file){
return fs.readFileSync(file, "utf8");
}).join("\n\n"))(
require("source-map"),
UglifyJS
);
UglifyJS.AST_Node.warn_function = function(txt) {
sys.error("WARN: " + txt);
console.error("WARN: %s", txt);
};
// XXX: perhaps we shouldn't export everything but heck, I'm lazy.
for (var i in UglifyJS) {
if (UglifyJS.hasOwnProperty(i)) {
exports[i] = UglifyJS[i];
}
}
exports.minify = function(files, options) {
options = UglifyJS.defaults(options, {
spidermonkey : false,
@@ -67,6 +45,7 @@ exports.minify = function(files, options) {
UglifyJS.base54.reset();
// 1. parse
var haveScope = false;
var toplevel = null,
sourcesContent = {};
@@ -75,23 +54,27 @@ exports.minify = function(files, options) {
} else {
if (typeof files == "string")
files = [ files ];
files.forEach(function(file){
files.forEach(function(file, i){
var code = options.fromString
? file
: fs.readFileSync(file, "utf8");
sourcesContent[file] = code;
toplevel = UglifyJS.parse(code, {
filename: options.fromString ? "?" : file,
filename: options.fromString ? i : file,
toplevel: toplevel
});
});
}
if (options.wrap) {
toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll);
}
// 2. compress
if (options.compress) {
var compress = { warnings: options.warnings };
UglifyJS.merge(compress, options.compress);
toplevel.figure_out_scope();
haveScope = true;
var sq = UglifyJS.Compressor(compress);
toplevel = toplevel.transform(sq);
}
@@ -99,11 +82,17 @@ exports.minify = function(files, options) {
// 3. mangle
if (options.mangle) {
toplevel.figure_out_scope(options.mangle);
haveScope = true;
toplevel.compute_char_frequency(options.mangle);
toplevel.mangle_names(options.mangle);
}
// 4. output
// 4. scope (if needed)
if (!haveScope) {
toplevel.figure_out_scope();
}
// 5. output
var inMap = options.inSourceMap;
var output = {};
if (typeof options.inSourceMap == "string") {
@@ -130,7 +119,7 @@ exports.minify = function(files, options) {
var stream = UglifyJS.OutputStream(output);
toplevel.print(stream);
if(options.outSourceMap){
if (options.outSourceMap && "string" === typeof options.outSourceMap) {
stream += "\n//# sourceMappingURL=" + options.outSourceMap;
}