uglifyjs 15 KB

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