@atlaspack/bundler-default 2.14.5-canary.20 → 2.14.5-canary.201

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +411 -0
  2. package/dist/DefaultBundler.js +84 -0
  3. package/dist/MonolithicBundler.js +68 -0
  4. package/dist/bundleMerge.js +137 -0
  5. package/dist/bundlerConfig.js +223 -0
  6. package/dist/decorateLegacyGraph.js +189 -0
  7. package/dist/idealGraph.js +1488 -0
  8. package/dist/memoize.js +31 -0
  9. package/dist/stats.js +69 -0
  10. package/lib/DefaultBundler.js +6 -1
  11. package/lib/MonolithicBundler.js +11 -3
  12. package/lib/bundleMerge.js +106 -37
  13. package/lib/bundlerConfig.js +51 -5
  14. package/lib/decorateLegacyGraph.js +24 -3
  15. package/lib/idealGraph.js +426 -50
  16. package/lib/memoize.js +39 -0
  17. package/lib/stats.js +85 -0
  18. package/lib/types/DefaultBundler.d.ts +18 -0
  19. package/lib/types/MonolithicBundler.d.ts +2 -0
  20. package/lib/types/bundleMerge.d.ts +9 -0
  21. package/lib/types/bundlerConfig.d.ts +36 -0
  22. package/lib/types/decorateLegacyGraph.d.ts +3 -0
  23. package/lib/types/idealGraph.d.ts +40 -0
  24. package/lib/types/memoize.d.ts +2 -0
  25. package/lib/types/stats.d.ts +16 -0
  26. package/package.json +20 -12
  27. package/src/{DefaultBundler.js → DefaultBundler.ts} +21 -6
  28. package/src/{MonolithicBundler.js → MonolithicBundler.ts} +17 -5
  29. package/src/bundleMerge.ts +250 -0
  30. package/src/{bundlerConfig.js → bundlerConfig.ts} +105 -44
  31. package/src/{decorateLegacyGraph.js → decorateLegacyGraph.ts} +26 -7
  32. package/src/{idealGraph.js → idealGraph.ts} +669 -102
  33. package/src/memoize.ts +32 -0
  34. package/src/stats.ts +97 -0
  35. package/tsconfig.json +30 -0
  36. package/tsconfig.tsbuildinfo +1 -0
  37. package/src/bundleMerge.js +0 -103
@@ -0,0 +1,1488 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.idealBundleGraphEdges = void 0;
7
+ exports.createIdealGraph = createIdealGraph;
8
+ const path_1 = __importDefault(require("path"));
9
+ const sorted_array_functions_1 = __importDefault(require("sorted-array-functions"));
10
+ const feature_flags_1 = require("@atlaspack/feature-flags");
11
+ const graph_1 = require("@atlaspack/graph");
12
+ const utils_1 = require("@atlaspack/utils");
13
+ const assert_1 = __importDefault(require("assert"));
14
+ const nullthrows_1 = __importDefault(require("nullthrows"));
15
+ const bundleMerge_1 = require("./bundleMerge");
16
+ const stats_1 = require("./stats");
17
+ const dependencyPriorityEdges = {
18
+ sync: 1,
19
+ parallel: 2,
20
+ lazy: 3,
21
+ conditional: 4,
22
+ };
23
+ exports.idealBundleGraphEdges = Object.freeze({
24
+ default: 1,
25
+ conditional: 2,
26
+ });
27
+ function isNonRootBundle(bundle, message) {
28
+ let existingBundle = (0, nullthrows_1.default)(bundle, message);
29
+ (0, assert_1.default)(existingBundle !== 'root', "Bundle cannot be 'root'");
30
+ return existingBundle;
31
+ }
32
+ function createIdealGraph(assetGraph, config, entries, logger) {
33
+ // Asset to the bundle and group it's an entry of
34
+ let bundleRoots = new Map();
35
+ let bundles = new Map();
36
+ let dependencyBundleGraph = new graph_1.ContentGraph();
37
+ let assetReference = new utils_1.DefaultMap(() => []);
38
+ let stats = new stats_1.Stats(config.projectRoot);
39
+ // A Graph of Bundles and a root node (dummy string), which models only Bundles, and connections to their
40
+ // referencing Bundle. There are no actual BundleGroup nodes, just bundles that take on that role.
41
+ let bundleGraph = new graph_1.Graph();
42
+ let stack = [];
43
+ let bundleRootEdgeTypes = {
44
+ parallel: 1,
45
+ lazy: 2,
46
+ };
47
+ // Graph that models bundleRoots, with parallel & async deps only to inform reachability
48
+ let bundleRootGraph = new graph_1.Graph();
49
+ let assetToBundleRootNodeId = new Map();
50
+ let bundleGroupBundleIds = new Set();
51
+ let bundleGraphRootNodeId = (0, nullthrows_1.default)(bundleGraph.addNode('root'));
52
+ bundleGraph.setRootNodeId(bundleGraphRootNodeId);
53
+ // Step Create Entry Bundles
54
+ for (let [asset, dependency] of entries) {
55
+ let bundle = createBundle({
56
+ asset,
57
+ target: (0, nullthrows_1.default)(dependency.target),
58
+ needsStableName: dependency.isEntry,
59
+ });
60
+ let nodeId = bundleGraph.addNode(bundle);
61
+ bundles.set(asset.id, nodeId);
62
+ bundleRoots.set(asset, [nodeId, nodeId]);
63
+ bundleGraph.addEdge(bundleGraphRootNodeId, nodeId);
64
+ dependencyBundleGraph.addEdge(dependencyBundleGraph.addNodeByContentKeyIfNeeded(dependency.id, {
65
+ value: dependency,
66
+ type: 'dependency',
67
+ }), dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(nodeId), {
68
+ value: bundle,
69
+ type: 'bundle',
70
+ }), dependencyPriorityEdges[dependency.priority]);
71
+ bundleGroupBundleIds.add(nodeId);
72
+ }
73
+ let assets = [];
74
+ let assetToIndex = new Map();
75
+ function makeManualAssetToConfigLookup() {
76
+ let manualAssetToConfig = new Map();
77
+ let constantModuleToMSB = new utils_1.DefaultMap(() => []);
78
+ if (config.manualSharedBundles.length === 0) {
79
+ return { manualAssetToConfig, constantModuleToMSB };
80
+ }
81
+ let parentsToConfig = new utils_1.DefaultMap(() => []);
82
+ for (let c of config.manualSharedBundles) {
83
+ if (c.root != null) {
84
+ // @ts-expect-error TS2345
85
+ parentsToConfig.get(path_1.default.join(config.projectRoot, c.root)).push(c);
86
+ }
87
+ }
88
+ let numParentsToFind = parentsToConfig.size;
89
+ let configToParentAsset = new Map();
90
+ assetGraph.traverse((node, _, actions) => {
91
+ if (node.type === 'asset' && parentsToConfig.has(node.value.filePath)) {
92
+ for (let c of parentsToConfig.get(node.value.filePath)) {
93
+ configToParentAsset.set(c, node.value);
94
+ }
95
+ numParentsToFind--;
96
+ if (numParentsToFind === 0) {
97
+ // If we've found all parents we can stop traversal
98
+ actions.stop();
99
+ }
100
+ }
101
+ });
102
+ // Process in reverse order so earlier configs take precedence
103
+ for (let c of config.manualSharedBundles.reverse()) {
104
+ if (c.root != null && !configToParentAsset.has(c)) {
105
+ logger.warn({
106
+ origin: '@atlaspack/bundler-default',
107
+ message: `Manual shared bundle "${c.name}" skipped, no root asset found`,
108
+ });
109
+ continue;
110
+ }
111
+ let parentAsset = configToParentAsset.get(c);
112
+ let assetRegexes = c.assets.map((glob) => (0, utils_1.globToRegex)(glob));
113
+ assetGraph.traverse((node, _, actions) => {
114
+ if (node.type === 'asset' &&
115
+ (!Array.isArray(c.types) || c.types.includes(node.value.type))) {
116
+ let projectRelativePath = path_1.default.relative(config.projectRoot, node.value.filePath);
117
+ // We track all matching MSB's for constant modules as they are never duplicated
118
+ // and need to be assigned to all matching bundles
119
+ if (node.value.meta.isConstantModule === true) {
120
+ // @ts-expect-error TS2345
121
+ constantModuleToMSB.get(node.value).push(c);
122
+ }
123
+ if (assetRegexes.some((regex) => regex.test(projectRelativePath))) {
124
+ manualAssetToConfig.set(node.value, c);
125
+ }
126
+ }
127
+ if (node.type === 'dependency' &&
128
+ (node.value.priority === 'lazy' ||
129
+ ((0, feature_flags_1.getFeatureFlag)('conditionalBundlingApi') &&
130
+ node.value.priority === 'conditional')) &&
131
+ parentAsset) {
132
+ // Don't walk past the bundle group assets
133
+ actions.skipChildren();
134
+ }
135
+ }, parentAsset);
136
+ }
137
+ return { manualAssetToConfig, constantModuleToMSB };
138
+ }
139
+ //Manual is a map of the user-given name to the bundle node Id that corresponds to ALL the assets that match any glob in that user-specified array
140
+ let manualSharedMap = new Map();
141
+ // May need a map to be able to look up NON- bundle root assets which need special case instructions
142
+ // Use this when placing assets into bundles, to avoid duplication
143
+ let manualAssetToBundle = new Map();
144
+ let { manualAssetToConfig, constantModuleToMSB } = makeManualAssetToConfigLookup();
145
+ let manualBundleToInternalizedAsset = new utils_1.DefaultMap(() => []);
146
+ let mergeSourceBundleLookup = new Map();
147
+ let mergeSourceBundleAssets = new Set(config.sharedBundleMerge?.flatMap((c) => c.sourceBundles?.map((assetMatch) => path_1.default.join(config.projectRoot, assetMatch)) ?? []));
148
+ /**
149
+ * Step Create Bundles: Traverse the assetGraph (aka MutableBundleGraph) and create bundles
150
+ * for asset type changes, parallel, inline, and async or lazy dependencies,
151
+ * adding only that asset to each bundle, not its entire subgraph.
152
+ */
153
+ assetGraph.traverse({
154
+ enter(node, context,
155
+ // @ts-expect-error TS2304
156
+ actions) {
157
+ if (node.type === 'asset') {
158
+ if (context?.type === 'dependency' &&
159
+ context?.value.isEntry &&
160
+ !entries.has(node.value)) {
161
+ // Skip whole subtrees of other targets by skipping those entries
162
+ actions.skipChildren();
163
+ return node;
164
+ }
165
+ assetToIndex.set(node.value, assets.length);
166
+ assets.push(node.value);
167
+ let bundleIdTuple = bundleRoots.get(node.value);
168
+ if (bundleIdTuple && bundleIdTuple[0] === bundleIdTuple[1]) {
169
+ // Push to the stack (only) when a new bundle is created
170
+ stack.push([node.value, bundleIdTuple[0]]);
171
+ }
172
+ else if (bundleIdTuple) {
173
+ // Otherwise, push on the last bundle that marks the start of a BundleGroup
174
+ stack.push([node.value, stack[stack.length - 1][1]]);
175
+ }
176
+ }
177
+ else if (node.type === 'dependency') {
178
+ if (context == null) {
179
+ return node;
180
+ }
181
+ let dependency = node.value;
182
+ (0, assert_1.default)(context?.type === 'asset');
183
+ let assets = assetGraph.getDependencyAssets(dependency);
184
+ if (assets.length === 0) {
185
+ return node;
186
+ }
187
+ for (let childAsset of assets) {
188
+ let bundleId = bundles.get(childAsset.id);
189
+ let bundle;
190
+ // MSB Step 1: Match glob on filepath and type for any asset
191
+ let manualSharedBundleKey;
192
+ let manualSharedObject = manualAssetToConfig.get(childAsset);
193
+ if (manualSharedObject) {
194
+ // MSB Step 2: Generate a key for which to look up this manual bundle with
195
+ manualSharedBundleKey =
196
+ manualSharedObject.name + ',' + childAsset.type;
197
+ }
198
+ if (
199
+ // MSB Step 3: If a bundle for these globs already exists, use it
200
+ manualSharedBundleKey != null &&
201
+ manualSharedMap.has(manualSharedBundleKey)) {
202
+ bundleId = (0, nullthrows_1.default)(manualSharedMap.get(manualSharedBundleKey));
203
+ }
204
+ if (dependency.priority === 'lazy' ||
205
+ ((0, feature_flags_1.getFeatureFlag)('conditionalBundlingApi') &&
206
+ node.value.priority === 'conditional') ||
207
+ childAsset.bundleBehavior === 'isolated' || // An isolated Dependency, or Bundle must contain all assets it needs to load.
208
+ childAsset.bundleBehavior === 'inlineIsolated') {
209
+ if (bundleId == null) {
210
+ let firstBundleGroup = (0, nullthrows_1.default)(bundleGraph.getNode(stack[0][1]));
211
+ (0, assert_1.default)(firstBundleGroup !== 'root');
212
+ bundle = createBundle({
213
+ asset: childAsset,
214
+ bundleBehavior: dependency.bundleBehavior ?? childAsset.bundleBehavior,
215
+ needsStableName: dependency.bundleBehavior === 'inline' ||
216
+ childAsset.bundleBehavior === 'inline' ||
217
+ dependency.bundleBehavior === 'inlineIsolated' ||
218
+ childAsset.bundleBehavior === 'inlineIsolated'
219
+ ? false
220
+ : dependency.isEntry || dependency.needsStableName,
221
+ target: firstBundleGroup.target,
222
+ });
223
+ bundleId = bundleGraph.addNode(bundle);
224
+ bundles.set(childAsset.id, bundleId);
225
+ bundleRoots.set(childAsset, [bundleId, bundleId]);
226
+ bundleGroupBundleIds.add(bundleId);
227
+ bundleGraph.addEdge(bundleGraphRootNodeId, bundleId);
228
+ // If this asset is relevant for merging then track it's source
229
+ // bundle id for later
230
+ if (mergeSourceBundleAssets.has(childAsset.filePath)) {
231
+ mergeSourceBundleLookup.set(path_1.default.relative(config.projectRoot, childAsset.filePath), bundleId);
232
+ }
233
+ if (manualSharedObject) {
234
+ // MSB Step 4: If this was the first instance of a match, mark mainAsset for internalization
235
+ // since MSBs should not have main entry assets
236
+ manualBundleToInternalizedAsset
237
+ .get(bundleId)
238
+ .push(childAsset);
239
+ }
240
+ }
241
+ else {
242
+ bundle = (0, nullthrows_1.default)(bundleGraph.getNode(bundleId));
243
+ (0, assert_1.default)(bundle !== 'root');
244
+ if (
245
+ // If this dependency requests isolated, but the bundle is not,
246
+ // make the bundle isolated for all uses.
247
+ (dependency.bundleBehavior === 'isolated' ||
248
+ dependency.bundleBehavior === 'inlineIsolated') &&
249
+ bundle.bundleBehavior == null) {
250
+ bundle.bundleBehavior = dependency.bundleBehavior;
251
+ }
252
+ }
253
+ dependencyBundleGraph.addEdge(dependencyBundleGraph.addNodeByContentKeyIfNeeded(dependency.id, {
254
+ value: dependency,
255
+ type: 'dependency',
256
+ }), dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
257
+ value: bundle,
258
+ type: 'bundle',
259
+ }),
260
+ // @ts-expect-error TS7053
261
+ dependencyPriorityEdges[dependency.priority]);
262
+ if ((0, feature_flags_1.getFeatureFlag)('conditionalBundlingApi') &&
263
+ dependency.priority === 'conditional') {
264
+ let [referencingBundleRoot, bundleGroupNodeId] = (0, nullthrows_1.default)(stack[stack.length - 1]);
265
+ let referencingBundleId = (0, nullthrows_1.default)(bundleRoots.get(referencingBundleRoot))[0];
266
+ if (config.loadConditionalBundlesInParallel) {
267
+ // When configured, serve conditional bundles in parallel so we don't get module not found errors
268
+ bundleRoots.set(childAsset, [bundleId, bundleGroupNodeId]);
269
+ bundleGraph.addEdge(referencingBundleId, bundleId);
270
+ }
271
+ // Add conditional edge to track which bundles request each other
272
+ bundleGraph.addEdge(referencingBundleId, bundleId, exports.idealBundleGraphEdges.conditional);
273
+ }
274
+ }
275
+ else if (dependency.priority === 'parallel' ||
276
+ childAsset.bundleBehavior === 'inline') {
277
+ // The referencing bundleRoot is the root of a Bundle that first brings in another bundle (essentially the FIRST parent of a bundle, this may or may not be a bundleGroup)
278
+ let [referencingBundleRoot, bundleGroupNodeId] = (0, nullthrows_1.default)(stack[stack.length - 1]);
279
+ let bundleGroup = (0, nullthrows_1.default)(bundleGraph.getNode(bundleGroupNodeId));
280
+ (0, assert_1.default)(bundleGroup !== 'root');
281
+ let referencingBundleId = (0, nullthrows_1.default)(bundleRoots.get(referencingBundleRoot))[0];
282
+ let referencingBundle = (0, nullthrows_1.default)(bundleGraph.getNode(referencingBundleId));
283
+ (0, assert_1.default)(referencingBundle !== 'root');
284
+ if (bundleId == null) {
285
+ bundle = createBundle({
286
+ // Bundles created from type changes shouldn't have an entry asset.
287
+ asset: childAsset,
288
+ type: childAsset.type,
289
+ env: childAsset.env,
290
+ bundleBehavior: dependency.bundleBehavior ?? childAsset.bundleBehavior,
291
+ target: referencingBundle.target,
292
+ needsStableName: childAsset.bundleBehavior === 'inline' ||
293
+ dependency.bundleBehavior === 'inline' ||
294
+ dependency.bundleBehavior === 'inlineIsolated' ||
295
+ (dependency.priority === 'parallel' &&
296
+ !dependency.needsStableName)
297
+ ? false
298
+ : referencingBundle.needsStableName,
299
+ });
300
+ bundleId = bundleGraph.addNode(bundle);
301
+ }
302
+ else {
303
+ bundle = bundleGraph.getNode(bundleId);
304
+ (0, assert_1.default)(bundle != null && bundle !== 'root');
305
+ if (
306
+ // If this dependency requests isolated, but the bundle is not,
307
+ // make the bundle isolated for all uses.
308
+ (dependency.bundleBehavior === 'isolated' ||
309
+ dependency.bundleBehavior === 'inlineIsolated') &&
310
+ bundle.bundleBehavior == null) {
311
+ bundle.bundleBehavior = dependency.bundleBehavior;
312
+ }
313
+ }
314
+ bundles.set(childAsset.id, bundleId);
315
+ // A bundle can belong to multiple bundlegroups, all the bundle groups of it's
316
+ // ancestors, and all async and entry bundles before it are "bundle groups"
317
+ // TODO: We may need to track bundles to all bundleGroups it belongs to in the future.
318
+ bundleRoots.set(childAsset, [bundleId, bundleGroupNodeId]);
319
+ bundleGraph.addEdge(referencingBundleId, bundleId);
320
+ if (bundleId != bundleGroupNodeId) {
321
+ dependencyBundleGraph.addEdge(dependencyBundleGraph.addNodeByContentKeyIfNeeded(dependency.id, {
322
+ value: dependency,
323
+ type: 'dependency',
324
+ }), dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
325
+ value: bundle,
326
+ type: 'bundle',
327
+ }), dependencyPriorityEdges.parallel);
328
+ }
329
+ assetReference.get(childAsset).push([dependency, bundle]);
330
+ }
331
+ else {
332
+ // @ts-expect-error TS2322
333
+ bundleId = null;
334
+ }
335
+ if (manualSharedObject && bundleId != null) {
336
+ // MSB Step 5: At this point we've either created or found an existing MSB bundle
337
+ // add the asset if it doesn't already have it and set key
338
+ (0, assert_1.default)(
339
+ // @ts-expect-error TS2367
340
+ bundle !== 'root' && bundle != null && bundleId != null);
341
+ manualAssetToBundle.set(childAsset, bundleId);
342
+ if (!bundle.assets.has(childAsset)) {
343
+ // Add asset to bundle
344
+ bundle.assets.add(childAsset);
345
+ bundle.size += childAsset.stats.size;
346
+ }
347
+ bundles.set(childAsset.id, bundleId);
348
+ bundleRoots.set(childAsset, [bundleId, bundleId]);
349
+ (0, assert_1.default)(manualSharedBundleKey != null);
350
+ // Ensure we set key to BundleId so the next glob match uses the appropriate bundle
351
+ if (!manualSharedMap.has(manualSharedBundleKey)) {
352
+ manualSharedMap.set(manualSharedBundleKey, bundleId);
353
+ }
354
+ bundle.manualSharedBundle = manualSharedObject.name;
355
+ bundle.uniqueKey = manualSharedObject.name + childAsset.type;
356
+ }
357
+ }
358
+ }
359
+ return node;
360
+ },
361
+ // @ts-expect-error TS2322
362
+ exit(node) {
363
+ if (stack[stack.length - 1]?.[0] === node.value) {
364
+ stack.pop();
365
+ }
366
+ },
367
+ }, null, { skipUnusedDependencies: true });
368
+ // Strip MSBs of entries
369
+ for (let [nodeId, internalizedAssets,] of manualBundleToInternalizedAsset.entries()) {
370
+ let bundle = bundleGraph.getNode(nodeId);
371
+ (0, assert_1.default)(bundle != null && bundle !== 'root');
372
+ if (!bundle.internalizedAssets) {
373
+ bundle.internalizedAssets = new graph_1.BitSet(assets.length);
374
+ }
375
+ for (let asset of internalizedAssets) {
376
+ bundle.internalizedAssets.add((0, nullthrows_1.default)(assetToIndex.get(asset)));
377
+ }
378
+ bundle.mainEntryAsset = null;
379
+ bundleGroupBundleIds.delete(nodeId); // manual bundles can now act as shared, non-bundle group, should they be non-bundleRoots as well?
380
+ }
381
+ /**
382
+ * Step Determine Reachability: Determine reachability for every asset from each bundleRoot.
383
+ * This is later used to determine which bundles to place each asset in. We build up two
384
+ * structures, one traversal each. ReachableRoots to store sync relationships,
385
+ * and bundleRootGraph to store the minimal availability through `parallel` and `async` relationships.
386
+ * The two graphs, are used to build up ancestorAssets, a structure which holds all availability by
387
+ * all means for each asset.
388
+ */
389
+ let rootNodeId = bundleRootGraph.addNode(-1);
390
+ bundleRootGraph.setRootNodeId(rootNodeId);
391
+ for (let [root] of bundleRoots) {
392
+ let nodeId = bundleRootGraph.addNode((0, nullthrows_1.default)(assetToIndex.get(root)));
393
+ assetToBundleRootNodeId.set(root, nodeId);
394
+ if (entries.has(root)) {
395
+ bundleRootGraph.addEdge(rootNodeId, nodeId);
396
+ }
397
+ }
398
+ // reachableRoots is an array of bit sets for each asset. Each bit set
399
+ // indicates which bundle roots are reachable from that asset synchronously.
400
+ let reachableRoots = [];
401
+ for (let i = 0; i < assets.length; i++) {
402
+ reachableRoots.push(new graph_1.BitSet(bundleRootGraph.nodes.length));
403
+ }
404
+ // reachableAssets is the inverse mapping of reachableRoots. For each bundle root,
405
+ // it contains a bit set that indicates which assets are reachable from it.
406
+ let reachableAssets = [];
407
+ // ancestorAssets maps bundle roots to the set of all assets available to it at runtime,
408
+ // including in earlier parallel bundles. These are intersected through all paths to
409
+ // the bundle to ensure that the available assets are always present no matter in which
410
+ // order the bundles are loaded.
411
+ let ancestorAssets = [];
412
+ let inlineConstantDeps = new utils_1.DefaultMap(() => new Set());
413
+ for (let [bundleRootId, assetId] of bundleRootGraph.nodes.entries()) {
414
+ let reachable = new graph_1.BitSet(assets.length);
415
+ reachableAssets.push(reachable);
416
+ ancestorAssets.push(null);
417
+ if (bundleRootId == rootNodeId || assetId == null)
418
+ continue;
419
+ // Add sync relationships to ReachableRoots
420
+ let root = assets[assetId];
421
+ assetGraph.traverse((node, _, actions) => {
422
+ if (node.value === root) {
423
+ return;
424
+ }
425
+ if (node.type === 'dependency') {
426
+ let dependency = node.value;
427
+ if (dependency.priority !== 'sync' &&
428
+ dependencyBundleGraph.hasContentKey(dependency.id)) {
429
+ let assets = assetGraph.getDependencyAssets(dependency);
430
+ if (assets.length === 0) {
431
+ return;
432
+ }
433
+ (0, assert_1.default)(assets.length === 1);
434
+ let bundleRoot = assets[0];
435
+ let bundle = (0, nullthrows_1.default)(bundleGraph.getNode((0, nullthrows_1.default)(bundles.get(bundleRoot.id))));
436
+ if (bundle !== 'root' &&
437
+ bundle.bundleBehavior == null &&
438
+ !bundle.env.isIsolated() &&
439
+ bundle.env.context === root.env.context) {
440
+ bundleRootGraph.addEdge(bundleRootId, (0, nullthrows_1.default)(assetToBundleRootNodeId.get(bundleRoot)), dependency.priority === 'parallel' ||
441
+ (config.loadConditionalBundlesInParallel &&
442
+ dependency.priority === 'conditional')
443
+ ? bundleRootEdgeTypes.parallel
444
+ : bundleRootEdgeTypes.lazy);
445
+ }
446
+ }
447
+ if (dependency.priority !== 'sync') {
448
+ actions.skipChildren();
449
+ }
450
+ return;
451
+ }
452
+ //asset node type
453
+ let asset = node.value;
454
+ if (asset.bundleBehavior != null) {
455
+ actions.skipChildren();
456
+ return;
457
+ }
458
+ let assetIndex = (0, nullthrows_1.default)(assetToIndex.get(node.value));
459
+ reachable.add(assetIndex);
460
+ reachableRoots[assetIndex].add(bundleRootId);
461
+ if (asset.meta.isConstantModule === true) {
462
+ let parents = assetGraph
463
+ .getIncomingDependencies(asset)
464
+ .map((dep) => (0, nullthrows_1.default)(assetGraph.getAssetWithDependency(dep)));
465
+ for (let parent of parents) {
466
+ inlineConstantDeps.get(parent).add(asset);
467
+ }
468
+ }
469
+ return;
470
+ }, root, { skipUnusedDependencies: true });
471
+ }
472
+ for (let entry of entries.keys()) {
473
+ // Initialize an empty set of ancestors available to entries
474
+ let entryId = (0, nullthrows_1.default)(assetToBundleRootNodeId.get(entry));
475
+ ancestorAssets[entryId] = new graph_1.BitSet(assets.length);
476
+ }
477
+ // Step Determine Availability
478
+ // Visit nodes in a topological order, visiting parent nodes before child nodes.
479
+ // This allows us to construct an understanding of which assets will already be
480
+ // loaded and available when a bundle runs, by pushing available assets downwards and
481
+ // computing the intersection of assets available through all possible paths to a bundle.
482
+ // We call this structure ancestorAssets, a Map that tracks a bundleRoot,
483
+ // to all assets available to it (meaning they will exist guaranteed when the bundleRoot is loaded)
484
+ // The topological sort ensures all parents are visited before the node we want to process.
485
+ for (let nodeId of bundleRootGraph.topoSort(graph_1.ALL_EDGE_TYPES)) {
486
+ if (nodeId === rootNodeId)
487
+ continue;
488
+ const bundleRoot = assets[(0, nullthrows_1.default)(bundleRootGraph.getNode(nodeId))];
489
+ let bundleGroupId = (0, nullthrows_1.default)(bundleRoots.get(bundleRoot))[1];
490
+ // At a BundleRoot, we access it's available assets (via ancestorAssets),
491
+ // and add to that all assets within the bundles in that BundleGroup.
492
+ // This set is available to all bundles in a particular bundleGroup because
493
+ // bundleGroups are just bundles loaded at the same time. However it is
494
+ // not true that a bundle's available assets = all assets of all the bundleGroups
495
+ // it belongs to. It's the intersection of those sets.
496
+ let available;
497
+ if (bundleRoot.bundleBehavior === 'isolated' ||
498
+ bundleRoot.bundleBehavior === 'inlineIsolated') {
499
+ available = new graph_1.BitSet(assets.length);
500
+ }
501
+ else {
502
+ available = (0, nullthrows_1.default)(ancestorAssets[nodeId]).clone();
503
+ for (let bundleIdInGroup of [
504
+ bundleGroupId,
505
+ ...bundleGraph.getNodeIdsConnectedFrom(bundleGroupId),
506
+ ]) {
507
+ let bundleInGroup = (0, nullthrows_1.default)(bundleGraph.getNode(bundleIdInGroup));
508
+ (0, assert_1.default)(bundleInGroup !== 'root');
509
+ if (bundleInGroup.bundleBehavior != null) {
510
+ continue;
511
+ }
512
+ for (let bundleRoot of bundleInGroup.assets) {
513
+ // Assets directly connected to current bundleRoot
514
+ available.add((0, nullthrows_1.default)(assetToIndex.get(bundleRoot)));
515
+ available.union(reachableAssets[(0, nullthrows_1.default)(assetToBundleRootNodeId.get(bundleRoot))]);
516
+ }
517
+ }
518
+ }
519
+ // Now that we have bundleGroup availability, we will propagate that down to all the children
520
+ // of this bundleGroup. For a child, we also must maintain parallel availability. If it has
521
+ // parallel siblings that come before it, those, too, are available to it. Add those parallel
522
+ // available assets to the set of available assets for this child as well.
523
+ let children = bundleRootGraph.getNodeIdsConnectedFrom(nodeId, graph_1.ALL_EDGE_TYPES);
524
+ let parallelAvailability = new graph_1.BitSet(assets.length);
525
+ for (let childId of children) {
526
+ let assetId = (0, nullthrows_1.default)(bundleRootGraph.getNode(childId));
527
+ let child = assets[assetId];
528
+ let bundleBehavior = getBundleFromBundleRoot(child).bundleBehavior;
529
+ if (bundleBehavior != null) {
530
+ continue;
531
+ }
532
+ let isParallel = bundleRootGraph.hasEdge(nodeId, childId, bundleRootEdgeTypes.parallel);
533
+ // Most of the time, a child will have many parent bundleGroups,
534
+ // so the next time we peek at a child from another parent, we will
535
+ // intersect the availability built there with the previously computed
536
+ // availability. this ensures no matter which bundleGroup loads a particular bundle,
537
+ // it will only assume availability of assets it has under any circumstance
538
+ const childAvailableAssets = ancestorAssets[childId];
539
+ let currentChildAvailable = isParallel
540
+ ? graph_1.BitSet.union(parallelAvailability, available)
541
+ : available;
542
+ if (childAvailableAssets != null) {
543
+ childAvailableAssets.intersect(currentChildAvailable);
544
+ }
545
+ else {
546
+ ancestorAssets[childId] = currentChildAvailable.clone();
547
+ }
548
+ if (isParallel) {
549
+ parallelAvailability.union(reachableAssets[childId]);
550
+ parallelAvailability.add(assetId); //The next sibling should have older sibling available via parallel
551
+ }
552
+ }
553
+ }
554
+ // Step Internalize async bundles - internalize Async bundles if and only if,
555
+ // the bundle is synchronously available elsewhere.
556
+ // We can query sync assets available via reachableRoots. If the parent has
557
+ // the bundleRoot by reachableRoots AND ancestorAssets, internalize it.
558
+ for (let [id, bundleRootId] of bundleRootGraph.nodes.entries()) {
559
+ if (bundleRootId == null || id === rootNodeId)
560
+ continue;
561
+ let bundleRoot = assets[bundleRootId];
562
+ if (manualAssetToConfig.has(bundleRoot)) {
563
+ // We internalize for MSBs later, we should never delete MSBs
564
+ continue;
565
+ }
566
+ let parentRoots = bundleRootGraph.getNodeIdsConnectedTo(id, graph_1.ALL_EDGE_TYPES);
567
+ let canDelete = getBundleFromBundleRoot(bundleRoot).bundleBehavior !== 'isolated' &&
568
+ getBundleFromBundleRoot(bundleRoot).bundleBehavior !== 'inlineIsolated';
569
+ if (parentRoots.length === 0)
570
+ continue;
571
+ for (let parentId of parentRoots) {
572
+ if (parentId === rootNodeId) {
573
+ // connected to root.
574
+ canDelete = false;
575
+ continue;
576
+ }
577
+ if (reachableAssets[parentId].has(bundleRootId) ||
578
+ ancestorAssets[parentId]?.has(bundleRootId)) {
579
+ let parentAssetId = (0, nullthrows_1.default)(bundleRootGraph.getNode(parentId));
580
+ let parent = assets[parentAssetId];
581
+ let parentBundle = bundleGraph.getNode((0, nullthrows_1.default)(bundles.get(parent.id)));
582
+ (0, assert_1.default)(parentBundle != null && parentBundle !== 'root');
583
+ if (!parentBundle.internalizedAssets) {
584
+ parentBundle.internalizedAssets = new graph_1.BitSet(assets.length);
585
+ }
586
+ parentBundle.internalizedAssets.add(bundleRootId);
587
+ }
588
+ else {
589
+ canDelete = false;
590
+ }
591
+ }
592
+ if (canDelete) {
593
+ deleteBundle(bundleRoot);
594
+ }
595
+ }
596
+ function assignInlineConstants(parentAsset, bundle) {
597
+ for (let inlineConstant of inlineConstantDeps.get(parentAsset)) {
598
+ // @ts-expect-error TS2345
599
+ if (!bundle.assets.has(inlineConstant)) {
600
+ // @ts-expect-error TS2345
601
+ bundle.assets.add(inlineConstant);
602
+ // @ts-expect-error TS18046
603
+ bundle.size += inlineConstant.stats.size;
604
+ }
605
+ }
606
+ }
607
+ // Step Insert Or Share: Place all assets into bundles or create shared bundles. Each asset
608
+ // is placed into a single bundle based on the bundle entries it is reachable from.
609
+ // This creates a maximally code split bundle graph with no duplication.
610
+ let reachable = new graph_1.BitSet(assets.length);
611
+ let reachableNonEntries = new graph_1.BitSet(assets.length);
612
+ let reachableIntersection = new graph_1.BitSet(assets.length);
613
+ for (let i = 0; i < assets.length; i++) {
614
+ let asset = assets[i];
615
+ let manualSharedObject = manualAssetToConfig.get(asset);
616
+ if (bundleRoots.has(asset) && inlineConstantDeps.get(asset).size > 0) {
617
+ let entryBundleId = (0, nullthrows_1.default)(bundleRoots.get(asset))[0];
618
+ let entryBundle = (0, nullthrows_1.default)(bundleGraph.getNode(entryBundleId));
619
+ (0, assert_1.default)(entryBundle !== 'root');
620
+ assignInlineConstants(asset, entryBundle);
621
+ }
622
+ if (asset.meta.isConstantModule === true) {
623
+ // Ignore constant modules as they are placed with their direct parents
624
+ continue;
625
+ }
626
+ // Unreliable bundleRoot assets which need to pulled in by shared bundles or other means.
627
+ // Filter out entries, since they can't have shared bundles.
628
+ // Neither can non-splittable, isolated, or needing of stable name bundles.
629
+ // Reserve those filtered out bundles since we add the asset back into them.
630
+ reachableNonEntries.clear();
631
+ reachableRoots[i].forEach((nodeId) => {
632
+ let assetId = bundleRootGraph.getNode(nodeId);
633
+ if (assetId == null)
634
+ return; // deleted
635
+ let a = assets[assetId];
636
+ if (entries.has(a) ||
637
+ !a.isBundleSplittable ||
638
+ (bundleRoots.get(a) &&
639
+ (getBundleFromBundleRoot(a).needsStableName ||
640
+ getBundleFromBundleRoot(a).bundleBehavior === 'isolated' ||
641
+ getBundleFromBundleRoot(a).bundleBehavior === 'inlineIsolated'))) {
642
+ // Add asset to non-splittable bundles.
643
+ addAssetToBundleRoot(asset, a);
644
+ }
645
+ else if (!ancestorAssets[nodeId]?.has(i)) {
646
+ // Filter out bundles from this asset's reachable array if
647
+ // bundle does not contain the asset in its ancestry
648
+ reachableNonEntries.add(assetId);
649
+ }
650
+ });
651
+ reachable.bits.set(reachableNonEntries.bits);
652
+ // If we encounter a "manual" asset, draw an edge from reachable to its MSB
653
+ if (manualSharedObject && !reachable.empty()) {
654
+ let bundle;
655
+ let bundleId;
656
+ let manualSharedBundleKey = manualSharedObject.name + ',' + asset.type;
657
+ let sourceBundles = [];
658
+ reachable.forEach((id) => {
659
+ sourceBundles.push((0, nullthrows_1.default)(bundleRoots.get(assets[id]))[0]);
660
+ });
661
+ if (!manualSharedMap.has(manualSharedBundleKey)) {
662
+ let firstSourceBundle = (0, nullthrows_1.default)(bundleGraph.getNode(sourceBundles[0]));
663
+ (0, assert_1.default)(firstSourceBundle !== 'root');
664
+ bundle = createBundle({
665
+ env: firstSourceBundle.env,
666
+ manualSharedBundle: manualSharedObject?.name,
667
+ sourceBundles: new Set(sourceBundles),
668
+ target: firstSourceBundle.target,
669
+ type: asset.type,
670
+ uniqueKey: manualSharedBundleKey,
671
+ });
672
+ bundle.assets.add(asset);
673
+ bundleId = bundleGraph.addNode(bundle);
674
+ manualSharedMap.set(manualSharedBundleKey, bundleId);
675
+ }
676
+ else {
677
+ bundleId = (0, nullthrows_1.default)(manualSharedMap.get(manualSharedBundleKey));
678
+ bundle = (0, nullthrows_1.default)(bundleGraph.getNode(bundleId));
679
+ (0, assert_1.default)(bundle != null && bundle !== 'root', 'We tried to use the root incorrectly');
680
+ if (!bundle.assets.has(asset)) {
681
+ bundle.assets.add(asset);
682
+ bundle.size += asset.stats.size;
683
+ }
684
+ for (let s of sourceBundles) {
685
+ if (s != bundleId) {
686
+ bundle.sourceBundles.add(s);
687
+ }
688
+ }
689
+ }
690
+ for (let sourceBundleId of sourceBundles) {
691
+ if (bundleId !== sourceBundleId) {
692
+ bundleGraph.addEdge(sourceBundleId, bundleId);
693
+ }
694
+ }
695
+ dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
696
+ value: bundle,
697
+ type: 'bundle',
698
+ });
699
+ continue;
700
+ }
701
+ // Finally, filter out bundleRoots (bundles) from this assets
702
+ // reachable if they are subgraphs, and reuse that subgraph bundle
703
+ // by drawing an edge. Essentially, if two bundles within an asset's
704
+ // reachable array, have an ancestor-subgraph relationship, draw that edge.
705
+ // This allows for us to reuse a bundle instead of making a shared bundle if
706
+ // a bundle represents the exact set of assets a set of bundles would share
707
+ // if a bundle b is a subgraph of another bundle f, reuse it, drawing an edge between the two
708
+ if (config.disableSharedBundles === false) {
709
+ reachableNonEntries.forEach((candidateId) => {
710
+ let candidateSourceBundleRoot = assets[candidateId];
711
+ let candidateSourceBundleId = (0, nullthrows_1.default)(bundleRoots.get(candidateSourceBundleRoot))[0];
712
+ if (candidateSourceBundleRoot.env.isIsolated()) {
713
+ return;
714
+ }
715
+ let reuseableBundleId = bundles.get(asset.id);
716
+ if (reuseableBundleId != null) {
717
+ reachable.delete(candidateId);
718
+ bundleGraph.addEdge(candidateSourceBundleId, reuseableBundleId);
719
+ let reusableBundle = bundleGraph.getNode(reuseableBundleId);
720
+ (0, assert_1.default)(reusableBundle !== 'root' && reusableBundle != null);
721
+ reusableBundle.sourceBundles.add(candidateSourceBundleId);
722
+ }
723
+ else {
724
+ // Asset is not a bundleRoot, but if its ancestor bundle (in the asset's reachable) can be
725
+ // reused as a subgraph of another bundleRoot in its reachable, reuse it
726
+ reachableIntersection.bits.set(reachableNonEntries.bits);
727
+ reachableIntersection.intersect(reachableAssets[(0, nullthrows_1.default)(assetToBundleRootNodeId.get(candidateSourceBundleRoot))]);
728
+ reachableIntersection.forEach((otherCandidateId) => {
729
+ // In the case of a circular dependency, you may end up with two
730
+ // reusable bundles that each delete the other, leaving no reusable
731
+ // bundles actually reachable. This check is to avoid assigning the
732
+ // asset to a reusable bundle that has already been marked unreachable.
733
+ if (!reachable.has(otherCandidateId))
734
+ return;
735
+ let otherReuseCandidate = assets[otherCandidateId];
736
+ if (candidateSourceBundleRoot === otherReuseCandidate)
737
+ return;
738
+ let reusableBundleId = (0, nullthrows_1.default)(bundles.get(otherReuseCandidate.id));
739
+ reachable.delete(candidateId);
740
+ bundleGraph.addEdge((0, nullthrows_1.default)(bundles.get(candidateSourceBundleRoot.id)), reusableBundleId);
741
+ let reusableBundle = bundleGraph.getNode(reusableBundleId);
742
+ (0, assert_1.default)(reusableBundle !== 'root' && reusableBundle != null);
743
+ reusableBundle.sourceBundles.add(candidateSourceBundleId);
744
+ });
745
+ }
746
+ });
747
+ }
748
+ let reachableArray = [];
749
+ reachable.forEach((id) => {
750
+ reachableArray.push(assets[id]);
751
+ });
752
+ // Create shared bundles for splittable bundles.
753
+ if (config.disableSharedBundles === false &&
754
+ reachableArray.length > config.minBundles) {
755
+ let sourceBundles = reachableArray.map((a) => (0, nullthrows_1.default)(bundleRoots.get(a))[0]);
756
+ let key = reachableArray.map((a) => a.id).join(',') + '.' + asset.type;
757
+ let bundleId = bundles.get(key);
758
+ let bundle;
759
+ if (bundleId == null) {
760
+ let firstSourceBundle = (0, nullthrows_1.default)(bundleGraph.getNode(sourceBundles[0]));
761
+ (0, assert_1.default)(firstSourceBundle !== 'root');
762
+ bundle = createBundle({
763
+ env: firstSourceBundle.env,
764
+ sourceBundles: new Set(sourceBundles),
765
+ target: firstSourceBundle.target,
766
+ type: asset.type,
767
+ });
768
+ let sharedInternalizedAssets = firstSourceBundle.internalizedAssets
769
+ ? firstSourceBundle.internalizedAssets.clone()
770
+ : new graph_1.BitSet(assets.length);
771
+ for (let p of sourceBundles) {
772
+ let parentBundle = (0, nullthrows_1.default)(bundleGraph.getNode(p));
773
+ (0, assert_1.default)(parentBundle !== 'root');
774
+ if (parentBundle === firstSourceBundle)
775
+ continue;
776
+ if (parentBundle.internalizedAssets) {
777
+ sharedInternalizedAssets.intersect(parentBundle.internalizedAssets);
778
+ }
779
+ else {
780
+ sharedInternalizedAssets.clear();
781
+ }
782
+ }
783
+ bundle.internalizedAssets = sharedInternalizedAssets;
784
+ bundleId = bundleGraph.addNode(bundle);
785
+ bundles.set(key, bundleId);
786
+ }
787
+ else {
788
+ bundle = (0, nullthrows_1.default)(bundleGraph.getNode(bundleId));
789
+ (0, assert_1.default)(bundle !== 'root');
790
+ }
791
+ bundle.assets.add(asset);
792
+ bundle.size += asset.stats.size;
793
+ assignInlineConstants(asset, bundle);
794
+ for (let sourceBundleId of sourceBundles) {
795
+ if (bundleId !== sourceBundleId) {
796
+ bundleGraph.addEdge(sourceBundleId, bundleId);
797
+ }
798
+ }
799
+ dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
800
+ value: bundle,
801
+ type: 'bundle',
802
+ });
803
+ }
804
+ else if (config.disableSharedBundles === true ||
805
+ reachableArray.length <= config.minBundles) {
806
+ for (let root of reachableArray) {
807
+ addAssetToBundleRoot(asset, root);
808
+ }
809
+ }
810
+ }
811
+ let manualSharedBundleIds = new Set([...manualSharedMap.values()]);
812
+ let modifiedSourceBundles = new Set();
813
+ // Step split manual shared bundles for those that have the "split" property set
814
+ let remainderMap = new utils_1.DefaultMap(() => []);
815
+ for (let id of manualSharedMap.values()) {
816
+ let manualBundle = bundleGraph.getNode(id);
817
+ (0, assert_1.default)(manualBundle !== 'root' && manualBundle != null);
818
+ if (manualBundle.sourceBundles.size > 0) {
819
+ let firstSourceBundle = (0, nullthrows_1.default)(bundleGraph.getNode([...manualBundle.sourceBundles][0]));
820
+ (0, assert_1.default)(firstSourceBundle !== 'root');
821
+ let firstAsset = [...manualBundle.assets][0];
822
+ let manualSharedObject = manualAssetToConfig.get(firstAsset);
823
+ (0, assert_1.default)(manualSharedObject != null);
824
+ let modNum = manualAssetToConfig.get(firstAsset)?.split;
825
+ if (modNum != null) {
826
+ for (let a of [...manualBundle.assets]) {
827
+ let numRep = getBigIntFromContentKey(a.id);
828
+ let r = Number(numRep % BigInt(modNum));
829
+ // @ts-expect-error TS2345
830
+ remainderMap.get(r).push(a);
831
+ }
832
+ for (let i = 1; i < [...remainderMap.keys()].length; i++) {
833
+ let bundle = createBundle({
834
+ env: firstSourceBundle.env,
835
+ manualSharedBundle: manualSharedObject.name,
836
+ sourceBundles: manualBundle.sourceBundles,
837
+ target: firstSourceBundle.target,
838
+ type: firstSourceBundle.type,
839
+ uniqueKey: manualSharedObject.name + firstSourceBundle.type + i,
840
+ });
841
+ bundle.internalizedAssets = manualBundle.internalizedAssets;
842
+ let bundleId = bundleGraph.addNode(bundle);
843
+ manualSharedBundleIds.add(bundleId);
844
+ for (let sourceBundleId of manualBundle.sourceBundles) {
845
+ if (bundleId !== sourceBundleId) {
846
+ bundleGraph.addEdge(sourceBundleId, bundleId);
847
+ }
848
+ }
849
+ for (let sp of remainderMap.get(i)) {
850
+ bundle.assets.add(sp);
851
+ // @ts-expect-error TS2339
852
+ bundle.size += sp.stats.size;
853
+ manualBundle.assets.delete(sp);
854
+ // @ts-expect-error TS2339
855
+ manualBundle.size -= sp.stats.size;
856
+ }
857
+ }
858
+ }
859
+ }
860
+ }
861
+ // Step insert constant modules into manual shared bundles.
862
+ // We have to do this separately as they're the only case where a single asset can
863
+ // match multiple MSB's
864
+ for (let [asset, msbs] of constantModuleToMSB.entries()) {
865
+ for (let manualSharedObject of msbs) {
866
+ // @ts-expect-error TS2339
867
+ let bundleId = manualSharedMap.get(manualSharedObject.name + ',js');
868
+ if (bundleId == null)
869
+ continue;
870
+ let bundle = (0, nullthrows_1.default)(bundleGraph.getNode(bundleId));
871
+ (0, assert_1.default)(bundle != null && bundle !== 'root', 'We tried to use the root incorrectly');
872
+ // @ts-expect-error TS2345
873
+ if (!bundle.assets.has(asset)) {
874
+ // @ts-expect-error TS2345
875
+ bundle.assets.add(asset);
876
+ // @ts-expect-error TS18046
877
+ bundle.size += asset.stats.size;
878
+ }
879
+ }
880
+ }
881
+ if ((0, feature_flags_1.getFeatureFlag)('supportWebpackChunkName')) {
882
+ // Merge webpack chunk name bundles
883
+ let chunkNameBundles = new utils_1.DefaultMap(() => new Set());
884
+ for (let [nodeId, node] of dependencyBundleGraph.nodes.entries()) {
885
+ // meta.chunkName is set by the Rust transformer, so we just need to find
886
+ // bundles that have a chunkName set.
887
+ if (!node ||
888
+ node.type !== 'dependency' ||
889
+ typeof node.value.meta.chunkName !== 'string') {
890
+ continue;
891
+ }
892
+ let connectedBundles = dependencyBundleGraph.getNodeIdsConnectedFrom(nodeId, dependencyPriorityEdges[node.value.priority]);
893
+ if (connectedBundles.length === 0) {
894
+ continue;
895
+ }
896
+ (0, assert_1.default)(connectedBundles.length === 1, 'Expected webpackChunkName dependency to be connected to no more than one bundle');
897
+ let bundleId = connectedBundles[0];
898
+ let bundleNode = dependencyBundleGraph.getNode(bundleId);
899
+ (0, assert_1.default)(bundleNode != null && bundleNode.type === 'bundle');
900
+ // If a bundle does not have a main entry asset, it's somehow just a
901
+ // shared bundle, and will be merged/deleted by other means.
902
+ if (bundleNode.value.mainEntryAsset == null) {
903
+ continue;
904
+ }
905
+ let bundleNodeId = null;
906
+ let mainEntryAssetId = bundleNode.value.mainEntryAsset?.id;
907
+ if (mainEntryAssetId != null) {
908
+ bundleNodeId = bundles.get(mainEntryAssetId);
909
+ }
910
+ if (bundleNodeId == null) {
911
+ continue;
912
+ }
913
+ chunkNameBundles
914
+ .get(node.value.meta.chunkName)
915
+ // DependencyBundleGraph uses content keys as node ids, so we can use that
916
+ // to get the bundle id.
917
+ .add(bundleNodeId);
918
+ }
919
+ for (let [chunkName, bundleIds] of chunkNameBundles.entries()) {
920
+ // The `[request]` placeholder is not yet supported
921
+ if (bundleIds.size <= 1 ||
922
+ (typeof chunkName === 'string' && chunkName.includes('[request]'))) {
923
+ continue; // Nothing to merge
924
+ }
925
+ // Merge all bundles with the same chunk name into the first one.
926
+ let [firstBundleId, ...rest] = Array.from(bundleIds);
927
+ for (let bundleId of rest) {
928
+ mergeBundles(firstBundleId, bundleId, 'webpack-chunk-name');
929
+ }
930
+ }
931
+ }
932
+ // Step merge async bundles that meet the configured params
933
+ if (config.asyncBundleMerge) {
934
+ mergeAsyncBundles(config.asyncBundleMerge);
935
+ }
936
+ // Step merge shared bundles that meet the configured params
937
+ if (config.sharedBundleMerge && config.sharedBundleMerge.length > 0) {
938
+ mergeSharedBundles(config.sharedBundleMerge);
939
+ }
940
+ // Step Merge Share Bundles: Merge any shared bundles under the minimum bundle size back into
941
+ // their source bundles, and remove the bundle.
942
+ // We should include "bundle reuse" as shared bundles that may be removed but the bundle itself would have to be retained
943
+ for (let [bundleNodeId, bundle] of bundleGraph.nodes.entries()) {
944
+ if (!bundle || bundle === 'root')
945
+ continue;
946
+ if (bundle.sourceBundles.size > 0 &&
947
+ bundle.mainEntryAsset == null &&
948
+ bundle.size < config.minBundleSize &&
949
+ !manualSharedBundleIds.has(bundleNodeId)) {
950
+ removeBundle(bundleGraph, bundleNodeId, assetReference);
951
+ }
952
+ }
953
+ // Step Remove Shared Bundles: Remove shared bundles from bundle groups that hit the parallel request limit.
954
+ if (config.disableSharedBundles === false) {
955
+ for (let bundleGroupId of bundleGraph.getNodeIdsConnectedFrom(rootNodeId)) {
956
+ // Find shared bundles in this bundle group.
957
+ let bundleId = bundleGroupId;
958
+ // We should include "bundle reuse" as shared bundles that may be removed but the bundle itself would have to be retained
959
+ let bundleIdsInGroup = getBundlesForBundleGroup(bundleId); //get all bundlegrups this bundle is an ancestor of
960
+ // Filter out inline assests as they should not contribute to PRL
961
+ let numBundlesContributingToPRL = bundleIdsInGroup.reduce((count, b) => {
962
+ let bundle = (0, nullthrows_1.default)(bundleGraph.getNode(b));
963
+ (0, assert_1.default)(bundle !== 'root');
964
+ return (count +
965
+ Number(bundle.bundleBehavior !== 'inline' &&
966
+ bundle.bundleBehavior !== 'inlineIsolated'));
967
+ }, 0);
968
+ if (numBundlesContributingToPRL > config.maxParallelRequests) {
969
+ let sharedBundleIdsInBundleGroup = bundleIdsInGroup.filter((b) => {
970
+ let bundle = (0, nullthrows_1.default)(bundleGraph.getNode(b));
971
+ // shared bundles must have source bundles, we could have a bundle
972
+ // connected to another bundle that isnt a shared bundle, so check
973
+ return (bundle !== 'root' &&
974
+ bundle.sourceBundles.size > 0 &&
975
+ bundleId != b &&
976
+ !manualSharedBundleIds.has(b));
977
+ });
978
+ // Sort the bundles so the smallest ones are removed first.
979
+ let sharedBundlesInGroup = sharedBundleIdsInBundleGroup
980
+ .map((id) => ({
981
+ id,
982
+ bundle: (0, nullthrows_1.default)(bundleGraph.getNode(id)),
983
+ }))
984
+ .map(({ id, bundle }) => {
985
+ // For Flow
986
+ (0, assert_1.default)(bundle !== 'root');
987
+ return { id, bundle };
988
+ })
989
+ .sort((a, b) => b.bundle.size - a.bundle.size);
990
+ // Remove bundles until the bundle group is within the parallel request limit.
991
+ while (sharedBundlesInGroup.length > 0 &&
992
+ numBundlesContributingToPRL > config.maxParallelRequests) {
993
+ let bundleTuple = sharedBundlesInGroup.pop();
994
+ // @ts-expect-error TS18048
995
+ let bundleToRemove = bundleTuple.bundle;
996
+ // @ts-expect-error TS18048
997
+ let bundleIdToRemove = bundleTuple.id;
998
+ //TODO add integration test where bundles in bunlde group > max parallel request limit & only remove a couple shared bundles
999
+ // but total # bundles still exceeds limit due to non shared bundles
1000
+ // Add all assets in the shared bundle into the source bundles that are within this bundle group.
1001
+ let sourceBundles = [...bundleToRemove.sourceBundles].filter((b) => bundleIdsInGroup.includes(b));
1002
+ for (let sourceBundleId of sourceBundles) {
1003
+ let sourceBundle = (0, nullthrows_1.default)(bundleGraph.getNode(sourceBundleId));
1004
+ (0, assert_1.default)(sourceBundle !== 'root');
1005
+ modifiedSourceBundles.add(sourceBundle);
1006
+ bundleToRemove.sourceBundles.delete(sourceBundleId);
1007
+ for (let asset of bundleToRemove.assets) {
1008
+ addAssetToBundleRoot(asset, (0, nullthrows_1.default)(sourceBundle.mainEntryAsset));
1009
+ }
1010
+ //This case is specific to reused bundles, which can have shared bundles attached to it
1011
+ for (let childId of bundleGraph.getNodeIdsConnectedFrom(bundleIdToRemove)) {
1012
+ let child = bundleGraph.getNode(childId);
1013
+ (0, assert_1.default)(child !== 'root' && child != null);
1014
+ child.sourceBundles.add(sourceBundleId);
1015
+ bundleGraph.addEdge(sourceBundleId, childId);
1016
+ }
1017
+ // needs to add test case where shared bundle is removed from ONE bundlegroup but not from the whole graph!
1018
+ // Remove the edge from this bundle group to the shared bundle.
1019
+ // If there is now only a single bundle group that contains this bundle,
1020
+ // merge it into the remaining source bundles. If it is orphaned entirely, remove it.
1021
+ let incomingNodeCount = bundleGraph.getNodeIdsConnectedTo(bundleIdToRemove).length;
1022
+ if (incomingNodeCount <= 2 &&
1023
+ //Never fully remove reused bundles
1024
+ bundleToRemove.mainEntryAsset == null) {
1025
+ // If one bundle group removes a shared bundle, but the other *can* keep it, still remove because that shared bundle is pointless (only one source bundle)
1026
+ removeBundle(bundleGraph, bundleIdToRemove, assetReference);
1027
+ // Stop iterating through bundleToRemove's sourceBundles as the bundle has been removed.
1028
+ break;
1029
+ }
1030
+ else {
1031
+ bundleGraph.removeEdge(sourceBundleId, bundleIdToRemove);
1032
+ }
1033
+ }
1034
+ numBundlesContributingToPRL--;
1035
+ }
1036
+ }
1037
+ }
1038
+ }
1039
+ function mergeBundles(bundleToKeepId, bundleToRemoveId, reason) {
1040
+ stats.trackMerge(bundleToKeepId, bundleToRemoveId, reason);
1041
+ let bundleToKeep = isNonRootBundle(bundleGraph.getNode(bundleToKeepId), `Bundle ${bundleToKeepId} not found`);
1042
+ let bundleToRemove = isNonRootBundle(bundleGraph.getNode(bundleToRemoveId), `Bundle ${bundleToRemoveId} not found`);
1043
+ modifiedSourceBundles.add(bundleToKeep);
1044
+ for (let asset of bundleToRemove.assets) {
1045
+ bundleToKeep.assets.add(asset);
1046
+ bundleToKeep.size += asset.stats.size;
1047
+ let newAssetReference = assetReference
1048
+ .get(asset)
1049
+ .map(([dep, bundle]) => bundle === bundleToRemove ? [dep, bundleToKeep] : [dep, bundle]);
1050
+ // @ts-expect-error TS2345
1051
+ assetReference.set(asset, newAssetReference);
1052
+ }
1053
+ // Merge any internalized assets
1054
+ if ((0, feature_flags_1.getFeatureFlag)('supportWebpackChunkName')) {
1055
+ if (bundleToKeep.internalizedAssets != null) {
1056
+ if (bundleToRemove.internalizedAssets != null) {
1057
+ bundleToKeep.internalizedAssets.intersect(bundleToRemove.internalizedAssets);
1058
+ }
1059
+ else {
1060
+ bundleToKeep.internalizedAssets.clear();
1061
+ }
1062
+ }
1063
+ }
1064
+ else {
1065
+ (0, assert_1.default)(bundleToKeep.internalizedAssets && bundleToRemove.internalizedAssets, 'All shared bundles should have internalized assets');
1066
+ bundleToKeep.internalizedAssets.union(bundleToRemove.internalizedAssets);
1067
+ }
1068
+ // Merge and clean up source bundles
1069
+ for (let sourceBundleId of bundleToRemove.sourceBundles) {
1070
+ if (bundleToKeep.sourceBundles.has(sourceBundleId)) {
1071
+ continue;
1072
+ }
1073
+ if (sourceBundleId !== bundleToKeepId) {
1074
+ bundleToKeep.sourceBundles.add(sourceBundleId);
1075
+ bundleGraph.addEdge(sourceBundleId, bundleToKeepId);
1076
+ }
1077
+ }
1078
+ if ((0, feature_flags_1.getFeatureFlag)('supportWebpackChunkName')) {
1079
+ bundleToKeep.sourceBundles.delete(bundleToRemoveId);
1080
+ for (let bundle of bundleGraph.getNodeIdsConnectedFrom(bundleToRemoveId)) {
1081
+ let bundleNode = (0, nullthrows_1.default)(bundleGraph.getNode(bundle));
1082
+ if (bundleNode === 'root') {
1083
+ continue;
1084
+ }
1085
+ // If the bundle is a source bundle, add it to the bundle to keep
1086
+ if (bundleNode.sourceBundles.has(bundleToRemoveId)) {
1087
+ bundleNode.sourceBundles.delete(bundleToRemoveId);
1088
+ if (bundle !== bundleToKeepId) {
1089
+ bundleNode.sourceBundles.add(bundleToKeepId);
1090
+ bundleGraph.addEdge(bundleToKeepId, bundle);
1091
+ }
1092
+ }
1093
+ }
1094
+ // Merge bundle roots
1095
+ for (let bundleRoot of bundleToRemove.bundleRoots) {
1096
+ bundleToKeep.bundleRoots.add(bundleRoot);
1097
+ }
1098
+ if (bundleToRemove.mainEntryAsset != null) {
1099
+ (0, assert_1.default)(bundleToKeep.mainEntryAsset != null);
1100
+ // Merge the bundles in bundle group
1101
+ let bundlesInRemoveBundleGroup = getBundlesForBundleGroup(bundleToRemoveId);
1102
+ let removedBundleSharedBundles = new Set();
1103
+ for (let bundleIdInGroup of bundlesInRemoveBundleGroup) {
1104
+ if (bundleIdInGroup === bundleToRemoveId) {
1105
+ continue;
1106
+ }
1107
+ bundleGraph.addEdge(bundleToKeepId, bundleIdInGroup);
1108
+ removedBundleSharedBundles.add(bundleIdInGroup);
1109
+ }
1110
+ if ((0, feature_flags_1.getFeatureFlag)('removeRedundantSharedBundles')) {
1111
+ // Merge any shared bundles that now have the same source bundles due to
1112
+ // the current bundle merge
1113
+ let sharedBundles = new utils_1.DefaultMap(() => []);
1114
+ for (let bundleId of removedBundleSharedBundles) {
1115
+ let bundleNode = (0, nullthrows_1.default)(bundleGraph.getNode(bundleId));
1116
+ (0, assert_1.default)(bundleNode !== 'root');
1117
+ if (bundleNode.mainEntryAsset != null ||
1118
+ bundleNode.manualSharedBundle != null) {
1119
+ continue;
1120
+ }
1121
+ let key = Array.from(bundleNode.sourceBundles)
1122
+ .filter((sourceBundle) => sourceBundle !== bundleToRemoveId)
1123
+ .sort()
1124
+ .join(',') +
1125
+ '.' +
1126
+ bundleNode.type;
1127
+ sharedBundles.get(key).push(bundleId);
1128
+ }
1129
+ for (let sharedBundlesToMerge of sharedBundles.values()) {
1130
+ if (sharedBundlesToMerge.length > 1) {
1131
+ let [firstBundleId, ...rest] = sharedBundlesToMerge;
1132
+ for (let bundleId of rest) {
1133
+ mergeBundles(firstBundleId, bundleId, 'redundant-shared');
1134
+ }
1135
+ }
1136
+ }
1137
+ }
1138
+ // Remove old bundle group
1139
+ bundleGroupBundleIds.delete(bundleToRemoveId);
1140
+ // Clean up bundle roots
1141
+ let bundleRootToRemoveNodeId = (0, nullthrows_1.default)(assetToBundleRootNodeId.get((0, nullthrows_1.default)(bundleToRemove.mainEntryAsset)));
1142
+ let bundleRootToKeepNodeId = (0, nullthrows_1.default)(assetToBundleRootNodeId.get((0, nullthrows_1.default)(bundleToKeep.mainEntryAsset)));
1143
+ for (let nodeId of bundleRootGraph.getNodeIdsConnectedTo(bundleRootToRemoveNodeId)) {
1144
+ bundleRootGraph.addEdge(nodeId, bundleRootToKeepNodeId);
1145
+ bundleRootGraph.removeEdge(nodeId, bundleRootToRemoveNodeId);
1146
+ }
1147
+ for (let nodeId of bundleRootGraph.getNodeIdsConnectedFrom(bundleRootToRemoveNodeId)) {
1148
+ bundleRootGraph.addEdge(bundleRootToKeepNodeId, nodeId);
1149
+ bundleRootGraph.removeEdge(bundleRootToRemoveNodeId, nodeId);
1150
+ }
1151
+ bundleRoots.set((0, nullthrows_1.default)(bundleToRemove.mainEntryAsset), [
1152
+ bundleToKeepId,
1153
+ bundleToKeepId,
1154
+ ]);
1155
+ // Merge dependency bundle graph
1156
+ for (let dependencyNodeId of dependencyBundleGraph.getNodeIdsConnectedTo(dependencyBundleGraph.getNodeIdByContentKey(String(bundleToRemoveId)), graph_1.ALL_EDGE_TYPES)) {
1157
+ let dependencyNode = (0, nullthrows_1.default)(dependencyBundleGraph.getNode(dependencyNodeId));
1158
+ (0, assert_1.default)(dependencyNode.type === 'dependency');
1159
+ // Add dependency to the bundle to keep
1160
+ dependencyBundleGraph.addEdge(dependencyNodeId, dependencyBundleGraph.getNodeIdByContentKey(String(bundleToKeepId)), dependencyPriorityEdges[dependencyNode.value.priority]);
1161
+ // Remove dependency from the bundle to remove
1162
+ dependencyBundleGraph.removeEdge(dependencyNodeId, dependencyBundleGraph.getNodeIdByContentKey(String(bundleToRemoveId)), dependencyPriorityEdges[dependencyNode.value.priority]);
1163
+ }
1164
+ }
1165
+ }
1166
+ bundleGraph.removeNode(bundleToRemoveId);
1167
+ }
1168
+ function mergeSharedBundles(mergeConfig) {
1169
+ // Find all shared bundles
1170
+ let sharedBundles = new Set();
1171
+ bundleGraph.traverse((nodeId) => {
1172
+ let bundle = bundleGraph.getNode(nodeId);
1173
+ if (!bundle) {
1174
+ throw new Error(`Unable to find bundle ${nodeId} in bundle graph`);
1175
+ }
1176
+ if (bundle === 'root') {
1177
+ return;
1178
+ }
1179
+ // Only consider JS shared bundles and non-reused bundles.
1180
+ // These count potentially be considered for merging in future but they're
1181
+ // more complicated to merge
1182
+ if (bundle.sourceBundles.size > 0 &&
1183
+ bundle.manualSharedBundle == null &&
1184
+ !bundle.mainEntryAsset &&
1185
+ bundle.type === 'js') {
1186
+ sharedBundles.add(nodeId);
1187
+ }
1188
+ });
1189
+ let clusters = (0, bundleMerge_1.findMergeCandidates)(bundleGraph, Array.from(sharedBundles), mergeConfig.map((config) => ({
1190
+ ...config,
1191
+ sourceBundles: config.sourceBundles?.map((assetMatch) => {
1192
+ let sourceBundleNodeId = mergeSourceBundleLookup.get(assetMatch);
1193
+ if (sourceBundleNodeId == null) {
1194
+ throw new Error(`Source bundle ${assetMatch} not found in merge source bundle lookup`);
1195
+ }
1196
+ return sourceBundleNodeId;
1197
+ }),
1198
+ })));
1199
+ let mergedBundles = new Set();
1200
+ for (let cluster of clusters) {
1201
+ let [mergeTarget, ...rest] = cluster;
1202
+ for (let bundleIdToMerge of rest) {
1203
+ mergeBundles(mergeTarget, bundleIdToMerge, 'shared-merge');
1204
+ }
1205
+ mergedBundles.add(mergeTarget);
1206
+ }
1207
+ if ((0, feature_flags_1.getFeatureFlag)('supportWebpackChunkName')) {
1208
+ return mergedBundles;
1209
+ }
1210
+ }
1211
+ function mergeAsyncBundles({ bundleSize, maxOverfetchSize, ignore, }) {
1212
+ let mergeCandidates = [];
1213
+ let ignoreRegexes = ignore?.map((glob) => (0, utils_1.globToRegex)(glob)) ?? [];
1214
+ let isIgnored = (bundle) => {
1215
+ if (!bundle.mainEntryAsset) {
1216
+ return false;
1217
+ }
1218
+ let mainEntryFilePath = path_1.default.relative(config.projectRoot, (0, nullthrows_1.default)(bundle.mainEntryAsset).filePath);
1219
+ return ignoreRegexes.some((regex) => regex.test(mainEntryFilePath));
1220
+ };
1221
+ for (let [_bundleRootAsset, [bundleRootBundleId]] of bundleRoots) {
1222
+ let bundleRootBundle = (0, nullthrows_1.default)(bundleGraph.getNode(bundleRootBundleId));
1223
+ (0, assert_1.default)(bundleRootBundle !== 'root');
1224
+ if (bundleRootBundle.type === 'js' &&
1225
+ bundleRootBundle.bundleBehavior !== 'inline' &&
1226
+ bundleRootBundle.bundleBehavior !== 'inlineIsolated' &&
1227
+ bundleRootBundle.size <= bundleSize &&
1228
+ !isIgnored(bundleRootBundle)) {
1229
+ mergeCandidates.push(bundleRootBundleId);
1230
+ }
1231
+ }
1232
+ let candidates = [];
1233
+ for (let i = 0; i < mergeCandidates.length; i++) {
1234
+ for (let j = i + 1; j < mergeCandidates.length; j++) {
1235
+ let a = mergeCandidates[i];
1236
+ let b = mergeCandidates[j];
1237
+ if (a === b)
1238
+ continue; // Skip self-comparison
1239
+ candidates.push(scoreAsyncMerge(a, b, maxOverfetchSize));
1240
+ }
1241
+ }
1242
+ let sortByScore = (a, b) => {
1243
+ let diff = a.score - b.score;
1244
+ if (diff > 0) {
1245
+ return 1;
1246
+ }
1247
+ else if (diff < 0) {
1248
+ return -1;
1249
+ }
1250
+ return 0;
1251
+ };
1252
+ candidates = candidates
1253
+ .filter(({ overfetchSize, score }) => overfetchSize <= maxOverfetchSize && score > 0)
1254
+ .sort(sortByScore);
1255
+ // Tracks the bundles that have been merged
1256
+ let merged = new Set();
1257
+ // Tracks the deleted bundles to the bundle they were merged into.
1258
+ let mergeRemap = new Map();
1259
+ // Tracks the bundles that have been rescored and added back into the
1260
+ // candidates.
1261
+ let rescored = new utils_1.DefaultMap(() => new Set());
1262
+ do {
1263
+ let [a, b] = (0, nullthrows_1.default)(candidates.pop()).bundleIds;
1264
+ if (bundleGraph.hasNode(a) &&
1265
+ bundleGraph.hasNode(b) &&
1266
+ ((!merged.has(a) && !merged.has(b)) || rescored.get(a).has(b))) {
1267
+ mergeRemap.set(b, a);
1268
+ merged.add(a);
1269
+ rescored.get(a).clear();
1270
+ mergeBundles(a, b, 'async-merge');
1271
+ continue;
1272
+ }
1273
+ // One or both of the bundles have been previously merged, so we'll
1274
+ // rescore and add the result back into the list of candidates.
1275
+ let getMergedBundleId = (bundleId) => {
1276
+ let seen = new Set();
1277
+ while (!bundleGraph.hasNode(bundleId) && !seen.has(bundleId)) {
1278
+ seen.add(bundleId);
1279
+ bundleId = (0, nullthrows_1.default)(mergeRemap.get(bundleId));
1280
+ }
1281
+ if (!bundleGraph.hasNode(bundleId)) {
1282
+ return;
1283
+ }
1284
+ return bundleId;
1285
+ };
1286
+ // Map a and b to their merged bundle ids if they've already been merged
1287
+ let currentA = getMergedBundleId(a);
1288
+ let currentB = getMergedBundleId(b);
1289
+ if (!currentA ||
1290
+ !currentB ||
1291
+ // Bundles are already merged
1292
+ currentA === currentB) {
1293
+ // This combiniation is not valid, so we skip it.
1294
+ continue;
1295
+ }
1296
+ let candidate = scoreAsyncMerge(currentA, currentB, maxOverfetchSize);
1297
+ if (candidate.overfetchSize <= maxOverfetchSize && candidate.score > 0) {
1298
+ sorted_array_functions_1.default.add(candidates, candidate, sortByScore);
1299
+ rescored.get(currentA).add(currentB);
1300
+ }
1301
+ } while (candidates.length > 0);
1302
+ }
1303
+ function getBundle(bundleId) {
1304
+ let bundle = bundleGraph.getNode(bundleId);
1305
+ if (bundle === 'root') {
1306
+ throw new Error(`Cannot access root bundle`);
1307
+ }
1308
+ if (bundle == null) {
1309
+ throw new Error(`Bundle ${bundleId} not found in bundle graph`);
1310
+ }
1311
+ return bundle;
1312
+ }
1313
+ function getBigIntFromContentKey(contentKey) {
1314
+ let b = Buffer.alloc(64);
1315
+ b.write(contentKey);
1316
+ return b.readBigInt64BE();
1317
+ }
1318
+ // Fix asset order in source bundles as they are likely now incorrect after shared bundle deletion
1319
+ if (modifiedSourceBundles.size > 0) {
1320
+ let assetOrderMap = new Map(assets.map((a, index) => [a, index]));
1321
+ for (let bundle of modifiedSourceBundles) {
1322
+ bundle.assets = new Set([...bundle.assets].sort((a, b) => {
1323
+ let aIndex = (0, nullthrows_1.default)(assetOrderMap.get(a));
1324
+ let bIndex = (0, nullthrows_1.default)(assetOrderMap.get(b));
1325
+ return aIndex - bIndex;
1326
+ }));
1327
+ }
1328
+ }
1329
+ function deleteBundle(bundleRoot) {
1330
+ bundleGraph.removeNode((0, nullthrows_1.default)(bundles.get(bundleRoot.id)));
1331
+ bundleRoots.delete(bundleRoot);
1332
+ bundles.delete(bundleRoot.id);
1333
+ let bundleRootId = assetToBundleRootNodeId.get(bundleRoot);
1334
+ if (bundleRootId != null && bundleRootGraph.hasNode(bundleRootId)) {
1335
+ bundleRootGraph.removeNode(bundleRootId);
1336
+ }
1337
+ }
1338
+ function getBundlesForBundleGroup(bundleGroupId) {
1339
+ let bundlesInABundleGroup = [];
1340
+ bundleGraph.traverse((nodeId) => {
1341
+ bundlesInABundleGroup.push(nodeId);
1342
+ }, bundleGroupId);
1343
+ return bundlesInABundleGroup;
1344
+ }
1345
+ function scoreAsyncMerge(bundleAId, bundleBId, maxOverfetchSize) {
1346
+ let bundleGroupA = new Set(getBundlesForBundleGroup(bundleAId));
1347
+ let bundleGroupB = new Set(getBundlesForBundleGroup(bundleBId));
1348
+ let overlapSize = 0;
1349
+ let overfetchSize = 0;
1350
+ for (let bundleId of new Set([...bundleGroupA, ...bundleGroupB])) {
1351
+ let bundle = getBundle(bundleId);
1352
+ if (bundleGroupA.has(bundleId) && bundleGroupB.has(bundleId)) {
1353
+ overlapSize += bundle.size;
1354
+ }
1355
+ else {
1356
+ overfetchSize += bundle.size;
1357
+ }
1358
+ }
1359
+ let overlapPercent = overlapSize / (overfetchSize + overlapSize);
1360
+ let bundleAParents = getBundleParents(bundleAId);
1361
+ let bundleBParents = getBundleParents(bundleBId);
1362
+ let sharedParentOverlap = 0;
1363
+ let sharedParentMismatch = 0;
1364
+ for (let bundleId of new Set([...bundleAParents, ...bundleBParents])) {
1365
+ if (bundleAParents.has(bundleId) && bundleBParents.has(bundleId)) {
1366
+ sharedParentOverlap++;
1367
+ }
1368
+ else {
1369
+ sharedParentMismatch++;
1370
+ }
1371
+ }
1372
+ let overfetchScore = overfetchSize / maxOverfetchSize;
1373
+ let sharedParentPercent = sharedParentOverlap / (sharedParentOverlap + sharedParentMismatch);
1374
+ let score = sharedParentPercent + overlapPercent + overfetchScore;
1375
+ return {
1376
+ overfetchSize,
1377
+ score,
1378
+ bundleIds: [bundleAId, bundleBId],
1379
+ };
1380
+ }
1381
+ function getBundleParents(bundleId) {
1382
+ let parents = new Set();
1383
+ let { bundleRoots } = getBundle(bundleId);
1384
+ for (let bundleRoot of bundleRoots) {
1385
+ let bundleRootNodeId = (0, nullthrows_1.default)(assetToBundleRootNodeId.get(bundleRoot));
1386
+ for (let parentId of bundleRootGraph.getNodeIdsConnectedTo(bundleRootNodeId, graph_1.ALL_EDGE_TYPES)) {
1387
+ parents.add(parentId);
1388
+ }
1389
+ }
1390
+ return parents;
1391
+ }
1392
+ function getBundleFromBundleRoot(bundleRoot) {
1393
+ let bundle = bundleGraph.getNode((0, nullthrows_1.default)(bundleRoots.get(bundleRoot))[0]);
1394
+ (0, assert_1.default)(bundle !== 'root' && bundle != null);
1395
+ return bundle;
1396
+ }
1397
+ function addAssetToBundleRoot(asset, bundleRoot) {
1398
+ let [bundleId, bundleGroupId] = (0, nullthrows_1.default)(bundleRoots.get(bundleRoot));
1399
+ let bundle = (0, nullthrows_1.default)(bundleGraph.getNode(bundleId));
1400
+ (0, assert_1.default)(bundle !== 'root');
1401
+ if (asset.type !== bundle.type) {
1402
+ let bundleGroup = (0, nullthrows_1.default)(bundleGraph.getNode(bundleGroupId));
1403
+ (0, assert_1.default)(bundleGroup !== 'root');
1404
+ let key = (0, nullthrows_1.default)(bundleGroup.mainEntryAsset).id + '.' + asset.type;
1405
+ let typeChangeBundleId = bundles.get(key);
1406
+ if (typeChangeBundleId == null) {
1407
+ let typeChangeBundle = createBundle({
1408
+ uniqueKey: key,
1409
+ needsStableName: bundle.needsStableName,
1410
+ bundleBehavior: bundle.bundleBehavior,
1411
+ type: asset.type,
1412
+ target: bundle.target,
1413
+ env: bundle.env,
1414
+ });
1415
+ typeChangeBundleId = bundleGraph.addNode(typeChangeBundle);
1416
+ bundleGraph.addEdge(bundleId, typeChangeBundleId);
1417
+ bundles.set(key, typeChangeBundleId);
1418
+ bundle = typeChangeBundle;
1419
+ }
1420
+ else {
1421
+ bundle = (0, nullthrows_1.default)(bundleGraph.getNode(typeChangeBundleId));
1422
+ (0, assert_1.default)(bundle !== 'root');
1423
+ }
1424
+ }
1425
+ bundle.assets.add(asset);
1426
+ bundle.size += asset.stats.size;
1427
+ assignInlineConstants(asset, bundle);
1428
+ }
1429
+ function removeBundle(bundleGraph, bundleId, assetReference) {
1430
+ let bundle = (0, nullthrows_1.default)(bundleGraph.getNode(bundleId));
1431
+ (0, assert_1.default)(bundle !== 'root');
1432
+ for (let asset of bundle.assets) {
1433
+ assetReference.set(asset, assetReference.get(asset).filter((t) => !t.includes(bundle)));
1434
+ for (let sourceBundleId of bundle.sourceBundles) {
1435
+ let sourceBundle = (0, nullthrows_1.default)(bundleGraph.getNode(sourceBundleId));
1436
+ (0, assert_1.default)(sourceBundle !== 'root');
1437
+ addAssetToBundleRoot(asset, (0, nullthrows_1.default)(sourceBundle.mainEntryAsset));
1438
+ }
1439
+ }
1440
+ bundleGraph.removeNode(bundleId);
1441
+ }
1442
+ stats.report((bundleId) => {
1443
+ let bundle = bundleGraph.getNode(bundleId);
1444
+ (0, assert_1.default)(bundle !== 'root');
1445
+ return bundle;
1446
+ });
1447
+ return {
1448
+ assets,
1449
+ bundleGraph,
1450
+ dependencyBundleGraph,
1451
+ bundleGroupBundleIds,
1452
+ assetReference,
1453
+ manualAssetToBundle,
1454
+ };
1455
+ }
1456
+ function createBundle(opts) {
1457
+ if (opts.asset == null) {
1458
+ return {
1459
+ assets: new Set(),
1460
+ bundleBehavior: opts.bundleBehavior,
1461
+ env: (0, nullthrows_1.default)(opts.env),
1462
+ mainEntryAsset: null,
1463
+ bundleRoots: new Set(),
1464
+ manualSharedBundle: opts.manualSharedBundle,
1465
+ needsStableName: Boolean(opts.needsStableName),
1466
+ size: 0,
1467
+ sourceBundles: opts.sourceBundles ?? new Set(),
1468
+ target: opts.target,
1469
+ type: (0, nullthrows_1.default)(opts.type),
1470
+ uniqueKey: opts.uniqueKey,
1471
+ };
1472
+ }
1473
+ let asset = (0, nullthrows_1.default)(opts.asset);
1474
+ return {
1475
+ assets: new Set([asset]),
1476
+ bundleBehavior: opts.bundleBehavior ?? asset.bundleBehavior,
1477
+ env: opts.env ?? asset.env,
1478
+ mainEntryAsset: asset,
1479
+ bundleRoots: new Set([asset]),
1480
+ manualSharedBundle: opts.manualSharedBundle,
1481
+ needsStableName: Boolean(opts.needsStableName),
1482
+ size: asset.stats.size,
1483
+ sourceBundles: opts.sourceBundles ?? new Set(),
1484
+ target: opts.target,
1485
+ type: opts.type ?? asset.type,
1486
+ uniqueKey: opts.uniqueKey,
1487
+ };
1488
+ }