@rollup/wasm-node 5.0.0-0 → 5.0.0-2

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.
Files changed (50) hide show
  1. package/LICENSE.md +0 -17
  2. package/dist/bin/rollup +119 -108
  3. package/dist/es/getLogFilter.js +2 -2
  4. package/dist/es/parseAst.js +2 -2
  5. package/dist/es/rollup.js +2 -2
  6. package/dist/es/shared/node-entry.js +1637 -1092
  7. package/dist/es/shared/parseAst.js +123 -31
  8. package/dist/es/shared/watch.js +3204 -1008
  9. package/dist/getLogFilter.js +2 -2
  10. package/dist/loadConfigFile.js +2 -2
  11. package/dist/native.js +19 -3
  12. package/dist/parseAst.js +2 -2
  13. package/dist/rollup.android-arm-eabi.node +0 -0
  14. package/dist/rollup.android-arm64.node +0 -0
  15. package/dist/rollup.android-x64.node +0 -0
  16. package/dist/rollup.d.ts +23 -9
  17. package/dist/rollup.darwin-arm64.node +0 -0
  18. package/dist/rollup.darwin-x64.node +0 -0
  19. package/dist/rollup.freebsd-arm64.node +0 -0
  20. package/dist/rollup.freebsd-x64.node +0 -0
  21. package/dist/rollup.js +2 -2
  22. package/dist/rollup.linux-arm-gnueabihf.node +0 -0
  23. package/dist/rollup.linux-arm-musleabihf.node +0 -0
  24. package/dist/rollup.linux-arm64-gnu.node +0 -0
  25. package/dist/rollup.linux-arm64-musl.node +0 -0
  26. package/dist/rollup.linux-loong64-gnu.node +0 -0
  27. package/dist/rollup.linux-loong64-musl.node +0 -0
  28. package/dist/rollup.linux-ppc64-gnu.node +0 -0
  29. package/dist/rollup.linux-ppc64-musl.node +0 -0
  30. package/dist/rollup.linux-riscv64-gnu.node +0 -0
  31. package/dist/rollup.linux-riscv64-musl.node +0 -0
  32. package/dist/rollup.linux-s390x-gnu.node +0 -0
  33. package/dist/rollup.linux-x64-gnu.node +0 -0
  34. package/dist/rollup.linux-x64-musl.node +0 -0
  35. package/dist/rollup.openbsd-x64.node +0 -0
  36. package/dist/rollup.openharmony-arm64.node +0 -0
  37. package/dist/rollup.win32-arm64-msvc.node +0 -0
  38. package/dist/rollup.win32-ia32-msvc.node +0 -0
  39. package/dist/rollup.win32-x64-gnu.node +0 -0
  40. package/dist/rollup.win32-x64-msvc.node +0 -0
  41. package/dist/shared/index.js +3198 -1002
  42. package/dist/shared/loadConfigFile.js +2 -2
  43. package/dist/shared/node-entry.js +2 -2
  44. package/dist/shared/parseAst.js +129 -37
  45. package/dist/shared/rollup.js +1594 -1049
  46. package/dist/shared/watch-cli.js +2 -2
  47. package/dist/shared/watch.js +2 -2
  48. package/dist/wasm-node/bindings_wasm.js +2 -18
  49. package/dist/wasm-node/bindings_wasm_bg.wasm +0 -0
  50. package/package.json +26 -26
@@ -1,15 +1,15 @@
1
1
  /*
2
2
  @license
3
- Rollup.js v5.0.0-0
4
- Tue, 06 Oct 2026 08:24:44 GMT - commit d78bf6bee48e411672e05d8977473f76e6758c35
3
+ Rollup.js v5.0.0-2
4
+ Sun, 01 Nov 2026 08:56:25 GMT - commit 4009894760dbcbff5ba6cefa494787cc54ffaa62
5
5
 
6
6
  https://github.com/rollup/rollup
7
7
 
8
8
  Released under the MIT License.
9
9
  */
10
- import { EMPTY_OBJECT, ExportDefaultDeclaration as ExportDefaultDeclaration$1, CallExpression as CallExpression$1, EMPTY_ARRAY, Program as Program$1, logRedeclarationError, LOGLEVEL_WARN, logUnusedExternalImports, Identifier as Identifier$1, ObjectExpression as ObjectExpression$1, FunctionExpression as FunctionExpression$1, ArrowFunctionExpression as ArrowFunctionExpression$1, Property as Property$1, logIllegalImportReassignment, BLANK, StaticBlock as StaticBlock$1, CatchClause as CatchClause$1, logDuplicateArgumentNameError, logModuleLevelDirective, ReturnStatement as ReturnStatement$1, VariableDeclarator as VariableDeclarator$1, ExpressionStatement as ExpressionStatement$1, logMissingExport, normalize, getImportPath, error, logSourcePhaseFormatUnsupported, logMissingNodeBuiltins, logReservedNamespace, logIllegalIdentifierAsName, logMissingNameOptionForIifeExport, logMissingNameOptionForUmdExport, RestElement as RestElement$1, logConstVariableReassignError, FunctionDeclaration as FunctionDeclaration$1, EMPTY_SET, logCannotCallNamespace, logEval, IfStatement as IfStatement$1, BlockStatement as BlockStatement$1, AwaitExpression as AwaitExpression$1, MemberExpression as MemberExpression$1, getRollupError, logParseError, logModuleParseError, LOGLEVEL_INFO, logFirstSideEffect, locate, logInvalidAnnotation, logThisIsUndefined, getAstBuffer, nodeTypeStrings, convertAnnotations, FIXED_STRINGS, convertNode as convertNode$1, logImportAttributeIsInvalid, logImportOptionsAreInvalid, logMissingEntryExport, logSyntheticNamedExportsNeedNamespaceExport, logDuplicateExportError, logInvalidSourcemapForError, augmentCodeLocation, logMissingJsxExport, logNamespaceConflict, logAmbiguousExternalNamespaces, logShimmedExport, deserializeLazyAst, TemplateLiteral as TemplateLiteral$1, Literal as Literal$1, logCircularReexport, logInvalidFormatForTopLevelAwait, logAddonNotGenerated, logIncompatibleExportOptionValue, logMixedExport, logFailedValidation, isPathFragment, logCyclicCrossChunkReexport, getAliasName, logUnexpectedNamedImport, isAbsolute as isAbsolute$1, relative as relative$1, logUnexpectedNamespaceReexport, logEmptyChunk, logMissingGlobalName, logAmbiguousGlobalName, logEmptyManualChunk, logOptimizeChunkStatus, logSourcemapBroken, logConflictingSourcemapSources, parseAst, logChunkInvalid, logInvalidOption, URL_OUTPUT_FORMAT, URL_OUTPUT_DIR, URL_OUTPUT_SOURCEMAPFILE, URL_OUTPUT_AMD_ID, logFileNameOutsideOutputDirectory, logCannotAssignModuleToChunk, logCircularChunk, logUnknownOption, printQuotedStringList, LOGLEVEL_ERROR, logLevelPriority, LOGLEVEL_DEBUG, logInvalidLogPosition, logAnonymousPluginCache, logDuplicatePluginName, parseAndWalk, logPluginError, warnDeprecation, URL_THIS_RESOLVE, logInvalidSetAssetSourceCall, serializeAst, logNoTransformMapOrAstWithoutCode, URL_TRANSFORM, relativeId, logBadLoader, logNonExternalSourcePhaseImport, logInternalIdCannotBeExternal, isRelative, logUnresolvedImport, logUnresolvedImportTreatedAsExternal, logExternalSyntheticExports, logUnresolvedEntry, logUnresolvedImplicitDependant, logExternalModulesCannotBeIncludedInManualChunks, logEntryCannotBeExternal, logImplicitDependantCannotBeExternal, logExternalModulesCannotBeTransformedToModules, URL_LOAD, logNoAssetSourceSet, logFileReferenceIdNotFoundForFilename, logAssetReferenceIdNotFoundForSetSource, logAssetSourceAlreadySet, logInvalidRollupPhaseForChunkEmission, logChunkNotGeneratedForFileName, logAssetNotFinalisedForFileName, logFileNameConflict, URL_GENERATEBUNDLE, logInputHookInOutputPlugin, logInvalidAddonPluginHook, logInvalidFunctionPluginHook, logImplicitDependantIsNotIncluded, logCircularDependency, augmentLogMessage, URL_JSX, URL_TREESHAKE, URL_TREESHAKE_MODULESIDEEFFECTS, URL_OUTPUT_INLINEDYNAMICIMPORTS, URL_PRESERVEENTRYSIGNATURES, URL_OUTPUT_GENERATEDCODE, isValidUrl, addTrailingSlashIfMissed, URL_OUTPUT_SOURCEMAPBASEURL, URL_OUTPUT_MANUALCHUNKS, logInvalidExportOptionValue, URL_OUTPUT_AMD_BASEPATH, URL_OUTPUT_INTEROP, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, URL_OUTPUT_IMPORTATTRIBUTESKEY, logAlreadyClosed, logMissingFileOrDirOption, logCannotEmitFromOptionsHook, URL_WATCH } from './parseAst.js';
10
+ import { EMPTY_OBJECT, ArrowFunctionExpression as ArrowFunctionExpression$1, FunctionExpression as FunctionExpression$1, Identifier as Identifier$1, ObjectExpression as ObjectExpression$1, ExportDefaultDeclaration as ExportDefaultDeclaration$1, CallExpression as CallExpression$1, EMPTY_ARRAY, Program as Program$1, logRedeclarationError, LOGLEVEL_WARN, logUnusedExternalImports, Property as Property$1, logIllegalImportReassignment, BLANK, StaticBlock as StaticBlock$1, CatchClause as CatchClause$1, logDuplicateArgumentNameError, logModuleLevelDirective, ReturnStatement as ReturnStatement$1, VariableDeclarator as VariableDeclarator$1, ExpressionStatement as ExpressionStatement$1, logMissingExport, normalize, getImportPath, error, logSourcePhaseFormatUnsupported, logMissingNodeBuiltins, logReservedNamespace, logIllegalIdentifierAsName, logMissingNameOptionForIifeExport, logMissingNameOptionForUmdExport, RestElement as RestElement$1, logConstVariableReassignError, FunctionDeclaration as FunctionDeclaration$1, EMPTY_SET, logCannotCallNamespace, logEval, IfStatement as IfStatement$1, BlockStatement as BlockStatement$1, AwaitExpression as AwaitExpression$1, MemberExpression as MemberExpression$1, getRollupError, logParseError, logModuleParseError, LOGLEVEL_INFO, logFirstSideEffect, locate, logInvalidAnnotation, logThisIsUndefined, getAstBuffer, nodeTypeStrings, convertAnnotations, FIXED_STRINGS, convertNode as convertNode$1, isAbsolute as isAbsolute$1, logImportAttributeIsInvalid, logImportOptionsAreInvalid, logMissingEntryExport, logSyntheticNamedExportsNeedNamespaceExport, logDuplicateExportError, logInvalidSourcemapForError, augmentCodeLocation, logMissingJsxExport, logNamespaceConflict, logAmbiguousExternalNamespaces, logShimmedExport, deserializeLazyAst, TemplateLiteral as TemplateLiteral$1, Literal as Literal$1, logCircularReexport, logInvalidFormatForTopLevelAwait, logAddonNotGenerated, logIncompatibleExportOptionValue, logMixedExport, logFailedValidation, isPathFragment, logCyclicCrossChunkReexport, getAliasName, logUnexpectedNamedImport, relative as relative$1, logUnexpectedNamespaceReexport, logEmptyChunk, logMissingGlobalName, logAmbiguousGlobalName, logEmptyManualChunk, logOptimizeChunkStatus, logSourcemapBroken, logConflictingSourcemapSources, logErrorInHook, parseAst, logChunkInvalid, logInvalidOption, URL_OUTPUT_FORMAT, URL_OUTPUT_DIR, URL_OUTPUT_SOURCEMAPFILE, URL_OUTPUT_AMD_ID, logFileNameOutsideOutputDirectory, logCannotAssignModuleToChunk, logCircularChunk, logUnknownOption, printQuotedStringList, LOGLEVEL_ERROR, logLevelPriority, LOGLEVEL_DEBUG, logInvalidLogPosition, logAnonymousPluginCache, logDuplicatePluginName, parseAndWalk, logPluginError, warnDeprecation, URL_THIS_RESOLVE, logInvalidSetAssetSourceCall, serializeAst, logNoTransformMapOrAstWithoutCode, URL_TRANSFORM, logNonExternalSourcePhaseImport, relativeId, logInternalIdCannotBeExternal, isRelative, logUnresolvedImport, logUnresolvedImportTreatedAsExternal, logExternalSyntheticExports, logUnresolvedEntry, logUnresolvedImplicitDependant, logExternalModulesCannotBeIncludedInManualChunks, logEntryCannotBeExternal, logImplicitDependantCannotBeExternal, logBadLoader, logExternalModulesCannotBeTransformedToModules, URL_LOAD, logNoAssetSourceSet, logFileReferenceIdNotFoundForFilename, logAssetReferenceIdNotFoundForSetSource, logAssetSourceAlreadySet, logInvalidRollupPhaseForChunkEmission, logChunkNotGeneratedForFileName, logAssetNotFinalisedForFileName, logFileNameConflict, URL_GENERATEBUNDLE, logInputHookInOutputPlugin, logInvalidAddonPluginHook, logInvalidFunctionPluginHook, logImplicitDependantIsNotIncluded, logCircularDependency, augmentLogMessage, URL_JSX, URL_TREESHAKE, URL_TREESHAKE_MODULESIDEEFFECTS, URL_OUTPUT_INLINEDYNAMICIMPORTS, URL_PRESERVEENTRYSIGNATURES, URL_OUTPUT_GENERATEDCODE, isValidUrl, addTrailingSlashIfMissed, URL_OUTPUT_SOURCEMAPBASEURL, URL_OUTPUT_MANUALCHUNKS, logInvalidExportOptionValue, URL_OUTPUT_AMD_BASEPATH, URL_OUTPUT_INTEROP, URL_OUTPUT_IMPORTATTRIBUTESKEY, logAlreadyClosed, logMissingFileOrDirOption, logCannotEmitFromOptionsHook, URL_WATCH } from './parseAst.js';
11
11
  import { relative, dirname, basename, extname, resolve as resolve$1, join } from 'node:path';
12
- import { posix, isAbsolute, resolve, win32 } from 'path';
12
+ import { isAbsolute, posix, win32, resolve } from 'path';
13
13
  import process$1, { env } from 'node:process';
14
14
  import { performance } from 'node:perf_hooks';
15
15
  import { xxhashBase16, xxhashBase64Url, xxhashBase36, parseAsync } from '../../native.js';
@@ -27,7 +27,7 @@ function _mergeNamespaces(n, m) {
27
27
  return Object.defineProperty(n, Symbol.toStringTag, { value: 'Module' });
28
28
  }
29
29
 
30
- var version = "5.0.0-0";
30
+ var version = "5.0.0-2";
31
31
  const pkg = {
32
32
  version: version};
33
33
 
@@ -232,6 +232,17 @@ var BitSet = class BitSet {
232
232
  has(n) {
233
233
  return !!(this.bits[n >> 5] & 1 << (n & 31));
234
234
  }
235
+ forEach(fn) {
236
+ const bits = this.bits;
237
+ for (let w = 0; w < bits.length; w++) {
238
+ let word = bits[w];
239
+ while (word) {
240
+ const lowest = word & -word;
241
+ fn((w << 5) + 31 - Math.clz32(lowest));
242
+ word ^= lowest;
243
+ }
244
+ }
245
+ }
235
246
  };
236
247
  //#endregion
237
248
  //#region src/Chunk.ts
@@ -245,6 +256,8 @@ var Chunk$1 = class Chunk {
245
256
  this.content = content;
246
257
  this.storeName = false;
247
258
  this.edited = false;
259
+ this.replacesUntil = -1;
260
+ this.replacedFrom = -1;
248
261
  this.previous = null;
249
262
  this.next = null;
250
263
  }
@@ -261,6 +274,8 @@ var Chunk$1 = class Chunk {
261
274
  chunk.content = this.content;
262
275
  chunk.storeName = this.storeName;
263
276
  chunk.edited = this.edited;
277
+ chunk.replacesUntil = this.replacesUntil;
278
+ chunk.replacedFrom = this.replacedFrom;
264
279
  return chunk;
265
280
  }
266
281
  contains(index) {
@@ -301,6 +316,8 @@ var Chunk$1 = class Chunk {
301
316
  reset() {
302
317
  this.intro = "";
303
318
  this.outro = "";
319
+ this.replacesUntil = -1;
320
+ this.replacedFrom = -1;
304
321
  if (this.edited) {
305
322
  this.content = this.original;
306
323
  this.storeName = false;
@@ -318,7 +335,7 @@ var Chunk$1 = class Chunk {
318
335
  this.end = index;
319
336
  if (this.edited) {
320
337
  newChunk.edit("", false, true);
321
- this.content = "";
338
+ newChunk.replacedFrom = this.replacedFrom;
322
339
  } else this.content = originalBefore;
323
340
  newChunk.next = this.next;
324
341
  if (newChunk.next) newChunk.next.previous = newChunk;
@@ -582,8 +599,8 @@ var Mappings = class {
582
599
  this.generatedCodeColumn = 0;
583
600
  this.raw = [];
584
601
  this.rawSegments = this.raw[this.generatedCodeLine] = [];
585
- this.rawRangeMappings = [];
586
- this.rawRangeMappingsIndices = this.rawRangeMappings[this.generatedCodeLine] = [];
602
+ this.rawRangeMappingsIndices = [];
603
+ this.rawRangeMappings = hires === "experimental-range" ? [this.rawRangeMappingsIndices] : void 0;
587
604
  this.encoder = encoder;
588
605
  }
589
606
  nextLine() {
@@ -596,7 +613,28 @@ var Mappings = class {
596
613
  this.generatedCodeLine += 1;
597
614
  }
598
615
  this.generatedCodeColumn = 0;
599
- this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
616
+ if (this.rawRangeMappings) this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
617
+ }
618
+ /**
619
+ * Emits the mappings for one MagicString: its intro, every chunk (with the
620
+ * chunk's own intro/outro) and its outro. `sourceIndex === -1` means the
621
+ * string has no source of its own, so its content only advances the
622
+ * generated position without mapping anything.
623
+ */
624
+ addMagicString(magicString, sourceIndex, nameIndex) {
625
+ const { original } = magicString;
626
+ const locate = getLocator(original);
627
+ if (magicString.intro) this.advance(magicString.intro);
628
+ magicString.firstChunk.eachNext((chunk) => {
629
+ if (chunk.intro.length) this.advance(chunk.intro);
630
+ if (sourceIndex === -1) this.advance(chunk.content);
631
+ else if (chunk.edited) {
632
+ const name = chunk.storeName ? nameIndex.get(original.slice(chunk.start, chunk.replacesUntil)) : void 0;
633
+ this.addEdit(sourceIndex, chunk.content, locate(chunk.start), name ?? -1);
634
+ } else this.addUneditedChunk(sourceIndex, chunk, original, locate(chunk.start), magicString.sourcemapLocations);
635
+ if (chunk.outro.length) this.advance(chunk.outro);
636
+ });
637
+ if (magicString.outro) this.advance(magicString.outro);
600
638
  }
601
639
  addEdit(sourceIndex, content, loc, nameIndex) {
602
640
  if (content.length) {
@@ -811,6 +849,9 @@ function expandReplacement(replacement, matched, position, str, captures, namedC
811
849
  return result;
812
850
  }
813
851
  var MagicString = class MagicString {
852
+ /**
853
+ * Wraps `string` for editing; every index passed to the editing methods refers to this original string.
854
+ */
814
855
  constructor(string, options = {}) {
815
856
  const chunk = new Chunk$1(0, string.length, string);
816
857
  Object.defineProperties(this, {
@@ -860,7 +901,7 @@ var MagicString = class MagicString {
860
901
  },
861
902
  storedNames: {
862
903
  writable: true,
863
- value: {}
904
+ value: /* @__PURE__ */ new Set()
864
905
  },
865
906
  indentStr: {
866
907
  writable: true,
@@ -900,7 +941,8 @@ var MagicString = class MagicString {
900
941
  * See also `s.prependLeft(...)`.
901
942
  */
902
943
  appendLeft(index, content) {
903
- index = index + this.offset;
944
+ index = this._resolveIndex(index);
945
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
904
946
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
905
947
  this._split(index);
906
948
  const chunk = this.byEnd.get(index);
@@ -914,7 +956,8 @@ var MagicString = class MagicString {
914
956
  * See also `s.prependRight(...)`.
915
957
  */
916
958
  appendRight(index, content) {
917
- index = index + this.offset;
959
+ index = this._resolveIndex(index);
960
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
918
961
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
919
962
  this._split(index);
920
963
  const chunk = this.byStart.get(index);
@@ -923,7 +966,10 @@ var MagicString = class MagicString {
923
966
  return this;
924
967
  }
925
968
  /**
926
- * Does what you'd expect.
969
+ * Returns an independent copy: the chunk list, string-level intro/outro,
970
+ * sourcemap locations, stored names, indent exclusion ranges, `offset`,
971
+ * `filename` and `ignoreList` are all copied; later edits to either string
972
+ * do not affect the other.
927
973
  */
928
974
  clone() {
929
975
  const cloned = new MagicString(this.original, {
@@ -948,7 +994,7 @@ var MagicString = class MagicString {
948
994
  cloned.lastChunk = clonedChunk;
949
995
  if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
950
996
  cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
951
- cloned.storedNames = { ...this.storedNames };
997
+ cloned.storedNames = new Set(this.storedNames);
952
998
  cloned.intro = this.intro;
953
999
  cloned.outro = this.outro;
954
1000
  cloned.hasMovedChunks = this.hasMovedChunks;
@@ -984,18 +1030,8 @@ var MagicString = class MagicString {
984
1030
  }
985
1031
  /** @internal */
986
1032
  _generateMappings(mappings) {
987
- const sourceIndex = 0;
988
- const names = Object.keys(this.storedNames);
989
- const locate = getLocator(this.original);
990
- if (this.intro) mappings.advance(this.intro);
991
- this.firstChunk.eachNext((chunk) => {
992
- const loc = locate(chunk.start);
993
- if (chunk.intro.length) mappings.advance(chunk.intro);
994
- if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
995
- else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
996
- if (chunk.outro.length) mappings.advance(chunk.outro);
997
- });
998
- if (this.outro) mappings.advance(this.outro);
1033
+ const names = [...this.storedNames];
1034
+ mappings.addMagicString(this, 0, new Map(names.map((name, i) => [name, i])));
999
1035
  return names;
1000
1036
  }
1001
1037
  /** @internal */
@@ -1017,9 +1053,13 @@ var MagicString = class MagicString {
1017
1053
  this._ensureindentStr();
1018
1054
  return this.indentStr;
1019
1055
  }
1056
+ /**
1057
+ * Returns the indentation string guessed from the original content, falling back to a single tab character.
1058
+ * This is the value `s.indent()` uses when no prefix is supplied.
1059
+ */
1020
1060
  getIndentString() {
1021
1061
  this._ensureindentStr();
1022
- return this.indentStr === null ? " " : this.indentStr;
1062
+ return this.indentStr ?? " ";
1023
1063
  }
1024
1064
  indent(indentStr, options) {
1025
1065
  const pattern = /^[^\r\n]/gm;
@@ -1034,9 +1074,9 @@ var MagicString = class MagicString {
1034
1074
  if (indentStr === "") return this;
1035
1075
  const resolvedIndentStr = indentStr;
1036
1076
  options = options || {};
1037
- const isExcluded = {};
1077
+ const isExcluded = new BitSet();
1038
1078
  if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
1039
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
1079
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded.add(i);
1040
1080
  });
1041
1081
  let shouldIndentNextCharacter = options.indentStart !== false;
1042
1082
  const indentPiece = (str) => {
@@ -1059,13 +1099,14 @@ var MagicString = class MagicString {
1059
1099
  };
1060
1100
  while (chunk) {
1061
1101
  const end = chunk.end;
1062
- if (!isExcluded[chunk.start]) chunk.intro = indentPiece(chunk.intro);
1102
+ if (!isExcluded.has(chunk.start)) chunk.intro = indentPiece(chunk.intro);
1063
1103
  if (chunk.edited) {
1064
- if (!isExcluded[charIndex]) chunk.content = indentPiece(chunk.content);
1104
+ if (!isExcluded.has(chunk.start)) chunk.content = indentPiece(chunk.content);
1105
+ else if (chunk.content) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1065
1106
  } else if (options.exclude) {
1066
1107
  charIndex = chunk.start;
1067
1108
  while (charIndex < end) {
1068
- if (!isExcluded[charIndex]) {
1109
+ if (!isExcluded.has(charIndex)) {
1069
1110
  const char = this.original.charCodeAt(charIndex);
1070
1111
  if (char === NEWLINE_CHAR) shouldIndentNextCharacter = true;
1071
1112
  else if (char !== CR_CHAR && shouldIndentNextCharacter) indentAt(charIndex);
@@ -1091,7 +1132,7 @@ var MagicString = class MagicString {
1091
1132
  charIndex += 1;
1092
1133
  }
1093
1134
  }
1094
- if (!isExcluded[chunk.end - 1]) chunk.outro = indentPiece(chunk.outro);
1135
+ if (!isExcluded.has(chunk.end - 1)) chunk.outro = indentPiece(chunk.outro);
1095
1136
  charIndex = chunk.end;
1096
1137
  chunk = chunk.next;
1097
1138
  }
@@ -1128,16 +1169,19 @@ var MagicString = class MagicString {
1128
1169
  * mirroring the `appendLeft`/`appendRight` distinction.
1129
1170
  */
1130
1171
  move(start, end, index, affinity = "right") {
1131
- start = start + this.offset;
1132
- end = end + this.offset;
1133
- index = index + this.offset;
1172
+ start = this._resolveIndex(start);
1173
+ end = this._resolveIndex(end);
1174
+ index = this._resolveIndex(index);
1134
1175
  if (start === end) return this;
1176
+ if (start < 0 || end > this.original.length || index < 0 || index > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1177
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1135
1178
  if (index >= start && index <= end) throw new MagicStringError("cannot move a selection inside itself");
1136
1179
  this._split(start);
1137
1180
  this._split(end);
1138
1181
  this._split(index);
1139
1182
  const first = this.byStart.get(start);
1140
1183
  const last = this.byEnd.get(end);
1184
+ if (!first || !last) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1141
1185
  if (this.hasMovedChunks) {
1142
1186
  let cursor = first;
1143
1187
  while (cursor !== last) {
@@ -1172,9 +1216,9 @@ var MagicString = class MagicString {
1172
1216
  if (oldRight) oldRight.previous = oldLeft;
1173
1217
  if (newLeft) newLeft.next = first;
1174
1218
  if (newRight) newRight.previous = last;
1175
- if (!first.previous) this.firstChunk = last.next;
1176
- if (!last.next) {
1177
- this.lastChunk = first.previous;
1219
+ if (!oldLeft) this.firstChunk = oldRight;
1220
+ if (!oldRight) {
1221
+ this.lastChunk = oldLeft;
1178
1222
  this.lastChunk.next = null;
1179
1223
  }
1180
1224
  first.previous = newLeft;
@@ -1195,6 +1239,16 @@ var MagicString = class MagicString {
1195
1239
  * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
1196
1240
  */
1197
1241
  overwrite(start, end, content, options) {
1242
+ if (options === true) {
1243
+ if (!warned.storeName) {
1244
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
1245
+ warned.storeName = true;
1246
+ }
1247
+ return this.update(start, end, content, {
1248
+ storeName: true,
1249
+ overwrite: true
1250
+ });
1251
+ }
1198
1252
  const optionObject = typeof options === "object" && options ? options : {};
1199
1253
  return this.update(start, end, content, {
1200
1254
  ...optionObject,
@@ -1209,13 +1263,9 @@ var MagicString = class MagicString {
1209
1263
  * the content is overwritten, or anything that was appended/prepended to the range as well.
1210
1264
  */
1211
1265
  update(start, end, content, options) {
1212
- start = start + this.offset;
1213
- end = end + this.offset;
1266
+ start = this._resolveIndex(start);
1267
+ end = this._resolveIndex(end);
1214
1268
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1215
- if (this.original.length !== 0) {
1216
- if (start < 0) start = Math.max(0, start + this.original.length);
1217
- if (end < 0) end = Math.max(0, end + this.original.length);
1218
- }
1219
1269
  if (start < 0) throw new MagicStringError(`start ${start} is out of bounds`);
1220
1270
  if (end > this.original.length) throw new MagicStringError(`end ${end} is out of bounds`);
1221
1271
  if (start === end) throw new MagicStringError(`cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`);
@@ -1232,30 +1282,21 @@ var MagicString = class MagicString {
1232
1282
  const optionObject = typeof options === "object" && options ? options : {};
1233
1283
  const storeName = optionObject.storeName || false;
1234
1284
  const overwrite = optionObject.overwrite || false;
1235
- if (storeName) {
1236
- const original = this.original.slice(start, end);
1237
- Object.defineProperty(this.storedNames, original, {
1238
- writable: true,
1239
- value: true,
1240
- enumerable: true
1241
- });
1242
- }
1285
+ if (storeName) this.storedNames.add(this.original.slice(start, end));
1243
1286
  const first = this.byStart.get(start);
1244
- const last = this.byEnd.get(end);
1245
- /* v8 ignore else -- unreachable: a valid start/end always yields a `first` chunk */
1246
- if (first) {
1247
- let chunk = first;
1248
- while (chunk !== last) {
1249
- if (chunk.next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
1250
- chunk = chunk.next;
1251
- chunk.edit("", false);
1252
- }
1253
- first.edit(content, storeName, !overwrite);
1254
- } else {
1255
- const newChunk = new Chunk$1(start, end, "").edit(content, storeName);
1256
- last.next = newChunk;
1257
- newChunk.previous = last;
1287
+ for (let chunk = first; chunk.end < end;) {
1288
+ const next = chunk.next;
1289
+ if (next === null || next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
1290
+ chunk = next;
1291
+ }
1292
+ for (let chunk = first.next; chunk !== null && chunk.start < end; chunk = chunk.next) {
1293
+ chunk.edit("", false, !overwrite);
1294
+ chunk.replacesUntil = -1;
1295
+ chunk.replacedFrom = start;
1258
1296
  }
1297
+ first.edit(content, storeName, !overwrite);
1298
+ first.replacesUntil = end;
1299
+ first.replacedFrom = -1;
1259
1300
  return this;
1260
1301
  }
1261
1302
  /**
@@ -1270,7 +1311,8 @@ var MagicString = class MagicString {
1270
1311
  * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
1271
1312
  */
1272
1313
  prependLeft(index, content) {
1273
- index = index + this.offset;
1314
+ index = this._resolveIndex(index);
1315
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1274
1316
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1275
1317
  this._split(index);
1276
1318
  const chunk = this.byEnd.get(index);
@@ -1282,7 +1324,8 @@ var MagicString = class MagicString {
1282
1324
  * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
1283
1325
  */
1284
1326
  prependRight(index, content) {
1285
- index = index + this.offset;
1327
+ index = this._resolveIndex(index);
1328
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1286
1329
  if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1287
1330
  this._split(index);
1288
1331
  const chunk = this.byStart.get(index);
@@ -1298,12 +1341,8 @@ var MagicString = class MagicString {
1298
1341
  * Repeated removals and removals with partially overlapping ranges are allowed.
1299
1342
  */
1300
1343
  remove(start, end) {
1301
- start = start + this.offset;
1302
- end = end + this.offset;
1303
- if (this.original.length !== 0) {
1304
- if (start < 0) start = Math.max(0, start + this.original.length);
1305
- if (end < 0) end = Math.max(0, end + this.original.length);
1306
- }
1344
+ start = this._resolveIndex(start);
1345
+ end = this._resolveIndex(end);
1307
1346
  if (start === end) return this;
1308
1347
  if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1309
1348
  if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
@@ -1314,7 +1353,9 @@ var MagicString = class MagicString {
1314
1353
  if (chunk.start > start) chunk.intro = "";
1315
1354
  if (chunk.end < end) chunk.outro = "";
1316
1355
  chunk.edit("", false, true);
1317
- chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
1356
+ chunk.replacesUntil = -1;
1357
+ chunk.replacedFrom = -1;
1358
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
1318
1359
  }
1319
1360
  return this;
1320
1361
  }
@@ -1322,12 +1363,8 @@ var MagicString = class MagicString {
1322
1363
  * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
1323
1364
  */
1324
1365
  reset(start, end) {
1325
- start = start + this.offset;
1326
- end = end + this.offset;
1327
- if (this.original.length !== 0) {
1328
- if (start < 0) start = Math.max(0, start + this.original.length);
1329
- if (end < 0) end = Math.max(0, end + this.original.length);
1330
- }
1366
+ start = this._resolveIndex(start);
1367
+ end = this._resolveIndex(end);
1331
1368
  if (start === end) return this;
1332
1369
  if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1333
1370
  if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
@@ -1336,10 +1373,13 @@ var MagicString = class MagicString {
1336
1373
  let chunk = this.byStart.get(start);
1337
1374
  while (chunk) {
1338
1375
  chunk.reset();
1339
- chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
1376
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
1340
1377
  }
1341
1378
  return this;
1342
1379
  }
1380
+ /**
1381
+ * Returns the last character of the generated string, or `''` if it is empty.
1382
+ */
1343
1383
  lastChar() {
1344
1384
  if (this.outro.length) return this.outro[this.outro.length - 1];
1345
1385
  let chunk = this.lastChunk;
@@ -1352,49 +1392,57 @@ var MagicString = class MagicString {
1352
1392
  if (this.intro.length) return this.intro[this.intro.length - 1];
1353
1393
  return "";
1354
1394
  }
1395
+ /**
1396
+ * Returns everything after the last newline in the generated string, or the whole string if there is no newline.
1397
+ */
1355
1398
  lastLine() {
1356
1399
  let lineIndex = this.outro.lastIndexOf(n);
1357
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1400
+ if (lineIndex !== -1) return this.outro.slice(lineIndex + 1);
1358
1401
  let lineStr = this.outro;
1359
1402
  let chunk = this.lastChunk;
1360
1403
  while (chunk) {
1361
1404
  if (chunk.outro.length > 0) {
1362
1405
  lineIndex = chunk.outro.lastIndexOf(n);
1363
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1406
+ if (lineIndex !== -1) return chunk.outro.slice(lineIndex + 1) + lineStr;
1364
1407
  lineStr = chunk.outro + lineStr;
1365
1408
  }
1366
1409
  if (chunk.content.length > 0) {
1367
1410
  lineIndex = chunk.content.lastIndexOf(n);
1368
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1411
+ if (lineIndex !== -1) return chunk.content.slice(lineIndex + 1) + lineStr;
1369
1412
  lineStr = chunk.content + lineStr;
1370
1413
  }
1371
1414
  if (chunk.intro.length > 0) {
1372
1415
  lineIndex = chunk.intro.lastIndexOf(n);
1373
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1416
+ if (lineIndex !== -1) return chunk.intro.slice(lineIndex + 1) + lineStr;
1374
1417
  lineStr = chunk.intro + lineStr;
1375
1418
  }
1376
1419
  chunk = chunk.previous;
1377
1420
  }
1378
1421
  lineIndex = this.intro.lastIndexOf(n);
1379
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1422
+ if (lineIndex !== -1) return this.intro.slice(lineIndex + 1) + lineStr;
1380
1423
  return this.intro + lineStr;
1381
1424
  }
1382
1425
  /**
1383
- * Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string.
1384
- * Throws error if the indices are for characters that were already removed.
1426
+ * Returns the content of the generated string that corresponds to the slice
1427
+ * between `start` and `end` of the original string, walking the generated
1428
+ * string from the chunk holding `start` to the chunk holding `end`. Throws
1429
+ * if either index falls inside replaced content. After `move()`, a range
1430
+ * whose end now comes before its start in the output yields `''`.
1385
1431
  */
1386
1432
  slice(start = 0, end = this.original.length - this.offset) {
1387
- start = start + this.offset;
1388
- end = end + this.offset;
1389
- if (this.original.length !== 0) {
1390
- if (start < 0) start = Math.max(0, start + this.original.length);
1391
- if (end < 0) end = Math.max(0, end + this.original.length);
1392
- }
1433
+ start = this._resolveIndex(start);
1434
+ end = this._resolveIndex(end);
1393
1435
  let result = "";
1394
- let chunk = this.firstChunk;
1395
- while (chunk && (chunk.start > start || chunk.end <= start)) {
1396
- if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
1397
- chunk = chunk.next;
1436
+ let chunk;
1437
+ if (this.hasMovedChunks) {
1438
+ chunk = this.firstChunk;
1439
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
1440
+ if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
1441
+ chunk = chunk.next;
1442
+ }
1443
+ } else {
1444
+ if (start >= end) return result;
1445
+ chunk = this._chunkAt(start);
1398
1446
  }
1399
1447
  if (chunk && chunk.edited && chunk.start !== start) throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
1400
1448
  const startChunk = chunk;
@@ -1417,10 +1465,39 @@ var MagicString = class MagicString {
1417
1465
  */
1418
1466
  snip(start, end) {
1419
1467
  const clone = this.clone();
1420
- clone.remove(0, start);
1421
- clone.remove(end, clone.original.length);
1468
+ clone.remove(-clone.offset, start);
1469
+ clone.remove(end, clone.original.length - clone.offset);
1422
1470
  return clone;
1423
1471
  }
1472
+ /**
1473
+ * Applies `offset`, resolves a negative index from the end of `original` as
1474
+ * `update`/`remove` always have, and rejects anything that is not an integer.
1475
+ * Bounds are checked by the caller, because the methods report them differently.
1476
+ *
1477
+ * @internal
1478
+ */
1479
+ _resolveIndex(index) {
1480
+ const resolved = index + this.offset;
1481
+ if (!Number.isInteger(resolved)) throw new MagicStringError(`index must be an integer, got ${index}`);
1482
+ if (resolved < 0 && this.original.length !== 0) return Math.max(0, resolved + this.original.length);
1483
+ return resolved;
1484
+ }
1485
+ /**
1486
+ * The chunk whose original range holds `index` (`chunk.start <= index < chunk.end`),
1487
+ * or `undefined` when `index` is at or past the end. Searches from the last
1488
+ * visited chunk so that scans over nearby indices stay cheap.
1489
+ *
1490
+ * @internal
1491
+ */
1492
+ _chunkAt(index) {
1493
+ let chunk = this.byStart.get(index);
1494
+ if (chunk) return chunk;
1495
+ chunk = this.lastSearchedChunk;
1496
+ const searchForward = index >= chunk.end;
1497
+ while (chunk && !chunk.contains(index)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1498
+ if (chunk) this.lastSearchedChunk = chunk;
1499
+ return chunk;
1500
+ }
1424
1501
  /** @internal */
1425
1502
  _split(index) {
1426
1503
  if (this.byStart.get(index) || this.byEnd.get(index)) return;
@@ -1473,6 +1550,11 @@ var MagicString = class MagicString {
1473
1550
  if (this.outro.length && this.outro.trim()) return false;
1474
1551
  return true;
1475
1552
  }
1553
+ /**
1554
+ * Returns the length of the generated string, counting only content attached to the original characters.
1555
+ * Content outside the string body (`s.prepend()`/`s.append()`, and inserts before the first or after the last
1556
+ * character) is not counted, so this can differ from `s.toString().length`.
1557
+ */
1476
1558
  length() {
1477
1559
  let chunk = this.firstChunk;
1478
1560
  let length = 0;
@@ -1504,10 +1586,11 @@ var MagicString = class MagicString {
1504
1586
  const end = chunk.end;
1505
1587
  const aborted = chunk.trimEnd(rx);
1506
1588
  if (chunk.end !== end) {
1507
- if (this.lastChunk === chunk) this.lastChunk = chunk.next;
1589
+ const next = chunk.next;
1590
+ if (this.lastChunk === chunk) this.lastChunk = next;
1508
1591
  this.byEnd.set(chunk.end, chunk);
1509
- this.byStart.set(chunk.next.start, chunk.next);
1510
- this.byEnd.set(chunk.next.end, chunk.next);
1592
+ this.byStart.set(next.start, next);
1593
+ this.byEnd.set(next.end, next);
1511
1594
  }
1512
1595
  if (aborted) return true;
1513
1596
  chunk = chunk.previous;
@@ -1532,10 +1615,11 @@ var MagicString = class MagicString {
1532
1615
  const end = chunk.end;
1533
1616
  const aborted = chunk.trimStart(rx);
1534
1617
  if (chunk.end !== end) {
1535
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1618
+ const next = chunk.next;
1619
+ if (chunk === this.lastChunk) this.lastChunk = next;
1536
1620
  this.byEnd.set(chunk.end, chunk);
1537
- this.byStart.set(chunk.next.start, chunk.next);
1538
- this.byEnd.set(chunk.next.end, chunk.next);
1621
+ this.byStart.set(next.start, next);
1622
+ this.byEnd.set(next.end, next);
1539
1623
  }
1540
1624
  if (aborted) return true;
1541
1625
  chunk = chunk.next;
@@ -1577,33 +1661,32 @@ var MagicString = class MagicString {
1577
1661
  * @internal
1578
1662
  */
1579
1663
  _hasRemovedContent(start, end) {
1580
- let chunk = this.byStart.get(start);
1581
- if (!chunk) {
1582
- chunk = this.lastSearchedChunk;
1583
- const searchForward = start >= chunk.end;
1584
- while (chunk && !chunk.contains(start)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1585
- if (chunk) this.lastSearchedChunk = chunk;
1664
+ const atBoundary = this.byStart.get(start);
1665
+ if (atBoundary && start === end) {
1666
+ const previous = this.byEnd.get(start);
1667
+ return !!previous && previous.content === "" && atBoundary.content === "";
1586
1668
  }
1669
+ let chunk = this._chunkAt(start);
1587
1670
  while (chunk && chunk.start < end) {
1588
- if (chunk.content === "") return true;
1671
+ if (chunk.content === "" && (chunk.replacedFrom < start || this.byStart.get(chunk.replacedFrom).replacesUntil < chunk.end)) return true;
1589
1672
  chunk = this.byStart.get(chunk.end);
1590
1673
  }
1591
1674
  return false;
1592
1675
  }
1593
1676
  /** @internal */
1594
1677
  _replaceRegexp(searchValue, replacement) {
1595
- function getReplacement(match, str) {
1596
- if (typeof replacement === "string") return expandReplacement(replacement, match[0], match.index, str, match.slice(1), match.groups);
1597
- else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), match.index, str) : replacement(match[0], ...match.slice(1), match.index, str, match.groups);
1678
+ function getReplacement(match, index, str) {
1679
+ if (typeof replacement === "string") return expandReplacement(replacement, match[0], index, str, match.slice(1), match.groups);
1680
+ else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), index, str) : replacement(match[0], ...match.slice(1), index, str, match.groups);
1598
1681
  }
1599
1682
  const replaceMatch = (match) => {
1600
1683
  /* v8 ignore next 2 -- `match.index` is always defined for matches from `matchAll` */
1601
1684
  if (match.index == null) return false;
1602
1685
  if (this._hasRemovedContent(match.index, match.index + match[0].length)) return false;
1603
- const replacement = getReplacement(match, this.original);
1686
+ const replacement = getReplacement(match, match.index, this.original);
1604
1687
  if (replacement === match[0]) return true;
1605
- if (match[0].length === 0) this.appendRight(match.index, replacement);
1606
- else this.overwrite(match.index, match.index + match[0].length, replacement);
1688
+ if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
1689
+ else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
1607
1690
  return true;
1608
1691
  };
1609
1692
  if (searchValue.global) {
@@ -1630,8 +1713,8 @@ var MagicString = class MagicString {
1630
1713
  if (typeof replacement === "function") replacement = replacement(string, index, original);
1631
1714
  else replacement = expandReplacement(replacement, string, index, original, [], void 0);
1632
1715
  if (string !== replacement) {
1633
- if (string.length === 0) this.appendRight(index, replacement);
1634
- else this.overwrite(index, index + string.length, replacement);
1716
+ if (string.length === 0) this.appendRight(index - this.offset, replacement);
1717
+ else this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
1635
1718
  }
1636
1719
  break;
1637
1720
  }
@@ -1652,7 +1735,7 @@ var MagicString = class MagicString {
1652
1735
  for (let index = 0; index <= original.length; index += 1) {
1653
1736
  if (this._hasRemovedContent(index, index)) continue;
1654
1737
  const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], void 0);
1655
- if (_replacement !== "") this.appendRight(index, _replacement);
1738
+ if (_replacement !== "") this.appendRight(index - this.offset, _replacement);
1656
1739
  }
1657
1740
  return this;
1658
1741
  }
@@ -1660,7 +1743,7 @@ var MagicString = class MagicString {
1660
1743
  if (this._hasRemovedContent(index, index + stringLength)) continue;
1661
1744
  const previous = original.slice(index, index + stringLength);
1662
1745
  const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], void 0);
1663
- if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
1746
+ if (previous !== _replacement) this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
1664
1747
  }
1665
1748
  return this;
1666
1749
  }
@@ -1682,7 +1765,7 @@ var Bundle$1 = class Bundle {
1682
1765
  this.separator = options.separator !== void 0 ? options.separator : "\n";
1683
1766
  this.sources = [];
1684
1767
  this.uniqueSources = [];
1685
- this.uniqueSourceIndexByFilename = {};
1768
+ this.uniqueSourceIndexByFilename = /* @__PURE__ */ new Map();
1686
1769
  }
1687
1770
  /**
1688
1771
  * Adds the specified source to the bundle, which can either be a `MagicString` object directly,
@@ -1701,30 +1784,31 @@ var Bundle$1 = class Bundle {
1701
1784
  separator: this.separator
1702
1785
  });
1703
1786
  if (!isObject(source) || !source.content) throw new MagicStringError("addSource() requires a `content` property that is a MagicString");
1704
- [
1705
- "filename",
1706
- "ignoreList",
1707
- "indentExclusionRanges",
1708
- "separator"
1709
- ].forEach((option) => {
1710
- if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
1711
- });
1712
- if (source.separator === void 0) source.separator = this.separator;
1713
- if (source.filename) {
1714
- if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1715
- this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1787
+ const content = source.content;
1788
+ const record = {
1789
+ content,
1790
+ filename: hasOwnProp.call(source, "filename") ? source.filename : content.filename,
1791
+ ignoreList: hasOwnProp.call(source, "ignoreList") ? source.ignoreList : content.ignoreList,
1792
+ indentExclusionRanges: hasOwnProp.call(source, "indentExclusionRanges") ? source.indentExclusionRanges : content.indentExclusionRanges,
1793
+ separator: source.separator ?? this.separator
1794
+ };
1795
+ if (record.filename) {
1796
+ const index = this.uniqueSourceIndexByFilename.get(record.filename);
1797
+ if (index === void 0) {
1798
+ this.uniqueSourceIndexByFilename.set(record.filename, this.uniqueSources.length);
1716
1799
  this.uniqueSources.push({
1717
- filename: source.filename,
1718
- content: source.content.original
1800
+ filename: record.filename,
1801
+ content: content.original
1719
1802
  });
1720
- } else {
1721
- const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1722
- if (source.content.original !== uniqueSource.content) throw new MagicStringError(`duplicate filename "${source.filename}" with different content, use unique filenames`);
1723
- }
1803
+ } else if (content.original !== this.uniqueSources[index].content) throw new MagicStringError(`duplicate filename "${record.filename}" with different content, use unique filenames`);
1724
1804
  }
1725
- this.sources.push(source);
1805
+ this.sources.push(record);
1726
1806
  return this;
1727
1807
  }
1808
+ /**
1809
+ * Appends `str` as a new source without a filename. Only `options.separator` is read, and it defaults to `''`
1810
+ * rather than to the bundle separator.
1811
+ */
1728
1812
  append(str, options) {
1729
1813
  this.addSource({
1730
1814
  content: new MagicString(str),
@@ -1732,6 +1816,10 @@ var Bundle$1 = class Bundle {
1732
1816
  });
1733
1817
  return this;
1734
1818
  }
1819
+ /**
1820
+ * Returns an independent copy of the bundle: every source's `MagicString` is cloned, so later edits to either
1821
+ * bundle do not affect the other.
1822
+ */
1735
1823
  clone() {
1736
1824
  const bundle = new Bundle({
1737
1825
  intro: this.intro,
@@ -1767,12 +1855,12 @@ var Bundle$1 = class Bundle {
1767
1855
  const byStart = /* @__PURE__ */ new Map();
1768
1856
  const byEnd = /* @__PURE__ */ new Map();
1769
1857
  let hasMovedChunks = false;
1770
- this.sources.forEach((source, i) => {
1858
+ for (const [i, source] of this.sources.entries()) {
1771
1859
  const magicString = source.content;
1772
- const separator = i > 0 ? source.separator !== void 0 ? source.separator : this.separator : "";
1860
+ const separator = i > 0 ? source.separator : "";
1773
1861
  if (magicString.original.length === 0) {
1774
1862
  pending += separator + magicString.toString();
1775
- return;
1863
+ continue;
1776
1864
  }
1777
1865
  pending += separator + magicString.intro;
1778
1866
  let sourceFirst = null;
@@ -1782,6 +1870,8 @@ var Bundle$1 = class Bundle {
1782
1870
  const chunk = originalChunk.clone();
1783
1871
  chunk.start += offset;
1784
1872
  chunk.end += offset;
1873
+ if (chunk.replacesUntil !== -1) chunk.replacesUntil += offset;
1874
+ if (chunk.replacedFrom !== -1) chunk.replacedFrom += offset;
1785
1875
  chunk.previous = previous;
1786
1876
  chunk.next = null;
1787
1877
  if (previous) previous.next = chunk;
@@ -1800,18 +1890,14 @@ var Bundle$1 = class Bundle {
1800
1890
  sourceFirst.previous = last;
1801
1891
  } else first = sourceFirst;
1802
1892
  last = sourceLast;
1803
- for (let index = 0; index < magicString.original.length; index += 1) if (magicString.sourcemapLocations.has(index)) combined.sourcemapLocations.add(index + offset);
1804
- Object.keys(magicString.storedNames).forEach((name) => {
1805
- Object.defineProperty(combined.storedNames, name, {
1806
- writable: true,
1807
- value: true,
1808
- enumerable: true
1809
- });
1893
+ magicString.sourcemapLocations.forEach((index) => {
1894
+ if (index < magicString.original.length) combined.sourcemapLocations.add(index + offset);
1810
1895
  });
1896
+ magicString.storedNames.forEach((name) => combined.storedNames.add(name));
1811
1897
  if (magicString.hasMovedChunks) hasMovedChunks = true;
1812
1898
  offset += magicString.original.length;
1813
- });
1814
- if (!first) {
1899
+ }
1900
+ if (!first || !last) {
1815
1901
  combined.intro = pending;
1816
1902
  return combined;
1817
1903
  }
@@ -1824,6 +1910,10 @@ var Bundle$1 = class Bundle {
1824
1910
  combined.hasMovedChunks = hasMovedChunks;
1825
1911
  return combined;
1826
1912
  }
1913
+ /**
1914
+ * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
1915
+ * Takes the same options as `generateMap`.
1916
+ */
1827
1917
  generateDecodedMap(options = {}) {
1828
1918
  const mappings = new Mappings(options.hires);
1829
1919
  const { names, x_google_ignoreList } = this._generateMappings(mappings);
@@ -1833,6 +1923,10 @@ var Bundle$1 = class Bundle {
1833
1923
  rangeMappings: mappings.rawRangeMappings
1834
1924
  };
1835
1925
  }
1926
+ /**
1927
+ * Generates a version 3 sourcemap covering every source that has a `filename`.
1928
+ * Options are as per `MagicString#generateMap`, except that `includeContent` can also be a per-source function.
1929
+ */
1836
1930
  generateMap(options = {}) {
1837
1931
  const encoder = new MappingsEncoder();
1838
1932
  const mappings = new Mappings(options.hires, encoder);
@@ -1845,32 +1939,16 @@ var Bundle$1 = class Bundle {
1845
1939
  }
1846
1940
  /** @internal */
1847
1941
  _generateMappings(mappings) {
1848
- const names = [];
1849
1942
  let x_google_ignoreList;
1850
- this.sources.forEach((source) => {
1851
- Object.keys(source.content.storedNames).forEach((name) => {
1852
- if (!names.includes(name)) names.push(name);
1853
- });
1854
- });
1943
+ const storedNames = /* @__PURE__ */ new Set();
1944
+ this.sources.forEach((source) => source.content.storedNames.forEach((name) => storedNames.add(name)));
1945
+ const names = [...storedNames];
1946
+ const nameIndex = new Map(names.map((name, i) => [name, i]));
1855
1947
  if (this.intro) mappings.advance(this.intro);
1856
1948
  this.sources.forEach((source, i) => {
1857
- if (i > 0)
1858
- /* v8 ignore next -- addSource always normalizes source.separator */
1859
- mappings.advance(source.separator !== void 0 ? source.separator : this.separator);
1860
- const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
1861
- const magicString = source.content;
1862
- const locate = getLocator(magicString.original);
1863
- if (magicString.intro) mappings.advance(magicString.intro);
1864
- magicString.firstChunk.eachNext((chunk) => {
1865
- const loc = locate(chunk.start);
1866
- if (chunk.intro.length) mappings.advance(chunk.intro);
1867
- if (source.filename) {
1868
- if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1869
- else mappings.addUneditedChunk(sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations);
1870
- } else mappings.advance(chunk.content);
1871
- if (chunk.outro.length) mappings.advance(chunk.outro);
1872
- });
1873
- if (magicString.outro) mappings.advance(magicString.outro);
1949
+ if (i > 0) mappings.advance(source.separator);
1950
+ const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename.get(source.filename) ?? -1 : -1;
1951
+ mappings.addMagicString(source.content, sourceIndex, nameIndex);
1874
1952
  if (source.ignoreList && sourceIndex !== -1) {
1875
1953
  if (x_google_ignoreList === void 0) x_google_ignoreList = [];
1876
1954
  x_google_ignoreList.push(sourceIndex);
@@ -1895,91 +1973,111 @@ var Bundle$1 = class Bundle {
1895
1973
  x_google_ignoreList
1896
1974
  };
1897
1975
  }
1976
+ /**
1977
+ * Returns the most common indent string among the sources, falling back to a tab.
1978
+ */
1898
1979
  getIndentString() {
1899
- const indentStringCounts = {};
1980
+ const indentStringCounts = /* @__PURE__ */ new Map();
1900
1981
  this.sources.forEach((source) => {
1901
1982
  const indentStr = source.content._getRawIndentString();
1902
- if (indentStr === null) return;
1903
- if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
1904
- indentStringCounts[indentStr] += 1;
1983
+ if (indentStr == null) return;
1984
+ indentStringCounts.set(indentStr, (indentStringCounts.get(indentStr) ?? 0) + 1);
1905
1985
  });
1906
- return Object.keys(indentStringCounts).sort((a, b) => {
1907
- return indentStringCounts[b] - indentStringCounts[a];
1908
- })[0] || " ";
1986
+ return [...indentStringCounts.entries()].sort(([, a], [, b]) => b - a)[0]?.[0] ?? " ";
1909
1987
  }
1988
+ /**
1989
+ * Prefixes each line of every source and of the intro with `indentStr`, guessed with `getIndentString()`
1990
+ * when not supplied. Each source's `indentExclusionRanges` are left unindented.
1991
+ */
1910
1992
  indent(indentStr) {
1911
1993
  if (!arguments.length) indentStr = this.getIndentString();
1912
1994
  if (indentStr === "") return this;
1913
1995
  let trailingNewline = !this.intro || this.intro.slice(-1) === "\n";
1914
1996
  this.sources.forEach((source, i) => {
1915
- /* v8 ignore next -- addSource always normalizes source.separator */
1916
- const separator = source.separator !== void 0 ? source.separator : this.separator;
1917
- const indentStart = trailingNewline || i > 0 && /\r?\n$/.test(separator);
1997
+ const indentStart = trailingNewline || i > 0 && /\r?\n$/.test(source.separator);
1918
1998
  source.content.indent(indentStr, {
1919
1999
  exclude: source.indentExclusionRanges,
1920
2000
  indentStart
1921
2001
  });
1922
2002
  trailingNewline = source.content.lastChar() === "\n";
1923
2003
  });
1924
- if (this.intro) this.intro = indentStr + this.intro.replace(/^[^\n]/gm, (match, index) => {
2004
+ if (this.intro) this.intro = indentStr + this.intro.replace(/^[^\r\n]/gm, (match, index) => {
1925
2005
  return index > 0 ? indentStr + match : match;
1926
2006
  });
1927
2007
  return this;
1928
2008
  }
2009
+ /**
2010
+ * Prepends `str` to the bundle's intro.
2011
+ */
1929
2012
  prepend(str) {
1930
2013
  this.intro = str + this.intro;
1931
2014
  return this;
1932
2015
  }
2016
+ /**
2017
+ * Returns the intro followed by every source's generated string, joined by their separators.
2018
+ */
1933
2019
  toString() {
1934
2020
  const body = this.sources.map((source, i) => {
1935
- /* v8 ignore next -- addSource always normalizes source.separator */
1936
- const separator = source.separator !== void 0 ? source.separator : this.separator;
1937
- return (i > 0 ? separator : "") + source.content.toString();
2021
+ return (i > 0 ? source.separator : "") + source.content.toString();
1938
2022
  }).join("");
1939
2023
  return this.intro + body;
1940
2024
  }
2025
+ /**
2026
+ * Returns true if the bundle's output is empty (disregarding white space).
2027
+ */
1941
2028
  isEmpty() {
1942
2029
  if (this.intro.length && this.intro.trim()) return false;
1943
2030
  if (this.sources.some((source, i) => {
1944
- /* v8 ignore next -- addSource always normalizes source.separator */
1945
- const separator = source.separator !== void 0 ? source.separator : this.separator;
1946
- return i > 0 && separator.trim() !== "" || !source.content.isEmpty();
2031
+ return i > 0 && source.separator.trim() !== "" || !source.content.isEmpty();
1947
2032
  })) return false;
1948
2033
  return true;
1949
2034
  }
2035
+ /**
2036
+ * Returns the length of the bundle's output; unlike `MagicString#length`, this equals `bundle.toString().length`.
2037
+ */
1950
2038
  length() {
1951
2039
  return this.sources.reduce((length, source, i) => {
1952
- /* v8 ignore next -- addSource always normalizes source.separator */
1953
- const separator = source.separator !== void 0 ? source.separator : this.separator;
1954
- return length + (i > 0 ? separator.length : 0) + source.content.toString().length;
2040
+ return length + (i > 0 ? source.separator.length : 0) + source.content.length() + source.content.intro.length + source.content.outro.length;
1955
2041
  }, this.intro.length);
1956
2042
  }
2043
+ /**
2044
+ * Removes empty lines from the start and end.
2045
+ */
1957
2046
  trimLines() {
1958
2047
  return this.trim("[\\r\\n]");
1959
2048
  }
2049
+ /**
2050
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
2051
+ */
1960
2052
  trim(charType) {
1961
2053
  return this.trimStart(charType).trimEnd(charType);
1962
2054
  }
2055
+ /**
2056
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
2057
+ */
1963
2058
  trimStart(charType) {
1964
2059
  const rx = new RegExp(`^${charType || "\\s"}+`);
1965
2060
  this.intro = this.intro.replace(rx, "");
1966
2061
  if (!this.intro) for (let i = 0; i < this.sources.length; i += 1) {
1967
2062
  const source = this.sources[i];
1968
2063
  if (i > 0) {
1969
- source.separator = (source.separator !== void 0 ? source.separator : this.separator).replace(rx, "");
2064
+ source.separator = source.separator.replace(rx, "");
1970
2065
  if (source.separator) break;
1971
2066
  }
1972
2067
  if (source.content.trimStartAborted(charType)) break;
1973
2068
  }
1974
2069
  return this;
1975
2070
  }
2071
+ /**
2072
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
2073
+ */
1976
2074
  trimEnd(charType) {
1977
2075
  const rx = new RegExp(`${charType || "\\s"}+$`);
1978
2076
  for (let i = this.sources.length - 1; i >= 0; i -= 1) {
1979
2077
  const source = this.sources[i];
1980
2078
  if (source.content.trimEndAborted(charType)) return this;
1981
2079
  if (i > 0) {
1982
- source.separator = (source.separator !== void 0 ? source.separator : this.separator).replace(rx, "");
2080
+ source.separator = source.separator.replace(rx, "");
1983
2081
  if (source.separator) return this;
1984
2082
  }
1985
2083
  }
@@ -2214,8 +2312,8 @@ const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
2214
2312
  const UnknownInteger = Symbol('Unknown Integer');
2215
2313
  const UnknownWellKnown = Symbol('Unknown Well-Known');
2216
2314
  const SymbolToStringTag = Symbol('Symbol.toStringTag');
2217
- const SymbolDispose = Symbol('Symbol.asyncDispose');
2218
- const SymbolAsyncDispose = Symbol('Symbol.dispose');
2315
+ const SymbolDispose = Symbol('Symbol.dispose');
2316
+ const SymbolAsyncDispose = Symbol('Symbol.asyncDispose');
2219
2317
  const SymbolHasInstance = Symbol('Symbol.hasInstance');
2220
2318
  const WELL_KNOWN_SYMBOLS_LIST = [
2221
2319
  SymbolToStringTag,
@@ -2322,6 +2420,25 @@ class IncludedFullPathTracker {
2322
2420
  }
2323
2421
  return included;
2324
2422
  }
2423
+ includeAllPaths(entity, context, basePath) {
2424
+ if (this.includedPaths) {
2425
+ includeAllSubPaths(entity, context, basePath, this.includedPaths);
2426
+ }
2427
+ }
2428
+ }
2429
+ function includeAllSubPaths(entity, context, path, includedPaths) {
2430
+ if (includedPaths[UnknownKey]) {
2431
+ entity.includePath([...path, UnknownKey], context);
2432
+ return;
2433
+ }
2434
+ const keys = Reflect.ownKeys(includedPaths);
2435
+ if (keys.length === 0) {
2436
+ entity.includePath(path, context);
2437
+ return;
2438
+ }
2439
+ for (const key of keys) {
2440
+ includeAllSubPaths(entity, context, [...path, key], includedPaths[key]);
2441
+ }
2325
2442
  }
2326
2443
  const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
2327
2444
  [UnknownKey]: true
@@ -2365,13 +2482,15 @@ class IncludedTopLevelPathTracker {
2365
2482
  entity.includePath([...basePath, UnknownKey], context);
2366
2483
  }
2367
2484
  else {
2368
- const inclusionEntries = Object.entries(includedPaths);
2369
- if (inclusionEntries.length === 0) {
2485
+ const keys = Reflect.ownKeys(includedPaths);
2486
+ if (keys.length === 0) {
2370
2487
  entity.includePath(basePath, context);
2371
2488
  }
2372
2489
  else {
2373
- for (const [key, value] of inclusionEntries) {
2374
- entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
2490
+ for (const key of keys) {
2491
+ entity.includePath(includedPaths[key] === UnknownKey
2492
+ ? [...basePath, key, UnknownKey]
2493
+ : [...basePath, key], context);
2375
2494
  }
2376
2495
  }
2377
2496
  }
@@ -2403,6 +2522,9 @@ class ExpressionEntity {
2403
2522
  deoptimizeInteraction(interaction);
2404
2523
  }
2405
2524
  deoptimizePath(_path) { }
2525
+ getKnownFunctionAtPath(_path, _recursionTracker, _origin) {
2526
+ return null;
2527
+ }
2406
2528
  /**
2407
2529
  * If possible it returns a stringifyable literal value for this node that
2408
2530
  * can be used for inlining or comparing values. Otherwise, it should return
@@ -2560,228 +2682,343 @@ function getSafeName(baseName, usedNames, forbiddenNames) {
2560
2682
  return safeName;
2561
2683
  }
2562
2684
 
2563
- // To avoid infinite recursions
2564
- const MAX_PATH_DEPTH = 6;
2565
- // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
2566
- // most MAX_PATH_DEPTH long. The last element is always UnknownKey
2567
- const limitConcatenatedPathDepth = (path1, path2) => {
2568
- const { length: length1 } = path1;
2569
- const { length: length2 } = path2;
2570
- return length1 === 0
2571
- ? path2
2572
- : length2 === 0
2573
- ? path1
2574
- : length1 + length2 > MAX_PATH_DEPTH
2575
- ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
2576
- : [...path1, ...path2];
2685
+ // This file is generated by scripts/generate-child-node-keys.ts.
2686
+ // Do not edit this file directly.
2687
+ const childNodeKeys = {
2688
+ ArrayExpression: ['elements'],
2689
+ ArrayPattern: ['elements'],
2690
+ ArrowFunctionExpression: ['params', 'body'],
2691
+ AssignmentExpression: ['left', 'right'],
2692
+ AssignmentPattern: ['left', 'right'],
2693
+ AwaitExpression: ['argument'],
2694
+ BinaryExpression: ['left', 'right'],
2695
+ BlockStatement: ['body'],
2696
+ BreakStatement: ['label'],
2697
+ CallExpression: ['callee', 'arguments'],
2698
+ CatchClause: ['param', 'body'],
2699
+ ChainExpression: ['expression'],
2700
+ ClassBody: ['body'],
2701
+ ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
2702
+ ClassExpression: ['decorators', 'id', 'superClass', 'body'],
2703
+ ConditionalExpression: ['test', 'consequent', 'alternate'],
2704
+ ContinueStatement: ['label'],
2705
+ DebuggerStatement: [],
2706
+ Decorator: ['expression'],
2707
+ DoWhileStatement: ['body', 'test'],
2708
+ EmptyStatement: [],
2709
+ ExportAllDeclaration: ['exported', 'source', 'attributes'],
2710
+ ExportDefaultDeclaration: ['declaration'],
2711
+ ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
2712
+ ExportSpecifier: ['local', 'exported'],
2713
+ ExpressionStatement: ['expression'],
2714
+ ForInStatement: ['left', 'right', 'body'],
2715
+ ForOfStatement: ['left', 'right', 'body'],
2716
+ ForStatement: ['init', 'test', 'update', 'body'],
2717
+ FunctionDeclaration: ['id', 'params', 'body'],
2718
+ FunctionExpression: ['id', 'params', 'body'],
2719
+ Identifier: [],
2720
+ IfStatement: ['test', 'consequent', 'alternate'],
2721
+ ImportAttribute: ['key', 'value'],
2722
+ ImportDeclaration: ['specifiers', 'source', 'attributes'],
2723
+ ImportDefaultSpecifier: ['local'],
2724
+ ImportExpression: ['source', 'options'],
2725
+ ImportNamespaceSpecifier: ['local'],
2726
+ ImportSpecifier: ['imported', 'local'],
2727
+ JSXAttribute: ['name', 'value'],
2728
+ JSXClosingElement: ['name'],
2729
+ JSXClosingFragment: [],
2730
+ JSXElement: ['openingElement', 'children', 'closingElement'],
2731
+ JSXEmptyExpression: [],
2732
+ JSXExpressionContainer: ['expression'],
2733
+ JSXFragment: ['openingFragment', 'children', 'closingFragment'],
2734
+ JSXIdentifier: [],
2735
+ JSXMemberExpression: ['object', 'property'],
2736
+ JSXNamespacedName: ['namespace', 'name'],
2737
+ JSXOpeningElement: ['name', 'attributes'],
2738
+ JSXOpeningFragment: [],
2739
+ JSXSpreadAttribute: ['argument'],
2740
+ JSXSpreadChild: ['expression'],
2741
+ JSXText: [],
2742
+ LabeledStatement: ['label', 'body'],
2743
+ Literal: [],
2744
+ LogicalExpression: ['left', 'right'],
2745
+ MemberExpression: ['object', 'property'],
2746
+ MetaProperty: ['meta', 'property'],
2747
+ MethodDefinition: ['decorators', 'key', 'value'],
2748
+ NewExpression: ['callee', 'arguments'],
2749
+ ObjectExpression: ['properties'],
2750
+ ObjectPattern: ['properties'],
2751
+ PanicError: [],
2752
+ ParseError: [],
2753
+ PrivateIdentifier: [],
2754
+ Program: ['body'],
2755
+ Property: ['key', 'value'],
2756
+ PropertyDefinition: ['decorators', 'key', 'value'],
2757
+ RestElement: ['argument'],
2758
+ ReturnStatement: ['argument'],
2759
+ SequenceExpression: ['expressions'],
2760
+ SpreadElement: ['argument'],
2761
+ StaticBlock: ['body'],
2762
+ Super: [],
2763
+ SwitchCase: ['test', 'consequent'],
2764
+ SwitchStatement: ['discriminant', 'cases'],
2765
+ TaggedTemplateExpression: ['tag', 'quasi'],
2766
+ TemplateElement: [],
2767
+ TemplateLiteral: ['quasis', 'expressions'],
2768
+ ThisExpression: [],
2769
+ ThrowStatement: ['argument'],
2770
+ TryStatement: ['block', 'handler', 'finalizer'],
2771
+ UnaryExpression: ['argument'],
2772
+ UpdateExpression: ['argument'],
2773
+ VariableDeclaration: ['declarations'],
2774
+ VariableDeclarator: ['id', 'init'],
2775
+ WhileStatement: ['test', 'body'],
2776
+ YieldExpression: ['argument']
2577
2777
  };
2578
2778
 
2579
- function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
2580
- return Object.create(inheritedDescriptions, memberDescriptions);
2779
+ function createInclusionContext() {
2780
+ return {
2781
+ brokenFlow: false,
2782
+ hasBreak: false,
2783
+ hasContinue: false,
2784
+ includedCallArguments: new Set(),
2785
+ includedLabels: new Set()
2786
+ };
2581
2787
  }
2582
- const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
2583
- getLiteralValueAtPath(path) {
2584
- return path.length > 0 ? UnknownValue : undefined;
2585
- }
2586
- })();
2587
- const returnsUnknown = {
2588
- value: {
2589
- hasEffectsWhenCalled: null,
2590
- returns: UNKNOWN_EXPRESSION
2591
- }
2592
- };
2593
- const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
2594
- getReturnExpressionWhenCalledAtPath(path) {
2595
- if (path.length === 1) {
2596
- return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
2597
- }
2598
- return UNKNOWN_RETURN_EXPRESSION;
2599
- }
2600
- hasEffectsOnInteractionAtPath(path, interaction, context) {
2601
- if (interaction.type === INTERACTION_ACCESSED) {
2602
- return path.length > 1;
2603
- }
2604
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
2605
- return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
2606
- }
2607
- return true;
2788
+ function createHasEffectsContext() {
2789
+ return {
2790
+ accessed: new EntityPathTracker(),
2791
+ assigned: new EntityPathTracker(),
2792
+ brokenFlow: false,
2793
+ called: new DiscriminatedPathTracker(),
2794
+ hasBreak: false,
2795
+ hasContinue: false,
2796
+ ignore: {
2797
+ breaks: false,
2798
+ continues: false,
2799
+ labels: new Set(),
2800
+ returnYield: false,
2801
+ this: false
2802
+ },
2803
+ includedLabels: new Set(),
2804
+ instantiated: new DiscriminatedPathTracker(),
2805
+ replacedVariableInits: new Map()
2806
+ };
2807
+ }
2808
+
2809
+ const INCLUDE_PARAMETERS = 'variables';
2810
+ const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
2811
+ class NodeBase extends ExpressionEntity {
2812
+ /**
2813
+ * Nodes can apply custom deoptimizations once they become part of the
2814
+ * executed code. To do this, they must initialize this as false, implement
2815
+ * applyDeoptimizations and call this from include and hasEffects if they have
2816
+ * custom handlers
2817
+ */
2818
+ get deoptimized() {
2819
+ return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
2608
2820
  }
2609
- })();
2610
- const returnsBoolean = {
2611
- value: {
2612
- hasEffectsWhenCalled: null,
2613
- returns: UNKNOWN_LITERAL_BOOLEAN
2821
+ set deoptimized(value) {
2822
+ this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
2614
2823
  }
2615
- };
2616
- const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
2617
- getReturnExpressionWhenCalledAtPath(path) {
2618
- if (path.length === 1) {
2619
- return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
2620
- }
2621
- return UNKNOWN_RETURN_EXPRESSION;
2824
+ constructor(parent, parentScope) {
2825
+ super();
2826
+ this.parent = parent;
2827
+ this.scope = parentScope;
2828
+ this.createScope(parentScope);
2622
2829
  }
2623
- hasEffectsOnInteractionAtPath(path, interaction, context) {
2624
- if (interaction.type === INTERACTION_ACCESSED) {
2625
- return path.length > 1;
2626
- }
2627
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
2628
- return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
2830
+ addExportedVariables(_variables, _exportNamesByVariable) { }
2831
+ /**
2832
+ * Override this to bind assignments to variables and do any initialisations
2833
+ * that require the scopes to be populated with variables.
2834
+ */
2835
+ bind() {
2836
+ for (const key of childNodeKeys[this.type]) {
2837
+ const value = this[key];
2838
+ if (Array.isArray(value)) {
2839
+ for (const child of value) {
2840
+ child?.bind();
2841
+ }
2842
+ }
2843
+ else if (value) {
2844
+ value.bind();
2845
+ }
2629
2846
  }
2630
- return true;
2631
2847
  }
2632
- })();
2633
- const returnsNumber = {
2634
- value: {
2635
- hasEffectsWhenCalled: null,
2636
- returns: UNKNOWN_LITERAL_NUMBER
2848
+ /**
2849
+ * Override if this node should receive a different scope than the parent
2850
+ * scope.
2851
+ */
2852
+ createScope(parentScope) {
2853
+ this.scope = parentScope;
2637
2854
  }
2638
- };
2639
- const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
2640
- getReturnExpressionWhenCalledAtPath(path) {
2641
- if (path.length === 1) {
2642
- return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2855
+ hasEffects(context) {
2856
+ if (!this.deoptimized)
2857
+ this.applyDeoptimizations();
2858
+ for (const key of childNodeKeys[this.type]) {
2859
+ const value = this[key];
2860
+ if (value === null)
2861
+ continue;
2862
+ if (Array.isArray(value)) {
2863
+ for (const child of value) {
2864
+ if (child?.hasEffects(context))
2865
+ return true;
2866
+ }
2867
+ }
2868
+ else if (value.hasEffects(context))
2869
+ return true;
2643
2870
  }
2644
- return UNKNOWN_RETURN_EXPRESSION;
2871
+ return false;
2645
2872
  }
2646
- hasEffectsOnInteractionAtPath(path, interaction, context) {
2647
- if (interaction.type === INTERACTION_ACCESSED) {
2648
- return path.length > 1;
2649
- }
2650
- if (interaction.type === INTERACTION_CALLED && path.length === 1) {
2651
- return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
2873
+ hasEffectsAsAssignmentTarget(context, _checkAccess) {
2874
+ return (this.hasEffects(context) ||
2875
+ this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
2876
+ }
2877
+ include(context, includeChildrenRecursively, _options) {
2878
+ if (!this.included)
2879
+ this.includeNode(context);
2880
+ for (const key of childNodeKeys[this.type]) {
2881
+ const value = this[key];
2882
+ if (value === null)
2883
+ continue;
2884
+ if (Array.isArray(value)) {
2885
+ for (const child of value) {
2886
+ child?.include(context, includeChildrenRecursively);
2887
+ }
2888
+ }
2889
+ else {
2890
+ value.include(context, includeChildrenRecursively);
2891
+ }
2652
2892
  }
2653
- return true;
2654
2893
  }
2655
- })();
2656
- const returnsString = {
2657
- value: {
2658
- hasEffectsWhenCalled: null,
2659
- returns: UNKNOWN_LITERAL_STRING
2894
+ includeNode(context) {
2895
+ this.included = true;
2896
+ if (!this.deoptimized)
2897
+ this.applyDeoptimizations();
2898
+ for (const key of childNodeKeys[this.type]) {
2899
+ const value = this[key];
2900
+ if (value === null)
2901
+ continue;
2902
+ if (Array.isArray(value)) {
2903
+ for (const child of value) {
2904
+ child?.includePath(UNKNOWN_PATH, context);
2905
+ }
2906
+ }
2907
+ else {
2908
+ value.includePath(UNKNOWN_PATH, context);
2909
+ }
2910
+ }
2660
2911
  }
2661
- };
2662
- const stringReplace = {
2663
- value: {
2664
- hasEffectsWhenCalled({ args }, context) {
2665
- const argument1 = args[2];
2666
- return (args.length < 3 ||
2667
- (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
2668
- deoptimizeCache() { }
2669
- }) === 'symbol' &&
2670
- argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
2671
- },
2672
- returns: UNKNOWN_LITERAL_STRING
2912
+ includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
2913
+ this.include(context, includeChildrenRecursively);
2673
2914
  }
2674
- };
2675
- const objectMembers = assembleMemberDescriptions({
2676
- hasOwnProperty: returnsBoolean,
2677
- isPrototypeOf: returnsBoolean,
2678
- propertyIsEnumerable: returnsBoolean,
2679
- toLocaleString: returnsString,
2680
- toString: returnsString,
2681
- valueOf: returnsUnknown
2682
- });
2683
- const literalBooleanMembers = assembleMemberDescriptions({
2684
- valueOf: returnsBoolean
2685
- }, objectMembers);
2686
- const literalNumberMembers = assembleMemberDescriptions({
2687
- toExponential: returnsString,
2688
- toFixed: returnsString,
2689
- toLocaleString: returnsString,
2690
- toPrecision: returnsString,
2691
- valueOf: returnsNumber
2692
- }, objectMembers);
2693
- /**
2694
- * RegExp are stateful when they have the global or sticky flags set.
2695
- * But if we actually don't use them, the side effect does not matter.
2696
- * the check logic in `hasEffectsOnInteractionAtPath`.
2697
- */
2698
- const literalRegExpMembers = assembleMemberDescriptions({
2699
- exec: returnsUnknown,
2700
- test: returnsBoolean
2701
- }, objectMembers);
2702
- const literalStringMembers = assembleMemberDescriptions({
2703
- anchor: returnsString,
2704
- at: returnsUnknown,
2705
- big: returnsString,
2706
- blink: returnsString,
2707
- bold: returnsString,
2708
- charAt: returnsString,
2709
- charCodeAt: returnsNumber,
2710
- codePointAt: returnsUnknown,
2711
- concat: returnsString,
2712
- endsWith: returnsBoolean,
2713
- fixed: returnsString,
2714
- fontcolor: returnsString,
2715
- fontsize: returnsString,
2716
- includes: returnsBoolean,
2717
- indexOf: returnsNumber,
2718
- italics: returnsString,
2719
- lastIndexOf: returnsNumber,
2720
- link: returnsString,
2721
- localeCompare: returnsNumber,
2722
- match: returnsUnknown,
2723
- matchAll: returnsUnknown,
2724
- normalize: returnsString,
2725
- padEnd: returnsString,
2726
- padStart: returnsString,
2727
- repeat: returnsString,
2728
- replace: stringReplace,
2729
- replaceAll: stringReplace,
2730
- search: returnsNumber,
2731
- slice: returnsString,
2732
- small: returnsString,
2733
- split: returnsUnknown,
2734
- startsWith: returnsBoolean,
2735
- strike: returnsString,
2736
- sub: returnsString,
2737
- substr: returnsString,
2738
- substring: returnsString,
2739
- sup: returnsString,
2740
- toLocaleLowerCase: returnsString,
2741
- toLocaleUpperCase: returnsString,
2742
- toLowerCase: returnsString,
2743
- toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
2744
- toUpperCase: returnsString,
2745
- trim: returnsString,
2746
- trimEnd: returnsString,
2747
- trimLeft: returnsString,
2748
- trimRight: returnsString,
2749
- trimStart: returnsString,
2750
- valueOf: returnsString
2751
- }, objectMembers);
2752
- function getLiteralMembersForValue(value) {
2753
- if (value instanceof RegExp) {
2754
- return literalRegExpMembers;
2915
+ /**
2916
+ * Override to perform special initialisation steps after the scope is
2917
+ * initialised
2918
+ */
2919
+ initialise() {
2920
+ this.scope.context.magicString.addSourcemapLocation(this.start);
2921
+ this.scope.context.magicString.addSourcemapLocation(this.end);
2755
2922
  }
2756
- switch (typeof value) {
2757
- case 'boolean': {
2758
- return literalBooleanMembers;
2923
+ removeAnnotations(code) {
2924
+ if (this.annotations) {
2925
+ for (const annotation of this.annotations) {
2926
+ code.remove(annotation.start, annotation.end);
2927
+ }
2759
2928
  }
2760
- case 'number': {
2761
- return literalNumberMembers;
2929
+ }
2930
+ render(code, options) {
2931
+ for (const key of childNodeKeys[this.type]) {
2932
+ const value = this[key];
2933
+ if (value === null)
2934
+ continue;
2935
+ if (Array.isArray(value)) {
2936
+ for (const child of value) {
2937
+ child?.render(code, options);
2938
+ }
2939
+ }
2940
+ else {
2941
+ value.render(code, options);
2942
+ }
2762
2943
  }
2763
- case 'string': {
2764
- return literalStringMembers;
2944
+ }
2945
+ setAssignedValue(value) {
2946
+ this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
2947
+ }
2948
+ shouldBeIncluded(context) {
2949
+ return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
2950
+ }
2951
+ /**
2952
+ * Just deoptimize everything by default so that when e.g. we do not track
2953
+ * something properly, it is deoptimized.
2954
+ * @protected
2955
+ */
2956
+ applyDeoptimizations() {
2957
+ this.deoptimized = true;
2958
+ for (const key of childNodeKeys[this.type]) {
2959
+ const value = this[key];
2960
+ if (value === null)
2961
+ continue;
2962
+ if (Array.isArray(value)) {
2963
+ for (const child of value) {
2964
+ child?.deoptimizePath(UNKNOWN_PATH);
2965
+ }
2966
+ }
2967
+ else {
2968
+ value.deoptimizePath(UNKNOWN_PATH);
2969
+ }
2765
2970
  }
2971
+ this.scope.context.requestTreeshakingPass();
2766
2972
  }
2767
- return Object.create(null);
2768
2973
  }
2769
- function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
2770
- if (typeof memberName !== 'string' || !members[memberName]) {
2771
- return true;
2772
- }
2773
- return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
2974
+ function onlyIncludeSelf() {
2975
+ this.included = true;
2976
+ if (!this.deoptimized)
2977
+ this.applyDeoptimizations();
2774
2978
  }
2775
- function getMemberReturnExpressionWhenCalled(members, memberName) {
2776
- if (typeof memberName !== 'string' || !members[memberName])
2777
- return UNKNOWN_RETURN_EXPRESSION;
2778
- return [members[memberName].returns, false];
2979
+ function onlyIncludeSelfNoDeoptimize() {
2980
+ this.included = true;
2981
+ }
2982
+ function doNotDeoptimize() {
2983
+ this.deoptimized = true;
2984
+ }
2985
+
2986
+ function isObjectExpressionNode(node) {
2987
+ return node instanceof NodeBase && node.type === ObjectExpression$1;
2988
+ }
2989
+ function isArrowFunctionExpressionNode(node) {
2990
+ return node instanceof NodeBase && node.type === ArrowFunctionExpression$1;
2991
+ }
2992
+ function isFunctionExpressionNode(node) {
2993
+ return node instanceof NodeBase && node.type === FunctionExpression$1;
2994
+ }
2995
+ function isIdentifierNode(node) {
2996
+ return node instanceof NodeBase && node.type === Identifier$1;
2779
2997
  }
2780
2998
 
2999
+ // To avoid infinite recursions
3000
+ const MAX_PATH_DEPTH = 6;
3001
+ // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
3002
+ // most MAX_PATH_DEPTH long. The last element is always UnknownKey
3003
+ const limitConcatenatedPathDepth = (path1, path2) => {
3004
+ const { length: length1 } = path1;
3005
+ const { length: length2 } = path2;
3006
+ return length1 === 0
3007
+ ? path2
3008
+ : length2 === 0
3009
+ ? path1
3010
+ : length1 + length2 > MAX_PATH_DEPTH
3011
+ ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
3012
+ : [...path1, ...path2];
3013
+ };
3014
+
2781
3015
  class Variable extends ExpressionEntity {
2782
3016
  markReassigned() {
2783
3017
  this.isReassigned = true;
2784
3018
  }
3019
+ markTargetOfAssignment() {
3020
+ this.isTargetOfAssignment = true;
3021
+ }
2785
3022
  constructor(name) {
2786
3023
  super();
2787
3024
  this.name = name;
@@ -2794,6 +3031,9 @@ class Variable extends ExpressionEntity {
2794
3031
  this.renderBaseName = null;
2795
3032
  this.renderName = null;
2796
3033
  this.isReassigned = false;
3034
+ // Unlike isReassigned, set eagerly during binding for every assignment,
3035
+ // including ones that are never included
3036
+ this.isTargetOfAssignment = false;
2797
3037
  this.onlyFunctionCallUsed = true;
2798
3038
  }
2799
3039
  /**
@@ -2882,10 +3122,9 @@ class LocalVariable extends Variable {
2882
3122
  this.kind = kind;
2883
3123
  this.calledFromTryStatement = false;
2884
3124
  this.additionalInitializers = null;
2885
- // A possibly incomplete list of values assigned to this variable after its
2886
- // declaration; as it is incomplete, it must never be used for value queries
2887
- // but only to forward call arguments to possible values
2888
- this.reassignedValues = null;
3125
+ // A possibly incomplete list of functions assigned to this variable; only used
3126
+ // to retain call arguments of assigned try-catch helpers, never for value queries
3127
+ this.assignedFunctions = null;
2889
3128
  this.includedPathTracker = new IncludedFullPathTracker();
2890
3129
  this.expressionsToBeDeoptimized = [];
2891
3130
  this.declarations = declarator ? [declarator] : [];
@@ -2930,6 +3169,15 @@ class LocalVariable extends Variable {
2930
3169
  this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
2931
3170
  }
2932
3171
  }
3172
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
3173
+ if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
3174
+ return null;
3175
+ }
3176
+ return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
3177
+ this.expressionsToBeDeoptimized.push(origin);
3178
+ return this.init.getKnownFunctionAtPath([...this.initPath, ...path], recursionTracker, origin);
3179
+ }, null);
3180
+ }
2933
3181
  getLiteralValueAtPath(path, recursionTracker, origin) {
2934
3182
  if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
2935
3183
  return UnknownValue;
@@ -3011,16 +3259,12 @@ class LocalVariable extends Variable {
3011
3259
  }
3012
3260
  includeCallArgumentsWhenCalledAtPath(path, interaction, context) {
3013
3261
  if (this.isReassigned) {
3014
- // Even when the value is unknown, it may be one of the assigned values;
3015
- // forwarding to all of them retains the arguments of try-catch helpers
3262
+ // The value may still be one of the assigned functions, whose try-catch
3263
+ // helpers need their call arguments retained
3016
3264
  includeInteraction(interaction, context);
3017
- // Each possible value is visited at most once per path and call
3018
- // per traversal so that dense assignment graphs do not repeat work
3019
- // for every simple path
3020
- const previousTracker = context.includedCallArgumentsOfPossibleValues;
3021
- context.includedCallArgumentsOfPossibleValues ??= new DiscriminatedPathTracker();
3022
- this.includeCallArgumentsOfPossibleValues(path, interaction, context, context.includedCallArgumentsOfPossibleValues);
3023
- context.includedCallArgumentsOfPossibleValues = previousTracker;
3265
+ if (path.length === 0) {
3266
+ this.includeCallArgumentsOfAssignedTryCatchHelpers(interaction, context);
3267
+ }
3024
3268
  return;
3025
3269
  }
3026
3270
  if (context.includedCallArguments.has(this.init) ||
@@ -3032,25 +3276,25 @@ class LocalVariable extends Variable {
3032
3276
  this.init.includeCallArgumentsWhenCalledAtPath([...this.initPath, ...path], interaction, context);
3033
3277
  context.includedCallArguments.delete(this.init);
3034
3278
  }
3035
- includeCallArgumentsOfPossibleValues(path, interaction, context, tracker) {
3036
- if (this.reassignedValues === null || path.length + this.initPath.length > MAX_PATH_DEPTH) {
3037
- return;
3279
+ includeCallArgumentsOfAssignedTryCatchHelpers(interaction, context) {
3280
+ if (this.initPath.length === 0) {
3281
+ this.includeCallArgumentsOfTryCatchHelper(this.init, interaction, context);
3038
3282
  }
3039
- this.includeCallArgumentsOfPossibleValue(this.init, [...this.initPath, ...path], interaction, context, tracker);
3040
- for (const entity of this.reassignedValues) {
3041
- this.includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker);
3283
+ for (const assignedFunction of this.assignedFunctions ?? EMPTY_ARRAY) {
3284
+ this.includeCallArgumentsOfTryCatchHelper(assignedFunction, interaction, context);
3042
3285
  }
3043
3286
  }
3044
- includeCallArgumentsOfPossibleValue(entity, path, interaction, context, tracker) {
3045
- if (entity === UNKNOWN_EXPRESSION ||
3046
- entity === UNDEFINED_EXPRESSION ||
3047
- tracker.trackEntityAtPathAndGetIfTracked(path, interaction, entity)) {
3048
- return;
3287
+ includeCallArgumentsOfTryCatchHelper(value, interaction, context) {
3288
+ if (isArrowFunctionExpressionNode(value) || isFunctionExpressionNode(value)) {
3289
+ if (value.scope.hasParameterCalledFromTryStatement()) {
3290
+ value.scope.includeCallArguments(interaction, context);
3291
+ }
3049
3292
  }
3050
- entity.includeCallArgumentsWhenCalledAtPath(path, interaction, context);
3051
3293
  }
3052
3294
  addReassignedValue(value) {
3053
- (this.reassignedValues ??= []).push(value);
3295
+ if (isArrowFunctionExpressionNode(value) || isFunctionExpressionNode(value)) {
3296
+ (this.assignedFunctions ??= []).push(value);
3297
+ }
3054
3298
  }
3055
3299
  markCalledFromTryStatement() {
3056
3300
  this.calledFromTryStatement = true;
@@ -3263,37 +3507,6 @@ function is_reference(node, parent) {
3263
3507
  }
3264
3508
  }
3265
3509
 
3266
- function createInclusionContext() {
3267
- return {
3268
- brokenFlow: false,
3269
- hasBreak: false,
3270
- hasContinue: false,
3271
- includedCallArguments: new Set(),
3272
- includedCallArgumentsOfPossibleValues: null,
3273
- includedLabels: new Set()
3274
- };
3275
- }
3276
- function createHasEffectsContext() {
3277
- return {
3278
- accessed: new EntityPathTracker(),
3279
- assigned: new EntityPathTracker(),
3280
- brokenFlow: false,
3281
- called: new DiscriminatedPathTracker(),
3282
- hasBreak: false,
3283
- hasContinue: false,
3284
- ignore: {
3285
- breaks: false,
3286
- continues: false,
3287
- labels: new Set(),
3288
- returnYield: false,
3289
- this: false
3290
- },
3291
- includedLabels: new Set(),
3292
- instantiated: new DiscriminatedPathTracker(),
3293
- replacedVariableInits: new Map()
3294
- };
3295
- }
3296
-
3297
3510
  const PureFunctionKey = Symbol('PureFunction');
3298
3511
  const getPureFunctions = ({ treeshake }) => {
3299
3512
  const pureFunctions = Object.create(null);
@@ -3488,297 +3701,215 @@ function markModuleAndImpureDependenciesAsExecuted(baseModule) {
3488
3701
  (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
3489
3702
  !visitedModules.has(dependency.id)) {
3490
3703
  dependency.isExecuted = true;
3491
- visitedModules.add(dependency.id);
3492
- modules.push(dependency);
3493
- }
3494
- }
3495
- }
3496
- }
3497
-
3498
- const doNothing = () => { };
3499
-
3500
- // This file is generated by scripts/generate-child-node-keys.ts.
3501
- // Do not edit this file directly.
3502
- const childNodeKeys = {
3503
- ArrayExpression: ['elements'],
3504
- ArrayPattern: ['elements'],
3505
- ArrowFunctionExpression: ['params', 'body'],
3506
- AssignmentExpression: ['left', 'right'],
3507
- AssignmentPattern: ['left', 'right'],
3508
- AwaitExpression: ['argument'],
3509
- BinaryExpression: ['left', 'right'],
3510
- BlockStatement: ['body'],
3511
- BreakStatement: ['label'],
3512
- CallExpression: ['callee', 'arguments'],
3513
- CatchClause: ['param', 'body'],
3514
- ChainExpression: ['expression'],
3515
- ClassBody: ['body'],
3516
- ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
3517
- ClassExpression: ['decorators', 'id', 'superClass', 'body'],
3518
- ConditionalExpression: ['test', 'consequent', 'alternate'],
3519
- ContinueStatement: ['label'],
3520
- DebuggerStatement: [],
3521
- Decorator: ['expression'],
3522
- DoWhileStatement: ['body', 'test'],
3523
- EmptyStatement: [],
3524
- ExportAllDeclaration: ['exported', 'source', 'attributes'],
3525
- ExportDefaultDeclaration: ['declaration'],
3526
- ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
3527
- ExportSpecifier: ['local', 'exported'],
3528
- ExpressionStatement: ['expression'],
3529
- ForInStatement: ['left', 'right', 'body'],
3530
- ForOfStatement: ['left', 'right', 'body'],
3531
- ForStatement: ['init', 'test', 'update', 'body'],
3532
- FunctionDeclaration: ['id', 'params', 'body'],
3533
- FunctionExpression: ['id', 'params', 'body'],
3534
- Identifier: [],
3535
- IfStatement: ['test', 'consequent', 'alternate'],
3536
- ImportAttribute: ['key', 'value'],
3537
- ImportDeclaration: ['specifiers', 'source', 'attributes'],
3538
- ImportDefaultSpecifier: ['local'],
3539
- ImportExpression: ['source', 'options'],
3540
- ImportNamespaceSpecifier: ['local'],
3541
- ImportSpecifier: ['imported', 'local'],
3542
- JSXAttribute: ['name', 'value'],
3543
- JSXClosingElement: ['name'],
3544
- JSXClosingFragment: [],
3545
- JSXElement: ['openingElement', 'children', 'closingElement'],
3546
- JSXEmptyExpression: [],
3547
- JSXExpressionContainer: ['expression'],
3548
- JSXFragment: ['openingFragment', 'children', 'closingFragment'],
3549
- JSXIdentifier: [],
3550
- JSXMemberExpression: ['object', 'property'],
3551
- JSXNamespacedName: ['namespace', 'name'],
3552
- JSXOpeningElement: ['name', 'attributes'],
3553
- JSXOpeningFragment: [],
3554
- JSXSpreadAttribute: ['argument'],
3555
- JSXSpreadChild: ['expression'],
3556
- JSXText: [],
3557
- LabeledStatement: ['label', 'body'],
3558
- Literal: [],
3559
- LogicalExpression: ['left', 'right'],
3560
- MemberExpression: ['object', 'property'],
3561
- MetaProperty: ['meta', 'property'],
3562
- MethodDefinition: ['decorators', 'key', 'value'],
3563
- NewExpression: ['callee', 'arguments'],
3564
- ObjectExpression: ['properties'],
3565
- ObjectPattern: ['properties'],
3566
- PanicError: [],
3567
- ParseError: [],
3568
- PrivateIdentifier: [],
3569
- Program: ['body'],
3570
- Property: ['key', 'value'],
3571
- PropertyDefinition: ['decorators', 'key', 'value'],
3572
- RestElement: ['argument'],
3573
- ReturnStatement: ['argument'],
3574
- SequenceExpression: ['expressions'],
3575
- SpreadElement: ['argument'],
3576
- StaticBlock: ['body'],
3577
- Super: [],
3578
- SwitchCase: ['test', 'consequent'],
3579
- SwitchStatement: ['discriminant', 'cases'],
3580
- TaggedTemplateExpression: ['tag', 'quasi'],
3581
- TemplateElement: [],
3582
- TemplateLiteral: ['quasis', 'expressions'],
3583
- ThisExpression: [],
3584
- ThrowStatement: ['argument'],
3585
- TryStatement: ['block', 'handler', 'finalizer'],
3586
- UnaryExpression: ['argument'],
3587
- UpdateExpression: ['argument'],
3588
- VariableDeclaration: ['declarations'],
3589
- VariableDeclarator: ['id', 'init'],
3590
- WhileStatement: ['test', 'body'],
3591
- YieldExpression: ['argument']
3592
- };
3593
-
3594
- const INCLUDE_PARAMETERS = 'variables';
3595
- const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
3596
- class NodeBase extends ExpressionEntity {
3597
- /**
3598
- * Nodes can apply custom deoptimizations once they become part of the
3599
- * executed code. To do this, they must initialize this as false, implement
3600
- * applyDeoptimizations and call this from include and hasEffects if they have
3601
- * custom handlers
3602
- */
3603
- get deoptimized() {
3604
- return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
3605
- }
3606
- set deoptimized(value) {
3607
- this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
3608
- }
3609
- constructor(parent, parentScope) {
3610
- super();
3611
- this.parent = parent;
3612
- this.scope = parentScope;
3613
- this.createScope(parentScope);
3614
- }
3615
- addExportedVariables(_variables, _exportNamesByVariable) { }
3616
- /**
3617
- * Override this to bind assignments to variables and do any initialisations
3618
- * that require the scopes to be populated with variables.
3619
- */
3620
- bind() {
3621
- for (const key of childNodeKeys[this.type]) {
3622
- const value = this[key];
3623
- if (Array.isArray(value)) {
3624
- for (const child of value) {
3625
- child?.bind();
3626
- }
3627
- }
3628
- else if (value) {
3629
- value.bind();
3630
- }
3631
- }
3632
- }
3633
- /**
3634
- * Override if this node should receive a different scope than the parent
3635
- * scope.
3636
- */
3637
- createScope(parentScope) {
3638
- this.scope = parentScope;
3639
- }
3640
- hasEffects(context) {
3641
- if (!this.deoptimized)
3642
- this.applyDeoptimizations();
3643
- for (const key of childNodeKeys[this.type]) {
3644
- const value = this[key];
3645
- if (value === null)
3646
- continue;
3647
- if (Array.isArray(value)) {
3648
- for (const child of value) {
3649
- if (child?.hasEffects(context))
3650
- return true;
3651
- }
3704
+ visitedModules.add(dependency.id);
3705
+ modules.push(dependency);
3652
3706
  }
3653
- else if (value.hasEffects(context))
3654
- return true;
3655
3707
  }
3656
- return false;
3657
3708
  }
3658
- hasEffectsAsAssignmentTarget(context, _checkAccess) {
3659
- return (this.hasEffects(context) ||
3660
- this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
3709
+ }
3710
+
3711
+ const doNothing = () => { };
3712
+
3713
+ function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
3714
+ return Object.create(inheritedDescriptions, memberDescriptions);
3715
+ }
3716
+ const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
3717
+ getLiteralValueAtPath(path) {
3718
+ return path.length > 0 ? UnknownValue : undefined;
3661
3719
  }
3662
- include(context, includeChildrenRecursively, _options) {
3663
- if (!this.included)
3664
- this.includeNode(context);
3665
- for (const key of childNodeKeys[this.type]) {
3666
- const value = this[key];
3667
- if (value === null)
3668
- continue;
3669
- if (Array.isArray(value)) {
3670
- for (const child of value) {
3671
- child?.include(context, includeChildrenRecursively);
3672
- }
3673
- }
3674
- else {
3675
- value.include(context, includeChildrenRecursively);
3676
- }
3720
+ })();
3721
+ const returnsUnknown = {
3722
+ value: {
3723
+ hasEffectsWhenCalled: null,
3724
+ returns: UNKNOWN_EXPRESSION
3725
+ }
3726
+ };
3727
+ const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
3728
+ getReturnExpressionWhenCalledAtPath(path) {
3729
+ if (path.length === 1) {
3730
+ return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
3677
3731
  }
3732
+ return UNKNOWN_RETURN_EXPRESSION;
3678
3733
  }
3679
- includeNode(context) {
3680
- this.included = true;
3681
- if (!this.deoptimized)
3682
- this.applyDeoptimizations();
3683
- for (const key of childNodeKeys[this.type]) {
3684
- const value = this[key];
3685
- if (value === null)
3686
- continue;
3687
- if (Array.isArray(value)) {
3688
- for (const child of value) {
3689
- child?.includePath(UNKNOWN_PATH, context);
3690
- }
3691
- }
3692
- else {
3693
- value.includePath(UNKNOWN_PATH, context);
3694
- }
3734
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
3735
+ if (interaction.type === INTERACTION_ACCESSED) {
3736
+ return path.length > 1;
3695
3737
  }
3738
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
3739
+ return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
3740
+ }
3741
+ return true;
3696
3742
  }
3697
- includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
3698
- this.include(context, includeChildrenRecursively);
3743
+ })();
3744
+ const returnsBoolean = {
3745
+ value: {
3746
+ hasEffectsWhenCalled: null,
3747
+ returns: UNKNOWN_LITERAL_BOOLEAN
3699
3748
  }
3700
- /**
3701
- * Override to perform special initialisation steps after the scope is
3702
- * initialised
3703
- */
3704
- initialise() {
3705
- this.scope.context.magicString.addSourcemapLocation(this.start);
3706
- this.scope.context.magicString.addSourcemapLocation(this.end);
3749
+ };
3750
+ const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
3751
+ getReturnExpressionWhenCalledAtPath(path) {
3752
+ if (path.length === 1) {
3753
+ return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
3754
+ }
3755
+ return UNKNOWN_RETURN_EXPRESSION;
3707
3756
  }
3708
- removeAnnotations(code) {
3709
- if (this.annotations) {
3710
- for (const annotation of this.annotations) {
3711
- code.remove(annotation.start, annotation.end);
3712
- }
3757
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
3758
+ if (interaction.type === INTERACTION_ACCESSED) {
3759
+ return path.length > 1;
3760
+ }
3761
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
3762
+ return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
3713
3763
  }
3764
+ return true;
3714
3765
  }
3715
- render(code, options) {
3716
- for (const key of childNodeKeys[this.type]) {
3717
- const value = this[key];
3718
- if (value === null)
3719
- continue;
3720
- if (Array.isArray(value)) {
3721
- for (const child of value) {
3722
- child?.render(code, options);
3723
- }
3724
- }
3725
- else {
3726
- value.render(code, options);
3727
- }
3766
+ })();
3767
+ const returnsNumber = {
3768
+ value: {
3769
+ hasEffectsWhenCalled: null,
3770
+ returns: UNKNOWN_LITERAL_NUMBER
3771
+ }
3772
+ };
3773
+ const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
3774
+ getReturnExpressionWhenCalledAtPath(path) {
3775
+ if (path.length === 1) {
3776
+ return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
3728
3777
  }
3778
+ return UNKNOWN_RETURN_EXPRESSION;
3729
3779
  }
3730
- setAssignedValue(value) {
3731
- this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
3780
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
3781
+ if (interaction.type === INTERACTION_ACCESSED) {
3782
+ return path.length > 1;
3783
+ }
3784
+ if (interaction.type === INTERACTION_CALLED && path.length === 1) {
3785
+ return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
3786
+ }
3787
+ return true;
3732
3788
  }
3733
- shouldBeIncluded(context) {
3734
- return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
3789
+ })();
3790
+ const returnsString = {
3791
+ value: {
3792
+ hasEffectsWhenCalled: null,
3793
+ returns: UNKNOWN_LITERAL_STRING
3735
3794
  }
3736
- /**
3737
- * Just deoptimize everything by default so that when e.g. we do not track
3738
- * something properly, it is deoptimized.
3739
- * @protected
3740
- */
3741
- applyDeoptimizations() {
3742
- this.deoptimized = true;
3743
- for (const key of childNodeKeys[this.type]) {
3744
- const value = this[key];
3745
- if (value === null)
3746
- continue;
3747
- if (Array.isArray(value)) {
3748
- for (const child of value) {
3749
- child?.deoptimizePath(UNKNOWN_PATH);
3750
- }
3751
- }
3752
- else {
3753
- value.deoptimizePath(UNKNOWN_PATH);
3754
- }
3795
+ };
3796
+ const stringReplace = {
3797
+ value: {
3798
+ hasEffectsWhenCalled({ args }, context) {
3799
+ const argument1 = args[2];
3800
+ return (args.length < 3 ||
3801
+ (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
3802
+ deoptimizeCache() { }
3803
+ }) === 'symbol' &&
3804
+ argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
3805
+ },
3806
+ returns: UNKNOWN_LITERAL_STRING
3807
+ }
3808
+ };
3809
+ const objectMembers = assembleMemberDescriptions({
3810
+ hasOwnProperty: returnsBoolean,
3811
+ isPrototypeOf: returnsBoolean,
3812
+ propertyIsEnumerable: returnsBoolean,
3813
+ toLocaleString: returnsString,
3814
+ toString: returnsString,
3815
+ valueOf: returnsUnknown
3816
+ });
3817
+ const literalBooleanMembers = assembleMemberDescriptions({
3818
+ valueOf: returnsBoolean
3819
+ }, objectMembers);
3820
+ const literalNumberMembers = assembleMemberDescriptions({
3821
+ toExponential: returnsString,
3822
+ toFixed: returnsString,
3823
+ toLocaleString: returnsString,
3824
+ toPrecision: returnsString,
3825
+ valueOf: returnsNumber
3826
+ }, objectMembers);
3827
+ /**
3828
+ * RegExp are stateful when they have the global or sticky flags set.
3829
+ * But if we actually don't use them, the side effect does not matter.
3830
+ * the check logic in `hasEffectsOnInteractionAtPath`.
3831
+ */
3832
+ const literalRegExpMembers = assembleMemberDescriptions({
3833
+ exec: returnsUnknown,
3834
+ test: returnsBoolean
3835
+ }, objectMembers);
3836
+ const literalStringMembers = assembleMemberDescriptions({
3837
+ anchor: returnsString,
3838
+ at: returnsUnknown,
3839
+ big: returnsString,
3840
+ blink: returnsString,
3841
+ bold: returnsString,
3842
+ charAt: returnsString,
3843
+ charCodeAt: returnsNumber,
3844
+ codePointAt: returnsUnknown,
3845
+ concat: returnsString,
3846
+ endsWith: returnsBoolean,
3847
+ fixed: returnsString,
3848
+ fontcolor: returnsString,
3849
+ fontsize: returnsString,
3850
+ includes: returnsBoolean,
3851
+ indexOf: returnsNumber,
3852
+ italics: returnsString,
3853
+ lastIndexOf: returnsNumber,
3854
+ link: returnsString,
3855
+ localeCompare: returnsNumber,
3856
+ match: returnsUnknown,
3857
+ matchAll: returnsUnknown,
3858
+ normalize: returnsString,
3859
+ padEnd: returnsString,
3860
+ padStart: returnsString,
3861
+ repeat: returnsString,
3862
+ replace: stringReplace,
3863
+ replaceAll: stringReplace,
3864
+ search: returnsNumber,
3865
+ slice: returnsString,
3866
+ small: returnsString,
3867
+ split: returnsUnknown,
3868
+ startsWith: returnsBoolean,
3869
+ strike: returnsString,
3870
+ sub: returnsString,
3871
+ substr: returnsString,
3872
+ substring: returnsString,
3873
+ sup: returnsString,
3874
+ toLocaleLowerCase: returnsString,
3875
+ toLocaleUpperCase: returnsString,
3876
+ toLowerCase: returnsString,
3877
+ toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
3878
+ toUpperCase: returnsString,
3879
+ trim: returnsString,
3880
+ trimEnd: returnsString,
3881
+ trimLeft: returnsString,
3882
+ trimRight: returnsString,
3883
+ trimStart: returnsString,
3884
+ valueOf: returnsString
3885
+ }, objectMembers);
3886
+ function getLiteralMembersForValue(value) {
3887
+ if (value instanceof RegExp) {
3888
+ return literalRegExpMembers;
3889
+ }
3890
+ switch (typeof value) {
3891
+ case 'boolean': {
3892
+ return literalBooleanMembers;
3893
+ }
3894
+ case 'number': {
3895
+ return literalNumberMembers;
3896
+ }
3897
+ case 'string': {
3898
+ return literalStringMembers;
3755
3899
  }
3756
- this.scope.context.requestTreeshakingPass();
3757
3900
  }
3901
+ return Object.create(null);
3758
3902
  }
3759
- function onlyIncludeSelf() {
3760
- this.included = true;
3761
- if (!this.deoptimized)
3762
- this.applyDeoptimizations();
3763
- }
3764
- function onlyIncludeSelfNoDeoptimize() {
3765
- this.included = true;
3766
- }
3767
- function doNotDeoptimize() {
3768
- this.deoptimized = true;
3769
- }
3770
-
3771
- function isObjectExpressionNode(node) {
3772
- return node instanceof NodeBase && node.type === ObjectExpression$1;
3773
- }
3774
- function isArrowFunctionExpressionNode(node) {
3775
- return node instanceof NodeBase && node.type === ArrowFunctionExpression$1;
3776
- }
3777
- function isFunctionExpressionNode(node) {
3778
- return node instanceof NodeBase && node.type === FunctionExpression$1;
3903
+ function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
3904
+ if (typeof memberName !== 'string' || !members[memberName]) {
3905
+ return true;
3906
+ }
3907
+ return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
3779
3908
  }
3780
- function isIdentifierNode(node) {
3781
- return node instanceof NodeBase && node.type === Identifier$1;
3909
+ function getMemberReturnExpressionWhenCalled(members, memberName) {
3910
+ if (typeof memberName !== 'string' || !members[memberName])
3911
+ return UNKNOWN_RETURN_EXPRESSION;
3912
+ return [members[memberName].returns, false];
3782
3913
  }
3783
3914
 
3784
3915
  class Method extends ExpressionEntity {
@@ -4061,6 +4192,17 @@ class ObjectEntity extends ExpressionEntity {
4061
4192
  }
4062
4193
  this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
4063
4194
  }
4195
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
4196
+ const key = path[0];
4197
+ // Setters can shadow data properties or inherited methods without appearing in the getter map.
4198
+ if (!isConcreteKey(key) || this.settersByKey.has(key) || this.unmatchableSetters.length > 0) {
4199
+ return null;
4200
+ }
4201
+ const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
4202
+ return expressionAtPath
4203
+ ? expressionAtPath.getKnownFunctionAtPath(path.slice(1), recursionTracker, origin)
4204
+ : this.prototypeExpression?.getKnownFunctionAtPath(path, recursionTracker, origin) || null;
4205
+ }
4064
4206
  getLiteralValueAtPath(path, recursionTracker, origin) {
4065
4207
  if (path.length === 0) {
4066
4208
  // This should actually be "UnknownTruthyValue". However, this currently
@@ -4317,22 +4459,25 @@ class ObjectEntity extends ExpressionEntity {
4317
4459
  }
4318
4460
  }
4319
4461
 
4320
- const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
4462
+ const isKnownToBeMissing = (property) => property === SymbolDispose ||
4463
+ property === SymbolAsyncDispose ||
4464
+ (typeof property === 'string' && /^\d+$/.test(property));
4321
4465
  // This makes sure unknown properties are not handled as "undefined" but as
4322
4466
  // "unknown" but without access side effects. An exception is done for numeric
4323
4467
  // properties as we do not expect new builtin properties to be numbers, this
4324
- // will improve tree-shaking for out-of-bounds array properties
4468
+ // will improve tree-shaking for out-of-bounds array properties. Disposal
4469
+ // methods are also known to be missing so that "await using" can rely on the
4470
+ // fallback to Symbol.dispose for plain objects.
4325
4471
  const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
4326
4472
  deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
4327
- if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
4473
+ if (interaction.type === INTERACTION_CALLED &&
4474
+ path.length === 1 &&
4475
+ !isKnownToBeMissing(path[0])) {
4328
4476
  deoptimizeInteraction(interaction);
4329
4477
  }
4330
4478
  }
4331
4479
  getLiteralValueAtPath(path) {
4332
- // We ignore number properties as we do not expect new properties to be
4333
- // numbers and also want to keep handling out-of-bound array elements as
4334
- // "undefined"
4335
- return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
4480
+ return path.length === 1 && isKnownToBeMissing(path[0]) ? undefined : UnknownValue;
4336
4481
  }
4337
4482
  hasEffectsOnInteractionAtPath(path, { type }) {
4338
4483
  return path.length > 1 || type === INTERACTION_CALLED;
@@ -4346,6 +4491,9 @@ const OBJECT_PROTOTYPE = new ObjectEntity(new Map([
4346
4491
  ['toString', METHOD_RETURNS_STRING],
4347
4492
  ['valueOf', METHOD_RETURNS_UNKNOWN]
4348
4493
  ]), OBJECT_PROTOTYPE_FALLBACK, true);
4494
+ // Generator prototypes inherit disposal methods from the iterator prototypes
4495
+ const GENERATOR_PROTOTYPE = new ObjectEntity([{ key: SymbolDispose, kind: 'init', property: UNKNOWN_EXPRESSION }], OBJECT_PROTOTYPE, true);
4496
+ const ASYNC_GENERATOR_PROTOTYPE = new ObjectEntity([{ key: SymbolAsyncDispose, kind: 'init', property: UNKNOWN_EXPRESSION }], OBJECT_PROTOTYPE, true);
4349
4497
 
4350
4498
  const NEW_ARRAY_PROPERTIES = [
4351
4499
  { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
@@ -4490,7 +4638,8 @@ const ARRAY_PROTOTYPE = new ObjectEntity(new Map([
4490
4638
 
4491
4639
  class SpreadElement extends NodeBase {
4492
4640
  deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
4493
- if (path.length > 0) {
4641
+ // Spread values are copied as data properties, so only calling them can still reach the argument
4642
+ if (path.length > 0 || interaction.type === INTERACTION_CALLED) {
4494
4643
  this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
4495
4644
  }
4496
4645
  }
@@ -4618,6 +4767,18 @@ const PURE_WITH_ARRAY = {
4618
4767
  return args.length > 1 && !(args[1] instanceof ArrayExpression);
4619
4768
  }
4620
4769
  };
4770
+ const PURE_WITH_ARRAY_OR_LENGTH = {
4771
+ deoptimizeArgumentsOnCall: doNothing,
4772
+ getLiteralValue: getUnknownValue,
4773
+ hasEffectsWhenCalled({ args }) {
4774
+ const [_thisArgument, firstArgument] = args;
4775
+ return (firstArgument !== undefined &&
4776
+ !(firstArgument instanceof ArrayExpression) &&
4777
+ typeof firstArgument.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
4778
+ deoptimizeCache: doNothing
4779
+ }) !== 'number');
4780
+ }
4781
+ };
4621
4782
  const GETTER_ACCESS = {
4622
4783
  deoptimizeArgumentsOnCall: doNothing,
4623
4784
  getLiteralValue: getUnknownValue,
@@ -4676,7 +4837,7 @@ const PC_WITH_ARRAY = {
4676
4837
  };
4677
4838
  const ARRAY_TYPE = {
4678
4839
  __proto__: null,
4679
- [ValueProperties]: PURE,
4840
+ [ValueProperties]: PURE_WITH_ARRAY_OR_LENGTH,
4680
4841
  from: O,
4681
4842
  of: PF,
4682
4843
  prototype: O
@@ -5653,6 +5814,9 @@ class IdentifierBase extends NodeBase {
5653
5814
  // Identifier as property that might be deoptimized by default
5654
5815
  this.variable?.deoptimizePath(path);
5655
5816
  }
5817
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
5818
+ return this.getVariableRespectingTDZ().getKnownFunctionAtPath(path, recursionTracker, origin);
5819
+ }
5656
5820
  getLiteralValueAtPath(path, recursionTracker, origin) {
5657
5821
  return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
5658
5822
  }
@@ -5844,6 +6008,9 @@ class Identifier extends IdentifierBase {
5844
6008
  this.variable = this.scope.findVariable(this.name);
5845
6009
  this.variable.addReference(this);
5846
6010
  this.isVariableReference = true;
6011
+ if (this.assignmentInteraction) {
6012
+ this.variable.markTargetOfAssignment();
6013
+ }
5847
6014
  }
5848
6015
  }
5849
6016
  declare(kind, destructuredInitPath, init) {
@@ -5961,6 +6128,11 @@ class PropertyBase extends NodeBase {
5961
6128
  deoptimizePath(path) {
5962
6129
  this.getAccessedValue()[0].deoptimizePath(path);
5963
6130
  }
6131
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
6132
+ return this.kind === 'get' || this.kind === 'set'
6133
+ ? null
6134
+ : this.value.getKnownFunctionAtPath(path, recursionTracker, origin);
6135
+ }
5964
6136
  getLiteralValueAtPath(path, recursionTracker, origin) {
5965
6137
  return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
5966
6138
  }
@@ -6010,9 +6182,51 @@ class MethodDefinition extends PropertyBase {
6010
6182
  }
6011
6183
  }
6012
6184
 
6185
+ class PropertyDefinition extends NodeBase {
6186
+ get computed() {
6187
+ return isFlagSet(this.flags, 1024 /* Flag.computed */);
6188
+ }
6189
+ set computed(value) {
6190
+ this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
6191
+ }
6192
+ deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
6193
+ this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
6194
+ }
6195
+ deoptimizePath(path) {
6196
+ this.value?.deoptimizePath(path);
6197
+ }
6198
+ getLiteralValueAtPath(path, recursionTracker, origin) {
6199
+ return this.value
6200
+ ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
6201
+ : UnknownValue;
6202
+ }
6203
+ getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
6204
+ return this.value
6205
+ ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
6206
+ : UNKNOWN_RETURN_EXPRESSION;
6207
+ }
6208
+ hasEffects(context) {
6209
+ return (this.key.hasEffects(context) ||
6210
+ (this.static && !!this.value?.hasEffects(context)) ||
6211
+ checkEffectForNodes(this.decorators, context));
6212
+ }
6213
+ hasEffectsOnInteractionAtPath(path, interaction, context) {
6214
+ return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
6215
+ }
6216
+ includeNode(context) {
6217
+ this.included = true;
6218
+ this.value?.includePath(UNKNOWN_PATH, context);
6219
+ for (const decorator of this.decorators) {
6220
+ decorator.includePath(UNKNOWN_PATH, context);
6221
+ }
6222
+ }
6223
+ }
6224
+ PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
6225
+
6013
6226
  class ClassNode extends NodeBase {
6014
6227
  constructor() {
6015
6228
  super(...arguments);
6229
+ this.instanceFieldValues = null;
6016
6230
  this.objectEntity = null;
6017
6231
  }
6018
6232
  createScope(parentScope) {
@@ -6046,7 +6260,7 @@ class ClassNode extends NodeBase {
6046
6260
  (this.classConstructor === null
6047
6261
  ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
6048
6262
  : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
6049
- false
6263
+ this.hasEffectsOnInstanceFieldInitialization(context)
6050
6264
  : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
6051
6265
  }
6052
6266
  include(context, includeChildrenRecursively) {
@@ -6064,6 +6278,10 @@ class ClassNode extends NodeBase {
6064
6278
  initialise() {
6065
6279
  super.initialise();
6066
6280
  this.id?.declare('class', EMPTY_PATH, this);
6281
+ this.instanceEntity = new ObjectEntity(new Map(), new ObjectMember(this, ['prototype']));
6282
+ // This makes sure that all deoptimizations of "this" are applied to the
6283
+ // instance entity, even if the class is only instantiated by unknown code.
6284
+ this.body.scope.instanceThisVariable.addArgumentForDeoptimization(this.instanceEntity);
6067
6285
  for (const method of this.body.body) {
6068
6286
  if (method instanceof MethodDefinition && method.kind === 'constructor') {
6069
6287
  this.classConstructor = method;
@@ -6084,6 +6302,36 @@ class ClassNode extends NodeBase {
6084
6302
  }
6085
6303
  this.scope.context.requestTreeshakingPass();
6086
6304
  }
6305
+ hasEffectsOnInstanceFieldInitialization(context) {
6306
+ const fieldValues = this.getInstanceFieldValues();
6307
+ if (fieldValues.length === 0)
6308
+ return false;
6309
+ const { replacedVariableInits } = context;
6310
+ const thisVariable = this.body.scope.instanceThisVariable;
6311
+ const thisInit = replacedVariableInits.get(thisVariable);
6312
+ replacedVariableInits.set(thisVariable, this.instanceEntity);
6313
+ const hasEffects = fieldValues.some(value => value.hasEffects(context));
6314
+ if (thisInit) {
6315
+ replacedVariableInits.set(thisVariable, thisInit);
6316
+ }
6317
+ else {
6318
+ replacedVariableInits.delete(thisVariable);
6319
+ }
6320
+ return hasEffects;
6321
+ }
6322
+ getInstanceFieldValues() {
6323
+ if (this.instanceFieldValues === null) {
6324
+ this.instanceFieldValues = [];
6325
+ for (const definition of this.body.body) {
6326
+ if (definition instanceof PropertyDefinition &&
6327
+ !definition.static &&
6328
+ definition.value !== null) {
6329
+ this.instanceFieldValues.push(definition.value);
6330
+ }
6331
+ }
6332
+ }
6333
+ return this.instanceFieldValues;
6334
+ }
6087
6335
  getObjectEntity() {
6088
6336
  if (this.objectEntity !== null) {
6089
6337
  return this.objectEntity;
@@ -6398,12 +6646,39 @@ class ParameterVariable extends LocalVariable {
6398
6646
  class ThisVariable extends ParameterVariable {
6399
6647
  constructor(context) {
6400
6648
  super('this', null, EMPTY_PATH, context);
6649
+ // Unlike parameters, track nested paths so receivers only keep what is accessed via "this"
6650
+ this.includedPathTracker = new IncludedFullPathTracker();
6401
6651
  }
6402
6652
  hasEffectsOnInteractionAtPath(path, interaction, context) {
6403
6653
  return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
6404
6654
  }
6405
6655
  }
6406
6656
 
6657
+ /**
6658
+ * Represents the return value of a function where all return statements return
6659
+ * the same variable that is the target of an assignment. As the assigned value
6660
+ * may replace the declaration initializer before the function returns, value
6661
+ * queries resolve to unknown, and call arguments are deoptimized directly
6662
+ * instead of being forwarded to the initializer alone.
6663
+ */
6664
+ class ReturnedIdentifier extends ExpressionEntity {
6665
+ constructor(returnedIdentifier) {
6666
+ super();
6667
+ this.returnedIdentifier = returnedIdentifier;
6668
+ }
6669
+ deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
6670
+ // The initializer may never be the value that is returned
6671
+ deoptimizeInteraction(interaction);
6672
+ this.returnedIdentifier.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
6673
+ }
6674
+ deoptimizePath(path) {
6675
+ this.returnedIdentifier.deoptimizePath(path);
6676
+ }
6677
+ includeCallArgumentsWhenCalledAtPath(path, interaction, context) {
6678
+ this.returnedIdentifier.includeCallArgumentsWhenCalledAtPath(path, interaction, context);
6679
+ }
6680
+ }
6681
+
6407
6682
  class CatchBodyScope extends ChildScope {
6408
6683
  constructor(parent) {
6409
6684
  super(parent, parent.context);
@@ -6512,6 +6787,9 @@ class ParameterScope extends ChildScope {
6512
6787
  }
6513
6788
  this.hasRest = hasRest;
6514
6789
  }
6790
+ hasParameterCalledFromTryStatement() {
6791
+ return this.parameters.some(parameterVariables => parameterVariables.some(variable => variable.calledFromTryStatement));
6792
+ }
6515
6793
  includeCallArguments({ args }, context) {
6516
6794
  let calledFromTryStatement = false;
6517
6795
  let argumentIncluded = false;
@@ -6635,21 +6913,21 @@ class ReturnValueScope extends ParameterScope {
6635
6913
  addArgumentToBeDeoptimized(_argument) { }
6636
6914
  updateReturnExpression() {
6637
6915
  const { returnExpressions } = this;
6638
- if (returnExpressions.length === 1) {
6639
- this.returnExpression = returnExpressions[0];
6916
+ const [firstExpression] = returnExpressions;
6917
+ // A single return, or the same variable returned on all paths, can be
6918
+ // resolved to that variable
6919
+ if (firstExpression && this.returnExpressionsResolveToSameVariable(firstExpression)) {
6920
+ this.returnExpression = firstExpression.variable.isTargetOfAssignment
6921
+ ? new ReturnedIdentifier(firstExpression)
6922
+ : firstExpression;
6923
+ }
6924
+ else if (returnExpressions.length === 1) {
6925
+ this.returnExpression = firstExpression;
6640
6926
  }
6641
6927
  else {
6642
- // Returning the same variable on all paths is equivalent to a single
6643
- // return, so the return expression can be resolved to that variable
6644
- const [firstExpression] = returnExpressions;
6645
- if (firstExpression && this.returnExpressionsResolveToSameVariable(firstExpression)) {
6646
- this.returnExpression = firstExpression;
6647
- }
6648
- else {
6649
- this.returnExpression = UNKNOWN_EXPRESSION;
6650
- for (const expression of returnExpressions) {
6651
- expression.deoptimizePath(UNKNOWN_PATH);
6652
- }
6928
+ this.returnExpression = UNKNOWN_EXPRESSION;
6929
+ for (const expression of returnExpressions) {
6930
+ expression.deoptimizePath(UNKNOWN_PATH);
6653
6931
  }
6654
6932
  }
6655
6933
  }
@@ -6674,8 +6952,11 @@ class FunctionScope extends ReturnValueScope {
6674
6952
  }
6675
6953
  includeCallArguments(interaction, context) {
6676
6954
  super.includeCallArguments(interaction, context);
6955
+ const { args } = interaction;
6956
+ if (args[0]) {
6957
+ this.thisVariable.includeArgumentPaths(args[0], context);
6958
+ }
6677
6959
  if (this.argumentsVariable.included) {
6678
- const { args } = interaction;
6679
6960
  for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
6680
6961
  const argument = args[argumentIndex];
6681
6962
  if (argument) {
@@ -6860,6 +7141,11 @@ class FunctionBase extends NodeBase {
6860
7141
  this.scope.deoptimizeAllParameters();
6861
7142
  }
6862
7143
  }
7144
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
7145
+ return path.length === 0
7146
+ ? this
7147
+ : this.getObjectEntity().getKnownFunctionAtPath(path, recursionTracker, origin);
7148
+ }
6863
7149
  getLiteralValueAtPath(path, recursionTracker, origin) {
6864
7150
  return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
6865
7151
  }
@@ -6867,7 +7153,7 @@ class FunctionBase extends NodeBase {
6867
7153
  if (path.length > 0) {
6868
7154
  return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
6869
7155
  }
6870
- if (this.async) {
7156
+ if (this.async || this.generator) {
6871
7157
  if (!this.deoptimizedReturn) {
6872
7158
  this.deoptimizedReturn = true;
6873
7159
  this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
@@ -7052,10 +7338,15 @@ class FunctionNode extends FunctionBase {
7052
7338
  {
7053
7339
  key: 'prototype',
7054
7340
  kind: 'init',
7055
- property: new ObjectEntity([], OBJECT_PROTOTYPE)
7341
+ property: new ObjectEntity([], this.getPrototypeOfPrototype())
7056
7342
  }
7057
7343
  ], OBJECT_PROTOTYPE));
7058
7344
  }
7345
+ getPrototypeOfPrototype() {
7346
+ if (!this.generator)
7347
+ return OBJECT_PROTOTYPE;
7348
+ return this.async ? ASYNC_GENERATOR_PROTOTYPE : GENERATOR_PROTOTYPE;
7349
+ }
7059
7350
  }
7060
7351
 
7061
7352
  class FunctionDeclaration extends FunctionNode {
@@ -7187,12 +7478,19 @@ ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
7187
7478
  ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
7188
7479
 
7189
7480
  const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
7190
- const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
7191
- const backSlashRegEx = /\\/g;
7481
+ const escapeRegEx = /[\n\r'\\\u2028\u2029]/g;
7482
+ const escapeReplacements = {
7483
+ '\n': '\\n',
7484
+ '\r': '\\r',
7485
+ "'": "\\'",
7486
+ '\\': '\\\\',
7487
+ '\u2028': '\\u2028',
7488
+ '\u2029': '\\u2029'
7489
+ };
7192
7490
  function escapeId(id) {
7193
7491
  if (!needsEscapeRegEx.test(id))
7194
7492
  return id;
7195
- return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
7493
+ return id.replace(escapeRegEx, character => escapeReplacements[character]);
7196
7494
  }
7197
7495
 
7198
7496
  const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
@@ -7608,6 +7906,20 @@ class MemberExpression extends NodeBase {
7608
7906
  ]);
7609
7907
  }
7610
7908
  }
7909
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
7910
+ if (this.variable) {
7911
+ return this.variable.getKnownFunctionAtPath(path, recursionTracker, origin);
7912
+ }
7913
+ if (this.isUndefined)
7914
+ return null;
7915
+ const propertyKey = this.getDynamicPropertyKey();
7916
+ if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
7917
+ if (propertyKey !== this.propertyKey)
7918
+ this.expressionsToBeDeoptimized.push(origin);
7919
+ return this.object.getKnownFunctionAtPath([propertyKey, ...path], recursionTracker, origin);
7920
+ }
7921
+ return null;
7922
+ }
7611
7923
  getLiteralValueAtPath(path, recursionTracker, origin) {
7612
7924
  if (this.variable) {
7613
7925
  return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
@@ -8395,7 +8707,7 @@ function getCompleteAmdId(options, chunkId) {
8395
8707
  }
8396
8708
 
8397
8709
  function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
8398
- const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
8710
+ const { _, getFunctionIntro, getPropertyAccess, n, s } = snippets;
8399
8711
  if (!namedExportsMode) {
8400
8712
  return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
8401
8713
  }
@@ -8411,15 +8723,7 @@ function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snip
8411
8723
  if (exportBlock)
8412
8724
  exportBlock += n;
8413
8725
  if (specifier.imported !== '*' && specifier.needsLiveBinding) {
8414
- const [left, right] = getDirectReturnFunction([], {
8415
- functionReturn: true,
8416
- lineBreakIndent: null,
8417
- name: null
8418
- });
8419
- exportBlock +=
8420
- `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
8421
- `${t}enumerable:${_}true,${n}` +
8422
- `${t}get:${_}${left}${importName}${right}${n}});`;
8726
+ exportBlock += `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}${getGetter(importName, false, t, snippets)});`;
8423
8727
  }
8424
8728
  else if (specifier.reexported === '__proto__') {
8425
8729
  exportBlock +=
@@ -8434,12 +8738,16 @@ function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snip
8434
8738
  }
8435
8739
  }
8436
8740
  }
8437
- for (const { exported, local } of exports) {
8741
+ for (const { exported, local, needsLiveBinding } of exports) {
8438
8742
  const lhs = `exports${getPropertyAccess(exported)}`;
8439
8743
  const rhs = local;
8440
8744
  if (lhs !== rhs) {
8441
8745
  if (exportBlock)
8442
8746
  exportBlock += n;
8747
+ if (needsLiveBinding) {
8748
+ exportBlock += `Object.defineProperty(exports,${_}${JSON.stringify(exported)},${_}${getGetter(rhs, true, t, snippets)});`;
8749
+ continue;
8750
+ }
8443
8751
  exportBlock +=
8444
8752
  exported === '__proto__'
8445
8753
  ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
@@ -8541,19 +8849,27 @@ function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringT
8541
8849
  }
8542
8850
  return '';
8543
8851
  }
8544
- const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
8852
+ const getDefineProperty = (name, needsLiveBinding, t, snippets) => {
8853
+ const { _ } = snippets;
8545
8854
  if (needsLiveBinding) {
8546
- const [left, right] = getDirectReturnFunction([], {
8547
- functionReturn: true,
8548
- lineBreakIndent: null,
8549
- name: null
8550
- });
8551
- return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
8552
- `${t}${t}enumerable:${_}true,${n}` +
8553
- `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
8855
+ return `Object.defineProperty(exports,${_}k,${_}${getGetter(`${name}[k]`, false, t, snippets, t)})`;
8554
8856
  }
8555
8857
  return `exports[k]${_}=${_}${name}[k]`;
8556
8858
  };
8859
+ const getGetter = (expression, configurable, t, { getDirectReturnFunction, getObject }, base = '') => {
8860
+ const [left, right] = getDirectReturnFunction([], {
8861
+ functionReturn: true,
8862
+ lineBreakIndent: null,
8863
+ name: null
8864
+ });
8865
+ const fields = [
8866
+ ['enumerable', 'true'],
8867
+ ['get', `${left}${expression}${right}`]
8868
+ ];
8869
+ if (configurable)
8870
+ fields.unshift(['configurable', 'true']);
8871
+ return getObject(fields, { lineBreakIndent: { base, t } });
8872
+ };
8557
8873
 
8558
8874
  function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
8559
8875
  const { _, cnst, n } = snippets;
@@ -11920,17 +12236,29 @@ function getMatcherString$1(id, resolutionBase) {
11920
12236
  }
11921
12237
  const createFilter$1 = function createFilter(include, exclude, options) {
11922
12238
  const resolutionBase = options && options.resolve;
11923
- const getMatcher = (id) => id instanceof RegExp
11924
- ? id
11925
- : {
12239
+ const getMatcher = (id) => {
12240
+ if (id instanceof RegExp) {
12241
+ return id;
12242
+ }
12243
+ // Compiling a pattern costs far more than matching against it, so only recompile when the cwd it resolves against changes
12244
+ const compile = () => picomatch(getMatcherString$1(id, resolutionBase), { dot: true });
12245
+ // These patterns never resolve against the cwd, so there is no need to read or track it
12246
+ if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
12247
+ return { test: compile() };
12248
+ }
12249
+ let compiledCwd = process.cwd();
12250
+ let fn = compile();
12251
+ return {
11926
12252
  test: (what) => {
11927
- // this refactor is a tad overly verbose but makes for easy debugging
11928
- const pattern = getMatcherString$1(id, resolutionBase);
11929
- const fn = picomatch(pattern, { dot: true });
11930
- const result = fn(what);
11931
- return result;
12253
+ const cwd = process.cwd();
12254
+ if (cwd !== compiledCwd) {
12255
+ compiledCwd = cwd;
12256
+ fn = compile();
12257
+ }
12258
+ return fn(what);
11932
12259
  }
11933
12260
  };
12261
+ };
11934
12262
  const includeMatchers = ensureArray$1(include).map(getMatcher);
11935
12263
  const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
11936
12264
  if (!includeMatchers.length && !excludeMatchers.length)
@@ -12043,6 +12371,14 @@ class ArrayPattern extends NodeBase {
12043
12371
  }
12044
12372
  }
12045
12373
  }
12374
+ setAssignedValue(value) {
12375
+ super.setAssignedValue(value);
12376
+ // Destructuring assigns each target only some subpath of the assigned
12377
+ // value, which is not tracked
12378
+ for (const element of this.elements) {
12379
+ element?.setAssignedValue(UNKNOWN_EXPRESSION);
12380
+ }
12381
+ }
12046
12382
  markDeclarationReached() {
12047
12383
  for (const element of this.elements) {
12048
12384
  element?.markDeclarationReached();
@@ -12212,6 +12548,14 @@ class ObjectPattern extends NodeBase {
12212
12548
  }
12213
12549
  }
12214
12550
  }
12551
+ setAssignedValue(value) {
12552
+ super.setAssignedValue(value);
12553
+ // Destructuring assigns each target only some subpath of the assigned
12554
+ // value, which is not tracked
12555
+ for (const property of this.properties) {
12556
+ property.setAssignedValue(UNKNOWN_EXPRESSION);
12557
+ }
12558
+ }
12215
12559
  }
12216
12560
  ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
12217
12561
  ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
@@ -12376,6 +12720,9 @@ class AssignmentPattern extends NodeBase {
12376
12720
  this.left.render(code, options, { isShorthandProperty });
12377
12721
  this.right.render(code, options);
12378
12722
  }
12723
+ setAssignedValue(value) {
12724
+ this.left.setAssignedValue(value);
12725
+ }
12379
12726
  applyDeoptimizations() {
12380
12727
  this.deoptimized = true;
12381
12728
  this.left.deoptimizePath(EMPTY_PATH);
@@ -12384,6 +12731,22 @@ class AssignmentPattern extends NodeBase {
12384
12731
  }
12385
12732
  }
12386
12733
 
12734
+ function markTopLevelAwait(node) {
12735
+ if (node.scope.context.usesTopLevelAwait)
12736
+ return;
12737
+ let parent = node.parent;
12738
+ while (parent) {
12739
+ const { type } = parent;
12740
+ if (type === ArrowFunctionExpression$1 ||
12741
+ type === FunctionExpression$1 ||
12742
+ type === FunctionDeclaration$1) {
12743
+ return;
12744
+ }
12745
+ parent = parent.parent;
12746
+ }
12747
+ node.scope.context.usesTopLevelAwait = true;
12748
+ }
12749
+
12387
12750
  class AwaitExpression extends NodeBase {
12388
12751
  deoptimizePath(path) {
12389
12752
  this.argument.deoptimizePath(path);
@@ -12395,16 +12758,7 @@ class AwaitExpression extends NodeBase {
12395
12758
  }
12396
12759
  initialise() {
12397
12760
  super.initialise();
12398
- let parent = this.parent;
12399
- do {
12400
- const { type } = parent;
12401
- if (type === ArrowFunctionExpression$1 ||
12402
- type === FunctionExpression$1 ||
12403
- type === FunctionDeclaration$1) {
12404
- return;
12405
- }
12406
- } while ((parent = parent.parent));
12407
- this.scope.context.usesTopLevelAwait = true;
12761
+ markTopLevelAwait(this);
12408
12762
  }
12409
12763
  include(context, includeChildrenRecursively) {
12410
12764
  if (!this.included)
@@ -12885,7 +13239,8 @@ class ClassBodyScope extends ChildScope {
12885
13239
  super(parent, context);
12886
13240
  this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
12887
13241
  this.instanceScope = new ChildScope(this, context);
12888
- this.instanceScope.variables.set('this', new ThisVariable(context));
13242
+ this.instanceThisVariable = new ThisVariable(context);
13243
+ this.instanceScope.variables.set('this', this.instanceThisVariable);
12889
13244
  }
12890
13245
  findLexicalBoundary() {
12891
13246
  return this;
@@ -13377,6 +13732,8 @@ class ForOfStatement extends NodeBase {
13377
13732
  }
13378
13733
  initialise() {
13379
13734
  super.initialise();
13735
+ if (this.await)
13736
+ markTopLevelAwait(this);
13380
13737
  this.left.setAssignedValue(UNKNOWN_EXPRESSION);
13381
13738
  }
13382
13739
  render(code, options) {
@@ -14081,19 +14438,17 @@ class JSXAttribute extends NodeBase {
14081
14438
  }
14082
14439
  if (value) {
14083
14440
  code.overwrite(name.end, value.start, ': ', { contentOnly: true });
14084
- // foo="aa \n aa"
14085
- if (value instanceof Literal &&
14086
- typeof value.value === 'string' &&
14087
- value.value.includes('\n')) {
14088
- code.overwrite(value.start, value.end, JSON.stringify(value.value), {
14089
- contentOnly: true
14090
- });
14091
- }
14092
14441
  }
14093
14442
  else {
14094
14443
  code.appendLeft(name.end, ': true');
14095
14444
  }
14096
14445
  }
14446
+ // JSX strings contain HTML entities but no escape sequences
14447
+ if (value instanceof Literal && typeof value.value === 'string') {
14448
+ code.overwrite(value.start, value.end, JSON.stringify(value.value), {
14449
+ contentOnly: true
14450
+ });
14451
+ }
14097
14452
  }
14098
14453
  }
14099
14454
  }
@@ -14878,6 +15233,9 @@ class ObjectExpression extends NodeBase {
14878
15233
  deoptimizePath(path) {
14879
15234
  this.getObjectEntity().deoptimizePath(path);
14880
15235
  }
15236
+ getKnownFunctionAtPath(path, recursionTracker, origin) {
15237
+ return this.getObjectEntity().getKnownFunctionAtPath(path, recursionTracker, origin);
15238
+ }
14881
15239
  getLiteralValueAtPath(path, recursionTracker, origin) {
14882
15240
  return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
14883
15241
  }
@@ -15111,83 +15469,45 @@ class Property extends PropertyBase {
15111
15469
  }
15112
15470
  }
15113
15471
  if (!this.included && included) {
15114
- this.includeNode(context);
15115
- }
15116
- return this.included;
15117
- }
15118
- include(context, includeChildrenRecursively) {
15119
- this.included = true;
15120
- this.key.include(context, includeChildrenRecursively);
15121
- this.value.include(context, includeChildrenRecursively);
15122
- }
15123
- includePath(path, context) {
15124
- this.included = true;
15125
- this.value.includePath(path, context);
15126
- }
15127
- markDeclarationReached() {
15128
- this.value.markDeclarationReached();
15129
- }
15130
- render(code, options) {
15131
- if (!this.shorthand) {
15132
- this.key.render(code, options);
15133
- }
15134
- this.value.render(code, options, { isShorthandProperty: this.shorthand });
15135
- }
15136
- getPathInProperty(destructuredInitPath) {
15137
- return destructuredInitPath.at(-1) === UnknownKey
15138
- ? destructuredInitPath
15139
- : // For now, we only consider static paths as we do not know how to
15140
- // deoptimize the path in the dynamic case.
15141
- this.computed
15142
- ? [...destructuredInitPath, UnknownKey]
15143
- : this.key instanceof Identifier
15144
- ? [...destructuredInitPath, this.key.name]
15145
- : [...destructuredInitPath, String(this.key.value)];
15146
- }
15147
- }
15148
- Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
15149
- Property.prototype.applyDeoptimizations = doNotDeoptimize;
15150
-
15151
- class PropertyDefinition extends NodeBase {
15152
- get computed() {
15153
- return isFlagSet(this.flags, 1024 /* Flag.computed */);
15154
- }
15155
- set computed(value) {
15156
- this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
15157
- }
15158
- deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
15159
- this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
15160
- }
15161
- deoptimizePath(path) {
15162
- this.value?.deoptimizePath(path);
15163
- }
15164
- getLiteralValueAtPath(path, recursionTracker, origin) {
15165
- return this.value
15166
- ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
15167
- : UnknownValue;
15168
- }
15169
- getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
15170
- return this.value
15171
- ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
15172
- : UNKNOWN_RETURN_EXPRESSION;
15173
- }
15174
- hasEffects(context) {
15175
- return (this.key.hasEffects(context) ||
15176
- (this.static && !!this.value?.hasEffects(context)) ||
15177
- checkEffectForNodes(this.decorators, context));
15472
+ this.includeNode(context);
15473
+ }
15474
+ return this.included;
15178
15475
  }
15179
- hasEffectsOnInteractionAtPath(path, interaction, context) {
15180
- return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
15476
+ include(context, includeChildrenRecursively) {
15477
+ this.included = true;
15478
+ this.key.include(context, includeChildrenRecursively);
15479
+ this.value.include(context, includeChildrenRecursively);
15181
15480
  }
15182
- includeNode(context) {
15481
+ includePath(path, context) {
15183
15482
  this.included = true;
15184
- this.value?.includePath(UNKNOWN_PATH, context);
15185
- for (const decorator of this.decorators) {
15186
- decorator.includePath(UNKNOWN_PATH, context);
15483
+ this.value.includePath(path, context);
15484
+ }
15485
+ markDeclarationReached() {
15486
+ this.value.markDeclarationReached();
15487
+ }
15488
+ render(code, options) {
15489
+ if (!this.shorthand) {
15490
+ this.key.render(code, options);
15187
15491
  }
15492
+ this.value.render(code, options, { isShorthandProperty: this.shorthand });
15493
+ }
15494
+ setAssignedValue(value) {
15495
+ this.value.setAssignedValue(value);
15496
+ }
15497
+ getPathInProperty(destructuredInitPath) {
15498
+ return destructuredInitPath.at(-1) === UnknownKey
15499
+ ? destructuredInitPath
15500
+ : // For now, we only consider static paths as we do not know how to
15501
+ // deoptimize the path in the dynamic case.
15502
+ this.computed
15503
+ ? [...destructuredInitPath, UnknownKey]
15504
+ : this.key instanceof Identifier
15505
+ ? [...destructuredInitPath, this.key.name]
15506
+ : [...destructuredInitPath, String(this.key.value)];
15188
15507
  }
15189
15508
  }
15190
- PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
15509
+ Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
15510
+ Property.prototype.applyDeoptimizations = doNotDeoptimize;
15191
15511
 
15192
15512
  class RestElement extends NodeBase {
15193
15513
  constructor() {
@@ -15233,6 +15553,9 @@ class RestElement extends NodeBase {
15233
15553
  markDeclarationReached() {
15234
15554
  this.argument.markDeclarationReached();
15235
15555
  }
15556
+ setAssignedValue(value) {
15557
+ this.argument.setAssignedValue(value);
15558
+ }
15236
15559
  applyDeoptimizations() {
15237
15560
  this.deoptimized = true;
15238
15561
  if (this.declarationInit !== null) {
@@ -15996,6 +16319,8 @@ class VariableDeclaration extends NodeBase {
15996
16319
  }
15997
16320
  initialise() {
15998
16321
  super.initialise();
16322
+ if (this.kind === 'await using')
16323
+ markTopLevelAwait(this);
15999
16324
  for (const declarator of this.declarations) {
16000
16325
  declarator.declareDeclarator(this.kind);
16001
16326
  }
@@ -16161,6 +16486,14 @@ class VariableDeclarator extends NodeBase {
16161
16486
  deoptimizePath(path) {
16162
16487
  this.id.deoptimizePath(path);
16163
16488
  }
16489
+ deoptimizeCache() {
16490
+ if (!this.hasDeoptimizedDisposal && this.init) {
16491
+ this.hasDeoptimizedDisposal = true;
16492
+ this.init.deoptimizePath(UNKNOWN_PATH);
16493
+ this.init.includePath(UNKNOWN_PATH, createInclusionContext());
16494
+ this.scope.context.requestTreeshakingPass();
16495
+ }
16496
+ }
16164
16497
  hasEffects(context) {
16165
16498
  const initEffect = this.init?.hasEffects(context);
16166
16499
  this.id.markDeclarationReached();
@@ -16176,6 +16509,11 @@ class VariableDeclarator extends NodeBase {
16176
16509
  const { id, init } = this;
16177
16510
  if (!this.included)
16178
16511
  this.includeNode(context);
16512
+ const { disposalCall, disposalFunction } = this;
16513
+ // Before including init so that newly included receiver paths are included in this pass
16514
+ if (disposalFunction && disposalCall) {
16515
+ disposalFunction.includeCallArgumentsWhenCalledAtPath(EMPTY_PATH, disposalCall, context);
16516
+ }
16179
16517
  init?.include(context, includeChildrenRecursively);
16180
16518
  id.markDeclarationReached();
16181
16519
  if (includeChildrenRecursively) {
@@ -16217,11 +16555,16 @@ class VariableDeclarator extends NodeBase {
16217
16555
  this.included = true;
16218
16556
  const { id, init } = this;
16219
16557
  if (init) {
16220
- if (this.isUsingDeclaration) {
16221
- init.includePath(SYMBOL_DISPOSE_PATH, context);
16222
- }
16223
- else if (this.isAsyncUsingDeclaration) {
16224
- init.includePath(SYMBOL_ASYNC_DISPOSE_PATH, context);
16558
+ if (this.isUsingDeclaration || this.isAsyncUsingDeclaration) {
16559
+ const disposalInteractions = {
16560
+ access: { args: [init], type: INTERACTION_ACCESSED },
16561
+ call: { args: [init], type: INTERACTION_CALLED, withNew: false }
16562
+ };
16563
+ if (this.isUsingDeclaration ||
16564
+ !this.includeDisposalMethodAndCheckIfKnownFunction(init, SYMBOL_ASYNC_DISPOSE_PATH, disposalInteractions, context)) {
16565
+ this.includeDisposalMethodAndCheckIfKnownFunction(init, SYMBOL_DISPOSE_PATH, disposalInteractions, context);
16566
+ }
16567
+ this.scope.context.requestTreeshakingPass();
16225
16568
  }
16226
16569
  if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
16227
16570
  const { name, variable } = id;
@@ -16233,6 +16576,23 @@ class VariableDeclarator extends NodeBase {
16233
16576
  }
16234
16577
  }
16235
16578
  }
16579
+ includeDisposalMethodAndCheckIfKnownFunction(init, path, { access, call }, context) {
16580
+ init.deoptimizeArgumentsOnInteractionAtPath(access, path, SHARED_RECURSION_TRACKER);
16581
+ const disposalFunction = init.getKnownFunctionAtPath(path, SHARED_RECURSION_TRACKER, this);
16582
+ init.includePath(path, context);
16583
+ if (!disposalFunction) {
16584
+ const disposalValue = init.getLiteralValueAtPath(path, SHARED_RECURSION_TRACKER, this);
16585
+ if (disposalValue !== null && disposalValue !== undefined) {
16586
+ init.deoptimizeArgumentsOnInteractionAtPath(call, path, SHARED_RECURSION_TRACKER);
16587
+ init.includeCallArgumentsWhenCalledAtPath(path, call, context);
16588
+ }
16589
+ return false;
16590
+ }
16591
+ this.disposalFunction = disposalFunction;
16592
+ this.disposalCall = call;
16593
+ disposalFunction.deoptimizeArgumentsOnInteractionAtPath(call, EMPTY_PATH, SHARED_RECURSION_TRACKER);
16594
+ return true;
16595
+ }
16236
16596
  }
16237
16597
  VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
16238
16598
  const SYMBOL_DISPOSE_PATH = [SymbolDispose];
@@ -16764,7 +17124,7 @@ const bufferParsers = [
16764
17124
  function literalNumber(node, position, buffer) {
16765
17125
  const rawPosition = buffer[position];
16766
17126
  node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
16767
- node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
17127
+ node.value = buffer.convertFloat64(position + 1);
16768
17128
  },
16769
17129
  function literalRegExp(node, position, buffer) {
16770
17130
  const flags = buffer.convertString(buffer[position]);
@@ -17033,6 +17393,9 @@ function decodedSourcemap(map) {
17033
17393
  if (typeof map === 'string') {
17034
17394
  map = JSON.parse(map);
17035
17395
  }
17396
+ if ('sections' in map) {
17397
+ map = flattenIndexSourceMap(map);
17398
+ }
17036
17399
  if (!map.mappings) {
17037
17400
  return {
17038
17401
  mappings: [],
@@ -17068,6 +17431,74 @@ function decodedSourcemap(map) {
17068
17431
  sourceMapCache.set(decodedMap, cache);
17069
17432
  return decodedMap;
17070
17433
  }
17434
+ function flattenIndexSourceMap({ file, sections }) {
17435
+ const mappings = [];
17436
+ const names = [];
17437
+ const sources = [];
17438
+ const sourcesContent = [];
17439
+ // As when collapsing sourcemaps, sources with the same name are shared unless their contents differ
17440
+ const sourceIndicesByName = new Map();
17441
+ for (const { map, offset } of sections) {
17442
+ const section = decodedSourcemap(map);
17443
+ const { sourceRoot } = section;
17444
+ const sourcePrefix = sourceRoot
17445
+ ? sourceRoot.endsWith('/')
17446
+ ? sourceRoot
17447
+ : `${sourceRoot}/`
17448
+ : '';
17449
+ const sourceIndices = section.sources.map((source, index) => {
17450
+ const name = source == null || isAbsolute$1(source) ? source : sourcePrefix + source;
17451
+ const content = section.sourcesContent?.[index] ?? null;
17452
+ let indices = sourceIndicesByName.get(name);
17453
+ if (!indices) {
17454
+ sourceIndicesByName.set(name, (indices = []));
17455
+ }
17456
+ let sourceIndex = indices.find(candidate => content == null ||
17457
+ sourcesContent[candidate] == null ||
17458
+ sourcesContent[candidate] === content);
17459
+ if (sourceIndex === undefined) {
17460
+ sourceIndex = sources.push(name) - 1;
17461
+ sourcesContent.push(content);
17462
+ indices.push(sourceIndex);
17463
+ }
17464
+ else {
17465
+ sourcesContent[sourceIndex] ??= content;
17466
+ }
17467
+ return sourceIndex;
17468
+ });
17469
+ const namesOffset = names.length;
17470
+ for (const name of section.names ?? []) {
17471
+ names.push(name);
17472
+ }
17473
+ for (const [lineIndex, line] of section.mappings.entries()) {
17474
+ const generatedLine = offset.line + lineIndex;
17475
+ while (mappings.length <= generatedLine) {
17476
+ mappings.push([]);
17477
+ }
17478
+ // Only the first line of a section starts at the column offset
17479
+ const columnOffset = lineIndex === 0 ? offset.column : 0;
17480
+ for (const segment of line) {
17481
+ const flatSegment = segment.slice();
17482
+ flatSegment[0] += columnOffset;
17483
+ if (flatSegment.length !== 1) {
17484
+ flatSegment[1] = sourceIndices[flatSegment[1]];
17485
+ if (flatSegment.length === 5) {
17486
+ flatSegment[4] += namesOffset;
17487
+ }
17488
+ }
17489
+ mappings[generatedLine].push(flatSegment);
17490
+ }
17491
+ }
17492
+ }
17493
+ return {
17494
+ file,
17495
+ mappings,
17496
+ names,
17497
+ sources,
17498
+ sourcesContent,
17499
+ version: 3
17500
+ };
17501
+ }
17071
17502
 
17072
17503
  function getId(m) {
17073
17504
  return m.id;
@@ -17084,7 +17515,7 @@ function getOriginalLocation(sourcemapChain, location) {
17084
17515
  let previousSegment = filteredLine[0];
17085
17516
  for (let segment of filteredLine) {
17086
17517
  if (segment[0] >= location.column || segment === lastSegment) {
17087
- const notMatched = segment[0] !== location.column;
17518
+ const notMatched = segment[0] > location.column;
17088
17519
  segment = notMatched ? previousSegment : segment;
17089
17520
  location = {
17090
17521
  column: segment[3],
@@ -17756,6 +18187,9 @@ class Module {
17756
18187
  hasEffects() {
17757
18188
  return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
17758
18189
  }
18190
+ hasTopLevelAwait() {
18191
+ return this.astContext.usesTopLevelAwait;
18192
+ }
17759
18193
  include() {
17760
18194
  const context = createInclusionContext();
17761
18195
  if (this.ast.shouldBeIncluded(context))
@@ -18370,7 +18804,8 @@ function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconf
18370
18804
  for (const variable of imports) {
18371
18805
  const module = variable.module;
18372
18806
  const name = variable.name;
18373
- if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
18807
+ if (variable.isNamespace &&
18808
+ (module instanceof ExternalModule || (preserveModules && !module.info.syntheticNamedExports))) {
18374
18809
  variable.setRenderNames(null, (module instanceof ExternalModule
18375
18810
  ? externalChunkByModule.get(module)
18376
18811
  : chunkByModule.get(module)).variableName);
@@ -18434,7 +18869,7 @@ function deconflictImportsOther(usedNames, imports, { deconflictedDefault, decon
18434
18869
  }
18435
18870
  else {
18436
18871
  const chunk = chunkByModule.get(module);
18437
- if (preserveModules && variable.isNamespace) {
18872
+ if (preserveModules && variable.isNamespace && !module.info.syntheticNamedExports) {
18438
18873
  variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
18439
18874
  }
18440
18875
  else if (chunk.exportMode === 'default') {
@@ -18808,7 +19243,8 @@ class Chunk {
18808
19243
  const chunkModules = new Set(orderedModules);
18809
19244
  for (const module of orderedModules) {
18810
19245
  chunkByModule.set(module, this);
18811
- if (module.namespace.included && !outputOptions.preserveModules) {
19246
+ if (module.namespace.included &&
19247
+ (!outputOptions.preserveModules || module.info.syntheticNamedExports)) {
18812
19248
  includedNamespaces.add(module);
18813
19249
  }
18814
19250
  if (this.isEmpty && module.isIncluded()) {
@@ -19112,11 +19548,16 @@ class Chunk {
19112
19548
  });
19113
19549
  }
19114
19550
  getVariableExportName(variable) {
19115
- if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
19551
+ if (this.isNativeNamespace(variable)) {
19116
19552
  return '*';
19117
19553
  }
19118
19554
  return this.exportNamesByVariable.get(variable)[0];
19119
19555
  }
19556
+ isNativeNamespace(variable) {
19557
+ return (this.outputOptions.preserveModules &&
19558
+ variable instanceof NamespaceVariable &&
19559
+ !variable.module.info.syntheticNamedExports);
19560
+ }
19120
19561
  link() {
19121
19562
  this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
19122
19563
  for (const module of this.orderedModules) {
@@ -19144,6 +19585,7 @@ class Chunk {
19144
19585
  const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
19145
19586
  const renderedDependencies = [...this.getRenderedDependencies().values()];
19146
19587
  const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
19588
+ const renderedExportNames = format === 'es' && new Set(renderedExports.map(({ exported }) => exported));
19147
19589
  let hasExports = renderedExports.length > 0;
19148
19590
  let hasDefaultExport = false;
19149
19591
  for (const renderedDependency of renderedDependencies) {
@@ -19153,8 +19595,8 @@ class Chunk {
19153
19595
  if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
19154
19596
  hasDefaultExport = true;
19155
19597
  }
19156
- if (format === 'es') {
19157
- renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
19598
+ if (renderedExportNames) {
19599
+ renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExportNames.has(reexported));
19158
19600
  }
19159
19601
  }
19160
19602
  }
@@ -19258,8 +19700,9 @@ class Chunk {
19258
19700
  const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
19259
19701
  this.checkCircularDependencyImport(importedVariable, module);
19260
19702
  // When preserving modules, we do not create namespace objects but directly
19261
- // use the actual namespaces, which would be broken by this logic.
19262
- if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
19703
+ // use the actual namespaces, which would be broken by this logic. Modules with
19704
+ // synthetic named exports still need a namespace object.
19705
+ if (!this.isNativeNamespace(importedVariable)) {
19263
19706
  const exportingModule = importedVariable.module;
19264
19707
  if (exportingModule instanceof Module) {
19265
19708
  const chunk = this.chunkByModule.get(exportingModule);
@@ -19343,7 +19786,8 @@ class Chunk {
19343
19786
  exported: exportName,
19344
19787
  expression,
19345
19788
  hoisted,
19346
- local
19789
+ local,
19790
+ needsLiveBinding: variable.isReassigned && this.exportNamesByVariable.get(variable).length > 1
19347
19791
  });
19348
19792
  }
19349
19793
  return exports;
@@ -19830,9 +20274,8 @@ class Chunk {
19830
20274
  }
19831
20275
  setUpChunkImportsAndExportsForModule(module) {
19832
20276
  const moduleImports = new Set(module.includedImports);
19833
- // when we are not preserving modules, we need to make all namespace variables available for
19834
- // rendering the namespace object
19835
- if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
20277
+ // we need to make all namespace variables available for rendering the namespace object
20278
+ if (this.includedNamespaces.has(module)) {
19836
20279
  for (const variable of module.getExportedVariablesByName().values()) {
19837
20280
  if (variable.included) {
19838
20281
  moduleImports.add(variable);
@@ -19852,8 +20295,9 @@ class Chunk {
19852
20295
  if (variable.module instanceof Module) {
19853
20296
  this.checkCircularDependencyImport(variable, module);
19854
20297
  // When preserving modules, we do not create namespace objects but directly
19855
- // use the actual namespaces, which would be broken by this logic.
19856
- if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
20298
+ // use the actual namespaces, which would be broken by this logic. Modules with
20299
+ // synthetic named exports still need a namespace object.
20300
+ if (!this.isNativeNamespace(variable)) {
19857
20301
  chunk.exports.add(variable);
19858
20302
  }
19859
20303
  }
@@ -20046,7 +20490,8 @@ function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log
20046
20490
  // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
20047
20491
  // If we no longer want this, we should make a copy here.
20048
20492
  const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, entriesAndManualChunksCount);
20049
- const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, entriesAndManualChunksCount);
20493
+ // Warning: This will consume dynamicallyDependentEntriesByAwaitedDynamicEntry.
20494
+ const awaitedAlreadyLoadedAtomsByEntry = getAwaitedAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, entriesAndManualChunksCount);
20050
20495
  // A manual chunk only behaves like a dynamic entry if its whole member atom
20051
20496
  // is not already loaded whenever any entry dynamically loads it. Otherwise
20052
20497
  // there is nothing to gain (and cycles could be created) and the manual
@@ -20149,9 +20594,11 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
20149
20594
  dynamicManualChunksForCurrentEntry;
20150
20595
  awaitedLoadedManualChunksByEntry[entryOrManualChunkIndex] = awaitedManualChunksForCurrentEntry;
20151
20596
  const staticDependencies = new Set(currentEntryModules);
20597
+ let hasTopLevelAwait = false;
20152
20598
  // If we have a very large manual chunk, tracking if it is already added to the dependencies will improve performance
20153
20599
  const addedManualChunks = new Set();
20154
20600
  for (const module of staticDependencies) {
20601
+ hasTopLevelAwait ||= module.hasTopLevelAwait();
20155
20602
  getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryOrManualChunkIndex);
20156
20603
  const manualChunk = manualChunkByModule.get(module);
20157
20604
  if (manualChunk && !addedManualChunks.has(manualChunk)) {
@@ -20166,7 +20613,6 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
20166
20613
  }
20167
20614
  }
20168
20615
  for (const { node: { resolution } } of module.dynamicImports) {
20169
- let manuallyLoadedChunk = null;
20170
20616
  if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
20171
20617
  if (!allEntriesSet.has(resolution)) {
20172
20618
  dynamicEntryModules.add(resolution);
@@ -20174,25 +20620,13 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
20174
20620
  allEntriesAndManualChunks.push([resolution]);
20175
20621
  }
20176
20622
  else if (!dynamicEntryModules.has(resolution)) {
20177
- manuallyLoadedChunk = manualChunkByModule.get(resolution) ?? null;
20623
+ const manuallyLoadedChunk = manualChunkByModule.get(resolution);
20178
20624
  if (!manuallyLoadedChunk) {
20179
20625
  continue;
20180
20626
  }
20181
20627
  dynamicManualChunksForCurrentEntry.add(manuallyLoadedChunk);
20182
20628
  }
20183
20629
  dynamicImportsForCurrentEntry.add(resolution);
20184
- for (const includedTopLevelAwaitingDynamicImporter of resolution.includedTopLevelAwaitingDynamicImporters) {
20185
- if (staticDependencies.has(includedTopLevelAwaitingDynamicImporter)) {
20186
- awaitedDynamicImportsForCurrentEntry.add(resolution);
20187
- if (manuallyLoadedChunk) {
20188
- awaitedManualChunksForCurrentEntry.add(manuallyLoadedChunk);
20189
- }
20190
- else {
20191
- awaitedDynamicEntryModules.add(resolution);
20192
- }
20193
- break;
20194
- }
20195
- }
20196
20630
  }
20197
20631
  }
20198
20632
  for (const dependency of module.implicitlyLoadedBefore) {
@@ -20210,13 +20644,30 @@ function analyzeModuleGraph(entries, manualChunks, manualChunkByModule, manualCh
20210
20644
  }
20211
20645
  }
20212
20646
  }
20647
+ // A dynamic import can be awaited indirectly through a static dependency:
20648
+ // if any module of this entry uses a top-level await, the entry may
20649
+ // still be evaluating when any of its dynamic imports runs, so all of
20650
+ // them are awaited. This includes manual chunks that are loaded
20651
+ // dynamically or implicitly, which behave like dynamic entries here.
20652
+ if (hasTopLevelAwait) {
20653
+ for (const dynamicImportTarget of dynamicImportsForCurrentEntry) {
20654
+ const manualChunk = manualChunkByModule.get(dynamicImportTarget);
20655
+ if (manualChunk) {
20656
+ awaitedManualChunksForCurrentEntry.add(manualChunk);
20657
+ }
20658
+ else {
20659
+ awaitedDynamicEntryModules.add(dynamicImportTarget);
20660
+ }
20661
+ awaitedDynamicImportsForCurrentEntry.add(dynamicImportTarget);
20662
+ }
20663
+ }
20213
20664
  entryOrManualChunkIndex++;
20214
20665
  }
20215
20666
  const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntriesAndManualChunks, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry, dynamicallyLoadedManualChunksByEntry, awaitedLoadedManualChunksByEntry, manualChunkIndexByChunk);
20216
20667
  return {
20217
20668
  awaitedDynamicImportsByEntry,
20218
20669
  dependentEntriesByModule,
20219
- dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntriesAndManualChunks, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters),
20670
+ dynamicallyDependentEntriesByAwaitedDynamicEntry: addAwaitingEntries(getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntriesAndManualChunks, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters), awaitedDynamicImportsByEntry),
20220
20671
  dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntriesAndManualChunks, dynamicEntry => dynamicEntry.includedDynamicImporters),
20221
20672
  dynamicImportsByEntry,
20222
20673
  entriesAndManualChunksCount: allEntriesAndManualChunks.length
@@ -20270,6 +20721,18 @@ function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModul
20270
20721
  }
20271
20722
  return dynamicImportsByEntry;
20272
20723
  }
20724
+ // A dynamic entry can be awaited by an entry even if the importing module does
20725
+ // not have a top-level await itself, e.g. if the import is inside a function
20726
+ // that is awaited in the entry. In that case, the entry is still evaluating
20727
+ // when the dynamic entry is executed, so we add all awaiting entries here.
20728
+ function addAwaitingEntries(dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry) {
20729
+ for (const [entryIndex, awaitedDynamicImports] of awaitedDynamicImportsByEntry.entries()) {
20730
+ for (const dynamicEntryIndex of awaitedDynamicImports) {
20731
+ getOrCreate(dynamicallyDependentEntriesByAwaitedDynamicEntry, dynamicEntryIndex, (getNewSet)).add(entryIndex);
20732
+ }
20733
+ }
20734
+ return dynamicallyDependentEntriesByAwaitedDynamicEntry;
20735
+ }
20273
20736
  function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntriesAndManualChunks, getDynamicImporters) {
20274
20737
  const dynamicallyDependentEntriesByDynamicEntry = new Map();
20275
20738
  for (const dynamicEntryIndex of dynamicEntries) {
@@ -20365,6 +20828,34 @@ function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyD
20365
20828
  }
20366
20829
  return alreadyLoadedAtomsByEntry;
20367
20830
  }
20831
+ // Warning: This will consume dynamicallyDependentEntriesByAwaitedDynamicEntry.
20832
+ function getAwaitedAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntriesCount) {
20833
+ // Unlike already loaded atoms, this is a union and not an intersection: If
20834
+ // any importer that is still evaluating while it awaits a dynamic entry has
20835
+ // loaded an atom, merging that atom into the chunk of this importer would
20836
+ // create a cycle. Entries that are not awaited have no such atoms.
20837
+ const awaitedAlreadyLoadedAtomsByEntry = new Array(allEntriesCount).fill(0n);
20838
+ for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByAwaitedDynamicEntry) {
20839
+ // We delete here so that they can be added again if necessary to be handled
20840
+ // again by the loop
20841
+ dynamicallyDependentEntriesByAwaitedDynamicEntry.delete(dynamicEntryIndex);
20842
+ const knownLoadedAtoms = awaitedAlreadyLoadedAtomsByEntry[dynamicEntryIndex];
20843
+ let updatedLoadedAtoms = knownLoadedAtoms;
20844
+ for (const entryIndex of dynamicallyDependentEntries) {
20845
+ updatedLoadedAtoms |=
20846
+ staticDependencyAtomsByEntry[entryIndex] | awaitedAlreadyLoadedAtomsByEntry[entryIndex];
20847
+ }
20848
+ // If the knownLoadedAtoms changed, all awaited dynamic imports of this
20849
+ // entry need to be updated again
20850
+ if (updatedLoadedAtoms !== knownLoadedAtoms) {
20851
+ awaitedAlreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
20852
+ for (const dynamicImport of awaitedDynamicImportsByEntry[dynamicEntryIndex]) {
20853
+ getOrCreate(dynamicallyDependentEntriesByAwaitedDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
20854
+ }
20855
+ }
20856
+ }
20857
+ return awaitedAlreadyLoadedAtomsByEntry;
20858
+ }
20368
20859
  /**
20369
20860
  * Manual chunks whose member atom is already loaded in every context that
20370
20861
  * dynamically loads them must not be treated like dynamic entries as that
@@ -21002,7 +21493,10 @@ function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapCha
21002
21493
  const sourcesContent = originalSourcemap.sourcesContent || [];
21003
21494
  const directory = dirname(id) || '.';
21004
21495
  const sourceRoot = originalSourcemap.sourceRoot || '.';
21005
- const baseSources = sources.map((source, index) => new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
21496
+ // A source whose name is not known is null, and mappings to it are treated as unmapped
21497
+ const baseSources = sources.map((source, index) => source == null
21498
+ ? null
21499
+ : new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
21006
21500
  source = new Link(originalSourcemap, baseSources);
21007
21501
  }
21008
21502
  else {
@@ -21035,13 +21529,17 @@ function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeCon
21035
21529
  });
21036
21530
  }
21037
21531
  function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
21038
- if (sourcemapChain.length === 0) {
21532
+ if (sourcemapChain.length === 0 &&
21533
+ (!originalSourcemap || hasOnlyNamedSources(originalSourcemap))) {
21039
21534
  return originalSourcemap;
21040
21535
  }
21041
21536
  const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
21042
21537
  const map = source.traceMappings();
21043
21538
  return decodedSourcemap({ version: 3, ...map });
21044
21539
  }
21540
+ function hasOnlyNamedSources(map) {
21541
+ return map.sources.every(source => source != null);
21542
+ }
21045
21543
 
21046
21544
  let textEncoder;
21047
21545
  const getHash64 = input => xxhashBase64Url(ensureBuffer(input));
@@ -21076,8 +21574,8 @@ async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
21076
21574
  timeStart('transform chunks', 2);
21077
21575
  const getHash = hasherByType[outputOptions.hashCharacters];
21078
21576
  const chunkGraph = getChunkGraph(chunks);
21079
- const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
21080
- const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
21577
+ const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder, usedFileNames } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log, bundle);
21578
+ const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, usedFileNames, getHash);
21081
21579
  addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
21082
21580
  timeEnd('transform chunks', 2);
21083
21581
  }
@@ -21157,7 +21655,7 @@ async function transformChunk(magicString, fileName, usedModules, chunkGraph, op
21157
21655
  map
21158
21656
  };
21159
21657
  }
21160
- async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
21658
+ async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log, bundle) {
21161
21659
  const nonHashedChunksWithPlaceholders = [];
21162
21660
  const renderedChunksByPlaceholder = new Map();
21163
21661
  const hashDependenciesByPlaceholder = new Map();
@@ -21167,51 +21665,93 @@ async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGrap
21167
21665
  if (hashPlaceholder)
21168
21666
  placeholders.add(hashPlaceholder);
21169
21667
  }
21170
- await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
21668
+ const transformedChunks = await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
21171
21669
  const transformedChunk = {
21172
21670
  chunk,
21173
21671
  fileName,
21174
21672
  sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
21175
21673
  ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
21176
21674
  };
21177
- const { code, map } = transformedChunk;
21675
+ const hashAugmentation = hashPlaceholder
21676
+ ? pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => augmentation + (pluginHash || ''))
21677
+ : '';
21678
+ return {
21679
+ hashAugmentation,
21680
+ hashPlaceholder,
21681
+ preliminarySourcemapFileName,
21682
+ transformedChunk
21683
+ };
21684
+ }));
21685
+ const usedFileNames = new Set(bundle[lowercaseBundleKeys]);
21686
+ for (const { transformedChunk, hashPlaceholder, preliminarySourcemapFileName, hashAugmentation } of transformedChunks) {
21687
+ const { map } = transformedChunk;
21688
+ const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
21689
+ if (map && sourcemapHashPlaceholder) {
21690
+ const { transformedCode: normalizedSourcemap } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(map.toString(), placeholders);
21691
+ initialHashesByPlaceholder.set(sourcemapHashPlaceholder, outputOptions.sourcemap === 'inline'
21692
+ ? getHash(normalizedSourcemap).slice(0, sourcemapHashPlaceholder.length)
21693
+ : getUniqueHash(normalizedSourcemap, preliminarySourcemapFileName.fileName, sourcemapHashPlaceholder, usedFileNames, getHash));
21694
+ }
21178
21695
  if (hashPlaceholder) {
21179
- // To create a reproducible content-only hash, all placeholders are
21180
- // replaced with the same value before hashing
21181
- const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
21182
- let contentToHash = transformedCode;
21183
- const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
21184
- if (pluginHash) {
21185
- augmentation += pluginHash;
21186
- }
21187
- return augmentation;
21188
- });
21189
- if (hashAugmentation) {
21190
- contentToHash += hashAugmentation;
21191
- }
21192
21696
  renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
21193
- hashDependenciesByPlaceholder.set(hashPlaceholder, {
21194
- containedPlaceholders,
21195
- contentHash: getHash(contentToHash)
21196
- });
21697
+ hashDependenciesByPlaceholder.set(hashPlaceholder, getChunkHash(transformedChunk, outputOptions, getHash, placeholders, initialHashesByPlaceholder, hashAugmentation));
21197
21698
  }
21198
21699
  else {
21199
21700
  nonHashedChunksWithPlaceholders.push(transformedChunk);
21200
21701
  }
21201
- const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
21202
- if (map && sourcemapHashPlaceholder) {
21203
- initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
21204
- }
21205
- }));
21702
+ }
21206
21703
  return {
21207
21704
  hashDependenciesByPlaceholder,
21208
21705
  initialHashesByPlaceholder,
21209
21706
  nonHashedChunksWithPlaceholders,
21210
21707
  placeholders,
21211
- renderedChunksByPlaceholder
21708
+ renderedChunksByPlaceholder,
21709
+ usedFileNames
21212
21710
  };
21213
21711
  }
21214
- function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
21712
+ function getChunkHash({ code, map, fileName, sourcemapFileName }, outputOptions, getHash, placeholders, initialHashesByPlaceholder, hashAugmentation) {
21713
+ // To create a reproducible content-only hash, all placeholders are
21714
+ // replaced with the same value before hashing
21715
+ const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
21716
+ let contentToHash = transformedCode;
21717
+ if (map && outputOptions.sourcemap !== 'hidden') {
21718
+ // Normalize raw map data and file names before base64 or URL encoding
21719
+ // can hide placeholders and make hashes depend on chunk order.
21720
+ let sourcemapPlaceholders;
21721
+ if (outputOptions.sourcemap === 'inline') {
21722
+ const { containedPlaceholders: inlinePlaceholders, transformedCode: sourcemapJson } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(map.toString(), placeholders);
21723
+ sourcemapPlaceholders = inlinePlaceholders;
21724
+ contentToHash += `//# ${SOURCEMAPPING_URL}=data:application/json,${sourcemapJson}\n`;
21725
+ }
21726
+ else {
21727
+ const { containedPlaceholders: externalPlaceholders, transformedCode: normalizedFileName } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(replacePlaceholders(sourcemapFileName ?? `${fileName}.map`, initialHashesByPlaceholder), placeholders);
21728
+ sourcemapPlaceholders = externalPlaceholders;
21729
+ contentToHash += getSourceMapComment(normalizedFileName, map, outputOptions.sourcemap, outputOptions.sourcemapBaseUrl);
21730
+ }
21731
+ for (const placeholder of sourcemapPlaceholders) {
21732
+ containedPlaceholders.add(placeholder);
21733
+ }
21734
+ }
21735
+ if (hashAugmentation) {
21736
+ contentToHash += hashAugmentation;
21737
+ }
21738
+ return { containedPlaceholders, contentHash: getHash(contentToHash) };
21739
+ }
21740
+ function getUniqueHash(contentToHash, fileName, placeholder, usedFileNames, getHash) {
21741
+ let finalFileName;
21742
+ let finalHash;
21743
+ do {
21744
+ // In case of a hash collision, create a hash of the hash
21745
+ if (finalHash) {
21746
+ contentToHash = finalHash;
21747
+ }
21748
+ finalHash = getHash(contentToHash).slice(0, placeholder.length);
21749
+ finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash).toLowerCase();
21750
+ } while (usedFileNames.has(finalFileName));
21751
+ usedFileNames.add(finalFileName);
21752
+ return finalHash;
21753
+ }
21754
+ function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, usedFileNames, getHash) {
21215
21755
  const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
21216
21756
  for (const placeholder of placeholders) {
21217
21757
  const { fileName } = renderedChunksByPlaceholder.get(placeholder);
@@ -21225,17 +21765,8 @@ function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlac
21225
21765
  hashDependencyPlaceholders.add(containedPlaceholder);
21226
21766
  }
21227
21767
  }
21228
- let finalFileName;
21229
- let finalHash;
21230
- do {
21231
- // In case of a hash collision, create a hash of the hash
21232
- if (finalHash) {
21233
- contentToHash = finalHash;
21234
- }
21235
- finalHash = getHash(contentToHash).slice(0, placeholder.length);
21236
- finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
21237
- } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
21238
- bundle[finalFileName] = FILE_PLACEHOLDER;
21768
+ const finalHash = getUniqueHash(contentToHash, fileName, placeholder, usedFileNames, getHash);
21769
+ bundle[replaceSinglePlaceholder(fileName, placeholder, finalHash)] = FILE_PLACEHOLDER;
21239
21770
  hashesByPlaceholder.set(placeholder, finalHash);
21240
21771
  }
21241
21772
  return hashesByPlaceholder;
@@ -21273,15 +21804,7 @@ function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bun
21273
21804
  }
21274
21805
  }
21275
21806
  function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
21276
- let url;
21277
- if (sourcemap === 'inline') {
21278
- url = map.toUrl();
21279
- }
21280
- else {
21281
- const sourcemapFileName = basename(fileName);
21282
- url = sourcemapBaseUrl
21283
- ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
21284
- : sourcemapFileName;
21807
+ if (sourcemap !== 'inline') {
21285
21808
  pluginDriver.emitFile({
21286
21809
  fileName,
21287
21810
  originalFileName: null,
@@ -21289,6 +21812,14 @@ function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, so
21289
21812
  type: 'asset'
21290
21813
  });
21291
21814
  }
21815
+ return getSourceMapComment(fileName, map, sourcemap, sourcemapBaseUrl);
21816
+ }
21817
+ function getSourceMapComment(fileName, map, sourcemap, sourcemapBaseUrl) {
21818
+ const url = sourcemap === 'inline'
21819
+ ? map.toUrl()
21820
+ : sourcemapBaseUrl
21821
+ ? new URL(basename(fileName), sourcemapBaseUrl).toString()
21822
+ : basename(fileName);
21292
21823
  return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
21293
21824
  }
21294
21825
  function calculateDebugIdAndGetComment(code, map) {
@@ -21338,7 +21869,12 @@ class Bundle {
21338
21869
  await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
21339
21870
  }
21340
21871
  catch (error_) {
21341
- await this.pluginDriver.hookParallel('renderError', [error_]);
21872
+ try {
21873
+ await this.pluginDriver.hookParallel('renderError', [error_]);
21874
+ }
21875
+ catch (hookError) {
21876
+ error(logErrorInHook(error_, hookError, 'renderError'));
21877
+ }
21342
21878
  throw error_;
21343
21879
  }
21344
21880
  removeUnreferencedAssets(outputBundle);
@@ -22050,7 +22586,7 @@ async function transform(source, module, pluginDriver, options) {
22050
22586
  }
22051
22587
  const getLogHandler = (handler) => (log, pos) => {
22052
22588
  log = normalizeLog(log);
22053
- if (pos)
22589
+ if (pos != null)
22054
22590
  augmentCodeLocation(log, pos, currentSource, id);
22055
22591
  log.id = id;
22056
22592
  log.hook = 'transform';
@@ -22084,7 +22620,7 @@ async function transform(source, module, pluginDriver, options) {
22084
22620
  error(error_, pos) {
22085
22621
  if (typeof error_ === 'string')
22086
22622
  error_ = { message: error_ };
22087
- if (pos)
22623
+ if (pos != null)
22088
22624
  augmentCodeLocation(error_, pos, currentSource, id);
22089
22625
  error_.id = id;
22090
22626
  error_.hook = 'transform';
@@ -22236,37 +22772,7 @@ class ModuleLoader {
22236
22772
  }));
22237
22773
  }
22238
22774
  async addModuleSource(id, importer, module) {
22239
- let source;
22240
- try {
22241
- source = await this.graph.fileOperationQueue.run(async () => {
22242
- const content = await this.pluginDriver.hookFirst('load', [
22243
- id,
22244
- { attributes: module.info.attributes, rawId: module.info.rawId }
22245
- ]);
22246
- if (content !== null) {
22247
- if (typeof content === 'object' && content.attributes) {
22248
- warnDeprecation('Returning attributes from the "load" hook is deprecated.', URL_LOAD, true, this.options);
22249
- }
22250
- return content;
22251
- }
22252
- this.graph.watchFiles[module.info.rawId] = true;
22253
- return (await this.options.fs.readFile(module.info.rawId, { encoding: 'utf8' }));
22254
- });
22255
- }
22256
- catch (error_) {
22257
- let message = `Could not load ${id}`;
22258
- if (importer)
22259
- message += ` (imported by ${relativeId(importer)})`;
22260
- message += `: ${error_.message}`;
22261
- error_.message = message;
22262
- throw error_;
22263
- }
22264
- const sourceDescription = typeof source === 'string'
22265
- ? { code: source }
22266
- : source != null && typeof source === 'object' && typeof source.code === 'string'
22267
- ? source
22268
- : error(logBadLoader(id));
22269
- sourceDescription.code = stripBom(sourceDescription.code);
22775
+ const sourceDescription = await this.loadSourceDescription(id, importer, module);
22270
22776
  const cachedModule = this.graph.cachedModules.get(id);
22271
22777
  if (cachedModule &&
22272
22778
  !cachedModule.customTransformCache &&
@@ -22579,6 +23085,37 @@ class ModuleLoader {
22579
23085
  ? resolveIdResult
22580
23086
  : { id: resolveIdResult }, attributes)), undefined, isEntry, false);
22581
23087
  }
23088
+ async loadSourceDescription(id, importer, module) {
23089
+ let source;
23090
+ try {
23091
+ source = await this.pluginDriver.hookFirst('load', [
23092
+ id,
23093
+ { attributes: module.info.attributes, rawId: module.info.rawId }
23094
+ ]);
23095
+ if (source === null) {
23096
+ this.graph.watchFiles[module.info.rawId] = true;
23097
+ source = await this.options.fs.readFile(module.info.rawId, { encoding: 'utf8' });
23098
+ }
23099
+ else if (typeof source === 'object' && source.attributes) {
23100
+ warnDeprecation('Returning attributes from the "load" hook is deprecated.', URL_LOAD, true, this.options);
23101
+ }
23102
+ }
23103
+ catch (error_) {
23104
+ let message = `Could not load ${id}`;
23105
+ if (importer)
23106
+ message += ` (imported by ${relativeId(importer)})`;
23107
+ message += `: ${error_.message}`;
23108
+ error_.message = message;
23109
+ throw error_;
23110
+ }
23111
+ const sourceDescription = typeof source === 'string'
23112
+ ? { code: source }
23113
+ : source != null && typeof source === 'object' && typeof source.code === 'string'
23114
+ ? source
23115
+ : error(logBadLoader(id));
23116
+ sourceDescription.code = stripBom(sourceDescription.code);
23117
+ return sourceDescription;
23118
+ }
22582
23119
  toModuleResolvedId(resolveIdResult) {
22583
23120
  const { id, attributes } = resolveIdResult;
22584
23121
  return {
@@ -22644,22 +23181,20 @@ async function waitForDependencyResolution(loadPromise) {
22644
23181
  function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
22645
23182
  const emittedName = outputOptions.sanitizeFileName(name || 'asset');
22646
23183
  return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
22647
- ? outputOptions.assetFileNames({
22648
- // Additionally, this should be non-enumerable in the next major
23184
+ ? outputOptions.assetFileNames(makeDeprecatedAssetPropertiesNonEnumerable({
22649
23185
  get name() {
22650
- warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
23186
+ warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, true, inputOptions);
22651
23187
  return name;
22652
23188
  },
22653
23189
  names,
22654
- // Additionally, this should be non-enumerable in the next major
22655
23190
  get originalFileName() {
22656
- warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
23191
+ warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, true, inputOptions);
22657
23192
  return originalFileName;
22658
23193
  },
22659
23194
  originalFileNames,
22660
23195
  source,
22661
23196
  type: 'asset'
22662
- })
23197
+ }))
22663
23198
  : outputOptions.assetFileNames, 'output.assetFileNames', {
22664
23199
  ext: () => extname(emittedName).slice(1),
22665
23200
  extname: () => extname(emittedName),
@@ -22949,50 +23484,44 @@ class FileEmitter {
22949
23484
  const existingAsset = bundle[fileName];
22950
23485
  if (existingAsset?.type === 'asset') {
22951
23486
  existingAsset.needsCodeReference &&= needsCodeReference;
22952
- if (name) {
23487
+ if (name && !existingAsset.names.includes(name)) {
22953
23488
  existingAsset.names.push(name);
22954
23489
  }
22955
- if (originalFileName) {
23490
+ if (originalFileName && !existingAsset.originalFileNames.includes(originalFileName)) {
22956
23491
  existingAsset.originalFileNames.push(originalFileName);
22957
23492
  }
22958
23493
  }
22959
23494
  else {
22960
23495
  const { options } = this;
22961
- bundle[fileName] = {
23496
+ bundle[fileName] = makeDeprecatedAssetPropertiesNonEnumerable({
22962
23497
  fileName,
22963
23498
  get name() {
22964
- // Additionally, this should be non-enumerable in the next major
22965
- warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
23499
+ warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, true, options);
22966
23500
  return name;
22967
23501
  },
22968
23502
  names: name ? [name] : [],
22969
23503
  needsCodeReference,
22970
23504
  get originalFileName() {
22971
- // Additionally, this should be non-enumerable in the next major
22972
- warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
23505
+ warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, true, options);
22973
23506
  return originalFileName;
22974
23507
  },
22975
23508
  originalFileNames: originalFileName ? [originalFileName] : [],
22976
23509
  source,
22977
23510
  type: 'asset'
22978
- };
23511
+ });
22979
23512
  }
22980
23513
  }
22981
23514
  finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
22982
23515
  const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
22983
- let fileName = '';
22984
- let usedConsumedFile;
23516
+ let representative = consumedFiles[0];
22985
23517
  let needsCodeReference = true;
22986
23518
  for (const consumedFile of consumedFiles) {
22987
23519
  needsCodeReference &&= consumedFile.needsCodeReference;
22988
- const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
22989
- if (!fileName ||
22990
- assetFileName.length < fileName.length ||
22991
- (assetFileName.length === fileName.length && assetFileName < fileName)) {
22992
- fileName = assetFileName;
22993
- usedConsumedFile = consumedFile;
23520
+ if (compareConsumedAssets(consumedFile, representative) < 0) {
23521
+ representative = consumedFile;
22994
23522
  }
22995
23523
  }
23524
+ const fileName = generateAssetFileName(representative.name, names, representative.source, representative.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
22996
23525
  fileNamesBySourceHash.set(sourceHash, fileName);
22997
23526
  for (const consumedFile of consumedFiles) {
22998
23527
  // We must not modify the original assets to avoid interaction between outputs
@@ -23000,42 +23529,53 @@ class FileEmitter {
23000
23529
  this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
23001
23530
  }
23002
23531
  const { options } = this;
23003
- bundle[fileName] = {
23532
+ bundle[fileName] = makeDeprecatedAssetPropertiesNonEnumerable({
23004
23533
  fileName,
23005
23534
  get name() {
23006
- // Additionally, this should be non-enumerable in the next major
23007
- warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
23008
- return usedConsumedFile.name;
23535
+ warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, true, options);
23536
+ return representative.name;
23009
23537
  },
23010
23538
  names,
23011
23539
  needsCodeReference,
23012
23540
  get originalFileName() {
23013
- // Additionally, this should be non-enumerable in the next major
23014
- warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
23015
- return usedConsumedFile.originalFileName;
23541
+ warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, true, options);
23542
+ return representative.originalFileName;
23016
23543
  },
23017
23544
  originalFileNames,
23018
- source: usedConsumedFile.source,
23545
+ source: representative.source,
23019
23546
  type: 'asset'
23020
- };
23547
+ });
23021
23548
  }
23022
23549
  }
23550
+ function makeDeprecatedAssetPropertiesNonEnumerable(asset) {
23551
+ for (const property of ['name', 'originalFileName']) {
23552
+ const descriptor = Object.getOwnPropertyDescriptor(asset, property);
23553
+ Object.defineProperty(asset, property, { ...descriptor, enumerable: false });
23554
+ }
23555
+ return asset;
23556
+ }
23557
+ const compareNames = (a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0);
23558
+ const compareOptionalNames = (a, b) => a === b ? 0 : a == null ? 1 : b == null ? -1 : a < b ? -1 : 1;
23559
+ const compareSourceTypes = (a, b) => typeof a === 'string' ? (typeof b === 'string' ? 0 : -1) : typeof b === 'string' ? 1 : 0;
23560
+ const compareConsumedAssets = (a, b) => compareNames(a.name || 'asset', b.name || 'asset') ||
23561
+ compareOptionalNames(a.originalFileName, b.originalFileName) ||
23562
+ compareOptionalNames(a.name, b.name) ||
23563
+ compareSourceTypes(a.source, b.source);
23023
23564
  function getNamesFromAssets(consumedFiles) {
23024
- const names = [];
23025
- const originalFileNames = [];
23565
+ const names = new Set();
23566
+ const originalFileNames = new Set();
23026
23567
  for (const { name, originalFileName } of consumedFiles) {
23027
23568
  if (typeof name === 'string') {
23028
- names.push(name);
23569
+ names.add(name);
23029
23570
  }
23030
23571
  if (originalFileName) {
23031
- originalFileNames.push(originalFileName);
23572
+ originalFileNames.add(originalFileName);
23032
23573
  }
23033
23574
  }
23034
- originalFileNames.sort();
23035
- // Sort by length first and then alphabetically so that the order is stable
23036
- // and the shortest names come first
23037
- names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
23038
- return { names, originalFileNames };
23575
+ return {
23576
+ names: [...names].sort(compareNames),
23577
+ originalFileNames: [...originalFileNames].sort()
23578
+ };
23039
23579
  }
23040
23580
 
23041
23581
  function ensureArray(items) {
@@ -23425,37 +23965,6 @@ function validateAddonPluginHandler(handler, hookName, plugin) {
23425
23965
  }
23426
23966
  function noReturn() { }
23427
23967
 
23428
- class Queue {
23429
- constructor(maxParallel) {
23430
- this.maxParallel = maxParallel;
23431
- this.queue = [];
23432
- this.workerCount = 0;
23433
- }
23434
- run(task) {
23435
- return new Promise((resolve, reject) => {
23436
- this.queue.push({ reject, resolve, task });
23437
- this.work();
23438
- });
23439
- }
23440
- async work() {
23441
- if (this.workerCount >= this.maxParallel)
23442
- return;
23443
- this.workerCount++;
23444
- let entry;
23445
- while ((entry = this.queue.shift())) {
23446
- const { reject, resolve, task } = entry;
23447
- try {
23448
- const result = await task();
23449
- resolve(result);
23450
- }
23451
- catch (error) {
23452
- reject(error);
23453
- }
23454
- }
23455
- this.workerCount--;
23456
- }
23457
- }
23458
-
23459
23968
  function normalizeEntryModules(entryModules) {
23460
23969
  if (Array.isArray(entryModules)) {
23461
23970
  return entryModules.map(id => ({
@@ -23519,7 +24028,6 @@ class Graph {
23519
24028
  }
23520
24029
  this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
23521
24030
  this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
23522
- this.fileOperationQueue = new Queue(options.maxParallelFileOps);
23523
24031
  this.pureFunctions = getPureFunctions(options);
23524
24032
  }
23525
24033
  async build() {
@@ -23738,6 +24246,55 @@ function getLogger(plugins, onLog, watchMode, logLevel) {
23738
24246
  return logger;
23739
24247
  }
23740
24248
 
24249
+ class FileOperationQueue {
24250
+ constructor(maxParallel) {
24251
+ this.maxParallel = maxParallel;
24252
+ this.queue = [];
24253
+ this.workerCount = 0;
24254
+ }
24255
+ run(task) {
24256
+ return new Promise((resolve, reject) => {
24257
+ this.queue.push({ reject, resolve, task });
24258
+ this.work();
24259
+ });
24260
+ }
24261
+ async work() {
24262
+ if (this.workerCount >= this.maxParallel)
24263
+ return;
24264
+ this.workerCount++;
24265
+ let entry;
24266
+ while ((entry = this.queue.shift())) {
24267
+ const { reject, resolve, task } = entry;
24268
+ try {
24269
+ resolve(await task());
24270
+ }
24271
+ catch (error) {
24272
+ reject(error);
24273
+ }
24274
+ }
24275
+ this.workerCount--;
24276
+ }
24277
+ }
24278
+ function createLimitedFs(fs, maxParallelFileOps) {
24279
+ const queue = new FileOperationQueue(maxParallelFileOps);
24280
+ const limit = (method) => ((...parameters) => queue.run(() => Reflect.apply(fs[method], fs, parameters)));
24281
+ return {
24282
+ appendFile: limit('appendFile'),
24283
+ copyFile: limit('copyFile'),
24284
+ lstat: limit('lstat'),
24285
+ mkdir: limit('mkdir'),
24286
+ mkdtemp: limit('mkdtemp'),
24287
+ readdir: limit('readdir'),
24288
+ readFile: limit('readFile'),
24289
+ realpath: limit('realpath'),
24290
+ rename: limit('rename'),
24291
+ rmdir: limit('rmdir'),
24292
+ stat: limit('stat'),
24293
+ unlink: limit('unlink'),
24294
+ writeFile: limit('writeFile')
24295
+ };
24296
+ }
24297
+
23741
24298
  const fs = /*#__PURE__*/_mergeNamespaces({
23742
24299
  __proto__: null
23743
24300
  }, [promises]);
@@ -23758,7 +24315,7 @@ async function normalizeInputOptions(config, watchMode) {
23758
24315
  experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
23759
24316
  experimentalLogSideEffects: config.experimentalLogSideEffects || false,
23760
24317
  external: getIdMatcher(config.external),
23761
- fs: config.fs ?? fs,
24318
+ fs: createLimitedFs(config.fs ?? fs, maxParallelFileOps),
23762
24319
  input: getInput(config),
23763
24320
  jsx: getJsx(config),
23764
24321
  logLevel,
@@ -23798,7 +24355,8 @@ const getIdMatcher = (option) => {
23798
24355
  ids.add(value);
23799
24356
  }
23800
24357
  }
23801
- return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
24358
+ return (id, ..._arguments) => ids.has(id) ||
24359
+ matchers.some(matcher => matcher.global || matcher.sticky ? id.search(matcher) !== -1 : matcher.test(id));
23802
24360
  }
23803
24361
  return () => false;
23804
24362
  };
@@ -23929,7 +24487,6 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
23929
24487
  const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
23930
24488
  const file = getFile(config, preserveModules, inputOptions);
23931
24489
  const generatedCode = getGeneratedCode(config);
23932
- const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
23933
24490
  const outputOptions = {
23934
24491
  amd: getAmd(config),
23935
24492
  assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
@@ -23943,8 +24500,7 @@ async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
23943
24500
  experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
23944
24501
  exports: getExports(config, unsetOptions),
23945
24502
  extend: config.extend || false,
23946
- externalImportAssertions: externalImportAttributes,
23947
- externalImportAttributes,
24503
+ externalImportAttributes: config.externalImportAttributes ?? true,
23948
24504
  externalLiveBindings: config.externalLiveBindings ?? true,
23949
24505
  file,
23950
24506
  footer: getAddon(config, 'footer'),
@@ -24119,12 +24675,6 @@ function getExports(config, unsetOptions) {
24119
24675
  }
24120
24676
  return configExports || 'auto';
24121
24677
  }
24122
- const getExternalImportAttributes = (config, inputOptions) => {
24123
- if (config.externalImportAssertions != undefined) {
24124
- warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
24125
- }
24126
- return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
24127
- };
24128
24678
  const getGeneratedCode = (config) => {
24129
24679
  const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
24130
24680
  return {
@@ -24238,22 +24788,18 @@ async function rollupInternal(rawInputOptions, registerWatchHooks) {
24238
24788
  await graph.pluginDriver.hookParallel('buildEnd', [error_]);
24239
24789
  }
24240
24790
  catch (buildEndError) {
24241
- // Create a compound error object to include both errors, based on the original error
24242
- const compoundError = getRollupError({
24243
- ...error_,
24244
- message: `There was an error during the build:\n ${error_.message}\nAdditionally, handling the error in the 'buildEnd' hook caused the following error:\n ${buildEndError.message}`
24245
- });
24246
- await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
24791
+ const compoundError = getRollupError(logErrorInHook(error_, buildEndError, 'buildEnd'));
24792
+ await graph.pluginDriver.hookParallel('closeBundle', [compoundError]).catch(() => { });
24247
24793
  throw compoundError;
24248
24794
  }
24249
- await graph.pluginDriver.hookParallel('closeBundle', [error_]);
24795
+ await graph.pluginDriver.hookParallel('closeBundle', [error_]).catch(() => { });
24250
24796
  throw error_;
24251
24797
  }
24252
24798
  try {
24253
24799
  await graph.pluginDriver.hookParallel('buildEnd', []);
24254
24800
  }
24255
24801
  catch (buildEndError) {
24256
- await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
24802
+ await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]).catch(() => { });
24257
24803
  throw buildEndError;
24258
24804
  }
24259
24805
  });
@@ -24336,7 +24882,7 @@ async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, raw
24336
24882
  if (!outputOptions.dir && !outputOptions.file) {
24337
24883
  return error(logMissingFileOrDirOption());
24338
24884
  }
24339
- await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions, inputOptions))));
24885
+ await Promise.all(Object.values(generated).map(chunk => writeOutputFile(chunk, outputOptions, inputOptions)));
24340
24886
  await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
24341
24887
  timeEnd('WRITE', 1);
24342
24888
  }
@@ -24672,7 +25218,6 @@ async function mergeOutputOptions(config, overrides, log) {
24672
25218
  experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
24673
25219
  exports: getOption('exports'),
24674
25220
  extend: getOption('extend'),
24675
- externalImportAssertions: getOption('externalImportAssertions'),
24676
25221
  externalImportAttributes: getOption('externalImportAttributes'),
24677
25222
  externalLiveBindings: getOption('externalLiveBindings'),
24678
25223
  file: getOption('file'),