IdHelpers.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const createHash = require("../util/createHash");
  7. const { makePathsRelative } = require("../util/identifier");
  8. const numberHash = require("../util/numberHash");
  9. /** @typedef {import("../Chunk")} Chunk */
  10. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  11. /** @typedef {import("../Compilation")} Compilation */
  12. /** @typedef {import("../Module")} Module */
  13. /** @typedef {import("../util/Hash").HashFunction} HashFunction */
  14. /** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
  15. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  16. /**
  17. * Returns hash.
  18. * @param {string} str string to hash
  19. * @param {number} len max length of the hash
  20. * @param {HashFunction} hashFunction hash function to use
  21. * @returns {string} hash
  22. */
  23. const getHash = (str, len, hashFunction) => {
  24. const hash = createHash(hashFunction);
  25. hash.update(str);
  26. const digest = hash.digest("hex");
  27. return digest.slice(0, len);
  28. };
  29. /**
  30. * Returns string prefixed by an underscore if it is a number.
  31. * @param {string} str the string
  32. * @returns {string} string prefixed by an underscore if it is a number
  33. */
  34. const avoidNumber = (str) => {
  35. // max length of a number is 21 chars, bigger numbers a written as "...e+xx"
  36. if (str.length > 21) return str;
  37. const firstChar = str.charCodeAt(0);
  38. // skip everything that doesn't look like a number
  39. // charCodes: "-": 45, "1": 49, "9": 57
  40. if (firstChar < 49) {
  41. if (firstChar !== 45) return str;
  42. } else if (firstChar > 57) {
  43. return str;
  44. }
  45. if (str === String(Number(str))) {
  46. return `_${str}`;
  47. }
  48. return str;
  49. };
  50. /**
  51. * Returns id representation.
  52. * @param {string} request the request
  53. * @returns {string} id representation
  54. */
  55. const requestToId = (request) =>
  56. request.replace(/^(\.\.?\/)+/, "").replace(/(^[.-]|[^a-z0-9_-])+/gi, "_");
  57. /**
  58. * Shorten long string.
  59. * @param {string} string the string
  60. * @param {string} delimiter separator for string and hash
  61. * @param {HashFunction} hashFunction hash function to use
  62. * @returns {string} string with limited max length to 100 chars
  63. */
  64. const shortenLongString = (string, delimiter, hashFunction) => {
  65. if (string.length < 100) return string;
  66. return (
  67. string.slice(0, 100 - 6 - delimiter.length) +
  68. delimiter +
  69. getHash(string, 6, hashFunction)
  70. );
  71. };
  72. /**
  73. * Gets short module name.
  74. * @param {Module} module the module
  75. * @param {string} context context directory
  76. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  77. * @returns {string} short module name
  78. */
  79. const getShortModuleName = (module, context, associatedObjectForCache) => {
  80. const libIdent = module.libIdent({ context, associatedObjectForCache });
  81. if (libIdent) return avoidNumber(libIdent);
  82. const nameForCondition = module.nameForCondition();
  83. if (nameForCondition) {
  84. return avoidNumber(
  85. makePathsRelative(context, nameForCondition, associatedObjectForCache)
  86. );
  87. }
  88. return "";
  89. };
  90. /**
  91. * Gets long module name.
  92. * @param {string} shortName the short name
  93. * @param {Module} module the module
  94. * @param {string} context context directory
  95. * @param {HashFunction} hashFunction hash function to use
  96. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  97. * @returns {string} long module name
  98. */
  99. const getLongModuleName = (
  100. shortName,
  101. module,
  102. context,
  103. hashFunction,
  104. associatedObjectForCache
  105. ) => {
  106. const fullName = getFullModuleName(module, context, associatedObjectForCache);
  107. return `${shortName}?${getHash(fullName, 4, hashFunction)}`;
  108. };
  109. /**
  110. * Gets full module name.
  111. * @param {Module} module the module
  112. * @param {string} context context directory
  113. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  114. * @returns {string} full module name
  115. */
  116. const getFullModuleName = (module, context, associatedObjectForCache) =>
  117. makePathsRelative(context, module.identifier(), associatedObjectForCache);
  118. /**
  119. * Gets short chunk name.
  120. * @param {Chunk} chunk the chunk
  121. * @param {ChunkGraph} chunkGraph the chunk graph
  122. * @param {string} context context directory
  123. * @param {string} delimiter delimiter for names
  124. * @param {HashFunction} hashFunction hash function to use
  125. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  126. * @returns {string} short chunk name
  127. */
  128. const getShortChunkName = (
  129. chunk,
  130. chunkGraph,
  131. context,
  132. delimiter,
  133. hashFunction,
  134. associatedObjectForCache
  135. ) => {
  136. const modules = chunkGraph.getChunkRootModules(chunk);
  137. const shortModuleNames = modules.map((m) =>
  138. requestToId(getShortModuleName(m, context, associatedObjectForCache))
  139. );
  140. chunk.idNameHints.sort();
  141. const chunkName = [...chunk.idNameHints, ...shortModuleNames]
  142. .filter(Boolean)
  143. .join(delimiter);
  144. return shortenLongString(chunkName, delimiter, hashFunction);
  145. };
  146. /**
  147. * Gets long chunk name.
  148. * @param {Chunk} chunk the chunk
  149. * @param {ChunkGraph} chunkGraph the chunk graph
  150. * @param {string} context context directory
  151. * @param {string} delimiter delimiter for names
  152. * @param {HashFunction} hashFunction hash function to use
  153. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  154. * @returns {string} short chunk name
  155. */
  156. const getLongChunkName = (
  157. chunk,
  158. chunkGraph,
  159. context,
  160. delimiter,
  161. hashFunction,
  162. associatedObjectForCache
  163. ) => {
  164. const modules = chunkGraph.getChunkRootModules(chunk);
  165. const shortModuleNames = modules.map((m) =>
  166. requestToId(getShortModuleName(m, context, associatedObjectForCache))
  167. );
  168. const longModuleNames = modules.map((m) =>
  169. requestToId(
  170. getLongModuleName("", m, context, hashFunction, associatedObjectForCache)
  171. )
  172. );
  173. chunk.idNameHints.sort();
  174. const chunkName = [
  175. ...chunk.idNameHints,
  176. ...shortModuleNames,
  177. ...longModuleNames
  178. ]
  179. .filter(Boolean)
  180. .join(delimiter);
  181. return shortenLongString(chunkName, delimiter, hashFunction);
  182. };
  183. /**
  184. * Gets full chunk name.
  185. * @param {Chunk} chunk the chunk
  186. * @param {ChunkGraph} chunkGraph the chunk graph
  187. * @param {string} context context directory
  188. * @param {AssociatedObjectForCache=} associatedObjectForCache an object to which the cache will be attached
  189. * @returns {string} full chunk name
  190. */
  191. const getFullChunkName = (
  192. chunk,
  193. chunkGraph,
  194. context,
  195. associatedObjectForCache
  196. ) => {
  197. if (chunk.name) return chunk.name;
  198. const modules = chunkGraph.getChunkRootModules(chunk);
  199. const fullModuleNames = modules.map((m) =>
  200. makePathsRelative(context, m.identifier(), associatedObjectForCache)
  201. );
  202. return fullModuleNames.join();
  203. };
  204. /**
  205. * Adds to map of items.
  206. * @template K
  207. * @template V
  208. * @param {Map<K, V[]>} map a map from key to values
  209. * @param {K} key key
  210. * @param {V} value value
  211. * @returns {void}
  212. */
  213. const addToMapOfItems = (map, key, value) => {
  214. let array = map.get(key);
  215. if (array === undefined) {
  216. array = [];
  217. map.set(key, array);
  218. }
  219. array.push(value);
  220. };
  221. /** @typedef {Set<string>} UsedModuleIds */
  222. /**
  223. * Gets used module ids and modules.
  224. * @param {Compilation} compilation the compilation
  225. * @param {((module: Module) => boolean)=} filter filter modules
  226. * @returns {[UsedModuleIds, Module[]]} used module ids as strings and modules without id matching the filter
  227. */
  228. const getUsedModuleIdsAndModules = (compilation, filter) => {
  229. const chunkGraph = compilation.chunkGraph;
  230. /** @type {Module[]} */
  231. const modules = [];
  232. /** @type {UsedModuleIds} */
  233. const usedIds = new Set();
  234. if (compilation.usedModuleIds) {
  235. for (const id of compilation.usedModuleIds) {
  236. usedIds.add(String(id));
  237. }
  238. }
  239. for (const module of compilation.modules) {
  240. if (!module.needId) continue;
  241. const moduleId = chunkGraph.getModuleId(module);
  242. if (moduleId !== null) {
  243. usedIds.add(String(moduleId));
  244. } else if (
  245. (!filter || filter(module)) &&
  246. (chunkGraph.getNumberOfModuleChunks(module) !== 0 ||
  247. // CSS modules need IDs even when not in chunks, for generating CSS class names(i.e. [id]-[local])
  248. /** @type {BuildMeta} */ (module.buildMeta).isCSSModule)
  249. ) {
  250. modules.push(module);
  251. }
  252. }
  253. return [usedIds, modules];
  254. };
  255. /** @typedef {Set<string>} UsedChunkIds */
  256. /**
  257. * Gets used chunk ids.
  258. * @param {Compilation} compilation the compilation
  259. * @returns {UsedChunkIds} used chunk ids as strings
  260. */
  261. const getUsedChunkIds = (compilation) => {
  262. /** @type {UsedChunkIds} */
  263. const usedIds = new Set();
  264. if (compilation.usedChunkIds) {
  265. for (const id of compilation.usedChunkIds) {
  266. usedIds.add(String(id));
  267. }
  268. }
  269. for (const chunk of compilation.chunks) {
  270. const chunkId = chunk.id;
  271. if (chunkId !== null) {
  272. usedIds.add(String(chunkId));
  273. }
  274. }
  275. return usedIds;
  276. };
  277. /**
  278. * Returns list of items without a name.
  279. * @template T
  280. * @param {Iterable<T>} items list of items to be named
  281. * @param {(item: T) => string} getShortName get a short name for an item
  282. * @param {(item: T, name: string) => string} getLongName get a long name for an item
  283. * @param {(a: T, b: T) => -1 | 0 | 1} comparator order of items
  284. * @param {Set<string>} usedIds already used ids, will not be assigned
  285. * @param {(item: T, name: string) => void} assignName assign a name to an item
  286. * @returns {T[]} list of items without a name
  287. */
  288. const assignNames = (
  289. items,
  290. getShortName,
  291. getLongName,
  292. comparator,
  293. usedIds,
  294. assignName
  295. ) => {
  296. /**
  297. * Defines the map to item type used by this module.
  298. * @template T
  299. * @typedef {Map<string, T[]>} MapToItem
  300. */
  301. /** @type {MapToItem<T>} */
  302. const nameToItems = new Map();
  303. for (const item of items) {
  304. const name = getShortName(item);
  305. addToMapOfItems(nameToItems, name, item);
  306. }
  307. /** @type {MapToItem<T>} */
  308. const nameToItems2 = new Map();
  309. for (const [name, items] of nameToItems) {
  310. if (items.length > 1 || !name) {
  311. for (const item of items) {
  312. const longName = getLongName(item, name);
  313. addToMapOfItems(nameToItems2, longName, item);
  314. }
  315. } else {
  316. addToMapOfItems(nameToItems2, name, items[0]);
  317. }
  318. }
  319. /** @type {T[]} */
  320. const unnamedItems = [];
  321. for (const [name, items] of nameToItems2) {
  322. if (!name) {
  323. for (const item of items) {
  324. unnamedItems.push(item);
  325. }
  326. } else if (items.length === 1 && !usedIds.has(name)) {
  327. assignName(items[0], name);
  328. usedIds.add(name);
  329. } else {
  330. items.sort(comparator);
  331. let i = 0;
  332. for (const item of items) {
  333. while (nameToItems2.has(name + i) && usedIds.has(name + i)) i++;
  334. assignName(item, name + i);
  335. usedIds.add(name + i);
  336. i++;
  337. }
  338. }
  339. }
  340. unnamedItems.sort(comparator);
  341. return unnamedItems;
  342. };
  343. /**
  344. * Assign deterministic ids.
  345. * @template T
  346. * @param {T[]} items list of items to be named
  347. * @param {(item: T) => string} getName get a name for an item
  348. * @param {(a: T, n: T) => -1 | 0 | 1} comparator order of items
  349. * @param {(item: T, id: number) => boolean} assignId assign an id to an item
  350. * @param {number[]} ranges usable ranges for ids
  351. * @param {number} expandFactor factor to create more ranges
  352. * @param {number} extraSpace extra space to allocate, i. e. when some ids are already used
  353. * @param {number} salt salting number to initialize hashing
  354. * @returns {void}
  355. */
  356. const assignDeterministicIds = (
  357. items,
  358. getName,
  359. comparator,
  360. assignId,
  361. ranges = [10],
  362. expandFactor = 10,
  363. extraSpace = 0,
  364. salt = 0
  365. ) => {
  366. items.sort(comparator);
  367. // max 5% fill rate
  368. const optimalRange = Math.min(
  369. items.length * 20 + extraSpace,
  370. Number.MAX_SAFE_INTEGER
  371. );
  372. let i = 0;
  373. let range = ranges[i];
  374. while (range < optimalRange) {
  375. i++;
  376. if (i < ranges.length) {
  377. range = Math.min(ranges[i], Number.MAX_SAFE_INTEGER);
  378. } else if (expandFactor) {
  379. range = Math.min(range * expandFactor, Number.MAX_SAFE_INTEGER);
  380. } else {
  381. break;
  382. }
  383. }
  384. for (const item of items) {
  385. const ident = getName(item);
  386. /** @type {number} */
  387. let id;
  388. let i = salt;
  389. do {
  390. id = numberHash(ident + i++, range);
  391. } while (!assignId(item, id));
  392. }
  393. };
  394. /**
  395. * Assign ascending module ids.
  396. * @param {UsedModuleIds} usedIds used ids
  397. * @param {Iterable<Module>} modules the modules
  398. * @param {Compilation} compilation the compilation
  399. * @returns {void}
  400. */
  401. const assignAscendingModuleIds = (usedIds, modules, compilation) => {
  402. const chunkGraph = compilation.chunkGraph;
  403. let nextId = 0;
  404. /** @type {(mod: Module) => void} */
  405. let assignId;
  406. if (usedIds.size > 0) {
  407. /**
  408. * Processes the provided module.
  409. * @param {Module} module the module
  410. */
  411. assignId = (module) => {
  412. if (chunkGraph.getModuleId(module) === null) {
  413. while (usedIds.has(String(nextId))) nextId++;
  414. chunkGraph.setModuleId(module, nextId++);
  415. }
  416. };
  417. } else {
  418. /**
  419. * Processes the provided module.
  420. * @param {Module} module the module
  421. */
  422. assignId = (module) => {
  423. if (chunkGraph.getModuleId(module) === null) {
  424. chunkGraph.setModuleId(module, nextId++);
  425. }
  426. };
  427. }
  428. for (const module of modules) {
  429. assignId(module);
  430. }
  431. };
  432. /**
  433. * Assign ascending chunk ids.
  434. * @param {Iterable<Chunk>} chunks the chunks
  435. * @param {Compilation} compilation the compilation
  436. * @returns {void}
  437. */
  438. const assignAscendingChunkIds = (chunks, compilation) => {
  439. const usedIds = getUsedChunkIds(compilation);
  440. let nextId = 0;
  441. if (usedIds.size > 0) {
  442. for (const chunk of chunks) {
  443. if (chunk.id === null) {
  444. while (usedIds.has(String(nextId))) nextId++;
  445. chunk.id = nextId;
  446. chunk.ids = [nextId];
  447. nextId++;
  448. }
  449. }
  450. } else {
  451. for (const chunk of chunks) {
  452. if (chunk.id === null) {
  453. chunk.id = nextId;
  454. chunk.ids = [nextId];
  455. nextId++;
  456. }
  457. }
  458. }
  459. };
  460. module.exports.assignAscendingChunkIds = assignAscendingChunkIds;
  461. module.exports.assignAscendingModuleIds = assignAscendingModuleIds;
  462. module.exports.assignDeterministicIds = assignDeterministicIds;
  463. module.exports.assignNames = assignNames;
  464. module.exports.getFullChunkName = getFullChunkName;
  465. module.exports.getFullModuleName = getFullModuleName;
  466. module.exports.getLongChunkName = getLongChunkName;
  467. module.exports.getLongModuleName = getLongModuleName;
  468. module.exports.getShortChunkName = getShortChunkName;
  469. module.exports.getShortModuleName = getShortModuleName;
  470. module.exports.getUsedChunkIds = getUsedChunkIds;
  471. module.exports.getUsedModuleIdsAndModules = getUsedModuleIdsAndModules;
  472. module.exports.requestToId = requestToId;