@atlaspack/packager-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.
@@ -0,0 +1,1470 @@
1
+ // @flow
2
+
3
+ import type {
4
+ Asset,
5
+ BundleGraph,
6
+ Dependency,
7
+ PluginOptions,
8
+ NamedBundle,
9
+ } from '@atlaspack/types';
10
+
11
+ import {
12
+ DefaultMap,
13
+ PromiseQueue,
14
+ relativeBundlePath,
15
+ countLines,
16
+ normalizeSeparators,
17
+ } from '@atlaspack/utils';
18
+ import SourceMap from '@parcel/source-map';
19
+ import nullthrows from 'nullthrows';
20
+ import invariant, {AssertionError} from 'assert';
21
+ import ThrowableDiagnostic, {
22
+ convertSourceLocationToHighlight,
23
+ } from '@atlaspack/diagnostic';
24
+ import globals from 'globals';
25
+ import path from 'path';
26
+
27
+ import {ESMOutputFormat} from './ESMOutputFormat';
28
+ import {CJSOutputFormat} from './CJSOutputFormat';
29
+ import {GlobalOutputFormat} from './GlobalOutputFormat';
30
+ import {prelude, helpers, bundleQueuePrelude, fnExpr} from './helpers';
31
+ import {
32
+ replaceScriptDependencies,
33
+ getSpecifier,
34
+ isValidIdentifier,
35
+ makeValidIdentifier,
36
+ } from './utils';
37
+ // General regex used to replace imports with the resolved code, references with resolutions,
38
+ // and count the number of newlines in the file for source maps.
39
+ const REPLACEMENT_RE =
40
+ /\n|import\s+"([0-9a-f]{16}:.+?)";|(?:\$[0-9a-f]{16}\$exports)|(?:\$[0-9a-f]{16}\$(?:import|importAsync|require)\$[0-9a-f]+(?:\$[0-9a-f]+)?)/g;
41
+
42
+ const BUILTINS = Object.keys(globals.builtin);
43
+ const GLOBALS_BY_CONTEXT = {
44
+ browser: new Set([...BUILTINS, ...Object.keys(globals.browser)]),
45
+ 'web-worker': new Set([...BUILTINS, ...Object.keys(globals.worker)]),
46
+ 'service-worker': new Set([
47
+ ...BUILTINS,
48
+ ...Object.keys(globals.serviceworker),
49
+ ]),
50
+ worklet: new Set([...BUILTINS]),
51
+ node: new Set([...BUILTINS, ...Object.keys(globals.node)]),
52
+ 'electron-main': new Set([...BUILTINS, ...Object.keys(globals.node)]),
53
+ 'electron-renderer': new Set([
54
+ ...BUILTINS,
55
+ ...Object.keys(globals.node),
56
+ ...Object.keys(globals.browser),
57
+ ]),
58
+ };
59
+
60
+ const OUTPUT_FORMATS = {
61
+ esmodule: ESMOutputFormat,
62
+ commonjs: CJSOutputFormat,
63
+ global: GlobalOutputFormat,
64
+ };
65
+
66
+ export interface OutputFormat {
67
+ buildBundlePrelude(): [string, number];
68
+ buildBundlePostlude(): [string, number];
69
+ }
70
+
71
+ export class ScopeHoistingPackager {
72
+ options: PluginOptions;
73
+ bundleGraph: BundleGraph<NamedBundle>;
74
+ bundle: NamedBundle;
75
+ atlaspackRequireName: string;
76
+ useAsyncBundleRuntime: boolean;
77
+ outputFormat: OutputFormat;
78
+ isAsyncBundle: boolean;
79
+ globalNames: $ReadOnlySet<string>;
80
+ assetOutputs: Map<string, {|code: string, map: ?Buffer|}>;
81
+ exportedSymbols: Map<
82
+ string,
83
+ {|
84
+ asset: Asset,
85
+ exportSymbol: string,
86
+ local: string,
87
+ exportAs: Array<string>,
88
+ |},
89
+ > = new Map();
90
+ externals: Map<string, Map<string, string>> = new Map();
91
+ topLevelNames: Map<string, number> = new Map();
92
+ seenAssets: Set<string> = new Set();
93
+ wrappedAssets: Set<string> = new Set();
94
+ hoistedRequires: Map<string, Map<string, string>> = new Map();
95
+ needsPrelude: boolean = false;
96
+ usedHelpers: Set<string> = new Set();
97
+ externalAssets: Set<Asset> = new Set();
98
+
99
+ constructor(
100
+ options: PluginOptions,
101
+ bundleGraph: BundleGraph<NamedBundle>,
102
+ bundle: NamedBundle,
103
+ atlaspackRequireName: string,
104
+ useAsyncBundleRuntime: boolean,
105
+ ) {
106
+ this.options = options;
107
+ this.bundleGraph = bundleGraph;
108
+ this.bundle = bundle;
109
+ this.atlaspackRequireName = atlaspackRequireName;
110
+ this.useAsyncBundleRuntime = useAsyncBundleRuntime;
111
+
112
+ let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
113
+ this.outputFormat = new OutputFormat(this);
114
+
115
+ this.isAsyncBundle =
116
+ this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') &&
117
+ !this.bundle.env.isIsolated() &&
118
+ this.bundle.bundleBehavior !== 'isolated';
119
+
120
+ this.globalNames = GLOBALS_BY_CONTEXT[bundle.env.context];
121
+ }
122
+
123
+ async package(): Promise<{|contents: string, map: ?SourceMap|}> {
124
+ let wrappedAssets = await this.loadAssets();
125
+ this.buildExportedSymbols();
126
+
127
+ // If building a library, the target is actually another bundler rather
128
+ // than the final output that could be loaded in a browser. So, loader
129
+ // runtimes are excluded, and instead we add imports into the entry bundle
130
+ // of each bundle group pointing at the sibling bundles. These can be
131
+ // picked up by another bundler later at which point runtimes will be added.
132
+ if (
133
+ this.bundle.env.isLibrary ||
134
+ this.bundle.env.outputFormat === 'commonjs'
135
+ ) {
136
+ for (let b of this.bundleGraph.getReferencedBundles(this.bundle, {
137
+ recursive: false,
138
+ })) {
139
+ this.externals.set(relativeBundlePath(this.bundle, b), new Map());
140
+ }
141
+ }
142
+
143
+ let res = '';
144
+ let lineCount = 0;
145
+ let sourceMap = null;
146
+ let processAsset = asset => {
147
+ let [content, map, lines] = this.visitAsset(asset);
148
+ if (sourceMap && map) {
149
+ sourceMap.addSourceMap(map, lineCount);
150
+ } else if (this.bundle.env.sourceMap) {
151
+ sourceMap = map;
152
+ }
153
+
154
+ res += content + '\n';
155
+ lineCount += lines + 1;
156
+ };
157
+
158
+ // Hoist wrapped asset to the top of the bundle to ensure that they are registered
159
+ // before they are used.
160
+ for (let asset of wrappedAssets) {
161
+ if (!this.seenAssets.has(asset.id)) {
162
+ processAsset(asset);
163
+ }
164
+ }
165
+
166
+ // Add each asset that is directly connected to the bundle. Dependencies will be handled
167
+ // by replacing `import` statements in the code.
168
+ this.bundle.traverseAssets((asset, _, actions) => {
169
+ if (this.seenAssets.has(asset.id)) {
170
+ actions.skipChildren();
171
+ return;
172
+ }
173
+
174
+ processAsset(asset);
175
+ actions.skipChildren();
176
+ });
177
+
178
+ let [prelude, preludeLines] = this.buildBundlePrelude();
179
+ res = prelude + res;
180
+ lineCount += preludeLines;
181
+ sourceMap?.offsetLines(1, preludeLines);
182
+
183
+ let entries = this.bundle.getEntryAssets();
184
+ let mainEntry = this.bundle.getMainEntry();
185
+ if (this.isAsyncBundle) {
186
+ // In async bundles we don't want the main entry to execute until we require it
187
+ // as there might be dependencies in a sibling bundle that hasn't loaded yet.
188
+ entries = entries.filter(a => a.id !== mainEntry?.id);
189
+ mainEntry = null;
190
+ }
191
+
192
+ let needsBundleQueue = this.shouldBundleQueue(this.bundle);
193
+
194
+ // If any of the entry assets are wrapped, call atlaspackRequire so they are executed.
195
+ for (let entry of entries) {
196
+ if (this.wrappedAssets.has(entry.id) && !this.isScriptEntry(entry)) {
197
+ let atlaspackRequire = `atlaspackRequire(${JSON.stringify(
198
+ this.bundleGraph.getAssetPublicId(entry),
199
+ )});\n`;
200
+
201
+ let entryExports = entry.symbols.get('*')?.local;
202
+
203
+ if (
204
+ entryExports &&
205
+ entry === mainEntry &&
206
+ this.exportedSymbols.has(entryExports)
207
+ ) {
208
+ invariant(
209
+ !needsBundleQueue,
210
+ 'Entry exports are not yet compaitble with async bundles',
211
+ );
212
+ res += `\nvar ${entryExports} = ${atlaspackRequire}`;
213
+ } else {
214
+ if (needsBundleQueue) {
215
+ atlaspackRequire = this.runWhenReady(this.bundle, atlaspackRequire);
216
+ }
217
+
218
+ res += `\n${atlaspackRequire}`;
219
+ }
220
+
221
+ lineCount += 2;
222
+ }
223
+ }
224
+
225
+ let [postlude, postludeLines] = this.outputFormat.buildBundlePostlude();
226
+ res += postlude;
227
+ lineCount += postludeLines;
228
+
229
+ // The entry asset of a script bundle gets hoisted outside the bundle wrapper so that
230
+ // its top-level variables become globals like a real browser script. We need to replace
231
+ // all dependency references for runtimes with a atlaspackRequire call.
232
+ if (
233
+ this.bundle.env.outputFormat === 'global' &&
234
+ this.bundle.env.sourceType === 'script'
235
+ ) {
236
+ res += '\n';
237
+ lineCount++;
238
+
239
+ let mainEntry = nullthrows(this.bundle.getMainEntry());
240
+ let {code, map: mapBuffer} = nullthrows(
241
+ this.assetOutputs.get(mainEntry.id),
242
+ );
243
+ let map;
244
+ if (mapBuffer) {
245
+ map = new SourceMap(this.options.projectRoot, mapBuffer);
246
+ }
247
+ res += replaceScriptDependencies(
248
+ this.bundleGraph,
249
+ this.bundle,
250
+ code,
251
+ map,
252
+ this.atlaspackRequireName,
253
+ );
254
+ if (sourceMap && map) {
255
+ sourceMap.addSourceMap(map, lineCount);
256
+ }
257
+ }
258
+
259
+ return {
260
+ contents: res,
261
+ map: sourceMap,
262
+ };
263
+ }
264
+
265
+ shouldBundleQueue(bundle: NamedBundle): boolean {
266
+ let referencingBundles = this.bundleGraph.getReferencingBundles(bundle);
267
+ let hasHtmlReference = referencingBundles.some(b => b.type === 'html');
268
+
269
+ return (
270
+ this.useAsyncBundleRuntime &&
271
+ bundle.type === 'js' &&
272
+ bundle.bundleBehavior !== 'inline' &&
273
+ bundle.env.outputFormat === 'esmodule' &&
274
+ !bundle.env.isIsolated() &&
275
+ bundle.bundleBehavior !== 'isolated' &&
276
+ hasHtmlReference
277
+ );
278
+ }
279
+
280
+ runWhenReady(bundle: NamedBundle, codeToRun: string): string {
281
+ let deps = this.bundleGraph
282
+ .getReferencedBundles(bundle)
283
+ .filter(b => this.shouldBundleQueue(b))
284
+ .map(b => b.publicId);
285
+
286
+ if (deps.length === 0) {
287
+ // If no deps we can safely execute immediately
288
+ return codeToRun;
289
+ }
290
+
291
+ let params = [
292
+ JSON.stringify(this.bundle.publicId),
293
+ fnExpr(this.bundle.env, [], [codeToRun]),
294
+ JSON.stringify(deps),
295
+ ];
296
+
297
+ return `$atlaspack$global.rwr(${params.join(', ')});`;
298
+ }
299
+
300
+ async loadAssets(): Promise<Array<Asset>> {
301
+ let queue = new PromiseQueue({maxConcurrent: 32});
302
+ let wrapped = [];
303
+ this.bundle.traverseAssets(asset => {
304
+ queue.add(async () => {
305
+ let [code, map] = await Promise.all([
306
+ asset.getCode(),
307
+ this.bundle.env.sourceMap ? asset.getMapBuffer() : null,
308
+ ]);
309
+ return [asset.id, {code, map}];
310
+ });
311
+
312
+ if (
313
+ asset.meta.shouldWrap ||
314
+ this.bundle.env.sourceType === 'script' ||
315
+ this.bundleGraph.isAssetReferenced(this.bundle, asset) ||
316
+ this.bundleGraph
317
+ .getIncomingDependencies(asset)
318
+ .some(dep => dep.meta.shouldWrap && dep.specifierType !== 'url')
319
+ ) {
320
+ // Don't wrap constant "entry" modules _except_ if they are referenced by any lazy dependency
321
+ if (
322
+ !asset.meta.isConstantModule ||
323
+ this.bundleGraph
324
+ .getIncomingDependencies(asset)
325
+ .some(dep => dep.priority === 'lazy')
326
+ ) {
327
+ this.wrappedAssets.add(asset.id);
328
+ wrapped.push(asset);
329
+ }
330
+ }
331
+ });
332
+
333
+ for (let wrappedAssetRoot of [...wrapped]) {
334
+ this.bundle.traverseAssets((asset, _, actions) => {
335
+ if (asset === wrappedAssetRoot) {
336
+ return;
337
+ }
338
+
339
+ if (this.wrappedAssets.has(asset.id)) {
340
+ actions.skipChildren();
341
+ return;
342
+ }
343
+ if (!asset.meta.isConstantModule) {
344
+ this.wrappedAssets.add(asset.id);
345
+ wrapped.push(asset);
346
+ }
347
+ }, wrappedAssetRoot);
348
+ }
349
+
350
+ this.assetOutputs = new Map(await queue.run());
351
+ return wrapped;
352
+ }
353
+
354
+ buildExportedSymbols() {
355
+ if (
356
+ !this.bundle.env.isLibrary ||
357
+ this.bundle.env.outputFormat !== 'esmodule'
358
+ ) {
359
+ return;
360
+ }
361
+
362
+ // TODO: handle ESM exports of wrapped entry assets...
363
+ let entry = this.bundle.getMainEntry();
364
+ if (entry && !this.wrappedAssets.has(entry.id)) {
365
+ let hasNamespace = entry.symbols.hasExportSymbol('*');
366
+
367
+ for (let {
368
+ asset,
369
+ exportAs,
370
+ symbol,
371
+ exportSymbol,
372
+ } of this.bundleGraph.getExportedSymbols(entry)) {
373
+ if (typeof symbol === 'string') {
374
+ // If the module has a namespace (e.g. commonjs), and this is not an entry, only export the namespace
375
+ // as default, without individual exports. This mirrors the importing logic in addExternal, avoiding
376
+ // extra unused exports and potential for non-identifier export names.
377
+ if (hasNamespace && this.isAsyncBundle && exportAs !== '*') {
378
+ continue;
379
+ }
380
+
381
+ let symbols = this.exportedSymbols.get(
382
+ symbol === '*' ? nullthrows(entry.symbols.get('*')?.local) : symbol,
383
+ )?.exportAs;
384
+
385
+ if (!symbols) {
386
+ symbols = [];
387
+ this.exportedSymbols.set(symbol, {
388
+ asset,
389
+ exportSymbol,
390
+ local: symbol,
391
+ exportAs: symbols,
392
+ });
393
+ }
394
+
395
+ if (exportAs === '*') {
396
+ exportAs = 'default';
397
+ }
398
+
399
+ symbols.push(exportAs);
400
+ } else if (symbol === null) {
401
+ // TODO `meta.exportsIdentifier[exportSymbol]` should be exported
402
+ // let relativePath = relative(options.projectRoot, asset.filePath);
403
+ // throw getThrowableDiagnosticForNode(
404
+ // md`${relativePath} couldn't be statically analyzed when importing '${exportSymbol}'`,
405
+ // entry.filePath,
406
+ // loc,
407
+ // );
408
+ } else if (symbol !== false) {
409
+ // let relativePath = relative(options.projectRoot, asset.filePath);
410
+ // throw getThrowableDiagnosticForNode(
411
+ // md`${relativePath} does not export '${exportSymbol}'`,
412
+ // entry.filePath,
413
+ // loc,
414
+ // );
415
+ }
416
+ }
417
+ }
418
+ }
419
+
420
+ getTopLevelName(name: string): string {
421
+ name = makeValidIdentifier(name);
422
+ if (this.globalNames.has(name)) {
423
+ name = '_' + name;
424
+ }
425
+
426
+ let count = this.topLevelNames.get(name);
427
+ if (count == null) {
428
+ this.topLevelNames.set(name, 1);
429
+ return name;
430
+ }
431
+
432
+ this.topLevelNames.set(name, count + 1);
433
+ return name + count;
434
+ }
435
+
436
+ getPropertyAccess(obj: string, property: string): string {
437
+ if (isValidIdentifier(property)) {
438
+ return `${obj}.${property}`;
439
+ }
440
+
441
+ return `${obj}[${JSON.stringify(property)}]`;
442
+ }
443
+
444
+ visitAsset(asset: Asset): [string, ?SourceMap, number] {
445
+ invariant(!this.seenAssets.has(asset.id), 'Already visited asset');
446
+ this.seenAssets.add(asset.id);
447
+
448
+ let {code, map} = nullthrows(this.assetOutputs.get(asset.id));
449
+ return this.buildAsset(asset, code, map);
450
+ }
451
+
452
+ buildAsset(
453
+ asset: Asset,
454
+ code: string,
455
+ map: ?Buffer,
456
+ ): [string, ?SourceMap, number] {
457
+ let shouldWrap = this.wrappedAssets.has(asset.id);
458
+ let deps = this.bundleGraph.getDependencies(asset);
459
+
460
+ let sourceMap =
461
+ this.bundle.env.sourceMap && map
462
+ ? new SourceMap(this.options.projectRoot, map)
463
+ : null;
464
+
465
+ // If this asset is skipped, just add dependencies and not the asset's content.
466
+ if (this.shouldSkipAsset(asset)) {
467
+ let depCode = '';
468
+ let lineCount = 0;
469
+ for (let dep of deps) {
470
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
471
+ let skipped = this.bundleGraph.isDependencySkipped(dep);
472
+ if (skipped) {
473
+ continue;
474
+ }
475
+
476
+ if (!resolved) {
477
+ if (!dep.isOptional) {
478
+ this.addExternal(dep);
479
+ }
480
+
481
+ continue;
482
+ }
483
+
484
+ if (
485
+ this.bundle.hasAsset(resolved) &&
486
+ !this.seenAssets.has(resolved.id)
487
+ ) {
488
+ let [code, map, lines] = this.visitAsset(resolved);
489
+ depCode += code + '\n';
490
+ if (sourceMap && map) {
491
+ sourceMap.addSourceMap(map, lineCount);
492
+ }
493
+ lineCount += lines + 1;
494
+ }
495
+ }
496
+
497
+ return [depCode, sourceMap, lineCount];
498
+ }
499
+
500
+ // TODO: maybe a meta prop?
501
+ if (code.includes('$atlaspack$global')) {
502
+ this.usedHelpers.add('$atlaspack$global');
503
+ }
504
+
505
+ if (this.bundle.env.isNode() && asset.meta.has_node_replacements) {
506
+ const relPath = normalizeSeparators(
507
+ path.relative(this.bundle.target.distDir, path.dirname(asset.filePath)),
508
+ );
509
+ code = code.replace('$atlaspack$dirnameReplace', relPath);
510
+ code = code.replace('$atlaspack$filenameReplace', relPath);
511
+ }
512
+
513
+ let [depMap, replacements] = this.buildReplacements(asset, deps);
514
+ let [prepend, prependLines, append] = this.buildAssetPrelude(
515
+ asset,
516
+ deps,
517
+ replacements,
518
+ );
519
+ if (prependLines > 0) {
520
+ sourceMap?.offsetLines(1, prependLines);
521
+ code = prepend + code;
522
+ }
523
+
524
+ code += append;
525
+
526
+ let lineCount = 0;
527
+ let depContent = [];
528
+ if (depMap.size === 0 && replacements.size === 0) {
529
+ // If there are no dependencies or replacements, use a simple function to count the number of lines.
530
+ lineCount = countLines(code) - 1;
531
+ } else {
532
+ // Otherwise, use a regular expression to perform replacements.
533
+ // We need to track how many newlines there are for source maps, replace
534
+ // all import statements with dependency code, and perform inline replacements
535
+ // of all imported symbols with their resolved export symbols. This is all done
536
+ // in a single regex so that we only do one pass over the whole code.
537
+ let offset = 0;
538
+ let columnStartIndex = 0;
539
+ code = code.replace(REPLACEMENT_RE, (m, d, i) => {
540
+ if (m === '\n') {
541
+ columnStartIndex = i + offset + 1;
542
+ lineCount++;
543
+ return '\n';
544
+ }
545
+
546
+ // If we matched an import, replace with the source code for the dependency.
547
+ if (d != null) {
548
+ let deps = depMap.get(d);
549
+ if (!deps) {
550
+ return m;
551
+ }
552
+
553
+ let replacement = '';
554
+
555
+ // A single `${id}:${specifier}:esm` might have been resolved to multiple assets due to
556
+ // reexports.
557
+ for (let dep of deps) {
558
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
559
+ let skipped = this.bundleGraph.isDependencySkipped(dep);
560
+ if (resolved && !skipped) {
561
+ // Hoist variable declarations for the referenced atlaspackRequire dependencies
562
+ // after the dependency is declared. This handles the case where the resulting asset
563
+ // is wrapped, but the dependency in this asset is not marked as wrapped. This means
564
+ // that it was imported/required at the top-level, so its side effects should run immediately.
565
+ let [res, lines] = this.getHoistedAtlaspackRequires(
566
+ asset,
567
+ dep,
568
+ resolved,
569
+ );
570
+ let map;
571
+ if (
572
+ this.bundle.hasAsset(resolved) &&
573
+ !this.seenAssets.has(resolved.id)
574
+ ) {
575
+ // If this asset is wrapped, we need to hoist the code for the dependency
576
+ // outside our atlaspackRequire.register wrapper. This is safe because all
577
+ // assets referenced by this asset will also be wrapped. Otherwise, inline the
578
+ // asset content where the import statement was.
579
+ if (shouldWrap) {
580
+ depContent.push(this.visitAsset(resolved));
581
+ } else {
582
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
583
+ res = depCode + '\n' + res;
584
+ lines += 1 + depLines;
585
+ map = depMap;
586
+ }
587
+ }
588
+
589
+ // Push this asset's source mappings down by the number of lines in the dependency
590
+ // plus the number of hoisted atlaspackRequires. Then insert the source map for the dependency.
591
+ if (sourceMap) {
592
+ if (lines > 0) {
593
+ sourceMap.offsetLines(lineCount + 1, lines);
594
+ }
595
+
596
+ if (map) {
597
+ sourceMap.addSourceMap(map, lineCount);
598
+ }
599
+ }
600
+
601
+ replacement += res;
602
+ lineCount += lines;
603
+ }
604
+ }
605
+ return replacement;
606
+ }
607
+
608
+ // If it wasn't a dependency, then it was an inline replacement (e.g. $id$import$foo -> $id$export$foo).
609
+ let replacement = replacements.get(m) ?? m;
610
+ if (sourceMap) {
611
+ // Offset the source map columns for this line if the replacement was a different length.
612
+ // This assumes that the match and replacement both do not contain any newlines.
613
+ let lengthDifference = replacement.length - m.length;
614
+ if (lengthDifference !== 0) {
615
+ sourceMap.offsetColumns(
616
+ lineCount + 1,
617
+ i + offset - columnStartIndex + m.length,
618
+ lengthDifference,
619
+ );
620
+ offset += lengthDifference;
621
+ }
622
+ }
623
+ return replacement;
624
+ });
625
+ }
626
+
627
+ // If the asset is wrapped, we need to insert the dependency code outside the atlaspackRequire.register
628
+ // wrapper. Dependencies must be inserted AFTER the asset is registered so that circular dependencies work.
629
+ if (shouldWrap) {
630
+ // Offset by one line for the atlaspackRequire.register wrapper.
631
+ sourceMap?.offsetLines(1, 1);
632
+ lineCount++;
633
+
634
+ code = `atlaspackRegister(${JSON.stringify(
635
+ this.bundleGraph.getAssetPublicId(asset),
636
+ )}, function(module, exports) {
637
+ ${code}
638
+ });
639
+ `;
640
+
641
+ lineCount += 2;
642
+
643
+ for (let [depCode, map, lines] of depContent) {
644
+ if (!depCode) continue;
645
+ code += depCode + '\n';
646
+ if (sourceMap && map) {
647
+ sourceMap.addSourceMap(map, lineCount);
648
+ }
649
+ lineCount += lines + 1;
650
+ }
651
+
652
+ this.needsPrelude = true;
653
+ }
654
+
655
+ if (
656
+ !shouldWrap &&
657
+ this.shouldBundleQueue(this.bundle) &&
658
+ this.bundle.getEntryAssets().some(entry => entry.id === asset.id)
659
+ ) {
660
+ code = this.runWhenReady(this.bundle, code);
661
+ }
662
+
663
+ return [code, sourceMap, lineCount];
664
+ }
665
+
666
+ buildReplacements(
667
+ asset: Asset,
668
+ deps: Array<Dependency>,
669
+ ): [Map<string, Array<Dependency>>, Map<string, string>] {
670
+ let assetId = asset.meta.id;
671
+ invariant(typeof assetId === 'string');
672
+
673
+ // Build two maps: one of import specifiers, and one of imported symbols to replace.
674
+ // These will be used to build a regex below.
675
+ let depMap = new DefaultMap<string, Array<Dependency>>(() => []);
676
+ let replacements = new Map();
677
+ for (let dep of deps) {
678
+ let specifierType =
679
+ dep.specifierType === 'esm' ? `:${dep.specifierType}` : '';
680
+ depMap
681
+ .get(
682
+ `${assetId}:${getSpecifier(dep)}${
683
+ !dep.meta.placeholder ? specifierType : ''
684
+ }`,
685
+ )
686
+ .push(dep);
687
+
688
+ let asyncResolution = this.bundleGraph.resolveAsyncDependency(
689
+ dep,
690
+ this.bundle,
691
+ );
692
+ let resolved =
693
+ asyncResolution?.type === 'asset'
694
+ ? // Prefer the underlying asset over a runtime to load it. It will
695
+ // be wrapped in Promise.resolve() later.
696
+ asyncResolution.value
697
+ : this.bundleGraph.getResolvedAsset(dep, this.bundle);
698
+ if (
699
+ !resolved &&
700
+ !dep.isOptional &&
701
+ !this.bundleGraph.isDependencySkipped(dep)
702
+ ) {
703
+ this.addExternal(dep, replacements);
704
+ }
705
+
706
+ if (!resolved) {
707
+ continue;
708
+ }
709
+
710
+ // Handle imports from other bundles in libraries.
711
+ if (this.bundle.env.isLibrary && !this.bundle.hasAsset(resolved)) {
712
+ let referencedBundle = this.bundleGraph.getReferencedBundle(
713
+ dep,
714
+ this.bundle,
715
+ );
716
+ if (
717
+ referencedBundle &&
718
+ referencedBundle.getMainEntry() === resolved &&
719
+ referencedBundle.type === 'js' &&
720
+ !this.bundleGraph.isAssetReferenced(referencedBundle, resolved)
721
+ ) {
722
+ this.addExternal(dep, replacements, referencedBundle);
723
+ this.externalAssets.add(resolved);
724
+ continue;
725
+ }
726
+ }
727
+
728
+ for (let [imported, {local}] of dep.symbols) {
729
+ if (local === '*') {
730
+ continue;
731
+ }
732
+
733
+ let symbol = this.getSymbolResolution(asset, resolved, imported, dep);
734
+ replacements.set(
735
+ local,
736
+ // If this was an internalized async asset, wrap in a Promise.resolve.
737
+ asyncResolution?.type === 'asset'
738
+ ? `Promise.resolve(${symbol})`
739
+ : symbol,
740
+ );
741
+ }
742
+
743
+ // Async dependencies need a namespace object even if all used symbols were statically analyzed.
744
+ // This is recorded in the promiseSymbol meta property set by the transformer rather than in
745
+ // symbols so that we don't mark all symbols as used.
746
+ if (dep.priority === 'lazy' && dep.meta.promiseSymbol) {
747
+ let promiseSymbol = dep.meta.promiseSymbol;
748
+ invariant(typeof promiseSymbol === 'string');
749
+ let symbol = this.getSymbolResolution(asset, resolved, '*', dep);
750
+ replacements.set(
751
+ promiseSymbol,
752
+ asyncResolution?.type === 'asset'
753
+ ? `Promise.resolve(${symbol})`
754
+ : symbol,
755
+ );
756
+ }
757
+ }
758
+
759
+ // If this asset is wrapped, we need to replace the exports namespace with `module.exports`,
760
+ // which will be provided to us by the wrapper.
761
+ if (
762
+ this.wrappedAssets.has(asset.id) ||
763
+ (this.bundle.env.outputFormat === 'commonjs' &&
764
+ asset === this.bundle.getMainEntry())
765
+ ) {
766
+ let exportsName = asset.symbols.get('*')?.local || `$${assetId}$exports`;
767
+ replacements.set(exportsName, 'module.exports');
768
+ }
769
+
770
+ return [depMap, replacements];
771
+ }
772
+
773
+ addExternal(
774
+ dep: Dependency,
775
+ replacements?: Map<string, string>,
776
+ referencedBundle?: NamedBundle,
777
+ ) {
778
+ if (this.bundle.env.outputFormat === 'global') {
779
+ throw new ThrowableDiagnostic({
780
+ diagnostic: {
781
+ message:
782
+ 'External modules are not supported when building for browser',
783
+ codeFrames: [
784
+ {
785
+ filePath: nullthrows(dep.sourcePath),
786
+ codeHighlights: dep.loc
787
+ ? [convertSourceLocationToHighlight(dep.loc)]
788
+ : [],
789
+ },
790
+ ],
791
+ },
792
+ });
793
+ }
794
+
795
+ let specifier = dep.specifier;
796
+ if (referencedBundle) {
797
+ specifier = relativeBundlePath(this.bundle, referencedBundle);
798
+ }
799
+
800
+ // Map of DependencySpecifier -> Map<ExportedSymbol, Identifier>>
801
+ let external = this.externals.get(specifier);
802
+ if (!external) {
803
+ external = new Map();
804
+ this.externals.set(specifier, external);
805
+ }
806
+
807
+ for (let [imported, {local}] of dep.symbols) {
808
+ // If already imported, just add the already renamed variable to the mapping.
809
+ let renamed = external.get(imported);
810
+ if (renamed && local !== '*' && replacements) {
811
+ replacements.set(local, renamed);
812
+ continue;
813
+ }
814
+
815
+ // For CJS output, always use a property lookup so that exports remain live.
816
+ // For ESM output, use named imports which are always live.
817
+ if (this.bundle.env.outputFormat === 'commonjs') {
818
+ renamed = external.get('*');
819
+ if (!renamed) {
820
+ if (referencedBundle) {
821
+ let entry = nullthrows(referencedBundle.getMainEntry());
822
+ renamed =
823
+ entry.symbols.get('*')?.local ??
824
+ `$${String(entry.meta.id)}$exports`;
825
+ } else {
826
+ renamed = this.getTopLevelName(
827
+ `$${this.bundle.publicId}$${specifier}`,
828
+ );
829
+ }
830
+
831
+ external.set('*', renamed);
832
+ }
833
+
834
+ if (local !== '*' && replacements) {
835
+ let replacement;
836
+ if (imported === '*') {
837
+ replacement = renamed;
838
+ } else if (imported === 'default') {
839
+ let needsDefaultInterop = true;
840
+ if (referencedBundle) {
841
+ let entry = nullthrows(referencedBundle.getMainEntry());
842
+ needsDefaultInterop = this.needsDefaultInterop(entry);
843
+ }
844
+ if (needsDefaultInterop) {
845
+ replacement = `($atlaspack$interopDefault(${renamed}))`;
846
+ this.usedHelpers.add('$atlaspack$interopDefault');
847
+ } else {
848
+ replacement = `${renamed}.default`;
849
+ }
850
+ } else {
851
+ replacement = this.getPropertyAccess(renamed, imported);
852
+ }
853
+
854
+ replacements.set(local, replacement);
855
+ }
856
+ } else {
857
+ let property;
858
+ if (referencedBundle) {
859
+ let entry = nullthrows(referencedBundle.getMainEntry());
860
+ if (entry.symbols.hasExportSymbol('*')) {
861
+ // If importing * and the referenced module has a * export (e.g. CJS), use default instead.
862
+ // This mirrors the logic in buildExportedSymbols.
863
+ property = imported;
864
+ imported =
865
+ referencedBundle?.env.outputFormat === 'esmodule'
866
+ ? 'default'
867
+ : '*';
868
+ } else {
869
+ if (imported === '*') {
870
+ let exportedSymbols = this.bundleGraph.getExportedSymbols(entry);
871
+ if (local === '*') {
872
+ // Re-export all symbols.
873
+ for (let exported of exportedSymbols) {
874
+ if (exported.symbol) {
875
+ external.set(exported.exportSymbol, exported.symbol);
876
+ }
877
+ }
878
+ continue;
879
+ }
880
+ }
881
+ renamed = this.bundleGraph.getSymbolResolution(
882
+ entry,
883
+ imported,
884
+ this.bundle,
885
+ ).symbol;
886
+ }
887
+ }
888
+
889
+ // Rename the specifier so that multiple local imports of the same imported specifier
890
+ // are deduplicated. We have to prefix the imported name with the bundle id so that
891
+ // local variables do not shadow it.
892
+ if (!renamed) {
893
+ if (this.exportedSymbols.has(local)) {
894
+ renamed = local;
895
+ } else if (imported === 'default' || imported === '*') {
896
+ renamed = this.getTopLevelName(
897
+ `$${this.bundle.publicId}$${specifier}`,
898
+ );
899
+ } else {
900
+ renamed = this.getTopLevelName(
901
+ `$${this.bundle.publicId}$${imported}`,
902
+ );
903
+ }
904
+ }
905
+
906
+ external.set(imported, renamed);
907
+ if (local !== '*' && replacements) {
908
+ let replacement = renamed;
909
+ if (property === '*') {
910
+ replacement = renamed;
911
+ } else if (property === 'default') {
912
+ replacement = `($atlaspack$interopDefault(${renamed}))`;
913
+ this.usedHelpers.add('$atlaspack$interopDefault');
914
+ } else if (property) {
915
+ replacement = this.getPropertyAccess(renamed, property);
916
+ }
917
+ replacements.set(local, replacement);
918
+ }
919
+ }
920
+ }
921
+ }
922
+
923
+ isWrapped(resolved: Asset, parentAsset: Asset): boolean {
924
+ if (resolved.meta.isConstantModule) {
925
+ if (!this.bundle.hasAsset(resolved)) {
926
+ throw new AssertionError({
927
+ message: `Constant module ${path.relative(
928
+ this.options.projectRoot,
929
+ resolved.filePath,
930
+ )} referenced from ${path.relative(
931
+ this.options.projectRoot,
932
+ parentAsset.filePath,
933
+ )} not found in bundle ${this.bundle.name}`,
934
+ });
935
+ }
936
+ return false;
937
+ }
938
+ return (
939
+ (!this.bundle.hasAsset(resolved) && !this.externalAssets.has(resolved)) ||
940
+ (this.wrappedAssets.has(resolved.id) && resolved !== parentAsset)
941
+ );
942
+ }
943
+
944
+ getSymbolResolution(
945
+ parentAsset: Asset,
946
+ resolved: Asset,
947
+ imported: string,
948
+ dep?: Dependency,
949
+ replacements?: Map<string, string>,
950
+ ): string {
951
+ let {
952
+ asset: resolvedAsset,
953
+ exportSymbol,
954
+ symbol,
955
+ } = this.bundleGraph.getSymbolResolution(resolved, imported, this.bundle);
956
+
957
+ if (
958
+ resolvedAsset.type !== 'js' ||
959
+ (dep && this.bundleGraph.isDependencySkipped(dep))
960
+ ) {
961
+ // Graceful fallback for non-js imports or when trying to resolve a symbol
962
+ // that is actually unused but we still need a placeholder value.
963
+ return '{}';
964
+ }
965
+
966
+ let isWrapped = this.isWrapped(resolvedAsset, parentAsset);
967
+ let staticExports = resolvedAsset.meta.staticExports !== false;
968
+ let publicId = this.bundleGraph.getAssetPublicId(resolvedAsset);
969
+
970
+ // External CommonJS dependencies need to be accessed as an object property rather than imported
971
+ // directly to maintain live binding.
972
+ let isExternalCommonJS =
973
+ !isWrapped &&
974
+ this.bundle.env.isLibrary &&
975
+ this.bundle.env.outputFormat === 'commonjs' &&
976
+ !this.bundle.hasAsset(resolvedAsset);
977
+
978
+ // If the resolved asset is wrapped, but imported at the top-level by this asset,
979
+ // then we hoist atlaspackRequire calls to the top of this asset so side effects run immediately.
980
+ if (
981
+ isWrapped &&
982
+ dep &&
983
+ !dep?.meta.shouldWrap &&
984
+ symbol !== false &&
985
+ // Only do this if the asset is part of a different bundle (so it was definitely
986
+ // atlaspackRequire.register'ed there), or if it is indeed registered in this bundle.
987
+ (!this.bundle.hasAsset(resolvedAsset) ||
988
+ !this.shouldSkipAsset(resolvedAsset))
989
+ ) {
990
+ let hoisted = this.hoistedRequires.get(dep.id);
991
+ if (!hoisted) {
992
+ hoisted = new Map();
993
+ this.hoistedRequires.set(dep.id, hoisted);
994
+ }
995
+
996
+ hoisted.set(
997
+ resolvedAsset.id,
998
+ `var $${publicId} = atlaspackRequire(${JSON.stringify(publicId)});`,
999
+ );
1000
+ }
1001
+
1002
+ if (isWrapped) {
1003
+ this.needsPrelude = true;
1004
+ }
1005
+
1006
+ // If this is an ESM default import of a CJS module with a `default` symbol,
1007
+ // and no __esModule flag, we need to resolve to the namespace instead.
1008
+ let isDefaultInterop =
1009
+ exportSymbol === 'default' &&
1010
+ staticExports &&
1011
+ !isWrapped &&
1012
+ (dep?.meta.kind === 'Import' || dep?.meta.kind === 'Export') &&
1013
+ resolvedAsset.symbols.hasExportSymbol('*') &&
1014
+ resolvedAsset.symbols.hasExportSymbol('default') &&
1015
+ !resolvedAsset.symbols.hasExportSymbol('__esModule');
1016
+
1017
+ // Find the namespace object for the resolved module. If wrapped and this
1018
+ // is an inline require (not top-level), use a atlaspackRequire call, otherwise
1019
+ // the hoisted variable declared above. Otherwise, if not wrapped, use the
1020
+ // namespace export symbol.
1021
+ let assetId = resolvedAsset.meta.id;
1022
+ invariant(typeof assetId === 'string');
1023
+ let obj;
1024
+ if (isWrapped && (!dep || dep?.meta.shouldWrap)) {
1025
+ // Wrap in extra parenthesis to not change semantics, e.g.`new (atlaspackRequire("..."))()`.
1026
+ obj = `(atlaspackRequire(${JSON.stringify(publicId)}))`;
1027
+ } else if (isWrapped && dep) {
1028
+ obj = `$${publicId}`;
1029
+ } else {
1030
+ obj = resolvedAsset.symbols.get('*')?.local || `$${assetId}$exports`;
1031
+ obj = replacements?.get(obj) || obj;
1032
+ }
1033
+
1034
+ if (imported === '*' || exportSymbol === '*' || isDefaultInterop) {
1035
+ // Resolve to the namespace object if requested or this is a CJS default interop reqiure.
1036
+ if (
1037
+ parentAsset === resolvedAsset &&
1038
+ this.wrappedAssets.has(resolvedAsset.id)
1039
+ ) {
1040
+ // Directly use module.exports for wrapped assets importing themselves.
1041
+ return 'module.exports';
1042
+ } else {
1043
+ return obj;
1044
+ }
1045
+ } else if (
1046
+ (!staticExports || isWrapped || !symbol || isExternalCommonJS) &&
1047
+ resolvedAsset !== parentAsset
1048
+ ) {
1049
+ // If the resolved asset is wrapped or has non-static exports,
1050
+ // we need to use a member access off the namespace object rather
1051
+ // than a direct reference. If importing default from a CJS module,
1052
+ // use a helper to check the __esModule flag at runtime.
1053
+ let kind = dep?.meta.kind;
1054
+ if (
1055
+ (!dep || kind === 'Import' || kind === 'Export') &&
1056
+ exportSymbol === 'default' &&
1057
+ resolvedAsset.symbols.hasExportSymbol('*') &&
1058
+ this.needsDefaultInterop(resolvedAsset)
1059
+ ) {
1060
+ this.usedHelpers.add('$atlaspack$interopDefault');
1061
+ return `(/*@__PURE__*/$atlaspack$interopDefault(${obj}))`;
1062
+ } else {
1063
+ return this.getPropertyAccess(obj, exportSymbol);
1064
+ }
1065
+ } else if (!symbol) {
1066
+ invariant(false, 'Asset was skipped or not found.');
1067
+ } else {
1068
+ return replacements?.get(symbol) || symbol;
1069
+ }
1070
+ }
1071
+
1072
+ getHoistedAtlaspackRequires(
1073
+ parentAsset: Asset,
1074
+ dep: Dependency,
1075
+ resolved: Asset,
1076
+ ): [string, number] {
1077
+ if (resolved.type !== 'js') {
1078
+ return ['', 0];
1079
+ }
1080
+
1081
+ let hoisted = this.hoistedRequires.get(dep.id);
1082
+ let res = '';
1083
+ let lineCount = 0;
1084
+ let isWrapped = this.isWrapped(resolved, parentAsset);
1085
+
1086
+ // If the resolved asset is wrapped and is imported in the top-level by this asset,
1087
+ // we need to run side effects when this asset runs. If the resolved asset is not
1088
+ // the first one in the hoisted requires, we need to insert a atlaspackRequire here
1089
+ // so it runs first.
1090
+ if (
1091
+ isWrapped &&
1092
+ !dep.meta.shouldWrap &&
1093
+ (!hoisted || hoisted.keys().next().value !== resolved.id) &&
1094
+ !this.bundleGraph.isDependencySkipped(dep) &&
1095
+ !this.shouldSkipAsset(resolved)
1096
+ ) {
1097
+ this.needsPrelude = true;
1098
+ res += `atlaspackRequire(${JSON.stringify(
1099
+ this.bundleGraph.getAssetPublicId(resolved),
1100
+ )});`;
1101
+ }
1102
+
1103
+ if (hoisted) {
1104
+ this.needsPrelude = true;
1105
+ res += '\n' + [...hoisted.values()].join('\n');
1106
+ lineCount += hoisted.size;
1107
+ }
1108
+
1109
+ return [res, lineCount];
1110
+ }
1111
+
1112
+ buildAssetPrelude(
1113
+ asset: Asset,
1114
+ deps: Array<Dependency>,
1115
+ replacements: Map<string, string>,
1116
+ ): [string, number, string] {
1117
+ let prepend = '';
1118
+ let prependLineCount = 0;
1119
+ let append = '';
1120
+
1121
+ let shouldWrap = this.wrappedAssets.has(asset.id);
1122
+ let usedSymbols = nullthrows(this.bundleGraph.getUsedSymbols(asset));
1123
+ let assetId = asset.meta.id;
1124
+ invariant(typeof assetId === 'string');
1125
+
1126
+ // If the asset has a namespace export symbol, it is CommonJS.
1127
+ // If there's no __esModule flag, and default is a used symbol, we need
1128
+ // to insert an interop helper.
1129
+ let defaultInterop =
1130
+ asset.symbols.hasExportSymbol('*') &&
1131
+ usedSymbols.has('default') &&
1132
+ !asset.symbols.hasExportSymbol('__esModule');
1133
+
1134
+ let usedNamespace =
1135
+ // If the asset has * in its used symbols, we might need the exports namespace.
1136
+ // The one case where this isn't true is in ESM library entries, where the only
1137
+ // dependency on * is the entry dependency. In this case, we will use ESM exports
1138
+ // instead of the namespace object.
1139
+ (usedSymbols.has('*') &&
1140
+ (this.bundle.env.outputFormat !== 'esmodule' ||
1141
+ !this.bundle.env.isLibrary ||
1142
+ asset !== this.bundle.getMainEntry() ||
1143
+ this.bundleGraph
1144
+ .getIncomingDependencies(asset)
1145
+ .some(
1146
+ dep =>
1147
+ !dep.isEntry &&
1148
+ this.bundle.hasDependency(dep) &&
1149
+ nullthrows(this.bundleGraph.getUsedSymbols(dep)).has('*'),
1150
+ ))) ||
1151
+ // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
1152
+ // we fallback on the namespace object.
1153
+ (asset.symbols.hasExportSymbol('*') &&
1154
+ [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s))) ||
1155
+ // If the exports has this asset's namespace (e.g. ESM output from CJS input),
1156
+ // include the namespace object for the default export.
1157
+ this.exportedSymbols.has(`$${assetId}$exports`) ||
1158
+ // CommonJS library bundle entries always need a namespace.
1159
+ (this.bundle.env.isLibrary &&
1160
+ this.bundle.env.outputFormat === 'commonjs' &&
1161
+ asset === this.bundle.getMainEntry());
1162
+
1163
+ // If the asset doesn't have static exports, should wrap, the namespace is used,
1164
+ // or we need default interop, then we need to synthesize a namespace object for
1165
+ // this asset.
1166
+ if (
1167
+ asset.meta.staticExports === false ||
1168
+ shouldWrap ||
1169
+ usedNamespace ||
1170
+ defaultInterop
1171
+ ) {
1172
+ // Insert a declaration for the exports namespace object. If the asset is wrapped
1173
+ // we don't need to do this, because we'll use the `module.exports` object provided
1174
+ // by the wrapper instead. This is also true of CommonJS entry assets, which will use
1175
+ // the `module.exports` object provided by CJS.
1176
+ if (
1177
+ !shouldWrap &&
1178
+ (this.bundle.env.outputFormat !== 'commonjs' ||
1179
+ asset !== this.bundle.getMainEntry())
1180
+ ) {
1181
+ prepend += `var $${assetId}$exports = {};\n`;
1182
+ prependLineCount++;
1183
+ }
1184
+
1185
+ // Insert the __esModule interop flag for this module if it has a `default` export
1186
+ // and the namespace symbol is used.
1187
+ // TODO: only if required by CJS?
1188
+ if (asset.symbols.hasExportSymbol('default') && usedSymbols.has('*')) {
1189
+ prepend += `\n$atlaspack$defineInteropFlag($${assetId}$exports);\n`;
1190
+ prependLineCount += 2;
1191
+ this.usedHelpers.add('$atlaspack$defineInteropFlag');
1192
+ }
1193
+
1194
+ // Find wildcard re-export dependencies, and make sure their exports are also included in
1195
+ // ours. Importantly, add them before the asset's own exports so that wildcard exports get
1196
+ // correctly overwritten by own exports of the same name.
1197
+ for (let dep of deps) {
1198
+ let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
1199
+ if (dep.isOptional || this.bundleGraph.isDependencySkipped(dep)) {
1200
+ continue;
1201
+ }
1202
+
1203
+ let isWrapped = resolved && resolved.meta.shouldWrap;
1204
+
1205
+ for (let [imported, {local}] of dep.symbols) {
1206
+ if (imported === '*' && local === '*') {
1207
+ if (!resolved) {
1208
+ // Re-exporting an external module. This should have already been handled in buildReplacements.
1209
+ let external = nullthrows(
1210
+ nullthrows(this.externals.get(dep.specifier)).get('*'),
1211
+ );
1212
+ append += `$atlaspack$exportWildcard($${assetId}$exports, ${external});\n`;
1213
+ this.usedHelpers.add('$atlaspack$exportWildcard');
1214
+ continue;
1215
+ }
1216
+
1217
+ // If the resolved asset has an exports object, use the $atlaspack$exportWildcard helper
1218
+ // to re-export all symbols. Otherwise, if there's no namespace object available, add
1219
+ // $atlaspack$export calls for each used symbol of the dependency.
1220
+ if (
1221
+ isWrapped ||
1222
+ resolved.meta.staticExports === false ||
1223
+ nullthrows(this.bundleGraph.getUsedSymbols(resolved)).has('*') ||
1224
+ // an empty asset
1225
+ (!resolved.meta.hasCJSExports &&
1226
+ resolved.symbols.hasExportSymbol('*'))
1227
+ ) {
1228
+ let obj = this.getSymbolResolution(
1229
+ asset,
1230
+ resolved,
1231
+ '*',
1232
+ dep,
1233
+ replacements,
1234
+ );
1235
+ append += `$atlaspack$exportWildcard($${assetId}$exports, ${obj});\n`;
1236
+ this.usedHelpers.add('$atlaspack$exportWildcard');
1237
+ } else {
1238
+ for (let symbol of nullthrows(
1239
+ this.bundleGraph.getUsedSymbols(dep),
1240
+ )) {
1241
+ if (
1242
+ symbol === 'default' || // `export * as ...` does not include the default export
1243
+ symbol === '__esModule'
1244
+ ) {
1245
+ continue;
1246
+ }
1247
+
1248
+ let resolvedSymbol = this.getSymbolResolution(
1249
+ asset,
1250
+ resolved,
1251
+ symbol,
1252
+ undefined,
1253
+ replacements,
1254
+ );
1255
+ let get = this.buildFunctionExpression([], resolvedSymbol);
1256
+ let set = asset.meta.hasCJSExports
1257
+ ? ', ' +
1258
+ this.buildFunctionExpression(['v'], `${resolvedSymbol} = v`)
1259
+ : '';
1260
+ prepend += `$atlaspack$export($${assetId}$exports, ${JSON.stringify(
1261
+ symbol,
1262
+ )}, ${get}${set});\n`;
1263
+ this.usedHelpers.add('$atlaspack$export');
1264
+ prependLineCount++;
1265
+ }
1266
+ }
1267
+ }
1268
+ }
1269
+ }
1270
+
1271
+ // Find the used exports of this module. This is based on the used symbols of
1272
+ // incoming dependencies rather than the asset's own used exports so that we include
1273
+ // re-exported symbols rather than only symbols declared in this asset.
1274
+ let incomingDeps = this.bundleGraph.getIncomingDependencies(asset);
1275
+ let usedExports = [...asset.symbols.exportSymbols()].filter(symbol => {
1276
+ if (symbol === '*') {
1277
+ return false;
1278
+ }
1279
+
1280
+ // If we need default interop, then all symbols are needed because the `default`
1281
+ // symbol really maps to the whole namespace.
1282
+ if (defaultInterop) {
1283
+ return true;
1284
+ }
1285
+
1286
+ let unused = incomingDeps.every(d => {
1287
+ let symbols = nullthrows(this.bundleGraph.getUsedSymbols(d));
1288
+ return !symbols.has(symbol) && !symbols.has('*');
1289
+ });
1290
+ return !unused;
1291
+ });
1292
+
1293
+ if (usedExports.length > 0) {
1294
+ // Insert $atlaspack$export calls for each of the used exports. This creates a getter/setter
1295
+ // for the symbol so that when the value changes the object property also changes. This is
1296
+ // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
1297
+ // additional assignments after each mutation of the original binding.
1298
+ prepend += `\n${usedExports
1299
+ .map(exp => {
1300
+ let resolved = this.getSymbolResolution(
1301
+ asset,
1302
+ asset,
1303
+ exp,
1304
+ undefined,
1305
+ replacements,
1306
+ );
1307
+ let get = this.buildFunctionExpression([], resolved);
1308
+ let isEsmExport = !!asset.symbols.get(exp)?.meta?.isEsm;
1309
+ let set =
1310
+ !isEsmExport && asset.meta.hasCJSExports
1311
+ ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`)
1312
+ : '';
1313
+ return `$atlaspack$export($${assetId}$exports, ${JSON.stringify(
1314
+ exp,
1315
+ )}, ${get}${set});`;
1316
+ })
1317
+ .join('\n')}\n`;
1318
+ this.usedHelpers.add('$atlaspack$export');
1319
+ prependLineCount += 1 + usedExports.length;
1320
+ }
1321
+ }
1322
+
1323
+ return [prepend, prependLineCount, append];
1324
+ }
1325
+
1326
+ buildBundlePrelude(): [string, number] {
1327
+ let enableSourceMaps = this.bundle.env.sourceMap;
1328
+ let res = '';
1329
+ let lines = 0;
1330
+
1331
+ // Add hashbang if the entry asset recorded an interpreter.
1332
+ let mainEntry = this.bundle.getMainEntry();
1333
+ if (
1334
+ mainEntry &&
1335
+ !this.isAsyncBundle &&
1336
+ !this.bundle.target.env.isBrowser()
1337
+ ) {
1338
+ let interpreter = mainEntry.meta.interpreter;
1339
+ invariant(interpreter == null || typeof interpreter === 'string');
1340
+ if (interpreter != null) {
1341
+ res += `#!${interpreter}\n`;
1342
+ lines++;
1343
+ }
1344
+ }
1345
+
1346
+ // The output format may have specific things to add at the start of the bundle (e.g. imports).
1347
+ let [outputFormatPrelude, outputFormatLines] =
1348
+ this.outputFormat.buildBundlePrelude();
1349
+ res += outputFormatPrelude;
1350
+ lines += outputFormatLines;
1351
+
1352
+ // Add used helpers.
1353
+ if (this.needsPrelude) {
1354
+ this.usedHelpers.add('$atlaspack$global');
1355
+ }
1356
+
1357
+ for (let helper of this.usedHelpers) {
1358
+ let currentHelper = helpers[helper];
1359
+ if (typeof currentHelper === 'function') {
1360
+ currentHelper = helpers[helper](this.bundle.env);
1361
+ }
1362
+ res += currentHelper;
1363
+ if (enableSourceMaps) {
1364
+ lines += countLines(currentHelper) - 1;
1365
+ }
1366
+ }
1367
+
1368
+ if (this.needsPrelude) {
1369
+ // Add the prelude if this is potentially the first JS bundle to load in a
1370
+ // particular context (e.g. entry scripts in HTML, workers, etc.).
1371
+ let parentBundles = this.bundleGraph.getParentBundles(this.bundle);
1372
+ let mightBeFirstJS =
1373
+ parentBundles.length === 0 ||
1374
+ parentBundles.some(b => b.type !== 'js') ||
1375
+ this.bundleGraph
1376
+ .getBundleGroupsContainingBundle(this.bundle)
1377
+ .some(g => this.bundleGraph.isEntryBundleGroup(g)) ||
1378
+ this.bundle.env.isIsolated() ||
1379
+ this.bundle.bundleBehavior === 'isolated';
1380
+
1381
+ if (mightBeFirstJS) {
1382
+ let preludeCode = prelude(this.atlaspackRequireName);
1383
+ res += preludeCode;
1384
+ if (enableSourceMaps) {
1385
+ lines += countLines(preludeCode) - 1;
1386
+ }
1387
+
1388
+ if (this.shouldBundleQueue(this.bundle)) {
1389
+ let bundleQueuePreludeCode = bundleQueuePrelude(this.bundle.env);
1390
+ res += bundleQueuePreludeCode;
1391
+ if (enableSourceMaps) {
1392
+ lines += countLines(bundleQueuePreludeCode) - 1;
1393
+ }
1394
+ }
1395
+ } else {
1396
+ // Otherwise, get the current atlaspackRequire global.
1397
+ const escaped = JSON.stringify(this.atlaspackRequireName);
1398
+ res += `var atlaspackRequire = $atlaspack$global[${escaped}];\n`;
1399
+ lines++;
1400
+ res += `var atlaspackRegister = atlaspackRequire.register;\n`;
1401
+ lines++;
1402
+ }
1403
+ }
1404
+
1405
+ // Add importScripts for sibling bundles in workers.
1406
+ if (this.bundle.env.isWorker() || this.bundle.env.isWorklet()) {
1407
+ let importScripts = '';
1408
+ let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
1409
+ for (let b of bundles) {
1410
+ if (this.bundle.env.outputFormat === 'esmodule') {
1411
+ // importScripts() is not allowed in native ES module workers.
1412
+ importScripts += `import "${relativeBundlePath(this.bundle, b)}";\n`;
1413
+ } else {
1414
+ importScripts += `importScripts("${relativeBundlePath(
1415
+ this.bundle,
1416
+ b,
1417
+ )}");\n`;
1418
+ }
1419
+ }
1420
+
1421
+ res += importScripts;
1422
+ lines += bundles.length;
1423
+ }
1424
+
1425
+ return [res, lines];
1426
+ }
1427
+
1428
+ needsDefaultInterop(asset: Asset): boolean {
1429
+ if (
1430
+ asset.symbols.hasExportSymbol('*') &&
1431
+ !asset.symbols.hasExportSymbol('default')
1432
+ ) {
1433
+ let deps = this.bundleGraph.getIncomingDependencies(asset);
1434
+ return deps.some(
1435
+ dep =>
1436
+ this.bundle.hasDependency(dep) &&
1437
+ // dep.meta.isES6Module &&
1438
+ dep.symbols.hasExportSymbol('default'),
1439
+ );
1440
+ }
1441
+
1442
+ return false;
1443
+ }
1444
+
1445
+ shouldSkipAsset(asset: Asset): boolean {
1446
+ if (this.isScriptEntry(asset)) {
1447
+ return true;
1448
+ }
1449
+
1450
+ return (
1451
+ asset.sideEffects === false &&
1452
+ nullthrows(this.bundleGraph.getUsedSymbols(asset)).size == 0 &&
1453
+ !this.bundleGraph.isAssetReferenced(this.bundle, asset)
1454
+ );
1455
+ }
1456
+
1457
+ isScriptEntry(asset: Asset): boolean {
1458
+ return (
1459
+ this.bundle.env.outputFormat === 'global' &&
1460
+ this.bundle.env.sourceType === 'script' &&
1461
+ asset === this.bundle.getMainEntry()
1462
+ );
1463
+ }
1464
+
1465
+ buildFunctionExpression(args: Array<string>, expr: string): string {
1466
+ return this.bundle.env.supports('arrow-functions', true)
1467
+ ? `(${args.join(', ')}) => ${expr}`
1468
+ : `function (${args.join(', ')}) { return ${expr}; }`;
1469
+ }
1470
+ }