minify.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. "use strict";
  2. /* eslint-env browser, es6, node */
  3. import {
  4. defaults,
  5. map_from_object,
  6. map_to_object,
  7. HOP,
  8. } from "./utils/index.js";
  9. import { AST_Toplevel, AST_Node, walk, AST_Scope } from "./ast.js";
  10. import { parse } from "./parse.js";
  11. import { OutputStream } from "./output.js";
  12. import { Compressor } from "./compress/index.js";
  13. import { base54 } from "./scope.js";
  14. import { SourceMap } from "./sourcemap.js";
  15. import {
  16. mangle_properties,
  17. mangle_private_properties,
  18. reserve_quoted_keys,
  19. } from "./propmangle.js";
  20. // to/from base64 functions
  21. // Prefer built-in Buffer, if available, then use hack
  22. // https://developer.mozilla.org/en-US/docs/Glossary/Base64#The_Unicode_Problem
  23. var to_ascii = typeof Buffer !== "undefined"
  24. ? (b64) => Buffer.from(b64, "base64").toString()
  25. : (b64) => decodeURIComponent(escape(atob(b64)));
  26. var to_base64 = typeof Buffer !== "undefined"
  27. ? (str) => Buffer.from(str).toString("base64")
  28. : (str) => btoa(unescape(encodeURIComponent(str)));
  29. function read_source_map(code) {
  30. var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code);
  31. if (!match) {
  32. console.warn("inline source map not found");
  33. return null;
  34. }
  35. return to_ascii(match[2]);
  36. }
  37. function set_shorthand(name, options, keys) {
  38. if (options[name]) {
  39. keys.forEach(function(key) {
  40. if (options[key]) {
  41. if (typeof options[key] != "object") options[key] = {};
  42. if (!(name in options[key])) options[key][name] = options[name];
  43. }
  44. });
  45. }
  46. }
  47. function init_cache(cache) {
  48. if (!cache) return;
  49. if (!("props" in cache)) {
  50. cache.props = new Map();
  51. } else if (!(cache.props instanceof Map)) {
  52. cache.props = map_from_object(cache.props);
  53. }
  54. }
  55. function cache_to_json(cache) {
  56. return {
  57. props: map_to_object(cache.props)
  58. };
  59. }
  60. function log_input(files, options, fs, debug_folder) {
  61. if (!(fs && fs.writeFileSync && fs.mkdirSync)) {
  62. return;
  63. }
  64. try {
  65. fs.mkdirSync(debug_folder);
  66. } catch (e) {
  67. if (e.code !== "EEXIST") throw e;
  68. }
  69. const log_path = `${debug_folder}/terser-debug-${(Math.random() * 9999999) | 0}.log`;
  70. options = options || {};
  71. const options_str = JSON.stringify(options, (_key, thing) => {
  72. if (typeof thing === "function") return "[Function " + thing.toString() + "]";
  73. if (thing instanceof RegExp) return "[RegExp " + thing.toString() + "]";
  74. return thing;
  75. }, 4);
  76. const files_str = (file) => {
  77. if (typeof file === "object" && options.parse && options.parse.spidermonkey) {
  78. return JSON.stringify(file, null, 2);
  79. } else if (typeof file === "object") {
  80. return Object.keys(file)
  81. .map((key) => key + ": " + files_str(file[key]))
  82. .join("\n\n");
  83. } else if (typeof file === "string") {
  84. return "```\n" + file + "\n```";
  85. } else {
  86. return file; // What do?
  87. }
  88. };
  89. fs.writeFileSync(log_path, "Options: \n" + options_str + "\n\nInput files:\n\n" + files_str(files) + "\n");
  90. }
  91. async function minify(files, options, _fs_module) {
  92. if (
  93. _fs_module
  94. && typeof process === "object"
  95. && process.env
  96. && typeof process.env.TERSER_DEBUG_DIR === "string"
  97. ) {
  98. log_input(files, options, _fs_module, process.env.TERSER_DEBUG_DIR);
  99. }
  100. options = defaults(options, {
  101. compress: {},
  102. ecma: undefined,
  103. enclose: false,
  104. ie8: false,
  105. keep_classnames: undefined,
  106. keep_fnames: false,
  107. mangle: {},
  108. module: false,
  109. nameCache: null,
  110. output: null,
  111. format: null,
  112. parse: {},
  113. rename: undefined,
  114. safari10: false,
  115. sourceMap: false,
  116. spidermonkey: false,
  117. timings: false,
  118. toplevel: false,
  119. warnings: false,
  120. wrap: false,
  121. }, true);
  122. var timings = options.timings && {
  123. start: Date.now()
  124. };
  125. if (options.keep_classnames === undefined) {
  126. options.keep_classnames = options.keep_fnames;
  127. }
  128. if (options.rename === undefined) {
  129. options.rename = options.compress && options.mangle;
  130. }
  131. if (options.output && options.format) {
  132. throw new Error("Please only specify either output or format option, preferrably format.");
  133. }
  134. options.format = options.format || options.output || {};
  135. set_shorthand("ecma", options, [ "parse", "compress", "format" ]);
  136. set_shorthand("ie8", options, [ "compress", "mangle", "format" ]);
  137. set_shorthand("keep_classnames", options, [ "compress", "mangle" ]);
  138. set_shorthand("keep_fnames", options, [ "compress", "mangle" ]);
  139. set_shorthand("module", options, [ "parse", "compress", "mangle" ]);
  140. set_shorthand("safari10", options, [ "mangle", "format" ]);
  141. set_shorthand("toplevel", options, [ "compress", "mangle" ]);
  142. set_shorthand("warnings", options, [ "compress" ]); // legacy
  143. var quoted_props;
  144. if (options.mangle) {
  145. options.mangle = defaults(options.mangle, {
  146. cache: options.nameCache && (options.nameCache.vars || {}),
  147. eval: false,
  148. ie8: false,
  149. keep_classnames: false,
  150. keep_fnames: false,
  151. module: false,
  152. nth_identifier: base54,
  153. properties: false,
  154. reserved: [],
  155. safari10: false,
  156. toplevel: false,
  157. }, true);
  158. if (options.mangle.properties) {
  159. if (typeof options.mangle.properties != "object") {
  160. options.mangle.properties = {};
  161. }
  162. if (options.mangle.properties.keep_quoted) {
  163. quoted_props = options.mangle.properties.reserved;
  164. if (!Array.isArray(quoted_props)) quoted_props = [];
  165. options.mangle.properties.reserved = quoted_props;
  166. }
  167. if (options.nameCache && !("cache" in options.mangle.properties)) {
  168. options.mangle.properties.cache = options.nameCache.props || {};
  169. }
  170. }
  171. init_cache(options.mangle.cache);
  172. init_cache(options.mangle.properties.cache);
  173. }
  174. if (options.sourceMap) {
  175. options.sourceMap = defaults(options.sourceMap, {
  176. asObject: false,
  177. content: null,
  178. filename: null,
  179. includeSources: false,
  180. root: null,
  181. url: null,
  182. }, true);
  183. }
  184. // -- Parse phase --
  185. if (timings) timings.parse = Date.now();
  186. var toplevel;
  187. if (files instanceof AST_Toplevel) {
  188. toplevel = files;
  189. } else {
  190. if (typeof files == "string" || (options.parse.spidermonkey && !Array.isArray(files))) {
  191. files = [ files ];
  192. }
  193. options.parse = options.parse || {};
  194. options.parse.toplevel = null;
  195. if (options.parse.spidermonkey) {
  196. options.parse.toplevel = AST_Node.from_mozilla_ast(Object.keys(files).reduce(function(toplevel, name) {
  197. if (!toplevel) return files[name];
  198. toplevel.body = toplevel.body.concat(files[name].body);
  199. return toplevel;
  200. }, null));
  201. } else {
  202. delete options.parse.spidermonkey;
  203. for (var name in files) if (HOP(files, name)) {
  204. options.parse.filename = name;
  205. options.parse.toplevel = parse(files[name], options.parse);
  206. if (options.sourceMap && options.sourceMap.content == "inline") {
  207. if (Object.keys(files).length > 1)
  208. throw new Error("inline source map only works with singular input");
  209. options.sourceMap.content = read_source_map(files[name]);
  210. }
  211. }
  212. }
  213. toplevel = options.parse.toplevel;
  214. }
  215. if (quoted_props && options.mangle.properties.keep_quoted !== "strict") {
  216. reserve_quoted_keys(toplevel, quoted_props);
  217. }
  218. if (options.wrap) {
  219. toplevel = toplevel.wrap_commonjs(options.wrap);
  220. }
  221. if (options.enclose) {
  222. toplevel = toplevel.wrap_enclose(options.enclose);
  223. }
  224. if (timings) timings.rename = Date.now();
  225. // disable rename on harmony due to expand_names bug in for-of loops
  226. // https://github.com/mishoo/UglifyJS2/issues/2794
  227. if (0 && options.rename) {
  228. toplevel.figure_out_scope(options.mangle);
  229. toplevel.expand_names(options.mangle);
  230. }
  231. // -- Compress phase --
  232. if (timings) timings.compress = Date.now();
  233. if (options.compress) {
  234. toplevel = new Compressor(options.compress, {
  235. mangle_options: options.mangle
  236. }).compress(toplevel);
  237. }
  238. // -- Mangle phase --
  239. if (timings) timings.scope = Date.now();
  240. if (options.mangle) toplevel.figure_out_scope(options.mangle);
  241. if (timings) timings.mangle = Date.now();
  242. if (options.mangle) {
  243. toplevel.compute_char_frequency(options.mangle);
  244. toplevel.mangle_names(options.mangle);
  245. toplevel = mangle_private_properties(toplevel, options.mangle);
  246. }
  247. if (timings) timings.properties = Date.now();
  248. if (options.mangle && options.mangle.properties) {
  249. toplevel = mangle_properties(toplevel, options.mangle.properties);
  250. }
  251. // Format phase
  252. if (timings) timings.format = Date.now();
  253. var result = {};
  254. if (options.format.ast) {
  255. result.ast = toplevel;
  256. }
  257. if (options.format.spidermonkey) {
  258. result.ast = toplevel.to_mozilla_ast();
  259. }
  260. let format_options;
  261. if (!HOP(options.format, "code") || options.format.code) {
  262. // Make a shallow copy so that we can modify without mutating the user's input.
  263. format_options = {...options.format};
  264. if (!format_options.ast) {
  265. // Destroy stuff to save RAM. (unless the deprecated `ast` option is on)
  266. format_options._destroy_ast = true;
  267. walk(toplevel, node => {
  268. if (node instanceof AST_Scope) {
  269. node.variables = undefined;
  270. node.enclosed = undefined;
  271. node.parent_scope = undefined;
  272. }
  273. if (node.block_scope) {
  274. node.block_scope.variables = undefined;
  275. node.block_scope.enclosed = undefined;
  276. node.parent_scope = undefined;
  277. }
  278. });
  279. }
  280. if (options.sourceMap) {
  281. if (options.sourceMap.includeSources && files instanceof AST_Toplevel) {
  282. throw new Error("original source content unavailable");
  283. }
  284. format_options.source_map = await SourceMap({
  285. file: options.sourceMap.filename,
  286. orig: options.sourceMap.content,
  287. root: options.sourceMap.root,
  288. files: options.sourceMap.includeSources ? files : null,
  289. });
  290. }
  291. delete format_options.ast;
  292. delete format_options.code;
  293. delete format_options.spidermonkey;
  294. var stream = OutputStream(format_options);
  295. toplevel.print(stream);
  296. result.code = stream.get();
  297. if (options.sourceMap) {
  298. Object.defineProperty(result, "map", {
  299. configurable: true,
  300. enumerable: true,
  301. get() {
  302. const map = format_options.source_map.getEncoded();
  303. return (result.map = options.sourceMap.asObject ? map : JSON.stringify(map));
  304. },
  305. set(value) {
  306. Object.defineProperty(result, "map", {
  307. value,
  308. writable: true,
  309. });
  310. }
  311. });
  312. result.decoded_map = format_options.source_map.getDecoded();
  313. if (options.sourceMap.url == "inline") {
  314. var sourceMap = typeof result.map === "object" ? JSON.stringify(result.map) : result.map;
  315. result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap);
  316. } else if (options.sourceMap.url) {
  317. result.code += "\n//# sourceMappingURL=" + options.sourceMap.url;
  318. }
  319. }
  320. }
  321. if (options.nameCache && options.mangle) {
  322. if (options.mangle.cache) options.nameCache.vars = cache_to_json(options.mangle.cache);
  323. if (options.mangle.properties && options.mangle.properties.cache) {
  324. options.nameCache.props = cache_to_json(options.mangle.properties.cache);
  325. }
  326. }
  327. if (format_options && format_options.source_map) {
  328. format_options.source_map.destroy();
  329. }
  330. if (timings) {
  331. timings.end = Date.now();
  332. result.timings = {
  333. parse: 1e-3 * (timings.rename - timings.parse),
  334. rename: 1e-3 * (timings.compress - timings.rename),
  335. compress: 1e-3 * (timings.scope - timings.compress),
  336. scope: 1e-3 * (timings.mangle - timings.scope),
  337. mangle: 1e-3 * (timings.properties - timings.mangle),
  338. properties: 1e-3 * (timings.format - timings.properties),
  339. format: 1e-3 * (timings.end - timings.format),
  340. total: 1e-3 * (timings.end - timings.start)
  341. };
  342. }
  343. return result;
  344. }
  345. export {
  346. minify,
  347. to_ascii,
  348. };