@parcel/packager-js 2.0.0-nightly.92 → 2.0.1

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