terser 16 KB

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