@atlaspack/packager-js 2.14.5-canary.20 → 2.14.5-canary.201

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,37 @@ const OUTPUT_FORMATS = {
90
97
  global: _GlobalOutputFormat.GlobalOutputFormat
91
98
  };
92
99
  class ScopeHoistingPackager {
100
+ // @ts-expect-error TS2564
101
+
93
102
  exportedSymbols = new Map();
94
103
  externals = new Map();
95
104
  topLevelNames = new Map();
96
105
  seenAssets = new Set();
97
106
  wrappedAssets = 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, 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 ?? [];
110
119
  this.logger = logger;
111
120
  let OutputFormat = OUTPUT_FORMATS[this.bundle.env.outputFormat];
112
121
  this.outputFormat = new OutputFormat(this);
113
- this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated';
122
+ this.isAsyncBundle = this.bundleGraph.hasParentBundleOfType(this.bundle, 'js') && !this.bundle.env.isIsolated() && this.bundle.bundleBehavior !== 'isolated' && this.bundle.bundleBehavior !== 'inlineIsolated';
114
123
  this.globalNames = GLOBALS_BY_CONTEXT[bundle.env.context];
115
124
  }
116
125
  async package() {
117
126
  var _sourceMap;
118
- let wrappedAssets = await this.loadAssets();
127
+ let {
128
+ wrapped: wrappedAssets,
129
+ constant: constantAssets
130
+ } = await this.loadAssets();
119
131
  this.buildExportedSymbols();
120
132
 
121
133
  // If building a library, the target is actually another bundler rather
@@ -132,9 +144,13 @@ class ScopeHoistingPackager {
132
144
  }
133
145
  let res = '';
134
146
  let lineCount = 0;
147
+ // @ts-expect-error TS7034
135
148
  let sourceMap = null;
136
149
  let processAsset = asset => {
150
+ this.seenHoistedRequires.clear();
137
151
  let [content, map, lines] = this.visitAsset(asset);
152
+
153
+ // @ts-expect-error TS7005
138
154
  if (sourceMap && map) {
139
155
  sourceMap.addSourceMap(map, lineCount);
140
156
  } else if (this.bundle.env.sourceMap) {
@@ -143,6 +159,14 @@ class ScopeHoistingPackager {
143
159
  res += content + '\n';
144
160
  lineCount += lines + 1;
145
161
  };
162
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) {
163
+ // Write out all constant modules used by this bundle
164
+ for (let asset of constantAssets) {
165
+ if (!this.seenAssets.has(asset.id)) {
166
+ processAsset(asset);
167
+ }
168
+ }
169
+ }
146
170
 
147
171
  // Hoist wrapped asset to the top of the bundle to ensure that they are registered
148
172
  // before they are used.
@@ -165,16 +189,28 @@ class ScopeHoistingPackager {
165
189
  let [prelude, preludeLines] = this.buildBundlePrelude();
166
190
  res = prelude + res;
167
191
  lineCount += preludeLines;
192
+ // @ts-expect-error TS2339
168
193
  (_sourceMap = sourceMap) === null || _sourceMap === void 0 || _sourceMap.offsetLines(1, preludeLines);
169
194
  let entries = this.bundle.getEntryAssets();
170
195
  let mainEntry = this.bundle.getMainEntry();
171
196
  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
- });
197
+ if (this.useBothScopeHoistingImprovements || (0, _featureFlags().getFeatureFlag)('supportWebpackChunkName')) {
198
+ // Generally speaking, async bundles should not be executed on load, as
199
+ // they're just collections of assets that other assets require.
200
+ // However, there are some special cases where a runtime asset needs to be
201
+ // injected, but no other asset will require it (mostly the bundle
202
+ // manifest).
203
+ // In this case, those assets need to be required on load.
204
+ entries = entries.filter(a => {
205
+ var _a$meta;
206
+ return (_a$meta = a.meta) === null || _a$meta === void 0 ? void 0 : _a$meta.runtimeAssetRequiringExecutionOnLoad;
207
+ });
208
+ } else {
209
+ entries = entries.filter(a => {
210
+ var _mainEntry;
211
+ return a.id !== ((_mainEntry = mainEntry) === null || _mainEntry === void 0 ? void 0 : _mainEntry.id);
212
+ });
213
+ }
178
214
  mainEntry = null;
179
215
  }
180
216
  let needsBundleQueue = this.shouldBundleQueue(this.bundle);
@@ -218,6 +254,7 @@ class ScopeHoistingPackager {
218
254
  }
219
255
  res += (0, _utils2.replaceScriptDependencies)(this.bundleGraph, this.bundle, code, map, this.parcelRequireName);
220
256
  if (sourceMap && map) {
257
+ // @ts-expect-error TS2339
221
258
  sourceMap.addSourceMap(map, lineCount);
222
259
  }
223
260
  }
@@ -231,18 +268,18 @@ class ScopeHoistingPackager {
231
268
  let hasHtmlReference = referencingBundles.some(b => b.type === 'html');
232
269
  let hasConditionalReference = false;
233
270
  let isConditionalBundle = false;
234
- if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && (0, _featureFlags().getFeatureFlag)('conditionalBundlingAsyncRuntime')) {
271
+ if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi')) {
235
272
  // If the bundle has a conditional bundle reference (has an importCond)
236
273
  hasConditionalReference = this.bundleGraph.getReferencedConditionalBundles(bundle).length > 0;
237
274
  // If the bundle is a conditional bundle
238
275
  isConditionalBundle = this.hasConditionalDependency();
239
276
  }
240
- return this.useAsyncBundleRuntime && bundle.type === 'js' && bundle.bundleBehavior !== 'inline' && bundle.env.outputFormat === 'esmodule' && !bundle.env.isIsolated() && bundle.bundleBehavior !== 'isolated' && (hasHtmlReference || hasConditionalReference || isConditionalBundle);
277
+ 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
278
  }
242
279
  runWhenReady(bundle, codeToRun) {
243
280
  let deps = this.bundleGraph.getReferencedBundles(bundle).filter(b => this.shouldBundleQueue(b)).map(b => b.publicId);
244
281
  const conditions = [];
245
- if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && (0, _featureFlags().getFeatureFlag)('conditionalBundlingAsyncRuntime')) {
282
+ if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi')) {
246
283
  const conditionSet = this.bundleGraph.getConditionalBundleMapping().get(bundle.id);
247
284
  for (const [key, {
248
285
  ifTrueBundles,
@@ -265,6 +302,7 @@ class ScopeHoistingPackager {
265
302
  maxConcurrent: 32
266
303
  });
267
304
  let wrapped = [];
305
+ let constant = [];
268
306
  this.bundle.traverseAssets(asset => {
269
307
  queue.add(async () => {
270
308
  let [code, map] = await Promise.all([asset.getCode(), this.bundle.env.sourceMap ? asset.getMapBuffer() : null]);
@@ -278,38 +316,91 @@ class ScopeHoistingPackager {
278
316
  if (!asset.meta.isConstantModule || this.bundleGraph.getIncomingDependencies(asset).some(dep => dep.priority === 'lazy')) {
279
317
  this.wrappedAssets.add(asset.id);
280
318
  wrapped.push(asset);
319
+ } else if (((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') || this.useBothScopeHoistingImprovements) && asset.meta.isConstantModule) {
320
+ constant.push(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.id)) {
334
+ this.wrappedAssets.add(entryAsset.id);
335
+ wrapped.push(entryAsset);
336
+ }
304
337
  }
305
- if (!asset.meta.isConstantModule) {
306
- this.wrappedAssets.add(asset.id);
307
- wrapped.push(asset);
338
+ }
339
+ let moduleGroupParents = [...wrapped];
340
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
341
+ // The main entry needs to be check to find assets that would have gone in
342
+ // the top level scope
343
+ let mainEntry = this.bundle.getMainEntry();
344
+ if (mainEntry && !this.wrappedAssets.has(mainEntry.id)) {
345
+ moduleGroupParents.unshift(mainEntry);
308
346
  }
309
- }, wrappedAssetRoot);
347
+ }
348
+ for (let moduleGroupParentAsset of moduleGroupParents) {
349
+ this.bundle.traverseAssets((asset, _, actions) => {
350
+ if (asset === moduleGroupParentAsset) {
351
+ return;
352
+ }
353
+ if (this.wrappedAssets.has(asset.id)) {
354
+ actions.skipChildren();
355
+ return;
356
+ }
357
+ if (!asset.meta.isConstantModule && (assignedAssets.has(asset) || this.isReExported(asset))) {
358
+ wrapped.push(asset);
359
+ this.wrappedAssets.add(asset.id);
360
+
361
+ // This also needs to be added to the traversal so that we iterate
362
+ // it during this check.
363
+ moduleGroupParents.push(asset);
364
+ actions.skipChildren();
365
+ return;
366
+ }
367
+ assignedAssets.add(asset);
368
+ }, moduleGroupParentAsset);
369
+ }
370
+ } else {
371
+ for (let wrappedAssetRoot of [...wrapped]) {
372
+ this.bundle.traverseAssets((asset, _, actions) => {
373
+ if (asset === wrappedAssetRoot) {
374
+ return;
375
+ }
376
+ if (this.wrappedAssets.has(asset.id)) {
377
+ actions.skipChildren();
378
+ return;
379
+ }
380
+ if (!asset.meta.isConstantModule) {
381
+ this.wrappedAssets.add(asset.id);
382
+ wrapped.push(asset);
383
+ }
384
+ }, wrappedAssetRoot);
385
+ }
310
386
  }
387
+
388
+ // @ts-expect-error TS2769
311
389
  this.assetOutputs = new Map(await queue.run());
312
- return wrapped;
390
+ return {
391
+ wrapped,
392
+ constant
393
+ };
394
+ }
395
+ isReExported(asset) {
396
+ let parentSymbols = this.bundleGraph.getIncomingDependencies(asset).map(dep => this.bundleGraph.getAssetWithDependency(dep)).flatMap(parent => {
397
+ if (parent == null) {
398
+ return [];
399
+ }
400
+ return this.bundleGraph.getExportedSymbols(parent, this.bundle);
401
+ });
402
+ let assetSymbols = this.bundleGraph.getExportedSymbols(asset, this.bundle);
403
+ return assetSymbols.some(assetSymbol => parentSymbols.some(parentSymbol => parentSymbol.symbol === assetSymbol.symbol));
313
404
  }
314
405
  buildExportedSymbols() {
315
406
  if (!this.bundle.env.isLibrary || this.bundle.env.outputFormat !== 'esmodule') {
@@ -395,6 +486,9 @@ class ScopeHoistingPackager {
395
486
  } = (0, _nullthrows().default)(this.assetOutputs.get(asset.id));
396
487
  return this.buildAsset(asset, code, map);
397
488
  }
489
+ getAssetFilePath(asset) {
490
+ return _path().default.relative(this.options.projectRoot, asset.filePath);
491
+ }
398
492
  buildAsset(asset, code, map) {
399
493
  let shouldWrap = this.wrappedAssets.has(asset.id);
400
494
  let deps = this.bundleGraph.getDependencies(asset);
@@ -420,6 +514,7 @@ class ScopeHoistingPackager {
420
514
  let [code, map, lines] = this.visitAsset(resolved);
421
515
  depCode += code + '\n';
422
516
  if (sourceMap && map) {
517
+ // @ts-expect-error TS2551
423
518
  sourceMap.addSourceMap(map, lineCount);
424
519
  }
425
520
  lineCount += lines + 1;
@@ -445,6 +540,7 @@ class ScopeHoistingPackager {
445
540
  }
446
541
  code += append;
447
542
  let lineCount = 0;
543
+ // @ts-expect-error TS2552
448
544
  let depContent = [];
449
545
  if (depMap.size === 0 && replacements.size === 0) {
450
546
  // If there are no dependencies or replacements, use a simple function to count the number of lines.
@@ -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;
584
+ if (!(0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
585
+ [res, lines] = this.getHoistedParcelRequires(asset, dep, resolved);
586
+ }
487
587
  if (this.bundle.hasAsset(resolved) && !this.seenAssets.has(resolved.id)) {
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.id)) {
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
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
549
682
  sourceMap.addSourceMap(map, lineCount);
550
683
  }
551
684
  lineCount += lines + 1;
@@ -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,6 +845,8 @@ ${code}
711
845
  continue;
712
846
  }
713
847
  }
848
+
849
+ // @ts-expect-error TS2322
714
850
  renamed = this.bundleGraph.getSymbolResolution(entry, imported, this.bundle).symbol;
715
851
  }
716
852
  }
@@ -856,8 +992,17 @@ ${code}
856
992
  }
857
993
  if (hoisted) {
858
994
  this.needsPrelude = true;
859
- res += '\n' + [...hoisted.values()].join('\n');
860
- lineCount += hoisted.size;
995
+ if ((0, _featureFlags().getFeatureFlag)('applyScopeHoistingImprovementV2')) {
996
+ let hoistedValues = [...hoisted.values()].filter(val => !this.seenHoistedRequires.has(val));
997
+ for (let val of hoistedValues) {
998
+ this.seenHoistedRequires.add(val);
999
+ }
1000
+ res += '\n' + hoistedValues.join('\n');
1001
+ lineCount += hoisted.size;
1002
+ } else {
1003
+ res += '\n' + [...hoisted.values()].join('\n');
1004
+ lineCount += hoisted.size;
1005
+ }
861
1006
  }
862
1007
  return [res, lineCount];
863
1008
  }
@@ -874,20 +1019,28 @@ ${code}
874
1019
  // If there's no __esModule flag, and default is a used symbol, we need
875
1020
  // to insert an interop helper.
876
1021
  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();
1022
+ let usedNamespace;
1023
+ if ((0, _featureFlags().getFeatureFlag)('inlineConstOptimisationFix') && asset.meta.isConstantModule) {
1024
+ // Only set usedNamespace if there is an incoming dependency in the current bundle that uses '*'
1025
+ usedNamespace = this.bundleGraph.getIncomingDependencies(asset).some(dep => this.bundle.hasDependency(dep) && (0, _nullthrows().default)(this.bundleGraph.getUsedSymbols(dep)).has('*'));
1026
+ } else {
1027
+ usedNamespace =
1028
+ // If the asset has * in its used symbols, we might need the exports namespace.
1029
+ // The one case where this isn't true is in ESM library entries, where the only
1030
+ // dependency on * is the entry dependency. In this case, we will use ESM exports
1031
+ // instead of the namespace object.
1032
+
1033
+ 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('*'))) ||
1034
+ // If a symbol is imported (used) from a CJS asset but isn't listed in the symbols,
1035
+ // we fallback on the namespace object.
1036
+
1037
+ asset.symbols.hasExportSymbol('*') && [...usedSymbols].some(s => !asset.symbols.hasExportSymbol(s)) ||
1038
+ // If the exports has this asset's namespace (e.g. ESM output from CJS input),
1039
+ // include the namespace object for the default export.
1040
+ this.exportedSymbols.has(`$${assetId}$exports`) ||
1041
+ // CommonJS library bundle entries always need a namespace.
1042
+ this.bundle.env.isLibrary && this.bundle.env.outputFormat === 'commonjs' && asset === this.bundle.getMainEntry();
1043
+ }
891
1044
 
892
1045
  // If the asset doesn't have static exports, should wrap, the namespace is used,
893
1046
  // or we need default interop, then we need to synthesize a namespace object for
@@ -905,6 +1058,7 @@ ${code}
905
1058
  // Insert the __esModule interop flag for this module if it has a `default` export
906
1059
  // and the namespace symbol is used.
907
1060
  // TODO: only if required by CJS?
1061
+
908
1062
  if (asset.symbols.hasExportSymbol('default') && usedSymbols.has('*')) {
909
1063
  prepend += `\n$parcel$defineInteropFlag($${assetId}$exports);\n`;
910
1064
  prependLineCount += 2;
@@ -988,16 +1142,22 @@ ${code}
988
1142
  // for the symbol so that when the value changes the object property also changes. This is
989
1143
  // required to simulate ESM live bindings. It's easier to do it this way rather than inserting
990
1144
  // additional assignments after each mutation of the original binding.
991
- prepend += `\n${usedExports.map(exp => {
1145
+ for (let exp of usedExports) {
992
1146
  var _asset$symbols$get2;
993
1147
  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;
1148
+ const meta = (_asset$symbols$get2 = asset.symbols.get(exp)) === null || _asset$symbols$get2 === void 0 ? void 0 : _asset$symbols$get2.meta;
1149
+ if ((0, _featureFlags().getFeatureFlag)('exportsRebindingOptimisation') && meta !== null && meta !== void 0 && meta.isStaticBindingSafe) {
1150
+ append += `$${assetId}$exports[${JSON.stringify(exp)}] = ${resolved};\n`;
1151
+ } else {
1152
+ var _asset$symbols$get3;
1153
+ let get = this.buildFunctionExpression([], resolved);
1154
+ 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);
1155
+ let set = !isEsmExport && asset.meta.hasCJSExports ? ', ' + this.buildFunctionExpression(['v'], `${resolved} = v`) : '';
1156
+ prepend += `$parcel$export($${assetId}$exports, ${JSON.stringify(exp)}, ${get}${set});\n`;
1157
+ this.usedHelpers.add('$parcel$export');
1158
+ prependLineCount += 1 + usedExports.length;
1159
+ }
1160
+ }
1001
1161
  }
1002
1162
  }
1003
1163
  return [prepend, prependLineCount, append];
@@ -1028,8 +1188,10 @@ ${code}
1028
1188
  this.usedHelpers.add('$parcel$global');
1029
1189
  }
1030
1190
  for (let helper of this.usedHelpers) {
1191
+ // @ts-expect-error TS7053
1031
1192
  let currentHelper = _helpers.helpers[helper];
1032
1193
  if (typeof currentHelper === 'function') {
1194
+ // @ts-expect-error TS7053
1033
1195
  currentHelper = _helpers.helpers[helper](this.bundle.env);
1034
1196
  }
1035
1197
  res += currentHelper;
@@ -1041,11 +1203,11 @@ ${code}
1041
1203
  // Add the prelude if this is potentially the first JS bundle to load in a
1042
1204
  // particular context (e.g. entry scripts in HTML, workers, etc.).
1043
1205
  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' ||
1206
+ 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
1207
  // Conditional deps may be loaded before entrypoints on the server
1046
1208
  this.hasConditionalDependency();
1047
1209
  if (mightBeFirstJS) {
1048
- let preludeCode = (0, _helpers.prelude)(this.parcelRequireName);
1210
+ let preludeCode = ((0, _featureFlags().getFeatureFlag)('useNewPrelude') ? _helpers.preludeNew : _helpers.preludeOld)(this.parcelRequireName);
1049
1211
  res += preludeCode;
1050
1212
  if (enableSourceMaps) {
1051
1213
  lines += (0, _utils().countLines)(preludeCode) - 1;
@@ -1068,7 +1230,7 @@ ${code}
1068
1230
  }
1069
1231
 
1070
1232
  // Add importScripts for sibling bundles in workers.
1071
- if (this.bundle.env.isWorker() || this.bundle.env.isWorklet()) {
1233
+ if (this.bundle.env.isWorker() || this.bundle.env.isTesseract() || this.bundle.env.isWorklet()) {
1072
1234
  let importScripts = '';
1073
1235
  let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
1074
1236
  for (let b of bundles) {
@@ -12,12 +12,12 @@
12
12
  typeof globalThis !== 'undefined'
13
13
  ? globalThis
14
14
  : typeof self !== 'undefined'
15
- ? self
16
- : typeof window !== 'undefined'
17
- ? window
18
- : typeof global !== 'undefined'
19
- ? global
20
- : {};
15
+ ? self
16
+ : typeof window !== 'undefined'
17
+ ? window
18
+ : typeof global !== 'undefined'
19
+ ? global
20
+ : {};
21
21
  /* eslint-enable no-undef */
22
22
 
23
23
  // Save the require from previous bundle to this closure if any
package/lib/helpers.js CHANGED
@@ -3,8 +3,8 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.prelude = exports.helpers = exports.fnExpr = exports.bundleQueuePrelude = void 0;
7
- const prelude = parcelRequireName => `
6
+ exports.preludeOld = exports.preludeNew = exports.helpers = exports.fnExpr = exports.bundleQueuePrelude = void 0;
7
+ const preludeOld = parcelRequireName => `
8
8
  var $parcel$modules = {};
9
9
  var $parcel$inits = {};
10
10
 
@@ -37,7 +37,42 @@ if (parcelRequire == null) {
37
37
 
38
38
  var parcelRegister = parcelRequire.register;
39
39
  `;
40
- exports.prelude = prelude;
40
+ exports.preludeOld = preludeOld;
41
+ const preludeNew = parcelRequireName => `
42
+ var $parcel$modules = {};
43
+ var $parcel$inits = {};
44
+
45
+ var parcelRequire = $parcel$global[${JSON.stringify(parcelRequireName)}];
46
+
47
+ if (parcelRequire == null) {
48
+ parcelRequire = function(id) {
49
+ var mod = $parcel$modules[id];
50
+ if (mod !== undefined) {
51
+ return mod.exports;
52
+ }
53
+ var init = $parcel$inits[id];
54
+ if (init !== undefined) {
55
+ delete $parcel$inits[id];
56
+ var module = {id: id, exports: {}};
57
+ $parcel$modules[id] = module;
58
+ init.call(module.exports, module, module.exports);
59
+ return module.exports;
60
+ }
61
+ var err = new Error("Cannot find module '" + id + "'");
62
+ err.code = 'MODULE_NOT_FOUND';
63
+ throw err;
64
+ };
65
+
66
+ parcelRequire.register = function register(id, init) {
67
+ $parcel$inits[id] = init;
68
+ };
69
+
70
+ $parcel$global[${JSON.stringify(parcelRequireName)}] = parcelRequire;
71
+ }
72
+
73
+ var parcelRegister = parcelRequire.register;
74
+ `;
75
+ exports.preludeNew = preludeNew;
41
76
  const fnExpr = (env, params, body) => {
42
77
  let block = `{ ${body.join(' ')} }`;
43
78
  if (env.supports('arrow-functions')) {