ChunkGroup.js 15 KB

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