uglifyjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #! /usr/bin/env node
  2. // -*- js -*-
  3. "use strict";
  4. // workaround for tty output truncation upon process.exit()
  5. [process.stdout, process.stderr].forEach(function(stream){
  6. if (stream._handle && stream._handle.setBlocking)
  7. stream._handle.setBlocking(true);
  8. });
  9. var fs = require("fs");
  10. var info = require("../package.json");
  11. var path = require("path");
  12. var program = require("commander");
  13. var UglifyJS = require("../tools/node");
  14. var skip_keys = [ "cname", "enclosed", "parent_scope", "scope", "thedef", "uses_eval", "uses_with" ];
  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.indexOf("ast") >= 0) program.helpInformation = UglifyJS.describe_ast;
  24. else if (process.argv.indexOf("options") >= 0) program.helpInformation = function() {
  25. var text = [];
  26. var options = UglifyJS.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("--ie8", "Support non-standard Internet Explorer 8.");
  44. program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");
  45. program.option("--name-cache <file>", "File to hold mangled name mappings.");
  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_source_map());
  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.arguments("[files...]").parseArgv(process.argv);
  54. if (program.configFile) {
  55. options = JSON.parse(read_file(program.configFile));
  56. }
  57. if (!program.output && program.sourceMap && program.sourceMap.url != "inline") {
  58. fatal("ERROR: cannot write source map to STDOUT");
  59. }
  60. [
  61. "compress",
  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. var convert_path = function(name) {
  122. return name;
  123. };
  124. if (typeof program.sourceMap == "object" && "base" in program.sourceMap) {
  125. convert_path = function() {
  126. var base = program.sourceMap.base;
  127. delete options.sourceMap.base;
  128. return function(name) {
  129. return path.relative(base, name);
  130. };
  131. }();
  132. }
  133. if (program.verbose) {
  134. options.warnings = "verbose";
  135. } else if (program.warn) {
  136. options.warnings = true;
  137. }
  138. if (program.self) {
  139. if (program.args.length) {
  140. print_error("WARN: Ignoring input files since --self was passed");
  141. }
  142. if (!options.wrap) options.wrap = "UglifyJS";
  143. simple_glob(UglifyJS.FILES).forEach(function(name) {
  144. files[convert_path(name)] = read_file(name);
  145. });
  146. run();
  147. } else if (program.args.length) {
  148. simple_glob(program.args).forEach(function(name) {
  149. files[convert_path(name)] = read_file(name);
  150. });
  151. run();
  152. } else {
  153. var chunks = [];
  154. process.stdin.setEncoding("utf8");
  155. process.stdin.on("data", function(chunk) {
  156. chunks.push(chunk);
  157. }).on("end", function() {
  158. files = [ chunks.join("") ];
  159. run();
  160. });
  161. process.stdin.resume();
  162. }
  163. function convert_ast(fn) {
  164. return UglifyJS.AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
  165. }
  166. function run() {
  167. UglifyJS.AST_Node.warn_function = function(msg) {
  168. print_error("WARN: " + msg);
  169. };
  170. if (program.timings) options.timings = true;
  171. try {
  172. if (program.parse) {
  173. if (program.parse.acorn) {
  174. files = convert_ast(function(toplevel, name) {
  175. return require("acorn").parse(files[name], {
  176. locations: true,
  177. program: toplevel,
  178. sourceFile: name
  179. });
  180. });
  181. } else if (program.parse.spidermonkey) {
  182. files = convert_ast(function(toplevel, name) {
  183. var obj = JSON.parse(files[name]);
  184. if (!toplevel) return obj;
  185. toplevel.body = toplevel.body.concat(obj.body);
  186. return toplevel;
  187. });
  188. }
  189. }
  190. } catch (ex) {
  191. fatal(ex);
  192. }
  193. var result = UglifyJS.minify(files, options);
  194. if (result.error) {
  195. var ex = result.error;
  196. if (ex.name == "SyntaxError") {
  197. print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
  198. var col = ex.col;
  199. var lines = files[ex.filename].split(/\r?\n/);
  200. var line = lines[ex.line - 1];
  201. if (!line && !col) {
  202. line = lines[ex.line - 2];
  203. col = line.length;
  204. }
  205. if (line) {
  206. var limit = 70;
  207. if (col > limit) {
  208. line = line.slice(col - limit);
  209. col = limit;
  210. }
  211. print_error(line.slice(0, 80));
  212. print_error(line.slice(0, col).replace(/\S/g, " ") + "^");
  213. }
  214. }
  215. if (ex.defs) {
  216. print_error("Supported options:");
  217. print_error(format_object(ex.defs));
  218. }
  219. fatal(ex);
  220. } else if (program.output == "ast") {
  221. print(JSON.stringify(result.ast, function(key, value) {
  222. if (skip_key(key)) return;
  223. if (value instanceof UglifyJS.AST_Token) return;
  224. if (value instanceof UglifyJS.Dictionary) return;
  225. if (value instanceof UglifyJS.AST_Node) {
  226. var result = {
  227. _class: "AST_" + value.TYPE
  228. };
  229. value.CTOR.PROPS.forEach(function(prop) {
  230. result[prop] = value[prop];
  231. });
  232. return result;
  233. }
  234. return value;
  235. }, 2));
  236. } else if (program.output == "spidermonkey") {
  237. print(JSON.stringify(UglifyJS.minify(result.code, {
  238. compress: false,
  239. mangle: false,
  240. output: {
  241. ast: true,
  242. code: false
  243. }
  244. }).ast.to_mozilla_ast(), null, 2));
  245. } else if (program.output) {
  246. fs.writeFileSync(program.output, result.code);
  247. if (result.map) {
  248. fs.writeFileSync(program.output + ".map", result.map);
  249. }
  250. } else {
  251. print(result.code);
  252. }
  253. if (program.nameCache) {
  254. fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache));
  255. }
  256. if (result.timings) for (var phase in result.timings) {
  257. print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s");
  258. }
  259. }
  260. function fatal(message) {
  261. if (message instanceof Error) message = message.stack.replace(/^\S*?Error:/, "ERROR:")
  262. print_error(message);
  263. process.exit(1);
  264. }
  265. // A file glob function that only supports "*" and "?" wildcards in the basename.
  266. // Example: "foo/bar/*baz??.*.js"
  267. // Argument `glob` may be a string or an array of strings.
  268. // Returns an array of strings. Garbage in, garbage out.
  269. function simple_glob(glob) {
  270. if (Array.isArray(glob)) {
  271. return [].concat.apply([], glob.map(simple_glob));
  272. }
  273. if (glob.match(/\*|\?/)) {
  274. var dir = path.dirname(glob);
  275. try {
  276. var entries = fs.readdirSync(dir);
  277. } catch (ex) {}
  278. if (entries) {
  279. var pattern = "^" + path.basename(glob)
  280. .replace(/[.+^$[\]\\(){}]/g, "\\$&")
  281. .replace(/\*/g, "[^/\\\\]*")
  282. .replace(/\?/g, "[^/\\\\]") + "$";
  283. var mod = process.platform === "win32" ? "i" : "";
  284. var rx = new RegExp(pattern, mod);
  285. var results = entries.filter(function(name) {
  286. return rx.test(name);
  287. }).map(function(name) {
  288. return path.join(dir, name);
  289. });
  290. if (results.length) return results;
  291. }
  292. }
  293. return [ glob ];
  294. }
  295. function read_file(path, default_value) {
  296. try {
  297. return fs.readFileSync(path, "utf8");
  298. } catch (ex) {
  299. if (ex.code == "ENOENT" && default_value != null) return default_value;
  300. fatal(ex);
  301. }
  302. }
  303. function parse_js(flag) {
  304. return function(value, options) {
  305. options = options || {};
  306. try {
  307. UglifyJS.minify(value, {
  308. parse: {
  309. expression: true
  310. },
  311. compress: false,
  312. mangle: false,
  313. output: {
  314. ast: true,
  315. code: false
  316. }
  317. }).ast.walk(new UglifyJS.TreeWalker(function(node) {
  318. if (node instanceof UglifyJS.AST_Assign) {
  319. var name = node.left.print_to_string();
  320. var value = node.right;
  321. if (flag) {
  322. options[name] = value;
  323. } else if (value instanceof UglifyJS.AST_Array) {
  324. options[name] = value.elements.map(to_string);
  325. } else {
  326. options[name] = to_string(value);
  327. }
  328. return true;
  329. }
  330. if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_PropAccess) {
  331. var name = node.print_to_string();
  332. options[name] = true;
  333. return true;
  334. }
  335. if (!(node instanceof UglifyJS.AST_Sequence)) throw node;
  336. function to_string(value) {
  337. return value instanceof UglifyJS.AST_Constant ? value.getValue() : value.print_to_string({
  338. quote_keys: true
  339. });
  340. }
  341. }));
  342. } catch(ex) {
  343. if (flag) {
  344. fatal("Error parsing arguments for '" + flag + "': " + value);
  345. } else {
  346. options[value] = null;
  347. }
  348. }
  349. return options;
  350. }
  351. }
  352. function parse_source_map() {
  353. var parse = parse_js();
  354. return function(value, options) {
  355. var hasContent = options && "content" in options;
  356. var settings = parse(value, options);
  357. if (!hasContent && settings.content && settings.content != "inline") {
  358. print_error("INFO: Using input source map: " + settings.content);
  359. settings.content = read_file(settings.content, settings.content);
  360. }
  361. return settings;
  362. }
  363. }
  364. function skip_key(key) {
  365. return skip_keys.indexOf(key) >= 0;
  366. }
  367. function format_object(obj) {
  368. var lines = [];
  369. var padding = "";
  370. Object.keys(obj).map(function(name) {
  371. if (padding.length < name.length) padding = Array(name.length + 1).join(" ");
  372. return [ name, JSON.stringify(obj[name]) ];
  373. }).forEach(function(tokens) {
  374. lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
  375. });
  376. return lines.join("\n");
  377. }
  378. function print_error(msg) {
  379. process.stderr.write(msg);
  380. process.stderr.write("\n");
  381. }
  382. function print(txt) {
  383. process.stdout.write(txt);
  384. process.stdout.write("\n");
  385. }