ChunkGroup.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const SortableSet = require("./util/SortableSet");
  8. const {
  9. compareChunks,
  10. compareIterables,
  11. compareLocations
  12. } = require("./util/comparators");
  13. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  14. /** @typedef {import("./Chunk")} Chunk */
  15. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  16. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  17. /** @typedef {import("./Entrypoint")} Entrypoint */
  18. /** @typedef {import("./Module")} Module */
  19. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  20. /** @typedef {{ module: Module | null, loc: DependencyLocation, request: string }} OriginRecord */
  21. /**
  22. * @typedef {object} RawChunkGroupOptions
  23. * @property {number=} preloadOrder
  24. * @property {number=} prefetchOrder
  25. * @property {("low" | "high" | "auto")=} fetchPriority
  26. */
  27. /** @typedef {RawChunkGroupOptions & { name?: string | null }} ChunkGroupOptions */
  28. let debugId = 5000;
  29. /**
  30. * @template T
  31. * @param {SortableSet<T>} set set to convert to array.
  32. * @returns {T[]} the array format of existing set
  33. */
  34. const getArray = (set) => [...set];
  35. /**
  36. * A convenience method used to sort chunks based on their id's
  37. * @param {ChunkGroup} a first sorting comparator
  38. * @param {ChunkGroup} b second sorting comparator
  39. * @returns {1 | 0 | -1} a sorting index to determine order
  40. */
  41. const sortById = (a, b) => {
  42. if (a.id < b.id) return -1;
  43. if (b.id < a.id) return 1;
  44. return 0;
  45. };
  46. /**
  47. * @param {OriginRecord} a the first comparator in sort
  48. * @param {OriginRecord} b the second comparator in sort
  49. * @returns {1 | -1| 0} returns sorting order as index
  50. */
  51. const sortOrigin = (a, b) => {
  52. const aIdent = a.module ? a.module.identifier() : "";
  53. const bIdent = b.module ? b.module.identifier() : "";
  54. if (aIdent < bIdent) return -1;
  55. if (aIdent > bIdent) return 1;
  56. return compareLocations(a.loc, b.loc);
  57. };
  58. class ChunkGroup {
  59. /**
  60. * Creates an instance of ChunkGroup.
  61. * @param {string | ChunkGroupOptions=} options chunk group options passed to chunkGroup
  62. */
  63. constructor(options) {
  64. if (typeof options === "string") {
  65. options = { name: options };
  66. } else if (!options) {
  67. options = { name: undefined };
  68. }
  69. /** @type {number} */
  70. this.groupDebugId = debugId++;
  71. this.options = /** @type {ChunkGroupOptions} */ (options);
  72. /** @type {SortableSet<ChunkGroup>} */
  73. this._children = new SortableSet(undefined, sortById);
  74. /** @type {SortableSet<ChunkGroup>} */
  75. this._parents = new SortableSet(undefined, sortById);
  76. /** @type {SortableSet<ChunkGroup>} */
  77. this._asyncEntrypoints = new SortableSet(undefined, sortById);
  78. this._blocks = new SortableSet();
  79. /** @type {Chunk[]} */
  80. this.chunks = [];
  81. /** @type {OriginRecord[]} */
  82. this.origins = [];
  83. /** @typedef {Map<Module, number>} OrderIndices */
  84. /** Indices in top-down order */
  85. /**
  86. * @private
  87. * @type {OrderIndices}
  88. */
  89. this._modulePreOrderIndices = new Map();
  90. /** Indices in bottom-up order */
  91. /**
  92. * @private
  93. * @type {OrderIndices}
  94. */
  95. this._modulePostOrderIndices = new Map();
  96. /** @type {number | undefined} */
  97. this.index = undefined;
  98. }
  99. /**
  100. * when a new chunk is added to a chunkGroup, addingOptions will occur.
  101. * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions
  102. * @returns {void}
  103. */
  104. addOptions(options) {
  105. for (const key of /** @type {(keyof ChunkGroupOptions)[]} */ (
  106. Object.keys(options)
  107. )) {
  108. if (this.options[key] === undefined) {
  109. /** @type {ChunkGroupOptions[keyof ChunkGroupOptions]} */
  110. (this.options[key]) = options[key];
  111. } else if (this.options[key] !== options[key]) {
  112. if (key.endsWith("Order")) {
  113. const orderKey =
  114. /** @type {Exclude<keyof ChunkGroupOptions, "name" | "fetchPriority">} */
  115. (key);
  116. this.options[orderKey] = Math.max(
  117. /** @type {number} */
  118. (this.options[orderKey]),
  119. /** @type {number} */
  120. (options[orderKey])
  121. );
  122. } else {
  123. throw new Error(
  124. `ChunkGroup.addOptions: No option merge strategy for ${key}`
  125. );
  126. }
  127. }
  128. }
  129. }
  130. /**
  131. * returns the name of current ChunkGroup
  132. * @returns {ChunkGroupOptions["name"]} returns the ChunkGroup name
  133. */
  134. get name() {
  135. return this.options.name;
  136. }
  137. /**
  138. * sets a new name for current ChunkGroup
  139. * @param {string | undefined} value the new name for ChunkGroup
  140. * @returns {void}
  141. */
  142. set name(value) {
  143. this.options.name = value;
  144. }
  145. /* istanbul ignore next */
  146. /**
  147. * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's
  148. * @returns {string} a unique concatenation of chunk debugId's
  149. */
  150. get debugId() {
  151. return Array.from(this.chunks, (x) => x.debugId).join("+");
  152. }
  153. /**
  154. * get a unique id for ChunkGroup, made up of its member Chunk id's
  155. * @returns {string} a unique concatenation of chunk ids
  156. */
  157. get id() {
  158. return Array.from(this.chunks, (x) => x.id).join("+");
  159. }
  160. /**
  161. * Performs an unshift of a specific chunk
  162. * @param {Chunk} chunk chunk being unshifted
  163. * @returns {boolean} returns true if attempted chunk shift is accepted
  164. */
  165. unshiftChunk(chunk) {
  166. const oldIdx = this.chunks.indexOf(chunk);
  167. if (oldIdx > 0) {
  168. this.chunks.splice(oldIdx, 1);
  169. this.chunks.unshift(chunk);
  170. } else if (oldIdx < 0) {
  171. this.chunks.unshift(chunk);
  172. return true;
  173. }
  174. return false;
  175. }
  176. /**
  177. * inserts a chunk before another existing chunk in group
  178. * @param {Chunk} chunk Chunk being inserted
  179. * @param {Chunk} before Placeholder/target chunk marking new chunk insertion point
  180. * @returns {boolean} return true if insertion was successful
  181. */
  182. insertChunk(chunk, before) {
  183. const oldIdx = this.chunks.indexOf(chunk);
  184. const idx = this.chunks.indexOf(before);
  185. if (idx < 0) {
  186. throw new Error("before chunk not found");
  187. }
  188. if (oldIdx >= 0 && oldIdx > idx) {
  189. this.chunks.splice(oldIdx, 1);
  190. this.chunks.splice(idx, 0, chunk);
  191. } else if (oldIdx < 0) {
  192. this.chunks.splice(idx, 0, chunk);
  193. return true;
  194. }
  195. return false;
  196. }
  197. /**
  198. * add a chunk into ChunkGroup. Is pushed on or prepended
  199. * @param {Chunk} chunk chunk being pushed into ChunkGroupS
  200. * @returns {boolean} returns true if chunk addition was successful.
  201. */
  202. pushChunk(chunk) {
  203. const oldIdx = this.chunks.indexOf(chunk);
  204. if (oldIdx >= 0) {
  205. return false;
  206. }
  207. this.chunks.push(chunk);
  208. return true;
  209. }
  210. /**
  211. * @param {Chunk} oldChunk chunk to be replaced
  212. * @param {Chunk} newChunk New chunk that will be replaced with
  213. * @returns {boolean | undefined} returns true if the replacement was successful
  214. */
  215. replaceChunk(oldChunk, newChunk) {
  216. const oldIdx = this.chunks.indexOf(oldChunk);
  217. if (oldIdx < 0) return false;
  218. const newIdx = this.chunks.indexOf(newChunk);
  219. if (newIdx < 0) {
  220. this.chunks[oldIdx] = newChunk;
  221. return true;
  222. }
  223. if (newIdx < oldIdx) {
  224. this.chunks.splice(oldIdx, 1);
  225. return true;
  226. } else if (newIdx !== oldIdx) {
  227. this.chunks[oldIdx] = newChunk;
  228. this.chunks.splice(newIdx, 1);
  229. return true;
  230. }
  231. }
  232. /**
  233. * @param {Chunk} chunk chunk to remove
  234. * @returns {boolean} returns true if chunk was removed
  235. */
  236. removeChunk(chunk) {
  237. const idx = this.chunks.indexOf(chunk);
  238. if (idx >= 0) {
  239. this.chunks.splice(idx, 1);
  240. return true;
  241. }
  242. return false;
  243. }
  244. /**
  245. * @returns {boolean} true, when this chunk group will be loaded on initial page load
  246. */
  247. isInitial() {
  248. return false;
  249. }
  250. /**
  251. * @param {ChunkGroup} group chunk group to add
  252. * @returns {boolean} returns true if chunk group was added
  253. */
  254. addChild(group) {
  255. const size = this._children.size;
  256. this._children.add(group);
  257. return size !== this._children.size;
  258. }
  259. /**
  260. * @returns {ChunkGroup[]} returns the children of this group
  261. */
  262. getChildren() {
  263. return this._children.getFromCache(getArray);
  264. }
  265. getNumberOfChildren() {
  266. return this._children.size;
  267. }
  268. get childrenIterable() {
  269. return this._children;
  270. }
  271. /**
  272. * @param {ChunkGroup} group the chunk group to remove
  273. * @returns {boolean} returns true if the chunk group was removed
  274. */
  275. removeChild(group) {
  276. if (!this._children.has(group)) {
  277. return false;
  278. }
  279. this._children.delete(group);
  280. group.removeParent(this);
  281. return true;
  282. }
  283. /**
  284. * @param {ChunkGroup} parentChunk the parent group to be added into
  285. * @returns {boolean} returns true if this chunk group was added to the parent group
  286. */
  287. addParent(parentChunk) {
  288. if (!this._parents.has(parentChunk)) {
  289. this._parents.add(parentChunk);
  290. return true;
  291. }
  292. return false;
  293. }
  294. /**
  295. * @returns {ChunkGroup[]} returns the parents of this group
  296. */
  297. getParents() {
  298. return this._parents.getFromCache(getArray);
  299. }
  300. getNumberOfParents() {
  301. return this._parents.size;
  302. }
  303. /**
  304. * @param {ChunkGroup} parent the parent group
  305. * @returns {boolean} returns true if the parent group contains this group
  306. */
  307. hasParent(parent) {
  308. return this._parents.has(parent);
  309. }
  310. get parentsIterable() {
  311. return this._parents;
  312. }
  313. /**
  314. * @param {ChunkGroup} chunkGroup the parent group
  315. * @returns {boolean} returns true if this group has been removed from the parent
  316. */
  317. removeParent(chunkGroup) {
  318. if (this._parents.delete(chunkGroup)) {
  319. chunkGroup.removeChild(this);
  320. return true;
  321. }
  322. return false;
  323. }
  324. /**
  325. * @param {Entrypoint} entrypoint entrypoint to add
  326. * @returns {boolean} returns true if entrypoint was added
  327. */
  328. addAsyncEntrypoint(entrypoint) {
  329. const size = this._asyncEntrypoints.size;
  330. this._asyncEntrypoints.add(entrypoint);
  331. return size !== this._asyncEntrypoints.size;
  332. }
  333. get asyncEntrypointsIterable() {
  334. return this._asyncEntrypoints;
  335. }
  336. /**
  337. * @returns {AsyncDependenciesBlock[]} an array containing the blocks
  338. */
  339. getBlocks() {
  340. return this._blocks.getFromCache(getArray);
  341. }
  342. getNumberOfBlocks() {
  343. return this._blocks.size;
  344. }
  345. /**
  346. * @param {AsyncDependenciesBlock} block block
  347. * @returns {boolean} true, if block exists
  348. */
  349. hasBlock(block) {
  350. return this._blocks.has(block);
  351. }
  352. /**
  353. * @returns {Iterable<AsyncDependenciesBlock>} blocks
  354. */
  355. get blocksIterable() {
  356. return this._blocks;
  357. }
  358. /**
  359. * @param {AsyncDependenciesBlock} block a block
  360. * @returns {boolean} false, if block was already added
  361. */
  362. addBlock(block) {
  363. if (!this._blocks.has(block)) {
  364. this._blocks.add(block);
  365. return true;
  366. }
  367. return false;
  368. }
  369. /**
  370. * @param {Module | null} module origin module
  371. * @param {DependencyLocation} loc location of the reference in the origin module
  372. * @param {string} request request name of the reference
  373. * @returns {void}
  374. */
  375. addOrigin(module, loc, request) {
  376. this.origins.push({
  377. module,
  378. loc,
  379. request
  380. });
  381. }
  382. /**
  383. * @returns {string[]} the files contained this chunk group
  384. */
  385. getFiles() {
  386. const files = new Set();
  387. for (const chunk of this.chunks) {
  388. for (const file of chunk.files) {
  389. files.add(file);
  390. }
  391. }
  392. return [...files];
  393. }
  394. /**
  395. * @returns {void}
  396. */
  397. remove() {
  398. // cleanup parents
  399. for (const parentChunkGroup of this._parents) {
  400. // remove this chunk from its parents
  401. parentChunkGroup._children.delete(this);
  402. // cleanup "sub chunks"
  403. for (const chunkGroup of this._children) {
  404. /**
  405. * remove this chunk as "intermediary" and connect
  406. * it "sub chunks" and parents directly
  407. */
  408. // add parent to each "sub chunk"
  409. chunkGroup.addParent(parentChunkGroup);
  410. // add "sub chunk" to parent
  411. parentChunkGroup.addChild(chunkGroup);
  412. }
  413. }
  414. /**
  415. * we need to iterate again over the children
  416. * to remove this from the child's parents.
  417. * This can not be done in the above loop
  418. * as it is not guaranteed that `this._parents` contains anything.
  419. */
  420. for (const chunkGroup of this._children) {
  421. // remove this as parent of every "sub chunk"
  422. chunkGroup._parents.delete(this);
  423. }
  424. // remove chunks
  425. for (const chunk of this.chunks) {
  426. chunk.removeGroup(this);
  427. }
  428. }
  429. sortItems() {
  430. this.origins.sort(sortOrigin);
  431. }
  432. /**
  433. * Sorting predicate which allows current ChunkGroup to be compared against another.
  434. * Sorting values are based off of number of chunks in ChunkGroup.
  435. * @param {ChunkGraph} chunkGraph the chunk graph
  436. * @param {ChunkGroup} otherGroup the chunkGroup to compare this against
  437. * @returns {-1 | 0 | 1} sort position for comparison
  438. */
  439. compareTo(chunkGraph, otherGroup) {
  440. if (this.chunks.length > otherGroup.chunks.length) return -1;
  441. if (this.chunks.length < otherGroup.chunks.length) return 1;
  442. return compareIterables(compareChunks(chunkGraph))(
  443. this.chunks,
  444. otherGroup.chunks
  445. );
  446. }
  447. /**
  448. * @param {ModuleGraph} moduleGraph the module graph
  449. * @param {ChunkGraph} chunkGraph the chunk graph
  450. * @returns {Record<string, ChunkGroup[]>} mapping from children type to ordered list of ChunkGroups
  451. */
  452. getChildrenByOrders(moduleGraph, chunkGraph) {
  453. /** @type {Map<string, {order: number, group: ChunkGroup}[]>} */
  454. const lists = new Map();
  455. for (const childGroup of this._children) {
  456. for (const key of Object.keys(childGroup.options)) {
  457. if (key.endsWith("Order")) {
  458. const name = key.slice(0, key.length - "Order".length);
  459. let list = lists.get(name);
  460. if (list === undefined) {
  461. lists.set(name, (list = []));
  462. }
  463. list.push({
  464. order:
  465. /** @type {number} */
  466. (
  467. childGroup.options[/** @type {keyof ChunkGroupOptions} */ (key)]
  468. ),
  469. group: childGroup
  470. });
  471. }
  472. }
  473. }
  474. /** @type {Record<string, ChunkGroup[]>} */
  475. const result = Object.create(null);
  476. for (const [name, list] of lists) {
  477. list.sort((a, b) => {
  478. const cmp = b.order - a.order;
  479. if (cmp !== 0) return cmp;
  480. return a.group.compareTo(chunkGraph, b.group);
  481. });
  482. result[name] = list.map((i) => i.group);
  483. }
  484. return result;
  485. }
  486. /**
  487. * Sets the top-down index of a module in this ChunkGroup
  488. * @param {Module} module module for which the index should be set
  489. * @param {number} index the index of the module
  490. * @returns {void}
  491. */
  492. setModulePreOrderIndex(module, index) {
  493. this._modulePreOrderIndices.set(module, index);
  494. }
  495. /**
  496. * Gets the top-down index of a module in this ChunkGroup
  497. * @param {Module} module the module
  498. * @returns {number | undefined} index
  499. */
  500. getModulePreOrderIndex(module) {
  501. return this._modulePreOrderIndices.get(module);
  502. }
  503. /**
  504. * Sets the bottom-up index of a module in this ChunkGroup
  505. * @param {Module} module module for which the index should be set
  506. * @param {number} index the index of the module
  507. * @returns {void}
  508. */
  509. setModulePostOrderIndex(module, index) {
  510. this._modulePostOrderIndices.set(module, index);
  511. }
  512. /**
  513. * Gets the bottom-up index of a module in this ChunkGroup
  514. * @param {Module} module the module
  515. * @returns {number | undefined} index
  516. */
  517. getModulePostOrderIndex(module) {
  518. return this._modulePostOrderIndices.get(module);
  519. }
  520. /* istanbul ignore next */
  521. checkConstraints() {
  522. const chunk = this;
  523. for (const child of chunk._children) {
  524. if (!child._parents.has(chunk)) {
  525. throw new Error(
  526. `checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`
  527. );
  528. }
  529. }
  530. for (const parentChunk of chunk._parents) {
  531. if (!parentChunk._children.has(chunk)) {
  532. throw new Error(
  533. `checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`
  534. );
  535. }
  536. }
  537. }
  538. }
  539. ChunkGroup.prototype.getModuleIndex = util.deprecate(
  540. ChunkGroup.prototype.getModulePreOrderIndex,
  541. "ChunkGroup.getModuleIndex was renamed to getModulePreOrderIndex",
  542. "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX"
  543. );
  544. ChunkGroup.prototype.getModuleIndex2 = util.deprecate(
  545. ChunkGroup.prototype.getModulePostOrderIndex,
  546. "ChunkGroup.getModuleIndex2 was renamed to getModulePostOrderIndex",
  547. "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX_2"
  548. );
  549. module.exports = ChunkGroup;