@atlaspack/runtime-js 2.12.1-canary.3354

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 (44) hide show
  1. package/LICENSE +201 -0
  2. package/lib/JSRuntime.js +562 -0
  3. package/lib/helpers/browser/css-loader.js +28 -0
  4. package/lib/helpers/browser/esm-js-loader-retry.js +51 -0
  5. package/lib/helpers/browser/esm-js-loader.js +7 -0
  6. package/lib/helpers/browser/html-loader.js +8 -0
  7. package/lib/helpers/browser/import-polyfill.js +32 -0
  8. package/lib/helpers/browser/js-loader.js +35 -0
  9. package/lib/helpers/browser/prefetch-loader.js +13 -0
  10. package/lib/helpers/browser/preload-loader.js +14 -0
  11. package/lib/helpers/browser/wasm-loader.js +16 -0
  12. package/lib/helpers/bundle-manifest.js +20 -0
  13. package/lib/helpers/bundle-url.js +39 -0
  14. package/lib/helpers/cacheLoader.js +27 -0
  15. package/lib/helpers/get-worker-url.js +15 -0
  16. package/lib/helpers/node/css-loader.js +6 -0
  17. package/lib/helpers/node/html-loader.js +19 -0
  18. package/lib/helpers/node/js-loader.js +21 -0
  19. package/lib/helpers/node/wasm-loader.js +19 -0
  20. package/lib/helpers/worker/js-loader.js +14 -0
  21. package/lib/helpers/worker/wasm-loader.js +16 -0
  22. package/package.json +25 -0
  23. package/src/JSRuntime.js +742 -0
  24. package/src/helpers/.babelrc +9 -0
  25. package/src/helpers/.eslintrc.json +3 -0
  26. package/src/helpers/browser/css-loader.js +32 -0
  27. package/src/helpers/browser/esm-js-loader-retry.js +26 -0
  28. package/src/helpers/browser/esm-js-loader.js +6 -0
  29. package/src/helpers/browser/html-loader.js +7 -0
  30. package/src/helpers/browser/import-polyfill.js +32 -0
  31. package/src/helpers/browser/js-loader.js +42 -0
  32. package/src/helpers/browser/prefetch-loader.js +13 -0
  33. package/src/helpers/browser/preload-loader.js +19 -0
  34. package/src/helpers/browser/wasm-loader.js +17 -0
  35. package/src/helpers/bundle-manifest.js +21 -0
  36. package/src/helpers/bundle-url.js +51 -0
  37. package/src/helpers/cacheLoader.js +29 -0
  38. package/src/helpers/get-worker-url.js +15 -0
  39. package/src/helpers/node/css-loader.js +4 -0
  40. package/src/helpers/node/html-loader.js +18 -0
  41. package/src/helpers/node/js-loader.js +20 -0
  42. package/src/helpers/node/wasm-loader.js +20 -0
  43. package/src/helpers/worker/js-loader.js +13 -0
  44. package/src/helpers/worker/wasm-loader.js +17 -0
@@ -0,0 +1,742 @@
1
+ // @flow strict-local
2
+
3
+ import type {
4
+ BundleGraph,
5
+ BundleGroup,
6
+ Dependency,
7
+ Environment,
8
+ PluginOptions,
9
+ NamedBundle,
10
+ RuntimeAsset,
11
+ } from '@atlaspack/types';
12
+
13
+ import {Runtime} from '@atlaspack/plugin';
14
+ import {
15
+ relativeBundlePath,
16
+ validateSchema,
17
+ type SchemaEntity,
18
+ } from '@atlaspack/utils';
19
+ import {encodeJSONKeyComponent} from '@atlaspack/diagnostic';
20
+ import path from 'path';
21
+ import nullthrows from 'nullthrows';
22
+
23
+ // Used for as="" in preload/prefetch
24
+ const TYPE_TO_RESOURCE_PRIORITY = {
25
+ css: 'style',
26
+ js: 'script',
27
+ };
28
+
29
+ const BROWSER_PRELOAD_LOADER = './helpers/browser/preload-loader';
30
+ const BROWSER_PREFETCH_LOADER = './helpers/browser/prefetch-loader';
31
+
32
+ const LOADERS = {
33
+ browser: {
34
+ css: './helpers/browser/css-loader',
35
+ html: './helpers/browser/html-loader',
36
+ js: './helpers/browser/js-loader',
37
+ wasm: './helpers/browser/wasm-loader',
38
+ IMPORT_POLYFILL: './helpers/browser/import-polyfill',
39
+ },
40
+ worker: {
41
+ js: './helpers/worker/js-loader',
42
+ wasm: './helpers/worker/wasm-loader',
43
+ IMPORT_POLYFILL: false,
44
+ },
45
+ node: {
46
+ css: './helpers/node/css-loader',
47
+ html: './helpers/node/html-loader',
48
+ js: './helpers/node/js-loader',
49
+ wasm: './helpers/node/wasm-loader',
50
+ IMPORT_POLYFILL: null,
51
+ },
52
+ };
53
+
54
+ function getLoaders(
55
+ ctx: Environment,
56
+ ): ?{[string]: string, IMPORT_POLYFILL: null | false | string, ...} {
57
+ if (ctx.isWorker()) return LOADERS.worker;
58
+ if (ctx.isBrowser()) return LOADERS.browser;
59
+ if (ctx.isNode()) return LOADERS.node;
60
+ return null;
61
+ }
62
+
63
+ // This cache should be invalidated if new dependencies get added to the bundle without the bundle objects changing
64
+ // This can happen when we reuse the BundleGraph between subsequent builds
65
+ let bundleDependencies = new WeakMap<
66
+ NamedBundle,
67
+ {|
68
+ asyncDependencies: Array<Dependency>,
69
+ otherDependencies: Array<Dependency>,
70
+ |},
71
+ >();
72
+
73
+ type JSRuntimeConfig = {|
74
+ splitManifestThreshold: number,
75
+ |};
76
+
77
+ let defaultConfig: JSRuntimeConfig = {
78
+ splitManifestThreshold: 100000,
79
+ };
80
+
81
+ const CONFIG_SCHEMA: SchemaEntity = {
82
+ type: 'object',
83
+ properties: {
84
+ splitManifestThreshold: {
85
+ type: 'number',
86
+ },
87
+ },
88
+ additionalProperties: false,
89
+ };
90
+
91
+ export default (new Runtime({
92
+ async loadConfig({config, options}): Promise<JSRuntimeConfig> {
93
+ let packageKey = '@atlaspack/runtime-js';
94
+ let conf = await config.getConfig<JSRuntimeConfig>([], {
95
+ packageKey,
96
+ });
97
+
98
+ if (!conf) {
99
+ return defaultConfig;
100
+ }
101
+ validateSchema.diagnostic(
102
+ CONFIG_SCHEMA,
103
+ {
104
+ data: conf?.contents,
105
+ source: await options.inputFS.readFile(conf.filePath, 'utf8'),
106
+ filePath: conf.filePath,
107
+ prependKey: `/${encodeJSONKeyComponent(packageKey)}`,
108
+ },
109
+ packageKey,
110
+ `Invalid config for ${packageKey}`,
111
+ );
112
+
113
+ return {
114
+ ...defaultConfig,
115
+ ...conf?.contents,
116
+ };
117
+ },
118
+ apply({bundle, bundleGraph, options, config}) {
119
+ // Dependency ids in code replaced with referenced bundle names
120
+ // Loader runtime added for bundle groups that don't have a native loader (e.g. HTML/CSS/Worker - isURL?),
121
+ // and which are not loaded by a parent bundle.
122
+ // Loaders also added for modules that were moved to a separate bundle because they are a different type
123
+ // (e.g. WASM, HTML). These should be preloaded prior to the bundle being executed. Replace the entry asset(s)
124
+ // with the preload module.
125
+
126
+ if (bundle.type !== 'js') {
127
+ return;
128
+ }
129
+
130
+ let {asyncDependencies, otherDependencies} = getDependencies(bundle);
131
+
132
+ let assets = [];
133
+ for (let dependency of asyncDependencies) {
134
+ let resolved = bundleGraph.resolveAsyncDependency(dependency, bundle);
135
+ if (resolved == null) {
136
+ continue;
137
+ }
138
+
139
+ if (resolved.type === 'asset') {
140
+ if (!bundle.env.shouldScopeHoist) {
141
+ // If this bundle already has the asset this dependency references,
142
+ // return a simple runtime of `Promise.resolve(internalRequire(assetId))`.
143
+ // The linker handles this for scope-hoisting.
144
+ assets.push({
145
+ filePath: __filename,
146
+ code: `module.exports = Promise.resolve(module.bundle.root(${JSON.stringify(
147
+ bundleGraph.getAssetPublicId(resolved.value),
148
+ )}))`,
149
+ dependency,
150
+ env: {sourceType: 'module'},
151
+ });
152
+ }
153
+ } else {
154
+ // Resolve the dependency to a bundle. If inline, export the dependency id,
155
+ // which will be replaced with the contents of that bundle later.
156
+ let referencedBundle = bundleGraph.getReferencedBundle(
157
+ dependency,
158
+ bundle,
159
+ );
160
+ if (referencedBundle?.bundleBehavior === 'inline') {
161
+ assets.push({
162
+ filePath: path.join(
163
+ __dirname,
164
+ `/bundles/${referencedBundle.id}.js`,
165
+ ),
166
+ code: `module.exports = Promise.resolve(${JSON.stringify(
167
+ dependency.id,
168
+ )});`,
169
+ dependency,
170
+ env: {sourceType: 'module'},
171
+ });
172
+ continue;
173
+ }
174
+
175
+ let loaderRuntime = getLoaderRuntime({
176
+ bundle,
177
+ dependency,
178
+ bundleGraph,
179
+ bundleGroup: resolved.value,
180
+ options,
181
+ });
182
+
183
+ if (loaderRuntime != null) {
184
+ assets.push(loaderRuntime);
185
+ }
186
+ }
187
+ }
188
+
189
+ for (let dependency of otherDependencies) {
190
+ // Resolve the dependency to a bundle. If inline, export the dependency id,
191
+ // which will be replaced with the contents of that bundle later.
192
+ let referencedBundle = bundleGraph.getReferencedBundle(
193
+ dependency,
194
+ bundle,
195
+ );
196
+ if (referencedBundle?.bundleBehavior === 'inline') {
197
+ assets.push({
198
+ filePath: path.join(__dirname, `/bundles/${referencedBundle.id}.js`),
199
+ code: `module.exports = ${JSON.stringify(dependency.id)};`,
200
+ dependency,
201
+ env: {sourceType: 'module'},
202
+ });
203
+ continue;
204
+ }
205
+
206
+ // Otherwise, try to resolve the dependency to an external bundle group
207
+ // and insert a URL to that bundle.
208
+ let resolved = bundleGraph.resolveAsyncDependency(dependency, bundle);
209
+ if (dependency.specifierType === 'url' && resolved == null) {
210
+ // If a URL dependency was not able to be resolved, add a runtime that
211
+ // exports the original specifier.
212
+ assets.push({
213
+ filePath: __filename,
214
+ code: `module.exports = ${JSON.stringify(dependency.specifier)}`,
215
+ dependency,
216
+ env: {sourceType: 'module'},
217
+ });
218
+ continue;
219
+ }
220
+
221
+ if (resolved == null || resolved.type !== 'bundle_group') {
222
+ continue;
223
+ }
224
+
225
+ let bundleGroup = resolved.value;
226
+ let mainBundle = nullthrows(
227
+ bundleGraph.getBundlesInBundleGroup(bundleGroup).find(b => {
228
+ let entries = b.getEntryAssets();
229
+ return entries.some(e => bundleGroup.entryAssetId === e.id);
230
+ }),
231
+ );
232
+
233
+ // Skip URL runtimes for library builds. This is handled in packaging so that
234
+ // the url is inlined and statically analyzable.
235
+ if (bundle.env.isLibrary && mainBundle.bundleBehavior !== 'isolated') {
236
+ continue;
237
+ }
238
+
239
+ // URL dependency or not, fall back to including a runtime that exports the url
240
+ assets.push(getURLRuntime(dependency, bundle, mainBundle, options));
241
+ }
242
+
243
+ // In development, bundles can be created lazily. This means that the parent bundle may not
244
+ // know about all of the sibling bundles of a child when it is written for the first time.
245
+ // Therefore, we need to also ensure that the siblings are loaded when the child loads.
246
+ if (options.shouldBuildLazily && bundle.env.outputFormat === 'global') {
247
+ let referenced = bundleGraph.getReferencedBundles(bundle);
248
+ for (let referencedBundle of referenced) {
249
+ let loaders = getLoaders(bundle.env);
250
+ if (!loaders) {
251
+ continue;
252
+ }
253
+
254
+ let loader = loaders[referencedBundle.type];
255
+ if (!loader) {
256
+ continue;
257
+ }
258
+
259
+ let relativePathExpr = getRelativePathExpr(
260
+ bundle,
261
+ referencedBundle,
262
+ options,
263
+ );
264
+ let loaderCode = `require(${JSON.stringify(
265
+ loader,
266
+ )})( ${getAbsoluteUrlExpr(relativePathExpr, bundle)})`;
267
+ assets.push({
268
+ filePath: __filename,
269
+ code: loaderCode,
270
+ isEntry: true,
271
+ env: {sourceType: 'module'},
272
+ });
273
+ }
274
+ }
275
+
276
+ if (
277
+ shouldUseRuntimeManifest(bundle, options) &&
278
+ bundleGraph
279
+ .getChildBundles(bundle)
280
+ .some(b => b.bundleBehavior !== 'inline') &&
281
+ isNewContext(bundle, bundleGraph)
282
+ ) {
283
+ assets.push({
284
+ filePath: __filename,
285
+ code: getRegisterCode(bundle, bundleGraph),
286
+ isEntry: true,
287
+ env: {sourceType: 'module'},
288
+ priority: getManifestBundlePriority(
289
+ bundleGraph,
290
+ bundle,
291
+ config.splitManifestThreshold,
292
+ ),
293
+ });
294
+ }
295
+
296
+ return assets;
297
+ },
298
+ }): Runtime);
299
+
300
+ function getDependencies(bundle: NamedBundle): {|
301
+ asyncDependencies: Array<Dependency>,
302
+ otherDependencies: Array<Dependency>,
303
+ |} {
304
+ let cachedDependencies = bundleDependencies.get(bundle);
305
+
306
+ if (cachedDependencies) {
307
+ return cachedDependencies;
308
+ } else {
309
+ let asyncDependencies = [];
310
+ let otherDependencies = [];
311
+ bundle.traverse(node => {
312
+ if (node.type !== 'dependency') {
313
+ return;
314
+ }
315
+
316
+ let dependency = node.value;
317
+ if (
318
+ dependency.priority === 'lazy' &&
319
+ dependency.specifierType !== 'url'
320
+ ) {
321
+ asyncDependencies.push(dependency);
322
+ } else {
323
+ otherDependencies.push(dependency);
324
+ }
325
+ });
326
+ bundleDependencies.set(bundle, {asyncDependencies, otherDependencies});
327
+ return {asyncDependencies, otherDependencies};
328
+ }
329
+ }
330
+
331
+ function getLoaderRuntime({
332
+ bundle,
333
+ dependency,
334
+ bundleGroup,
335
+ bundleGraph,
336
+ options,
337
+ }: {|
338
+ bundle: NamedBundle,
339
+ dependency: Dependency,
340
+ bundleGroup: BundleGroup,
341
+ bundleGraph: BundleGraph<NamedBundle>,
342
+ options: PluginOptions,
343
+ |}): ?RuntimeAsset {
344
+ let loaders = getLoaders(bundle.env);
345
+ if (loaders == null) {
346
+ return;
347
+ }
348
+
349
+ let externalBundles = bundleGraph.getBundlesInBundleGroup(bundleGroup);
350
+ let mainBundle = nullthrows(
351
+ externalBundles.find(
352
+ bundle => bundle.getMainEntry()?.id === bundleGroup.entryAssetId,
353
+ ),
354
+ );
355
+
356
+ // CommonJS is a synchronous module system, so there is no need to load bundles in parallel.
357
+ // Importing of the other bundles will be handled by the bundle group entry.
358
+ // Do the same thing in library mode for ES modules, as we are building for another bundler
359
+ // and the imports for sibling bundles will be in the target bundle.
360
+
361
+ // Previously we also did this when building lazily, however it seemed to cause issues in some cases.
362
+ // The original comment as to why is left here, in case a future traveller is trying to fix that issue:
363
+ // > [...] the runtime itself could get deduplicated and only exist in the parent. This causes errors if an
364
+ // > old version of the parent without the runtime
365
+ // > is already loaded.
366
+ if (bundle.env.outputFormat === 'commonjs' || bundle.env.isLibrary) {
367
+ externalBundles = [mainBundle];
368
+ } else {
369
+ // Otherwise, load the bundle group entry after the others.
370
+ externalBundles.splice(externalBundles.indexOf(mainBundle), 1);
371
+ externalBundles.reverse().push(mainBundle);
372
+ }
373
+
374
+ // Determine if we need to add a dynamic import() polyfill, or if all target browsers support it natively.
375
+ let needsDynamicImportPolyfill =
376
+ !bundle.env.isLibrary && !bundle.env.supports('dynamic-import', true);
377
+
378
+ let needsEsmLoadPrelude = false;
379
+ let loaderModules = [];
380
+
381
+ for (let to of externalBundles) {
382
+ let loader = loaders[to.type];
383
+ if (!loader) {
384
+ continue;
385
+ }
386
+
387
+ if (
388
+ to.type === 'js' &&
389
+ to.env.outputFormat === 'esmodule' &&
390
+ !needsDynamicImportPolyfill &&
391
+ shouldUseRuntimeManifest(bundle, options)
392
+ ) {
393
+ loaderModules.push(`load(${JSON.stringify(to.publicId)})`);
394
+ needsEsmLoadPrelude = true;
395
+ continue;
396
+ }
397
+
398
+ let relativePathExpr = getRelativePathExpr(bundle, to, options);
399
+
400
+ // Use esmodule loader if possible
401
+ if (to.type === 'js' && to.env.outputFormat === 'esmodule') {
402
+ if (!needsDynamicImportPolyfill) {
403
+ loaderModules.push(`__atlaspack__import__("./" + ${relativePathExpr})`);
404
+ continue;
405
+ }
406
+
407
+ loader = nullthrows(
408
+ loaders.IMPORT_POLYFILL,
409
+ `No import() polyfill available for context '${bundle.env.context}'`,
410
+ );
411
+ } else if (to.type === 'js' && to.env.outputFormat === 'commonjs') {
412
+ loaderModules.push(
413
+ `Promise.resolve(__atlaspack__require__("./" + ${relativePathExpr}))`,
414
+ );
415
+ continue;
416
+ }
417
+
418
+ let absoluteUrlExpr = shouldUseRuntimeManifest(bundle, options)
419
+ ? `require('./helpers/bundle-manifest').resolve(${JSON.stringify(
420
+ to.publicId,
421
+ )})`
422
+ : getAbsoluteUrlExpr(relativePathExpr, bundle);
423
+ let code = `require(${JSON.stringify(loader)})(${absoluteUrlExpr})`;
424
+
425
+ // In development, clear the require cache when an error occurs so the
426
+ // user can try again (e.g. after fixing a build error).
427
+ if (
428
+ options.mode === 'development' &&
429
+ bundle.env.outputFormat === 'global'
430
+ ) {
431
+ code +=
432
+ '.catch(err => {delete module.bundle.cache[module.id]; throw err;})';
433
+ }
434
+ loaderModules.push(code);
435
+ }
436
+
437
+ // Similar to the comment above, this also used to be skipped when shouldBuildLazily was true,
438
+ // however it caused issues where a bundle group contained multiple bundles.
439
+ if (bundle.env.context === 'browser') {
440
+ loaderModules.push(
441
+ ...externalBundles
442
+ // TODO: Allow css to preload resources as well
443
+ .filter(to => to.type === 'js')
444
+ .flatMap(from => {
445
+ let {preload, prefetch} = getHintedBundleGroups(bundleGraph, from);
446
+
447
+ return [
448
+ ...getHintLoaders(
449
+ bundleGraph,
450
+ bundle,
451
+ preload,
452
+ BROWSER_PRELOAD_LOADER,
453
+ options,
454
+ ),
455
+ ...getHintLoaders(
456
+ bundleGraph,
457
+ bundle,
458
+ prefetch,
459
+ BROWSER_PREFETCH_LOADER,
460
+ options,
461
+ ),
462
+ ];
463
+ }),
464
+ );
465
+ }
466
+
467
+ if (loaderModules.length === 0) {
468
+ return;
469
+ }
470
+
471
+ let loaderCode = loaderModules.join(', ');
472
+ if (loaderModules.length > 1) {
473
+ loaderCode = `Promise.all([${loaderCode}])`;
474
+ } else {
475
+ loaderCode = `(${loaderCode})`;
476
+ }
477
+
478
+ if (mainBundle.type === 'js') {
479
+ let atlaspackRequire = bundle.env.shouldScopeHoist
480
+ ? 'atlaspackRequire'
481
+ : 'module.bundle.root';
482
+ loaderCode += `.then(() => ${atlaspackRequire}('${bundleGraph.getAssetPublicId(
483
+ bundleGraph.getAssetById(bundleGroup.entryAssetId),
484
+ )}'))`;
485
+ }
486
+
487
+ if (needsEsmLoadPrelude && options.featureFlags.importRetry) {
488
+ loaderCode = `
489
+ Object.defineProperty(module, 'exports', { get: () => {
490
+ let load = require('./helpers/browser/esm-js-loader-retry');
491
+ return ${loaderCode}.then((v) => {
492
+ Object.defineProperty(module, "exports", { value: Promise.resolve(v) })
493
+ return v
494
+ });
495
+ }})`;
496
+
497
+ return {
498
+ filePath: __filename,
499
+ code: loaderCode,
500
+ dependency,
501
+ env: {sourceType: 'module'},
502
+ };
503
+ }
504
+
505
+ let code = [];
506
+
507
+ if (needsEsmLoadPrelude) {
508
+ code.push(`let load = require('./helpers/browser/esm-js-loader');`);
509
+ }
510
+
511
+ code.push(`module.exports = ${loaderCode};`);
512
+
513
+ return {
514
+ filePath: __filename,
515
+ code: code.join('\n'),
516
+ dependency,
517
+ env: {sourceType: 'module'},
518
+ };
519
+ }
520
+
521
+ function getHintedBundleGroups(
522
+ bundleGraph: BundleGraph<NamedBundle>,
523
+ bundle: NamedBundle,
524
+ ): {|preload: Array<BundleGroup>, prefetch: Array<BundleGroup>|} {
525
+ let preload = [];
526
+ let prefetch = [];
527
+ let {asyncDependencies} = getDependencies(bundle);
528
+ for (let dependency of asyncDependencies) {
529
+ let attributes = dependency.meta?.importAttributes;
530
+ if (
531
+ typeof attributes === 'object' &&
532
+ attributes != null &&
533
+ // $FlowFixMe
534
+ (attributes.preload || attributes.prefetch)
535
+ ) {
536
+ let resolved = bundleGraph.resolveAsyncDependency(dependency, bundle);
537
+ if (resolved?.type === 'bundle_group') {
538
+ // === true for flow
539
+ if (attributes.preload === true) {
540
+ preload.push(resolved.value);
541
+ }
542
+ if (attributes.prefetch === true) {
543
+ prefetch.push(resolved.value);
544
+ }
545
+ }
546
+ }
547
+ }
548
+
549
+ return {preload, prefetch};
550
+ }
551
+
552
+ function getHintLoaders(
553
+ bundleGraph: BundleGraph<NamedBundle>,
554
+ from: NamedBundle,
555
+ bundleGroups: Array<BundleGroup>,
556
+ loader: string,
557
+ options: PluginOptions,
558
+ ): Array<string> {
559
+ let hintLoaders = [];
560
+ for (let bundleGroupToPreload of bundleGroups) {
561
+ let bundlesToPreload =
562
+ bundleGraph.getBundlesInBundleGroup(bundleGroupToPreload);
563
+
564
+ for (let bundleToPreload of bundlesToPreload) {
565
+ let relativePathExpr = getRelativePathExpr(
566
+ from,
567
+ bundleToPreload,
568
+ options,
569
+ );
570
+ let priority = TYPE_TO_RESOURCE_PRIORITY[bundleToPreload.type];
571
+ hintLoaders.push(
572
+ `require(${JSON.stringify(loader)})(${getAbsoluteUrlExpr(
573
+ relativePathExpr,
574
+ from,
575
+ )}, ${priority ? JSON.stringify(priority) : 'null'}, ${JSON.stringify(
576
+ bundleToPreload.target.env.outputFormat === 'esmodule',
577
+ )})`,
578
+ );
579
+ }
580
+ }
581
+
582
+ return hintLoaders;
583
+ }
584
+
585
+ function isNewContext(
586
+ bundle: NamedBundle,
587
+ bundleGraph: BundleGraph<NamedBundle>,
588
+ ): boolean {
589
+ let parents = bundleGraph.getParentBundles(bundle);
590
+ let isInEntryBundleGroup = bundleGraph
591
+ .getBundleGroupsContainingBundle(bundle)
592
+ .some(g => bundleGraph.isEntryBundleGroup(g));
593
+ return (
594
+ isInEntryBundleGroup ||
595
+ parents.length === 0 ||
596
+ parents.some(
597
+ parent =>
598
+ parent.env.context !== bundle.env.context || parent.type !== 'js',
599
+ )
600
+ );
601
+ }
602
+
603
+ function getURLRuntime(
604
+ dependency: Dependency,
605
+ from: NamedBundle,
606
+ to: NamedBundle,
607
+ options: PluginOptions,
608
+ ): RuntimeAsset {
609
+ let relativePathExpr = getRelativePathExpr(from, to, options);
610
+ let code;
611
+
612
+ if (dependency.meta.webworker === true && !from.env.isLibrary) {
613
+ code = `let workerURL = require('./helpers/get-worker-url');\n`;
614
+ if (
615
+ from.env.outputFormat === 'esmodule' &&
616
+ from.env.supports('import-meta-url')
617
+ ) {
618
+ code += `let url = new __atlaspack__URL__(${relativePathExpr});\n`;
619
+ code += `module.exports = workerURL(url.toString(), url.origin, ${String(
620
+ from.env.outputFormat === 'esmodule',
621
+ )});`;
622
+ } else {
623
+ code += `let bundleURL = require('./helpers/bundle-url');\n`;
624
+ code += `let url = bundleURL.getBundleURL('${from.publicId}') + ${relativePathExpr};`;
625
+ code += `module.exports = workerURL(url, bundleURL.getOrigin(url), ${String(
626
+ from.env.outputFormat === 'esmodule',
627
+ )});`;
628
+ }
629
+ } else {
630
+ code = `module.exports = ${getAbsoluteUrlExpr(relativePathExpr, from)};`;
631
+ }
632
+
633
+ return {
634
+ filePath: __filename,
635
+ code,
636
+ dependency,
637
+ env: {sourceType: 'module'},
638
+ };
639
+ }
640
+
641
+ function getRegisterCode(
642
+ entryBundle: NamedBundle,
643
+ bundleGraph: BundleGraph<NamedBundle>,
644
+ ): string {
645
+ let mappings = [];
646
+ bundleGraph.traverseBundles((bundle, _, actions) => {
647
+ if (bundle.bundleBehavior === 'inline') {
648
+ return;
649
+ }
650
+
651
+ // To make the manifest as small as possible all bundle key/values are
652
+ // serialised into a single array e.g. ['id', 'value', 'id2', 'value2'].
653
+ // `./helpers/bundle-manifest` accounts for this by iterating index by 2
654
+ mappings.push(
655
+ bundle.publicId,
656
+ relativeBundlePath(entryBundle, nullthrows(bundle), {
657
+ leadingDotSlash: false,
658
+ }),
659
+ );
660
+
661
+ if (bundle !== entryBundle && isNewContext(bundle, bundleGraph)) {
662
+ for (let referenced of bundleGraph.getReferencedBundles(bundle)) {
663
+ mappings.push(
664
+ referenced.publicId,
665
+ relativeBundlePath(entryBundle, nullthrows(referenced), {
666
+ leadingDotSlash: false,
667
+ }),
668
+ );
669
+ }
670
+ // New contexts have their own manifests, so there's no need to continue.
671
+ actions.skipChildren();
672
+ }
673
+ }, entryBundle);
674
+
675
+ let baseUrl =
676
+ entryBundle.env.outputFormat === 'esmodule' &&
677
+ entryBundle.env.supports('import-meta-url')
678
+ ? 'new __atlaspack__URL__("").toString()' // <-- this isn't ideal. We should use `import.meta.url` directly but it gets replaced currently
679
+ : `require('./helpers/bundle-url').getBundleURL('${entryBundle.publicId}')`;
680
+
681
+ return `require('./helpers/bundle-manifest').register(${baseUrl},JSON.parse(${JSON.stringify(
682
+ JSON.stringify(mappings),
683
+ )}));`;
684
+ }
685
+
686
+ function getRelativePathExpr(
687
+ from: NamedBundle,
688
+ to: NamedBundle,
689
+ options: PluginOptions,
690
+ ): string {
691
+ let relativePath = relativeBundlePath(from, to, {leadingDotSlash: false});
692
+ let res = JSON.stringify(relativePath);
693
+ if (options.hmrOptions) {
694
+ res += ' + "?" + Date.now()';
695
+ }
696
+
697
+ return res;
698
+ }
699
+
700
+ function getAbsoluteUrlExpr(relativePathExpr: string, bundle: NamedBundle) {
701
+ if (
702
+ (bundle.env.outputFormat === 'esmodule' &&
703
+ bundle.env.supports('import-meta-url')) ||
704
+ bundle.env.outputFormat === 'commonjs'
705
+ ) {
706
+ // This will be compiled to new URL(url, import.meta.url) or new URL(url, 'file:' + __filename).
707
+ return `new __atlaspack__URL__(${relativePathExpr}).toString()`;
708
+ } else {
709
+ return `require('./helpers/bundle-url').getBundleURL('${bundle.publicId}') + ${relativePathExpr}`;
710
+ }
711
+ }
712
+
713
+ function shouldUseRuntimeManifest(
714
+ bundle: NamedBundle,
715
+ options: PluginOptions,
716
+ ): boolean {
717
+ let env = bundle.env;
718
+ return (
719
+ !env.isLibrary &&
720
+ bundle.bundleBehavior !== 'inline' &&
721
+ env.isBrowser() &&
722
+ options.mode === 'production'
723
+ );
724
+ }
725
+
726
+ function getManifestBundlePriority(
727
+ bundleGraph: BundleGraph<NamedBundle>,
728
+ bundle: NamedBundle,
729
+ threshold: number,
730
+ ): $PropertyType<RuntimeAsset, 'priority'> {
731
+ let bundleSize = 0;
732
+
733
+ bundle.traverseAssets((asset, _, actions) => {
734
+ bundleSize += asset.stats.size;
735
+
736
+ if (bundleSize > threshold) {
737
+ actions.stop();
738
+ }
739
+ });
740
+
741
+ return bundleSize > threshold ? 'parallel' : 'sync';
742
+ }