minify.js 12 KB

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