@atlaspack/bundler-default 2.12.1-dev.3466 → 2.12.1-dev.3502

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