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