@atlaspack/packager-js 2.14.5-canary.25 → 2.14.5-canary.251

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.
@@ -60,6 +60,13 @@ function _featureFlags() {
60
60
  };
61
61
  return data;
62
62
  }
63
+ function _outdent() {
64
+ const data = require("outdent");
65
+ _outdent = function () {
66
+ return data;
67
+ };
68
+ return data;
69
+ }
63
70
  var _ESMOutputFormat = require("./ESMOutputFormat");
64
71
  var _CJSOutputFormat = require("./CJSOutputFormat");
65
72
  var _GlobalOutputFormat = require("./GlobalOutputFormat");
@@ -70,7 +77,6 @@ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e;
70
77
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
71
78
  // General regex used to replace imports with the resolved code, references with resolutions,
72
79
  // and count the number of newlines in the file for source maps.
73
- //
74
80
  // For conditional bundling the only difference in this regex is adding `importCond` where we have `importAsync` etc..
75
81
  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;
76
82
  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;
@@ -80,6 +86,7 @@ const GLOBALS_BY_CONTEXT = {
80
86
  'web-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.worker)]),
81
87
  'service-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.serviceworker)]),
82
88
  worklet: new Set([...BUILTINS]),
89
+ tesseract: new Set([...BUILTINS, ...Object.keys(_globals().default.worker)]),
83
90
  node: new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
84
91
  'electron-main': new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
85
92
  'electron-renderer': new Set([...BUILTINS, ...Object.keys(_globals().default.node), ...Object.keys(_globals().default.browser)])
@@ -90,32 +97,35 @@ const OUTPUT_FORMATS = {
90
97
  global: _GlobalOutputFormat.GlobalOutputFormat
91
98
  };
92
99
  class ScopeHoistingPackager {
100
+ assetOutputs = new Map();
93
101
  exportedSymbols = new Map();
94
102
  externals = new Map();
95
103
  topLevelNames = new Map();
96
104
  seenAssets = new Set();
97
105
  wrappedAssets = new Set();
106
+ constantAssets = new Set();
98
107
  hoistedRequires = new Map();
108
+ seenHoistedRequires = new Set();
99
109
  needsPrelude = false;
100
110
  usedHelpers = new Set();
101
111
  externalAssets = new Set();
102
- forceSkipWrapAssets = [];
103
- constructor(options, bundleGraph, bundle, parcelRequireName, useAsyncBundleRuntime, forceSkipWrapAssets, logger) {
112
+ useBothScopeHoistingImprovements = (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2') || (0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovement');
113
+ constructor(options, bundleGraph, bundle, parcelRequireName, useAsyncBundleRuntime, manualStaticBindingExports, logger) {
104
114
  this.options = options;
105
115
  this.bundleGraph = bundleGraph;
106
116
  this.bundle = bundle;
107
117
  this.parcelRequireName = parcelRequireName;
108
118
  this.useAsyncBundleRuntime = useAsyncBundleRuntime;
109
- this.forceSkipWrapAssets = forceSkipWrapAssets ?? [];
119
+ this.manualStaticBindingExports = (manualStaticBindingExports === null || manualStaticBindingExports === void 0 ? void 0 : manualStaticBindingExports.map(glob => (0, _utils().globToRegex)(glob))) ?? null;
110
120
  this.logger = logger;
111
121
  let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
112
122
  this.outputFormat = new OutputFormat(this);
113
- this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated';
123
+ this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated' && this.bundle.bundleBehavior !== 'inlineIsolated';
114
124
  this.globalNames = GLOBALS_BY_CONTEXT[bundle.env.context];
115
125
  }
116
126
  async package() {
117
127
  var _sourceMap;
118
- let wrappedAssets = await this.loadAssets();
128
+ await this.loadAssets();
119
129
  this.buildExportedSymbols();
120
130
 
121
131
  // If building a library, the target is actually another bundler rather
@@ -134,8 +144,10 @@ class ScopeHoistingPackager {
134
144
  let lineCount = 0;
135
145
  let sourceMap = null;
136
146
  let processAsset = asset => {
147
+ this.seenHoistedRequires.clear();
137
148
  let [content, map, lines] = this.visitAsset(asset);
138
149
  if (sourceMap && map) {
150
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
139
151
  sourceMap.addSourceMap(map, lineCount);
140
152
  } else if (this.bundle.env.sourceMap) {
141
153
  sourceMap = map;
@@ -143,11 +155,19 @@ class ScopeHoistingPackager {
143
155
  res += content + '\n';
144
156
  lineCount += lines + 1;
145
157
  };
158
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) {
159
+ // Write out all constant modules used by this bundle
160
+ for (let asset of this.constantAssets) {
161
+ if (!this.seenAssets.has(asset)) {
162
+ processAsset(asset);
163
+ }
164
+ }
165
+ }
146
166
 
147
167
  // Hoist wrapped asset to the top of the bundle to ensure that they are registered
148
168
  // before they are used.
149
- for (let asset of wrappedAssets) {
150
- if (!this.seenAssets.has(asset.id)) {
169
+ for (let asset of this.wrappedAssets) {
170
+ if (!this.seenAssets.has(asset)) {
151
171
  processAsset(asset);
152
172
  }
153
173
  }
@@ -155,7 +175,7 @@ class ScopeHoistingPackager {
155
175
  // Add each asset that is directly connected to the bundle. Dependencies will be handled
156
176
  // by replacing `import` statements in the code.
157
177
  this.bundle.traverseAssets((asset, _, actions) => {
158
- if (this.seenAssets.has(asset.id)) {
178
+ if (this.seenAssets.has(asset)) {
159
179
  actions.skipChildren();
160
180
  return;
161
181
  }
@@ -165,23 +185,35 @@ class ScopeHoistingPackager {
165
185
  let [prelude, preludeLines] = this.buildBundlePrelude();
166
186
  res = prelude + res;
167
187
  lineCount += preludeLines;
188
+ // @ts-expect-error TS2339 - offsetLines method exists but missing from @parcel/source-map type definitions
168
189
  (_sourceMap = sourceMap) === null || _sourceMap === void 0 || _sourceMap.offsetLines(1, preludeLines);
169
190
  let entries = this.bundle.getEntryAssets();
170
191
  let mainEntry = this.bundle.getMainEntry();
171
192
  if (this.isAsyncBundle) {
172
- // In async bundles we don't want the main entry to execute until we require it
173
- // as there might be dependencies in a sibling bundle that hasn't loaded yet.
174
- entries = entries.filter(a => {
175
- var _mainEntry;
176
- return a.id !== ((_mainEntry = mainEntry) === null || _mainEntry === void 0 ? void 0 : _mainEntry.id);
177
- });
193
+ if (this.useBothScopeHoistingImprovements || (0, _featureFlags().getFeatureFlag)('supportWebpackChunkName')) {
194
+ // Generally speaking, async bundles should not be executed on load, as
195
+ // they're just collections of assets that other assets require.
196
+ // However, there are some special cases where a runtime asset needs to be
197
+ // injected, but no other asset will require it (mostly the bundle
198
+ // manifest).
199
+ // In this case, those assets need to be required on load.
200
+ entries = entries.filter(a => {
201
+ var _a$meta;
202
+ return (_a$meta = a.meta) === null || _a$meta === void 0 ? void 0 : _a$meta.runtimeAssetRequiringExecutionOnLoad;
203
+ });
204
+ } else {
205
+ entries = entries.filter(a => {
206
+ var _mainEntry;
207
+ return a.id !== ((_mainEntry = mainEntry) === null || _mainEntry === void 0 ? void 0 : _mainEntry.id);
208
+ });
209
+ }
178
210
  mainEntry = null;
179
211
  }
180
212
  let needsBundleQueue = this.shouldBundleQueue(this.bundle);
181
213
 
182
214
  // If any of the entry assets are wrapped, call parcelRequire so they are executed.
183
215
  for (let entry of entries) {
184
- if (this.wrappedAssets.has(entry.id) && !this.isScriptEntry(entry)) {
216
+ if (this.wrappedAssets.has(entry) && !this.isScriptEntry(entry)) {
185
217
  var _entry$symbols$get;
186
218
  let parcelRequire = `parcelRequire(${JSON.stringify(this.bundleGraph.getAssetPublicId(entry))});\n`;
187
219
  let entryExports = (_entry$symbols$get = entry.symbols.get('*')) === null || _entry$symbols$get === void 0 ? void 0 : _entry$symbols$get.local;
@@ -211,38 +243,46 @@ class ScopeHoistingPackager {
211
243
  let {
212
244
  code,
213
245
  map: mapBuffer
214
- } = (0, _nullthrows().default)(this.assetOutputs.get(mainEntry.id));
246
+ } = (0, _nullthrows().default)(this.assetOutputs.get(mainEntry));
215
247
  let map;
216
248
  if (mapBuffer) {
217
249
  map = new (_sourceMap2().default)(this.options.projectRoot, mapBuffer);
218
250
  }
219
251
  res += (0, _utils2.replaceScriptDependencies)(this.bundleGraph, this.bundle, code, map, this.parcelRequireName);
220
252
  if (sourceMap && map) {
253
+ // @ts-expect-error TS2339 - addSourceMap method exists but missing from @parcel/source-map type definitions
221
254
  sourceMap.addSourceMap(map, lineCount);
222
255
  }
223
256
  }
224
- return {
257
+ const result = {
225
258
  contents: res,
226
259
  map: sourceMap
227
260
  };
261
+ if (_utils().debugTools['scope-hoisting-stats']) {
262
+ result.scopeHoistingStats = {
263
+ totalAssets: this.assetOutputs.size,
264
+ wrappedAssets: this.wrappedAssets.size
265
+ };
266
+ }
267
+ return result;
228
268
  }
229
269
  shouldBundleQueue(bundle) {
230
270
  let referencingBundles = this.bundleGraph.getReferencingBundles(bundle);
231
271
  let hasHtmlReference = referencingBundles.some(b => b.type === 'html');
232
272
  let hasConditionalReference = false;
233
273
  let isConditionalBundle = false;
234
- if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && (0, _featureFlags().getFeatureFlag)('conditionalBundlingAsyncRuntime')) {
274
+ if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi')) {
235
275
  // If the bundle has a conditional bundle reference (has an importCond)
236
276
  hasConditionalReference = this.bundleGraph.getReferencedConditionalBundles(bundle).length > 0;
237
277
  // If the bundle is a conditional bundle
238
278
  isConditionalBundle = this.hasConditionalDependency();
239
279
  }
240
- return this.useAsyncBundleRuntime && bundle.type === 'js' && bundle.bundleBehavior !== 'inline' && bundle.env.outputFormat === 'esmodule' && !bundle.env.isIsolated() && bundle.bundleBehavior !== 'isolated' && (hasHtmlReference || hasConditionalReference || isConditionalBundle);
280
+ return this.useAsyncBundleRuntime && bundle.type === 'js' && bundle.bundleBehavior !== 'inline' && bundle.bundleBehavior !== 'inlineIsolated' && bundle.env.outputFormat === 'esmodule' && !bundle.env.isIsolated() && bundle.bundleBehavior !== 'isolated' && (hasHtmlReference || hasConditionalReference || isConditionalBundle);
241
281
  }
242
282
  runWhenReady(bundle, codeToRun) {
243
283
  let deps = this.bundleGraph.getReferencedBundles(bundle).filter(b => this.shouldBundleQueue(b)).map(b => b.publicId);
244
284
  const conditions = [];
245
- if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && (0, _featureFlags().getFeatureFlag)('conditionalBundlingAsyncRuntime')) {
285
+ if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi')) {
246
286
  const conditionSet = this.bundleGraph.getConditionalBundleMapping().get(bundle.id);
247
287
  for (const [key, {
248
288
  ifTrueBundles,
@@ -264,11 +304,10 @@ class ScopeHoistingPackager {
264
304
  let queue = new (_utils().PromiseQueue)({
265
305
  maxConcurrent: 32
266
306
  });
267
- let wrapped = [];
268
307
  this.bundle.traverseAssets(asset => {
269
308
  queue.add(async () => {
270
309
  let [code, map] = await Promise.all([asset.getCode(), this.bundle.env.sourceMap ? asset.getMapBuffer() : null]);
271
- return [asset.id, {
310
+ return [asset, {
272
311
  code,
273
312
  map
274
313
  }];
@@ -276,40 +315,86 @@ class ScopeHoistingPackager {
276
315
  if (asset.meta.shouldWrap || this.bundle.env.sourceType === 'script' || this.bundleGraph.isAssetReferenced(this.bundle, asset) || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.meta.shouldWrap && dep.specifierType !== 'url')) {
277
316
  // Don't wrap constant "entry" modules _except_ if they are referenced by any lazy dependency
278
317
  if (!asset.meta.isConstantModule || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.priority === 'lazy')) {
279
- this.wrappedAssets.add(asset.id);
280
- wrapped.push(asset);
318
+ this.wrappedAssets.add(asset);
319
+ } else if (((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) && asset.meta.isConstantModule) {
320
+ this.constantAssets.add(asset);
281
321
  }
282
322
  }
283
323
  });
284
- for (let wrappedAssetRoot of [...wrapped]) {
285
- this.bundle.traverseAssets((asset, _, actions) => {
286
- if (asset === wrappedAssetRoot) {
287
- return;
288
- }
289
- if (this.wrappedAssets.has(asset.id)) {
290
- actions.skipChildren();
291
- return;
292
- }
293
- // This prevents children of a wrapped asset also being wrapped - it's an "unsafe" optimisation
294
- // that should only be used when you know (or think you know) what you're doing.
295
- //
296
- // In particular this can force an async bundle to be scope hoisted where it previously would not be
297
- // due to the entry asset being wrapped.
298
- if (this.forceSkipWrapAssets.length > 0 && this.forceSkipWrapAssets.some(p => p === _path().default.relative(this.options.projectRoot, asset.filePath))) {
299
- this.logger.verbose({
300
- message: `Force skipping wrapping of ${_path().default.relative(this.options.projectRoot, asset.filePath)}`
301
- });
302
- actions.skipChildren();
303
- return;
324
+ if (this.useBothScopeHoistingImprovements) {
325
+ // Tracks which assets have been assigned to a wrap group
326
+ let assignedAssets = new Set();
327
+
328
+ // In V2 scope hoisting, we iterate from the main entry, rather than
329
+ // wrapping the entry assets
330
+ if (!(0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
331
+ // Make all entry assets wrapped, to avoid any top level hoisting
332
+ for (let entryAsset of this.bundle.getEntryAssets()) {
333
+ if (!this.wrappedAssets.has(entryAsset)) {
334
+ this.wrappedAssets.add(entryAsset);
335
+ }
304
336
  }
305
- if (!asset.meta.isConstantModule) {
306
- this.wrappedAssets.add(asset.id);
307
- wrapped.push(asset);
337
+ }
338
+
339
+ // We need to make a new copy here so that we can add to the list and
340
+ // iterate the newly added items, without mutating the wrappedAssets set
341
+ let moduleGroupParents = [...this.wrappedAssets.values()];
342
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
343
+ // The main entry needs to be check to find assets that would have gone in
344
+ // the top level scope
345
+ let mainEntry = this.bundle.getMainEntry();
346
+ if (mainEntry && !this.wrappedAssets.has(mainEntry)) {
347
+ moduleGroupParents.unshift(mainEntry);
308
348
  }
309
- }, wrappedAssetRoot);
349
+ }
350
+ for (let moduleGroupParentAsset of moduleGroupParents) {
351
+ this.bundle.traverseAssets((asset, _, actions) => {
352
+ if (asset === moduleGroupParentAsset) {
353
+ return;
354
+ }
355
+ if (this.wrappedAssets.has(asset)) {
356
+ actions.skipChildren();
357
+ return;
358
+ }
359
+ if (!asset.meta.isConstantModule && (assignedAssets.has(asset) || this.isReExported(asset))) {
360
+ this.wrappedAssets.add(asset);
361
+
362
+ // This also needs to be added to the traversal so that we iterate
363
+ // it during this check.
364
+ moduleGroupParents.push(asset);
365
+ actions.skipChildren();
366
+ return;
367
+ }
368
+ assignedAssets.add(asset);
369
+ }, moduleGroupParentAsset);
370
+ }
371
+ } else {
372
+ for (let wrappedAssetRoot of this.wrappedAssets) {
373
+ this.bundle.traverseAssets((asset, _, actions) => {
374
+ if (asset === wrappedAssetRoot) {
375
+ return;
376
+ }
377
+ if (this.wrappedAssets.has(asset)) {
378
+ actions.skipChildren();
379
+ return;
380
+ }
381
+ if (!asset.meta.isConstantModule) {
382
+ this.wrappedAssets.add(asset);
383
+ }
384
+ }, wrappedAssetRoot);
385
+ }
310
386
  }
311
387
  this.assetOutputs = new Map(await queue.run());
312
- return wrapped;
388
+ }
389
+ isReExported(asset) {
390
+ let parentSymbols = this.bundleGraph.getIncomingDependencies(asset).map(dep => this.bundleGraph.getAssetWithDependency(dep)).flatMap(parent => {
391
+ if (parent == null) {
392
+ return [];
393
+ }
394
+ return this.bundleGraph.getExportedSymbols(parent, this.bundle);
395
+ });
396
+ let assetSymbols = this.bundleGraph.getExportedSymbols(asset, this.bundle);
397
+ return assetSymbols.some(assetSymbol => parentSymbols.some(parentSymbol => parentSymbol.symbol === assetSymbol.symbol));
313
398
  }
314
399
  buildExportedSymbols() {
315
400
  if (!this.bundle.env.isLibrary || this.bundle.env.outputFormat !== 'esmodule') {
@@ -318,7 +403,7 @@ class ScopeHoistingPackager {
318
403
 
319
404
  // TODO: handle ESM exports of wrapped entry assets...
320
405
  let entry = this.bundle.getMainEntry();
321
- if (entry && !this.wrappedAssets.has(entry.id)) {
406
+ if (entry && !this.wrappedAssets.has(entry)) {
322
407
  let hasNamespace = entry.symbols.hasExportSymbol('*');
323
408
  for (let {
324
409
  asset,
@@ -387,16 +472,19 @@ class ScopeHoistingPackager {
387
472
  return `${obj}[${JSON.stringify(property)}]`;
388
473
  }
389
474
  visitAsset(asset) {
390
- (0, _assert().default)(!this.seenAssets.has(asset.id), 'Already visited asset');
391
- this.seenAssets.add(asset.id);
475
+ (0, _assert().default)(!this.seenAssets.has(asset), 'Already visited asset');
476
+ this.seenAssets.add(asset);
392
477
  let {
393
478
  code,
394
479
  map
395
- } = (0, _nullthrows().default)(this.assetOutputs.get(asset.id));
480
+ } = (0, _nullthrows().default)(this.assetOutputs.get(asset));
396
481
  return this.buildAsset(asset, code, map);
397
482
  }
483
+ getAssetFilePath(asset) {
484
+ return _path().default.relative(this.options.projectRoot, asset.filePath);
485
+ }
398
486
  buildAsset(asset, code, map) {
399
- let shouldWrap = this.wrappedAssets.has(asset.id);
487
+ let shouldWrap = this.wrappedAssets.has(asset);
400
488
  let deps = this.bundleGraph.getDependencies(asset);
401
489
  let sourceMap = this.bundle.env.sourceMap && map ? new (_sourceMap2().default)(this.options.projectRoot, map) : null;
402
490
 
@@ -416,13 +504,21 @@ class ScopeHoistingPackager {
416
504
  }
417
505
  continue;
418
506
  }
419
- if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
420
- let [code, map, lines] = this.visitAsset(resolved);
421
- depCode += code + '\n';
422
- if (sourceMap && map) {
423
- sourceMap.addSourceMap(map, lineCount);
507
+ if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved)) {
508
+ if (this.useBothScopeHoistingImprovements && this.wrappedAssets.has(resolved)) {
509
+ // When the dep is wrapped then we just need to drop a side effect
510
+ // require instead of inlining
511
+ depCode += `parcelRequire("${this.bundleGraph.getAssetPublicId(resolved)}");\n`;
512
+ lineCount += 1;
513
+ } else {
514
+ let [code, map, lines] = this.visitAsset(resolved);
515
+ depCode += code + '\n';
516
+ if (sourceMap && map) {
517
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
518
+ sourceMap.addSourceMap(map, lineCount);
519
+ }
520
+ lineCount += lines + 1;
424
521
  }
425
- lineCount += lines + 1;
426
522
  }
427
523
  }
428
524
  return [depCode, sourceMap, lineCount];
@@ -482,20 +578,51 @@ class ScopeHoistingPackager {
482
578
  // after the dependency is declared. This handles the case where the resulting asset
483
579
  // is wrapped, but the dependency in this asset is not marked as wrapped. This means
484
580
  // that it was imported/required at the top-level, so its side effects should run immediately.
485
- let [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
581
+ let res = '';
582
+ let lines = 0;
486
583
  let map;
487
- if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
584
+ if (!(0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
585
+ [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
586
+ }
587
+ if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved)) {
488
588
  // If this asset is wrapped, we need to hoist the code for the dependency
489
589
  // outside our parcelRequire.register wrapper. This is safe because all
490
590
  // assets referenced by this asset will also be wrapped. Otherwise, inline the
491
591
  // asset content where the import statement was.
492
- if (shouldWrap) {
493
- depContent.push(this.visitAsset(resolved));
592
+ if (this.useBothScopeHoistingImprovements) {
593
+ if (!resolved.meta.isConstantModule && !this.wrappedAssets.has(resolved)) {
594
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
595
+ if (_utils().debugTools['asset-file-names-in-output']) {
596
+ let resolvedPath = this.getAssetFilePath(resolved);
597
+ res = (0, _outdent().outdent)`
598
+ /* Scope hoisted asset: ${resolvedPath} */
599
+ ${depCode}
600
+ /* End: ${resolvedPath} */
601
+ ${res}
602
+ `;
603
+ lines += 3 + depLines;
604
+ } else {
605
+ res = depCode + '\n' + res;
606
+ lines += 1 + depLines;
607
+ }
608
+ map = depMap;
609
+ }
494
610
  } else {
495
- let [depCode, depMap, depLines] = this.visitAsset(resolved);
496
- res = depCode + '\n' + res;
497
- lines += 1 + depLines;
498
- map = depMap;
611
+ if (shouldWrap) {
612
+ depContent.push(this.visitAsset(resolved));
613
+ } else {
614
+ let [depCode, depMap, depLines] = this.visitAsset(resolved);
615
+ res = depCode + '\n' + res;
616
+ lines += 1 + depLines;
617
+ map = depMap;
618
+ }
619
+ }
620
+ }
621
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
622
+ let [requiresCode, requiresLines] = this.getHoistedParcelRequires(asset, dep, resolved);
623
+ if (requiresCode) {
624
+ res = requiresCode + '\n' + res;
625
+ lines += requiresLines + 1;
499
626
  }
500
627
  }
501
628
 
@@ -506,6 +633,7 @@ class ScopeHoistingPackager {
506
633
  sourceMap.offsetLines(lineCount + 1, lines);
507
634
  }
508
635
  if (map) {
636
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
509
637
  sourceMap.addSourceMap(map, lineCount);
510
638
  }
511
639
  }
@@ -542,10 +670,15 @@ ${code}
542
670
  });
543
671
  `;
544
672
  lineCount += 2;
673
+ if (_utils().debugTools['asset-file-names-in-output']) {
674
+ code = `/* ${this.getAssetFilePath(asset)} */\n` + code;
675
+ lineCount += 1;
676
+ }
545
677
  for (let [depCode, map, lines] of depContent) {
546
678
  if (!depCode) continue;
547
679
  code += depCode + '\n';
548
680
  if (sourceMap && map) {
681
+ // @ts-expect-error TS2551 - addSourceMap method exists but missing from @parcel/source-map type definitions
549
682
  sourceMap.addSourceMap(map, lineCount);
550
683
  }
551
684
  lineCount += lines + 1;
@@ -614,7 +747,7 @@ ${code}
614
747
 
615
748
  // If this asset is wrapped, we need to replace the exports namespace with `module.exports`,
616
749
  // which will be provided to us by the wrapper.
617
- if (this.wrappedAssets.has(asset.id) || this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry()) {
750
+ if (this.wrappedAssets.has(asset) || this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry()) {
618
751
  var _asset$symbols$get;
619
752
  let exportsName = ((_asset$symbols$get = asset.symbols.get('*')) === null || _asset$symbols$get === void 0 ? void 0 : _asset$symbols$get.local) || `$${assetId}$exports`;
620
753
  replacements.set(exportsName, 'module.exports');
@@ -648,6 +781,7 @@ ${code}
648
781
  local
649
782
  }] of dep.symbols) {
650
783
  // If already imported, just add the already renamed variable to the mapping.
784
+
651
785
  let renamed = external.get(imported);
652
786
  if (renamed && local !== '*' && replacements) {
653
787
  replacements.set(local, renamed);
@@ -711,7 +845,7 @@ ${code}
711
845
  continue;
712
846
  }
713
847
  }
714
- renamed = this.bundleGraph.getSymbolResolution(entry, imported, this.bundle).symbol;
848
+ renamed = this.bundleGraph.getSymbolResolution(entry, imported, this.bundle).symbol || undefined;
715
849
  }
716
850
  }
717
851
 
@@ -752,7 +886,7 @@ ${code}
752
886
  }
753
887
  return false;
754
888
  }
755
- return !this.bundle.hasAsset(resolved) && !this.externalAssets.has(resolved) || this.wrappedAssets.has(resolved.id) && resolved !== parentAsset;
889
+ return !this.bundle.hasAsset(resolved) && !this.externalAssets.has(resolved) || this.wrappedAssets.has(resolved) && resolved !== parentAsset;
756
890
  }
757
891
  getSymbolResolution(parentAsset, resolved, imported, dep, replacements) {
758
892
  let {
@@ -779,12 +913,12 @@ ${code}
779
913
  // Only do this if the asset is part of a different bundle (so it was definitely
780
914
  // parcelRequire.register'ed there), or if it is indeed registered in this bundle.
781
915
  !this.bundle.hasAsset(resolvedAsset) || !this.shouldSkipAsset(resolvedAsset))) {
782
- let hoisted = this.hoistedRequires.get(dep.id);
916
+ let hoisted = this.hoistedRequires.get(dep);
783
917
  if (!hoisted) {
784
918
  hoisted = new Map();
785
- this.hoistedRequires.set(dep.id, hoisted);
919
+ this.hoistedRequires.set(dep, hoisted);
786
920
  }
787
- hoisted.set(resolvedAsset.id, `var $${publicId} = parcelRequire(${JSON.stringify(publicId)});`);
921
+ hoisted.set(resolvedAsset, `var $${publicId} = parcelRequire(${JSON.stringify(publicId)});`);
788
922
  }
789
923
  if (isWrapped) {
790
924
  this.needsPrelude = true;
@@ -813,7 +947,7 @@ ${code}
813
947
  }
814
948
  if (imported === '*' || exportSymbol === '*' || isDefaultInterop) {
815
949
  // Resolve to the namespace object if requested or this is a CJS default interop reqiure.
816
- if (parentAsset === resolvedAsset && this.wrappedAssets.has(resolvedAsset.id)) {
950
+ if (parentAsset === resolvedAsset && this.wrappedAssets.has(resolvedAsset)) {
817
951
  // Directly use module.exports for wrapped assets importing themselves.
818
952
  return 'module.exports';
819
953
  } else {
@@ -841,7 +975,7 @@ ${code}
841
975
  if (resolved.type !== 'js') {
842
976
  return ['', 0];
843
977
  }
844
- let hoisted = this.hoistedRequires.get(dep.id);
978
+ let hoisted = this.hoistedRequires.get(dep);
845
979
  let res = '';
846
980
  let lineCount = 0;
847
981
  let isWrapped = this.isWrapped(resolved, parentAsset);
@@ -850,14 +984,23 @@ ${code}
850
984
  // we need to run side effects when this asset runs. If the resolved asset is not
851
985
  // the first one in the hoisted requires, we need to insert a parcelRequire here
852
986
  // so it runs first.
853
- if (isWrapped && !dep.meta.shouldWrap && (!hoisted || hoisted.keys().next().value !== resolved.id) && !this.bundleGraph.isDependencySkipped(dep) && !this.shouldSkipAsset(resolved)) {
987
+ if (isWrapped && !dep.meta.shouldWrap && (!hoisted || hoisted.keys().next().value !== resolved) && !this.bundleGraph.isDependencySkipped(dep) && !this.shouldSkipAsset(resolved)) {
854
988
  this.needsPrelude = true;
855
989
  res += `parcelRequire(${JSON.stringify(this.bundleGraph.getAssetPublicId(resolved))});`;
856
990
  }
857
991
  if (hoisted) {
858
992
  this.needsPrelude = true;
859
- res += '\n' + [...hoisted.values()].join('\n');
860
- lineCount += hoisted.size;
993
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
994
+ let hoistedValues = [...hoisted.values()].filter(val => !this.seenHoistedRequires.has(val));
995
+ for (let val of hoistedValues) {
996
+ this.seenHoistedRequires.add(val);
997
+ }
998
+ res += '\n' + hoistedValues.join('\n');
999
+ lineCount += hoisted.size;
1000
+ } else {
1001
+ res += '\n' + [...hoisted.values()].join('\n');
1002
+ lineCount += hoisted.size;
1003
+ }
861
1004
  }
862
1005
  return [res, lineCount];
863
1006
  }
@@ -865,7 +1008,7 @@ ${code}
865
1008
  let prepend = '';
866
1009
  let prependLineCount = 0;
867
1010
  let append = '';
868
- let shouldWrap = this.wrappedAssets.has(asset.id);
1011
+ let shouldWrap = this.wrappedAssets.has(asset);
869
1012
  let usedSymbols = (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(asset));
870
1013
  let assetId = asset.meta.id;
871
1014
  (0, _assert().default)(typeof assetId === 'string');
@@ -874,20 +1017,28 @@ ${code}
874
1017
  // If there's no __esModule flag, and default is a used symbol, we need
875
1018
  // to insert an interop helper.
876
1019
  let defaultInterop = asset.symbols.hasExportSymbol('*') && usedSymbols.has('default') && !asset.symbols.hasExportSymbol('__esModule');
877
- let usedNamespace =
878
- // If the asset has * in its used symbols, we might need the exports namespace.
879
- // The one case where this isn't true is in ESM library entries, where the only
880
- // dependency on * is the entry dependency. In this case, we will use ESM exports
881
- // instead of the namespace object.
882
- usedSymbols.has('*') && (this.bundle.env.outputFormat !== 'esmodule' || !this.bundle.env.isLibrary || asset !== this.bundle.getMainEntry() || this.bundleGraph.getIncomingDependencies(asset).some(dep => !dep.isEntry && this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'))) ||
883
- // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
884
- // we fallback on the namespace object.
885
- asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) ||
886
- // If the exports has this asset's namespace (e.g. ESM output from CJS input),
887
- // include the namespace object for the default export.
888
- this.exportedSymbols.has(`$${assetId}$exports`) ||
889
- // CommonJS library bundle entries always need a namespace.
890
- this.bundle.env.isLibrary && this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry();
1020
+ let usedNamespace;
1021
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') && asset.meta.isConstantModule) {
1022
+ // Only set usedNamespace if there is an incoming dependency in the current bundle that uses '*'
1023
+ usedNamespace = this.bundleGraph.getIncomingDependencies(asset).some(dep => this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'));
1024
+ } else {
1025
+ usedNamespace =
1026
+ // If the asset has * in its used symbols, we might need the exports namespace.
1027
+ // The one case where this isn't true is in ESM library entries, where the only
1028
+ // dependency on * is the entry dependency. In this case, we will use ESM exports
1029
+ // instead of the namespace object.
1030
+
1031
+ usedSymbols.has('*') && (this.bundle.env.outputFormat !== 'esmodule' || !this.bundle.env.isLibrary || asset !== this.bundle.getMainEntry() || this.bundleGraph.getIncomingDependencies(asset).some(dep => !dep.isEntry && this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'))) ||
1032
+ // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
1033
+ // we fallback on the namespace object.
1034
+
1035
+ asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) ||
1036
+ // If the exports has this asset's namespace (e.g. ESM output from CJS input),
1037
+ // include the namespace object for the default export.
1038
+ this.exportedSymbols.has(`$${assetId}$exports`) ||
1039
+ // CommonJS library bundle entries always need a namespace.
1040
+ this.bundle.env.isLibrary && this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry();
1041
+ }
891
1042
 
892
1043
  // If the asset doesn't have static exports, should wrap, the namespace is used,
893
1044
  // or we need default interop, then we need to synthesize a namespace object for
@@ -905,6 +1056,7 @@ ${code}
905
1056
  // Insert the __esModule interop flag for this module if it has a `default` export
906
1057
  // and the namespace symbol is used.
907
1058
  // TODO: only if required by CJS?
1059
+
908
1060
  if (asset.symbols.hasExportSymbol('default') && usedSymbols.has('*')) {
909
1061
  prepend += `\n$parcel$defineInteropFlag($${assetId}$exports);\n`;
910
1062
  prependLineCount += 2;
@@ -988,16 +1140,22 @@ ${code}
988
1140
  // for the symbol so that when the value changes the object property also changes. This is
989
1141
  // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
990
1142
  // additional assignments after each mutation of the original binding.
991
- prepend += `\n${usedExports.map(exp => {
992
- var _asset$symbols$get2;
1143
+ for (let exp of usedExports) {
1144
+ var _asset$symbols$get2, _this$manualStaticBin;
993
1145
  let resolved = this.getSymbolResolution(asset, asset, exp, undefined, replacements);
994
- let get = this.buildFunctionExpression([], resolved);
995
- let isEsmExport = !!((_asset$symbols$get2 = asset.symbols.get(exp)) !== null && _asset$symbols$get2 !== void 0 && (_asset$symbols$get2 = _asset$symbols$get2.meta) !== null && _asset$symbols$get2 !== void 0 && _asset$symbols$get2.isEsm);
996
- let set = !isEsmExport && asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
997
- return `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});`;
998
- }).join('\n')}\n`;
999
- this.usedHelpers.add('$parcel$export');
1000
- prependLineCount += 1 + usedExports.length;
1146
+ const meta = (_asset$symbols$get2 = asset.symbols.get(exp)) === null || _asset$symbols$get2 === void 0 ? void 0 : _asset$symbols$get2.meta;
1147
+ if ((0, _featureFlags().getFeatureFlag)('exportsRebindingOptimisation') && (meta !== null && meta !== void 0 && meta.isStaticBindingSafe || (_this$manualStaticBin = this.manualStaticBindingExports) !== null && _this$manualStaticBin !== void 0 && _this$manualStaticBin.some(regex => regex.test(asset.filePath)))) {
1148
+ append += `$${assetId}$exports[${JSON.stringify(exp)}] = ${resolved};\n`;
1149
+ } else {
1150
+ var _asset$symbols$get3;
1151
+ let get = this.buildFunctionExpression([], resolved);
1152
+ let isEsmExport = !!((_asset$symbols$get3 = asset.symbols.get(exp)) !== null && _asset$symbols$get3 !== void 0 && (_asset$symbols$get3 = _asset$symbols$get3.meta) !== null && _asset$symbols$get3 !== void 0 && _asset$symbols$get3.isEsm);
1153
+ let set = !isEsmExport && asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
1154
+ prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});\n`;
1155
+ this.usedHelpers.add('$parcel$export');
1156
+ prependLineCount += 1 + usedExports.length;
1157
+ }
1158
+ }
1001
1159
  }
1002
1160
  }
1003
1161
  return [prepend, prependLineCount, append];
@@ -1041,11 +1199,11 @@ ${code}
1041
1199
  // Add the prelude if this is potentially the first JS bundle to load in a
1042
1200
  // particular context (e.g. entry scripts in HTML, workers, etc.).
1043
1201
  let parentBundles = this.bundleGraph.getParentBundles(this.bundle);
1044
- let mightBeFirstJS = parentBundles.length === 0 || parentBundles.some(b => b.type !== 'js') || this.bundleGraph.getBundleGroupsContainingBundle(this.bundle).some(g => this.bundleGraph.isEntryBundleGroup(g)) || this.bundle.env.isIsolated() || this.bundle.bundleBehavior === 'isolated' ||
1202
+ let mightBeFirstJS = parentBundles.length === 0 || parentBundles.some(b => b.type !== 'js') || this.bundleGraph.getBundleGroupsContainingBundle(this.bundle).some(g => this.bundleGraph.isEntryBundleGroup(g)) || this.bundle.env.isIsolated() || this.bundle.bundleBehavior === 'isolated' || this.bundle.bundleBehavior === 'inlineIsolated' ||
1045
1203
  // Conditional deps may be loaded before entrypoints on the server
1046
1204
  this.hasConditionalDependency();
1047
1205
  if (mightBeFirstJS) {
1048
- let preludeCode = (0, _helpers.prelude)(this.parcelRequireName);
1206
+ let preludeCode = ((0, _featureFlags().getFeatureFlag)('useNewPrelude') ? _helpers.preludeNew : _helpers.preludeOld)(this.parcelRequireName);
1049
1207
  res += preludeCode;
1050
1208
  if (enableSourceMaps) {
1051
1209
  lines += (0, _utils().countLines)(preludeCode) - 1;
@@ -1068,7 +1226,7 @@ ${code}
1068
1226
  }
1069
1227
 
1070
1228
  // Add importScripts for sibling bundles in workers.
1071
- if (this.bundle.env.isWorker() || this.bundle.env.isWorklet()) {
1229
+ if (this.bundle.env.isWorker() || this.bundle.env.isTesseract() || this.bundle.env.isWorklet()) {
1072
1230
  let importScripts = '';
1073
1231
  let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
1074
1232
  for (let b of bundles) {