@atlaspack/packager-js 2.14.5-canary.33 → 2.14.5-canary.331

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