uglifyjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. #! /usr/bin/env node
  2. // -*- js -*-
  3. "use strict";
  4. require("../tools/exit");
  5. var fs = require("fs");
  6. var info = require("../package.json");
  7. var path = require("path");
  8. var program = require("commander");
  9. var UglifyJS = require("../tools/node");
  10. var skip_keys = [ "cname", "inlined", "parent_scope", "scope", "uses_eval", "uses_with" ];
  11. var files = {};
  12. var options = {
  13. compress: false,
  14. mangle: false
  15. };
  16. program.version(info.name + " " + info.version);
  17. program.parseArgv = program.parse;
  18. program.parse = undefined;
  19. if (process.argv.indexOf("ast") >= 0) program.helpInformation = UglifyJS.describe_ast;
  20. else if (process.argv.indexOf("options") >= 0) program.helpInformation = function() {
  21. var text = [];
  22. var options = UglifyJS.default_options();
  23. for (var option in options) {
  24. text.push("--" + (option == "output" ? "beautify" : option == "sourceMap" ? "source-map" : option) + " options:");
  25. text.push(format_object(options[option]));
  26. text.push("");
  27. }
  28. return text.join("\n");
  29. };
  30. program.option("-p, --parse <options>", "Specify parser options.", parse_js());
  31. program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js());
  32. program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js());
  33. program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js());
  34. program.option("-b, --beautify [options]", "Beautify output/specify output options.", parse_js());
  35. program.option("-O, --output-opts [options]", "Output options (beautify disabled).", parse_js());
  36. program.option("-o, --output <file>", "Output file (default STDOUT).");
  37. program.option("--comments [filter]", "Preserve copyright comments in the output.");
  38. program.option("--config-file <file>", "Read minify() options from JSON file.");
  39. program.option("-d, --define <expr>[=value]", "Global definitions.", parse_js("define"));
  40. program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed everything in a big function, with configurable argument(s) & value(s).");
  41. program.option("--ie8", "Support non-standard Internet Explorer 8.");
  42. program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");
  43. program.option("--name-cache <file>", "File to hold mangled name mappings.");
  44. program.option("--rename", "Force symbol expansion.");
  45. program.option("--no-rename", "Disable symbol expansion.");
  46. program.option("--self", "Build UglifyJS as a library (implies --wrap UglifyJS)");
  47. program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js());
  48. program.option("--timings", "Display operations run time on STDERR.");
  49. program.option("--toplevel", "Compress and/or mangle variables in toplevel scope.");
  50. program.option("--verbose", "Print diagnostic messages.");
  51. program.option("--warn", "Print warning messages.");
  52. program.option("--wrap <name>", "Embed everything as a function with “exports” corresponding to “name” globally.");
  53. program.option("--reduce-test", "Reduce a standalone `console.log` based test case.");
  54. program.arguments("[files...]").parseArgv(process.argv);
  55. if (program.configFile) {
  56. options = JSON.parse(read_file(program.configFile));
  57. if (options.mangle && options.mangle.properties && options.mangle.properties.regex) {
  58. options.mangle.properties.regex = UglifyJS.parse(options.mangle.properties.regex, {
  59. expression: true
  60. }).value;
  61. }
  62. }
  63. if (!program.output && program.sourceMap && program.sourceMap.url != "inline") {
  64. fatal("cannot write source map to STDOUT");
  65. }
  66. [
  67. "compress",
  68. "enclose",
  69. "ie8",
  70. "mangle",
  71. "sourceMap",
  72. "toplevel",
  73. "wrap"
  74. ].forEach(function(name) {
  75. if (name in program) {
  76. options[name] = program[name];
  77. }
  78. });
  79. if (program.verbose) {
  80. options.warnings = "verbose";
  81. } else if (program.warn) {
  82. options.warnings = true;
  83. }
  84. if (options.warnings) {
  85. UglifyJS.AST_Node.log_function(print_error, options.warnings == "verbose");
  86. delete options.warnings;
  87. }
  88. if (program.beautify) {
  89. options.output = typeof program.beautify == "object" ? program.beautify : {};
  90. if (!("beautify" in options.output)) {
  91. options.output.beautify = true;
  92. }
  93. }
  94. if (program.outputOpts) {
  95. if (program.beautify) fatal("--beautify cannot be used with --output-opts");
  96. options.output = typeof program.outputOpts == "object" ? program.outputOpts : {};
  97. }
  98. if (program.comments) {
  99. if (typeof options.output != "object") options.output = {};
  100. options.output.comments = typeof program.comments == "string" ? program.comments : "some";
  101. }
  102. if (program.define) {
  103. if (typeof options.compress != "object") options.compress = {};
  104. if (typeof options.compress.global_defs != "object") options.compress.global_defs = {};
  105. for (var expr in program.define) {
  106. options.compress.global_defs[expr] = program.define[expr];
  107. }
  108. }
  109. if (program.keepFnames) {
  110. options.keep_fnames = true;
  111. }
  112. if (program.mangleProps) {
  113. if (program.mangleProps.domprops) {
  114. delete program.mangleProps.domprops;
  115. } else {
  116. if (typeof program.mangleProps != "object") program.mangleProps = {};
  117. if (!Array.isArray(program.mangleProps.reserved)) program.mangleProps.reserved = [];
  118. require("../tools/domprops").forEach(function(name) {
  119. UglifyJS.push_uniq(program.mangleProps.reserved, name);
  120. });
  121. }
  122. if (typeof options.mangle != "object") options.mangle = {};
  123. options.mangle.properties = program.mangleProps;
  124. }
  125. if (program.nameCache) {
  126. options.nameCache = JSON.parse(read_file(program.nameCache, "{}"));
  127. }
  128. if (program.output == "ast") {
  129. options.output = {
  130. ast: true,
  131. code: false
  132. };
  133. }
  134. if (program.parse) {
  135. if (!program.parse.acorn && !program.parse.spidermonkey) {
  136. options.parse = program.parse;
  137. } else if (program.sourceMap && program.sourceMap.content == "inline") {
  138. fatal("inline source map only works with built-in parser");
  139. }
  140. }
  141. if (~program.rawArgs.indexOf("--rename")) {
  142. options.rename = true;
  143. } else if (!program.rename) {
  144. options.rename = false;
  145. }
  146. var convert_path = function(name) {
  147. return name;
  148. };
  149. if (typeof program.sourceMap == "object" && "base" in program.sourceMap) {
  150. convert_path = function() {
  151. var base = program.sourceMap.base;
  152. delete options.sourceMap.base;
  153. return function(name) {
  154. return path.relative(base, name);
  155. };
  156. }();
  157. }
  158. if (program.self) {
  159. if (program.args.length) UglifyJS.AST_Node.warn("Ignoring input files since --self was passed");
  160. if (!options.wrap) options.wrap = "UglifyJS";
  161. simple_glob(UglifyJS.FILES).forEach(function(name) {
  162. files[convert_path(name)] = read_file(name);
  163. });
  164. run();
  165. } else if (program.args.length) {
  166. simple_glob(program.args).forEach(function(name) {
  167. files[convert_path(name)] = read_file(name);
  168. });
  169. run();
  170. } else {
  171. var chunks = [];
  172. process.stdin.setEncoding("utf8");
  173. process.stdin.on("data", function(chunk) {
  174. chunks.push(chunk);
  175. }).on("end", function() {
  176. files = [ chunks.join("") ];
  177. run();
  178. });
  179. process.stdin.resume();
  180. }
  181. function convert_ast(fn) {
  182. return UglifyJS.AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
  183. }
  184. function run() {
  185. var content = program.sourceMap && program.sourceMap.content;
  186. if (content && content != "inline") {
  187. UglifyJS.AST_Node.info("Using input source map: " + content);
  188. options.sourceMap.content = read_file(content, content);
  189. }
  190. if (program.timings) options.timings = true;
  191. try {
  192. if (program.parse) {
  193. if (program.parse.acorn) {
  194. files = convert_ast(function(toplevel, name) {
  195. return require("acorn").parse(files[name], {
  196. locations: true,
  197. program: toplevel,
  198. sourceFile: name
  199. });
  200. });
  201. } else if (program.parse.spidermonkey) {
  202. files = convert_ast(function(toplevel, name) {
  203. var obj = JSON.parse(files[name]);
  204. if (!toplevel) return obj;
  205. toplevel.body = toplevel.body.concat(obj.body);
  206. return toplevel;
  207. });
  208. }
  209. }
  210. } catch (ex) {
  211. fatal(ex);
  212. }
  213. if (program.reduceTest) {
  214. // load on demand - assumes dev tree checked out
  215. var reduce_test = require("../test/reduce");
  216. var testcase = files[0] || files[Object.keys(files)[0]];
  217. var result = reduce_test(testcase, options, {verbose: true});
  218. }
  219. else {
  220. var result = UglifyJS.minify(files, options);
  221. }
  222. if (result.error) {
  223. var ex = result.error;
  224. if (ex.name == "SyntaxError") {
  225. print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
  226. var file = files[ex.filename];
  227. if (file) {
  228. var col = ex.col;
  229. var lines = file.split(/\r?\n/);
  230. var line = lines[ex.line - 1];
  231. if (!line && !col) {
  232. line = lines[ex.line - 2];
  233. col = line.length;
  234. }
  235. if (line) {
  236. var limit = 70;
  237. if (col > limit) {
  238. line = line.slice(col - limit);
  239. col = limit;
  240. }
  241. print_error(line.slice(0, 80));
  242. print_error(line.slice(0, col).replace(/\S/g, " ") + "^");
  243. }
  244. }
  245. } else if (ex.defs) {
  246. print_error("Supported options:");
  247. print_error(format_object(ex.defs));
  248. }
  249. fatal(ex);
  250. } else if (program.output == "ast") {
  251. if (!options.compress && !options.mangle) {
  252. result.ast.figure_out_scope({});
  253. }
  254. print(JSON.stringify(result.ast, function(key, value) {
  255. if (value) switch (key) {
  256. case "thedef":
  257. return symdef(value);
  258. case "enclosed":
  259. return value.length ? value.map(symdef) : undefined;
  260. case "variables":
  261. case "functions":
  262. case "globals":
  263. return value.size() ? value.map(symdef) : undefined;
  264. }
  265. if (skip_key(key)) return;
  266. if (value instanceof UglifyJS.AST_Token) return;
  267. if (value instanceof UglifyJS.Dictionary) return;
  268. if (value instanceof UglifyJS.AST_Node) {
  269. var result = {
  270. _class: "AST_" + value.TYPE
  271. };
  272. value.CTOR.PROPS.forEach(function(prop) {
  273. result[prop] = value[prop];
  274. });
  275. return result;
  276. }
  277. return value;
  278. }, 2));
  279. } else if (program.output == "spidermonkey") {
  280. print(JSON.stringify(UglifyJS.minify(result.code, {
  281. compress: false,
  282. mangle: false,
  283. output: {
  284. ast: true,
  285. code: false
  286. }
  287. }).ast.to_mozilla_ast(), null, 2));
  288. } else if (program.output) {
  289. fs.writeFileSync(program.output, result.code);
  290. if (result.map) {
  291. fs.writeFileSync(program.output + ".map", result.map);
  292. }
  293. } else {
  294. print(result.code);
  295. }
  296. if (program.nameCache) {
  297. fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache));
  298. }
  299. if (result.timings) for (var phase in result.timings) {
  300. print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s");
  301. }
  302. }
  303. function fatal(message) {
  304. if (message instanceof Error) {
  305. message = message.stack.replace(/^\S*?Error:/, "ERROR:")
  306. } else {
  307. message = "ERROR: " + message;
  308. }
  309. print_error(message);
  310. process.exit(1);
  311. }
  312. // A file glob function that only supports "*" and "?" wildcards in the basename.
  313. // Example: "foo/bar/*baz??.*.js"
  314. // Argument `glob` may be a string or an array of strings.
  315. // Returns an array of strings. Garbage in, garbage out.
  316. function simple_glob(glob) {
  317. if (Array.isArray(glob)) {
  318. return [].concat.apply([], glob.map(simple_glob));
  319. }
  320. if (glob.match(/\*|\?/)) {
  321. var dir = path.dirname(glob);
  322. try {
  323. var entries = fs.readdirSync(dir);
  324. } catch (ex) {}
  325. if (entries) {
  326. var pattern = "^" + path.basename(glob)
  327. .replace(/[.+^$[\]\\(){}]/g, "\\$&")
  328. .replace(/\*/g, "[^/\\\\]*")
  329. .replace(/\?/g, "[^/\\\\]") + "$";
  330. var mod = process.platform === "win32" ? "i" : "";
  331. var rx = new RegExp(pattern, mod);
  332. var results = entries.filter(function(name) {
  333. return rx.test(name);
  334. }).map(function(name) {
  335. return path.join(dir, name);
  336. });
  337. if (results.length) return results;
  338. }
  339. }
  340. return [ glob ];
  341. }
  342. function read_file(path, default_value) {
  343. try {
  344. return fs.readFileSync(path, "utf8");
  345. } catch (ex) {
  346. if (ex.code == "ENOENT" && default_value != null) return default_value;
  347. fatal(ex);
  348. }
  349. }
  350. function parse_js(flag) {
  351. return function(value, options) {
  352. options = options || {};
  353. try {
  354. UglifyJS.parse(value, {
  355. expression: true
  356. }).walk(new UglifyJS.TreeWalker(function(node) {
  357. if (node instanceof UglifyJS.AST_Assign) {
  358. var name = node.left.print_to_string();
  359. var value = node.right;
  360. if (flag) {
  361. options[name] = value;
  362. } else if (value instanceof UglifyJS.AST_Array) {
  363. options[name] = value.elements.map(to_string);
  364. } else {
  365. options[name] = to_string(value);
  366. }
  367. return true;
  368. }
  369. if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_PropAccess) {
  370. var name = node.print_to_string();
  371. options[name] = true;
  372. return true;
  373. }
  374. if (!(node instanceof UglifyJS.AST_Sequence)) throw node;
  375. function to_string(value) {
  376. return value instanceof UglifyJS.AST_Constant ? value.value : value.print_to_string({
  377. quote_keys: true
  378. });
  379. }
  380. }));
  381. } catch (ex) {
  382. if (flag) {
  383. fatal("cannot parse arguments for '" + flag + "': " + value);
  384. } else {
  385. options[value] = null;
  386. }
  387. }
  388. return options;
  389. }
  390. }
  391. function skip_key(key) {
  392. return skip_keys.indexOf(key) >= 0;
  393. }
  394. function symdef(def) {
  395. var ret = (1e6 + def.id) + " " + def.name;
  396. if (def.mangled_name) ret += " " + def.mangled_name;
  397. return ret;
  398. }
  399. function format_object(obj) {
  400. var lines = [];
  401. var padding = "";
  402. Object.keys(obj).map(function(name) {
  403. if (padding.length < name.length) padding = Array(name.length + 1).join(" ");
  404. return [ name, JSON.stringify(obj[name]) ];
  405. }).forEach(function(tokens) {
  406. lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
  407. });
  408. return lines.join("\n");
  409. }
  410. function print_error(msg) {
  411. process.stderr.write(msg);
  412. process.stderr.write("\n");
  413. }
  414. function print(txt) {
  415. process.stdout.write(txt);
  416. process.stdout.write("\n");
  417. }