propmangle.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. "use strict";
  34. /* global global, self */
  35. import {
  36. defaults,
  37. push_uniq,
  38. } from "./utils/index.js";
  39. import { base54 } from "./scope.js";
  40. import {
  41. AST_Binary,
  42. AST_Call,
  43. AST_ClassPrivateProperty,
  44. AST_Conditional,
  45. AST_Dot,
  46. AST_DotHash,
  47. AST_ObjectKeyVal,
  48. AST_ObjectProperty,
  49. AST_PrivateMethod,
  50. AST_PrivateGetter,
  51. AST_PrivateSetter,
  52. AST_PrivateIn,
  53. AST_Sequence,
  54. AST_String,
  55. AST_Sub,
  56. TreeTransformer,
  57. TreeWalker,
  58. } from "./ast.js";
  59. import { domprops } from "../tools/domprops.js";
  60. function find_builtins(reserved) {
  61. domprops.forEach(add);
  62. // Compatibility fix for some standard defined globals not defined on every js environment
  63. var new_globals = ["Symbol", "Map", "Promise", "Proxy", "Reflect", "Set", "WeakMap", "WeakSet"];
  64. var objects = {};
  65. var global_ref = typeof global === "object" ? global : self;
  66. new_globals.forEach(function (new_global) {
  67. objects[new_global] = global_ref[new_global] || function() {};
  68. });
  69. [
  70. "null",
  71. "true",
  72. "false",
  73. "NaN",
  74. "Infinity",
  75. "-Infinity",
  76. "undefined",
  77. ].forEach(add);
  78. [ Object, Array, Function, Number,
  79. String, Boolean, Error, Math,
  80. Date, RegExp, objects.Symbol, ArrayBuffer,
  81. DataView, decodeURI, decodeURIComponent,
  82. encodeURI, encodeURIComponent, eval, EvalError,
  83. Float32Array, Float64Array, Int8Array, Int16Array,
  84. Int32Array, isFinite, isNaN, JSON, objects.Map, parseFloat,
  85. parseInt, objects.Promise, objects.Proxy, RangeError, ReferenceError,
  86. objects.Reflect, objects.Set, SyntaxError, TypeError, Uint8Array,
  87. Uint8ClampedArray, Uint16Array, Uint32Array, URIError,
  88. objects.WeakMap, objects.WeakSet
  89. ].forEach(function(ctor) {
  90. Object.getOwnPropertyNames(ctor).map(add);
  91. if (ctor.prototype) {
  92. Object.getOwnPropertyNames(ctor.prototype).map(add);
  93. }
  94. });
  95. function add(name) {
  96. reserved.add(name);
  97. }
  98. }
  99. function reserve_quoted_keys(ast, reserved) {
  100. function add(name) {
  101. push_uniq(reserved, name);
  102. }
  103. ast.walk(new TreeWalker(function(node) {
  104. if (node instanceof AST_ObjectKeyVal && node.quote) {
  105. add(node.key);
  106. } else if (node instanceof AST_ObjectProperty && node.quote) {
  107. add(node.key.name);
  108. } else if (node instanceof AST_Sub) {
  109. addStrings(node.property, add);
  110. }
  111. }));
  112. }
  113. function addStrings(node, add) {
  114. node.walk(new TreeWalker(function(node) {
  115. if (node instanceof AST_Sequence) {
  116. addStrings(node.tail_node(), add);
  117. } else if (node instanceof AST_String) {
  118. add(node.value);
  119. } else if (node instanceof AST_Conditional) {
  120. addStrings(node.consequent, add);
  121. addStrings(node.alternative, add);
  122. }
  123. return true;
  124. }));
  125. }
  126. function mangle_private_properties(ast, options) {
  127. var cprivate = -1;
  128. var private_cache = new Map();
  129. var nth_identifier = options.nth_identifier || base54;
  130. ast = ast.transform(new TreeTransformer(function(node) {
  131. if (
  132. node instanceof AST_ClassPrivateProperty
  133. || node instanceof AST_PrivateMethod
  134. || node instanceof AST_PrivateGetter
  135. || node instanceof AST_PrivateSetter
  136. || node instanceof AST_PrivateIn
  137. ) {
  138. node.key.name = mangle_private(node.key.name);
  139. } else if (node instanceof AST_DotHash) {
  140. node.property = mangle_private(node.property);
  141. }
  142. }));
  143. return ast;
  144. function mangle_private(name) {
  145. let mangled = private_cache.get(name);
  146. if (!mangled) {
  147. mangled = nth_identifier.get(++cprivate);
  148. private_cache.set(name, mangled);
  149. }
  150. return mangled;
  151. }
  152. }
  153. function mangle_properties(ast, options) {
  154. options = defaults(options, {
  155. builtins: false,
  156. cache: null,
  157. debug: false,
  158. keep_quoted: false,
  159. nth_identifier: base54,
  160. only_cache: false,
  161. regex: null,
  162. reserved: null,
  163. undeclared: false,
  164. }, true);
  165. var nth_identifier = options.nth_identifier;
  166. var reserved_option = options.reserved;
  167. if (!Array.isArray(reserved_option)) reserved_option = [reserved_option];
  168. var reserved = new Set(reserved_option);
  169. if (!options.builtins) find_builtins(reserved);
  170. var cname = -1;
  171. var cache;
  172. if (options.cache) {
  173. cache = options.cache.props;
  174. } else {
  175. cache = new Map();
  176. }
  177. var regex = options.regex && new RegExp(options.regex);
  178. // note debug is either false (disabled), or a string of the debug suffix to use (enabled).
  179. // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true'
  180. // the same as passing an empty string.
  181. var debug = options.debug !== false;
  182. var debug_name_suffix;
  183. if (debug) {
  184. debug_name_suffix = (options.debug === true ? "" : options.debug);
  185. }
  186. var names_to_mangle = new Set();
  187. var unmangleable = new Set();
  188. // Track each already-mangled name to prevent nth_identifier from generating
  189. // the same name.
  190. cache.forEach((mangled_name) => unmangleable.add(mangled_name));
  191. var keep_quoted = !!options.keep_quoted;
  192. // step 1: find candidates to mangle
  193. ast.walk(new TreeWalker(function(node) {
  194. if (
  195. node instanceof AST_ClassPrivateProperty
  196. || node instanceof AST_PrivateMethod
  197. || node instanceof AST_PrivateGetter
  198. || node instanceof AST_PrivateSetter
  199. || node instanceof AST_DotHash
  200. ) {
  201. // handled by mangle_private_properties
  202. } else if (node instanceof AST_ObjectKeyVal) {
  203. if (typeof node.key == "string" && (!keep_quoted || !node.quote)) {
  204. add(node.key);
  205. }
  206. } else if (node instanceof AST_ObjectProperty) {
  207. // setter or getter, since KeyVal is handled above
  208. if (!keep_quoted || !node.quote) {
  209. add(node.key.name);
  210. }
  211. } else if (node instanceof AST_Dot) {
  212. var declared = !!options.undeclared;
  213. if (!declared) {
  214. var root = node;
  215. while (root.expression) {
  216. root = root.expression;
  217. }
  218. declared = !(root.thedef && root.thedef.undeclared);
  219. }
  220. if (declared &&
  221. (!keep_quoted || !node.quote)) {
  222. add(node.property);
  223. }
  224. } else if (node instanceof AST_Sub) {
  225. if (!keep_quoted) {
  226. addStrings(node.property, add);
  227. }
  228. } else if (node instanceof AST_Call
  229. && node.expression.print_to_string() == "Object.defineProperty") {
  230. addStrings(node.args[1], add);
  231. } else if (node instanceof AST_Binary && node.operator === "in") {
  232. addStrings(node.left, add);
  233. }
  234. }));
  235. // step 2: transform the tree, renaming properties
  236. return ast.transform(new TreeTransformer(function(node) {
  237. if (
  238. node instanceof AST_ClassPrivateProperty
  239. || node instanceof AST_PrivateMethod
  240. || node instanceof AST_PrivateGetter
  241. || node instanceof AST_PrivateSetter
  242. || node instanceof AST_DotHash
  243. ) {
  244. // handled by mangle_private_properties
  245. } else if (node instanceof AST_ObjectKeyVal) {
  246. if (typeof node.key == "string" && (!keep_quoted || !node.quote)) {
  247. node.key = mangle(node.key);
  248. }
  249. } else if (node instanceof AST_ObjectProperty) {
  250. // setter, getter, method or class field
  251. if (!keep_quoted || !node.quote) {
  252. node.key.name = mangle(node.key.name);
  253. }
  254. } else if (node instanceof AST_Dot) {
  255. if (!keep_quoted || !node.quote) {
  256. node.property = mangle(node.property);
  257. }
  258. } else if (!keep_quoted && node instanceof AST_Sub) {
  259. node.property = mangleStrings(node.property);
  260. } else if (node instanceof AST_Call
  261. && node.expression.print_to_string() == "Object.defineProperty") {
  262. node.args[1] = mangleStrings(node.args[1]);
  263. } else if (node instanceof AST_Binary && node.operator === "in") {
  264. node.left = mangleStrings(node.left);
  265. }
  266. }));
  267. // only function declarations after this line
  268. function can_mangle(name) {
  269. if (unmangleable.has(name)) return false;
  270. if (reserved.has(name)) return false;
  271. if (options.only_cache) {
  272. return cache.has(name);
  273. }
  274. if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false;
  275. return true;
  276. }
  277. function should_mangle(name) {
  278. if (regex && !regex.test(name)) return false;
  279. if (reserved.has(name)) return false;
  280. return cache.has(name)
  281. || names_to_mangle.has(name);
  282. }
  283. function add(name) {
  284. if (can_mangle(name))
  285. names_to_mangle.add(name);
  286. if (!should_mangle(name)) {
  287. unmangleable.add(name);
  288. }
  289. }
  290. function mangle(name) {
  291. if (!should_mangle(name)) {
  292. return name;
  293. }
  294. var mangled = cache.get(name);
  295. if (!mangled) {
  296. if (debug) {
  297. // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_.
  298. var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_";
  299. if (can_mangle(debug_mangled)) {
  300. mangled = debug_mangled;
  301. }
  302. }
  303. // either debug mode is off, or it is on and we could not use the mangled name
  304. if (!mangled) {
  305. do {
  306. mangled = nth_identifier.get(++cname);
  307. } while (!can_mangle(mangled));
  308. }
  309. cache.set(name, mangled);
  310. }
  311. return mangled;
  312. }
  313. function mangleStrings(node) {
  314. return node.transform(new TreeTransformer(function(node) {
  315. if (node instanceof AST_Sequence) {
  316. var last = node.expressions.length - 1;
  317. node.expressions[last] = mangleStrings(node.expressions[last]);
  318. } else if (node instanceof AST_String) {
  319. node.value = mangle(node.value);
  320. } else if (node instanceof AST_Conditional) {
  321. node.consequent = mangleStrings(node.consequent);
  322. node.alternative = mangleStrings(node.alternative);
  323. }
  324. return node;
  325. }));
  326. }
  327. }
  328. export {
  329. reserve_quoted_keys,
  330. mangle_properties,
  331. mangle_private_properties,
  332. };