ChunkGroup.js 15 KB

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