uglifyjs 15 KB

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