webpack 5.111.0 → 5.111.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/lib/APIPlugin.js +3 -4
  2. package/lib/CompatibilityPlugin.js +3 -4
  3. package/lib/Compilation.js +16 -35
  4. package/lib/Compiler.js +4 -5
  5. package/lib/ConstPlugin.js +16 -132
  6. package/lib/DependencyTemplate.js +2 -1
  7. package/lib/DotenvPlugin.js +24 -28
  8. package/lib/ErrorHelpers.js +113 -0
  9. package/lib/ExportsInfo.js +20 -16
  10. package/lib/ExternalModule.js +6 -8
  11. package/lib/FlagDependencyExportsPlugin.js +8 -13
  12. package/lib/FlagDependencyUsagePlugin.js +9 -13
  13. package/lib/Generator.js +24 -2
  14. package/lib/HotModuleReplacementPlugin.js +2 -0
  15. package/lib/IgnorePlugin.js +1 -1
  16. package/lib/LoaderOptionsPlugin.js +1 -1
  17. package/lib/Module.js +3 -3
  18. package/lib/ModuleGraph.js +6 -9
  19. package/lib/MultiCompiler.js +6 -16
  20. package/lib/NormalModule.js +96 -44
  21. package/lib/RuntimeTemplate.js +33 -43
  22. package/lib/SourceMapDevToolPlugin.js +53 -103
  23. package/lib/TemplatedPathPlugin.js +16 -59
  24. package/lib/asset/AssetBytesGenerator.js +7 -1
  25. package/lib/asset/AssetGenerator.js +25 -16
  26. package/lib/asset/AssetSourceGenerator.js +7 -1
  27. package/lib/buildChunkGraph.js +11 -15
  28. package/lib/cache/MemoryCachePlugin.js +4 -4
  29. package/lib/cache/MemoryWithGcCachePlugin.js +7 -8
  30. package/lib/cache/PackFileCacheStrategy.js +3 -18
  31. package/lib/cache/getLazyHashedEtag.js +3 -5
  32. package/lib/config/browserslistTargetHandler.js +2 -8
  33. package/lib/config/defaults.js +52 -78
  34. package/lib/config/getClaimedAssetTypes.js +10 -11
  35. package/lib/config/target.js +3 -4
  36. package/lib/{ContextExclusionPlugin.js → context/ContextExclusionPlugin.js} +1 -1
  37. package/lib/{ContextModule.js → context/ContextModule.js} +37 -34
  38. package/lib/{ContextModuleFactory.js → context/ContextModuleFactory.js} +19 -21
  39. package/lib/{ContextReplacementPlugin.js → context/ContextReplacementPlugin.js} +4 -4
  40. package/lib/css/CssGenerator.js +19 -11
  41. package/lib/css/CssParser.js +18 -20
  42. package/lib/css/cssMinify.js +32 -29
  43. package/lib/css/data.js +797 -288
  44. package/lib/css/syntax.js +2250 -934
  45. package/lib/debug/ProfilingPlugin.js +3 -4
  46. package/lib/dependencies/CommonJsExportRequireDependency.js +10 -11
  47. package/lib/dependencies/CommonJsImportsParserPlugin.js +4 -5
  48. package/lib/dependencies/CommonJsSelfReferenceDependency.js +2 -4
  49. package/lib/dependencies/ContextDependency.js +1 -1
  50. package/lib/dependencies/ContextDependencyHelpers.js +3 -9
  51. package/lib/dependencies/ContextElementDependency.js +1 -1
  52. package/lib/dependencies/CssIcssExportDependency.js +6 -8
  53. package/lib/dependencies/CssIcssImportDependency.js +3 -6
  54. package/lib/dependencies/CssUrlDependency.js +3 -5
  55. package/lib/dependencies/HarmonyCompatibilityDependency.js +11 -20
  56. package/lib/dependencies/HarmonyDetectionParserPlugin.js +3 -4
  57. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +2 -4
  58. package/lib/dependencies/HarmonyExportExpressionDependency.js +3 -4
  59. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +3 -4
  60. package/lib/dependencies/HarmonyExportInitFragment.js +26 -19
  61. package/lib/dependencies/HarmonyExportSpecifierDependency.js +7 -28
  62. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +103 -16
  63. package/lib/dependencies/HarmonyImportSideEffectDependency.js +3 -4
  64. package/lib/dependencies/HarmonyImportSpecifierDependency.js +16 -2
  65. package/lib/dependencies/HtmlEntryDependency.js +74 -102
  66. package/lib/dependencies/HtmlInlineScriptDependency.js +3 -4
  67. package/lib/dependencies/HtmlInlineStyleDependency.js +3 -4
  68. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +1 -1
  69. package/lib/dependencies/ImportMetaGlobHelpers.js +1 -1
  70. package/lib/dependencies/ImportMetaPlugin.js +8 -10
  71. package/lib/dependencies/ImportParserPlugin.js +1 -1
  72. package/lib/dependencies/LoaderPlugin.js +26 -1
  73. package/lib/dependencies/RequireContextDependencyParserPlugin.js +1 -1
  74. package/lib/dependencies/URLContextDependency.js +1 -1
  75. package/lib/dependencies/URLDependency.js +6 -5
  76. package/lib/dependencies/WorkerAndWorkletPlugin.js +15 -21
  77. package/lib/dependencies/WorkerDependency.js +6 -5
  78. package/lib/dependencies/WorkletDependency.js +6 -9
  79. package/lib/errors/HookWebpackError.js +3 -2
  80. package/lib/hmr/LazyCompilationPlugin.js +3 -5
  81. package/lib/html/HtmlGenerator.js +61 -82
  82. package/lib/html/HtmlModulesPlugin.js +88 -139
  83. package/lib/html/HtmlParser.js +97 -141
  84. package/lib/html/data.js +21 -0
  85. package/lib/html/htmlMinify.js +10 -11
  86. package/lib/html/syntax.js +883 -993
  87. package/lib/index.js +46 -3
  88. package/lib/javascript/ChunkFormatHelpers.js +4 -3
  89. package/lib/javascript/JavascriptGenerator.js +8 -1
  90. package/lib/javascript/JavascriptModulesPlugin.js +21 -48
  91. package/lib/javascript/JavascriptParser.js +721 -178
  92. package/lib/javascript/parser.js +6 -0
  93. package/lib/javascript/syntax.js +420 -92
  94. package/lib/json/JsonGenerator.js +7 -1
  95. package/lib/library/ModuleLibraryPlugin.js +64 -136
  96. package/lib/loaders/LoaderRunner.js +137 -9
  97. package/lib/node/NodeWatchFileSystem.js +3 -9
  98. package/lib/optimize/AggressiveMergingPlugin.js +3 -5
  99. package/lib/optimize/ConcatenatedModule.js +81 -100
  100. package/lib/optimize/FlagIncludedChunksPlugin.js +3 -11
  101. package/lib/optimize/InnerGraphPlugin.js +7 -13
  102. package/lib/optimize/LimitChunkCountPlugin.js +5 -8
  103. package/lib/optimize/MangleExportsPlugin.js +3 -4
  104. package/lib/optimize/ModuleConcatenationPlugin.js +3 -4
  105. package/lib/optimize/SideEffectsFlagPlugin.js +7 -19
  106. package/lib/optimize/SplitChunksPlugin.js +2 -4
  107. package/lib/performance/BroadContextsPlugin.js +1 -1
  108. package/lib/performance/CacheEffectivenessPlugin.js +3 -4
  109. package/lib/performance/SizeLimitsPlugin.js +2 -4
  110. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +6 -8
  111. package/lib/prefetch/ResourceHintPlugin.js +17 -21
  112. package/lib/prefetch/StartupAssetHintRuntimeModule.js +7 -10
  113. package/lib/runtime/AsyncModuleRuntimeModule.js +3 -5
  114. package/lib/runtime/GetChunkFilenameRuntimeModule.js +3 -4
  115. package/lib/runtime/GlobalRuntimeModule.js +2 -4
  116. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +55 -85
  117. package/lib/schemes/DataUriPlugin.js +3 -6
  118. package/lib/schemes/VirtualUrlPlugin.js +1 -1
  119. package/lib/serialization/BinaryMiddleware.js +9 -9
  120. package/lib/serialization/FileMiddleware.js +16 -16
  121. package/lib/serialization/ObjectMiddleware.js +30 -33
  122. package/lib/stats/DefaultStatsFactoryPlugin.js +3 -4
  123. package/lib/typescript/TypeScriptPlugin.js +2 -3
  124. package/lib/url/URLParserPlugin.js +6 -8
  125. package/lib/util/LocConverter.js +4 -7
  126. package/lib/util/SourceProcessor.js +15 -22
  127. package/lib/util/chainedImports.js +3 -4
  128. package/lib/util/concatenate.js +4 -4
  129. package/lib/util/createHooksRegistry.js +1 -2
  130. package/lib/util/dataURL.js +2 -3
  131. package/lib/util/deterministicGrouping.js +8 -13
  132. package/lib/util/findGraphRoots.js +6 -13
  133. package/lib/util/globUtils.js +1 -1
  134. package/lib/util/hash/wasm-hash.js +3 -4
  135. package/lib/util/internalSerializables.js +1 -1
  136. package/lib/util/semver.js +5 -3
  137. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +6 -1
  138. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +5 -1
  139. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +3 -4
  140. package/lib/wasm-sync/WebAssemblyGenerator.js +6 -1
  141. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +5 -1
  142. package/lib/wasm-sync/WebAssemblyUtils.js +2 -4
  143. package/package.json +30 -23
  144. package/types.d.ts +299 -280
@@ -558,12 +558,13 @@ const getFinalBinding = (
558
558
  case "default":
559
559
  exportName = exportName.slice(1);
560
560
  if (deferred) {
561
- // `ns.default` for a deferred default-with-named external
562
- // module must read through the optimized `.a` getter
563
- // (which lazily evaluates the module and returns its
564
- // exports), not the proxy namespace itself — otherwise
565
- // `typeof ns.default` / `ns.default instanceof X`
566
- // observe the proxy instead of the actual default.
561
+ // WHY: `ns.default` for a deferred default-with-named external
562
+ // module must read through the optimized `.a` getter, which
563
+ // evaluates the
564
+ // module lazily and returns its exports, rather than through the
565
+ // proxy namespace — otherwise `typeof ns.default` and
566
+ // `ns.default instanceof X` observe the proxy, not the actual
567
+ // default.
567
568
  return {
568
569
  info,
569
570
  rawName: `${info.deferredName}.a`,
@@ -602,10 +603,9 @@ const getFinalBinding = (
602
603
  };
603
604
  }
604
605
  if (deferred) {
605
- // As with default-with-named above, `ns.default` for a
606
- // deferred default-only external must read through the
607
- // optimized `.a` getter so that `typeof` / `instanceof`
608
- // observe the actual default value rather than the proxy.
606
+ // As with default-with-named above, a deferred default-only
607
+ // external reads through the `.a` getter, so `typeof` and
608
+ // `instanceof` see the value rather than the proxy.
609
609
  return {
610
610
  info,
611
611
  rawName: `${info.deferredName}.a`,
@@ -759,10 +759,9 @@ const getFinalBinding = (
759
759
  if (usedName instanceof InlinedUsedName) {
760
760
  return {
761
761
  info,
762
- // Render the inlined literal only (e.g. `"str"`), not its property
763
- // suffix: that suffix is returned in `ids` and appended once by
764
- // getFinalName. Using `usedName.render()` would emit it here too,
765
- // duplicating the access (e.g. `"str".a.a`).
762
+ // Render the inlined literal only, not its property suffix: that
763
+ // comes back in `ids` and getFinalName appends it once, so emitting
764
+ // it here too would duplicate the access.
766
765
  rawName: usedName.render(
767
766
  Template.toNormalComment(
768
767
  `inlined export ${propertyAccess(exportName)}`
@@ -1027,7 +1026,6 @@ const getFinalName = (
1027
1026
 
1028
1027
  /**
1029
1028
  * @typedef {object} ConcatenateModuleHooks
1030
- * @property {SyncBailHook<[ConcatenatedModule, RuntimeSpec[], string, Record<string, string>], boolean>} onDemandExportsGeneration
1031
1029
  * @property {SyncBailHook<[Partial<ConcatenatedModuleInfo>, ConcatenatedModuleInfo], boolean | void>} concatenatedModuleInfo
1032
1030
  */
1033
1031
 
@@ -1244,10 +1242,9 @@ class ConcatenatedModule extends Module {
1244
1242
  this.dependencies.push(d);
1245
1243
  }
1246
1244
  }
1247
- // populate codeGenerationDependencies — the inner modules'
1248
- // templates are applied during ConcatenatedModule.codeGeneration,
1249
- // so the referenced modules must have been code-generated by then.
1250
- // Skip references that point back into the concat set itself.
1245
+ // populate codeGenerationDependencies: the inner templates are applied
1246
+ // during this module's own codeGeneration, so what they reference must be
1247
+ // generated by then. References back into the concat set are skipped.
1251
1248
  if (m.codeGenerationDependencies !== undefined) {
1252
1249
  for (const d of m.codeGenerationDependencies) {
1253
1250
  const referenced =
@@ -1403,10 +1400,9 @@ class ConcatenatedModule extends Module {
1403
1400
  (connection.dependency);
1404
1401
  return {
1405
1402
  connection,
1406
- // A require() edge carries no sourceOrder; Infinity sorts it last,
1407
- // matching the low-priority sentinel. NaN must not be used here:
1408
- // compareNumbers returns 0 against every number, which makes the
1409
- // comparator non-transitive and the order depend on insertion order.
1403
+ // A require() edge carries no sourceOrder, and Infinity sorts it
1404
+ // last. Not NaN: `compareNumbers` returns 0 against every number,
1405
+ // which makes the comparator non-transitive.
1410
1406
  sourceOrder:
1411
1407
  typeof dep.sourceOrder === "number" ? dep.sourceOrder : Infinity,
1412
1408
  rangeStart: dep.range && dep.range[0],
@@ -1704,40 +1700,38 @@ class ConcatenatedModule extends Module {
1704
1700
  }
1705
1701
  }
1706
1702
 
1707
- /*
1708
- * How the inner modules become one flat source. Stages [1]-[5] only mutate the
1709
- * per-module info records (names, ReplaceSource patches); stages [6]-[9] append
1710
- * to the single output ConcatSource, in exactly the order shown.
1711
- *
1712
- * _getModulesWithInfo() — ordered concatenation list + one info per module
1713
- * | (concatenated [+wrapped] | external | reference)
1714
- * v
1715
- * [1] ANALYSE — inner codeGeneration() per module, into a ConcatenationScope
1716
- * | plain -> ReplaceSource + ast + scope analysis
1717
- * | wrapped -> ReplaceSource only, body kept verbatim
1718
- * | external -> nothing yet, rendered as a require() below
1719
- * [2] RESERVE — free globals of the analysed bodies enter allUsedNames, so
1720
- * | renaming in [3] can't shadow them (a wrapped body is not analysed;
1721
- * | the reserved `__webpack_` prefix protects it)
1722
- * [3] RENAME — module-scope variables renamed inside the ReplaceSource, then
1723
- * | the generated names allocated: wrapper accessor, namespace object,
1724
- * | interop helpers, external import variable
1725
- * [4] LINK — __WEBPACK_MODULE_REFERENCE__ tokens replaced by their final
1726
- * | binding; through the ast for analysed bodies, textually for wrapped
1727
- * [5] COLLECT EXPORTS — root exports split into used / unused / inlined
1728
- * v
1729
- * ---- from here on everything is appended to the result ConcatSource ----
1730
- * |
1731
- * [6] EMIT EXPORTS — __esModule flag + exports getters, UNUSED/INLINED lists
1732
- * [7] BUILD NS — namespace object sources built as strings (not emitted yet)
1733
- * [8] DEFINE — everything that must exist before any body runs: namespace
1734
- * | objects, wrapper accessors (wrapped modules and wrapped externals),
1735
- * | deferred external loaders
1736
- * [9] EVALUATE — bodies in concatenation order: plain bodies inline, externals
1737
- * | as require(); a wrapped body stays behind its accessor
1738
- * v
1739
- * [10] RESULT — CodeGenerationResult { sources, data, runtimeRequirements }
1740
- */
1703
+ // WHY: how the inner modules become one flat source. Stages [1]-[5] only mutate
1704
+ // the per-module info records (names, ReplaceSource patches); stages [6]-[9]
1705
+ // append to the single output ConcatSource, in exactly the order shown.
1706
+ //
1707
+ // _getModulesWithInfo() — ordered concatenation list + one info per module
1708
+ // | (concatenated [+wrapped] | external | reference)
1709
+ // v
1710
+ // [1] ANALYSE — inner codeGeneration() per module, into a ConcatenationScope
1711
+ // | plain -> ReplaceSource + ast + scope analysis
1712
+ // | wrapped -> ReplaceSource only, body kept verbatim
1713
+ // | external -> nothing yet, rendered as a require() below
1714
+ // [2] RESERVE — free globals of the analysed bodies enter allUsedNames, so
1715
+ // | renaming in [3] can't shadow them (a wrapped body is not analysed;
1716
+ // | the reserved `__webpack_` prefix protects it)
1717
+ // [3] RENAME — module-scope variables renamed inside the ReplaceSource, then
1718
+ // | the generated names allocated: wrapper accessor, namespace object,
1719
+ // | interop helpers, external import variable
1720
+ // [4] LINK — __WEBPACK_MODULE_REFERENCE__ tokens replaced by their final
1721
+ // | binding; through the ast for analysed bodies, textually for wrapped
1722
+ // [5] COLLECT EXPORTS — root exports split into used / unused / inlined
1723
+ // v
1724
+ // ---- from here on everything is appended to the result ConcatSource ----
1725
+ // |
1726
+ // [6] EMIT EXPORTS — __esModule flag + exports getters, UNUSED/INLINED lists
1727
+ // [7] BUILD NS — namespace object sources built as strings (not emitted yet)
1728
+ // [8] DEFINE — everything that must exist before any body runs: namespace
1729
+ // | objects, wrapper accessors (wrapped modules and wrapped externals),
1730
+ // | deferred external loaders
1731
+ // [9] EVALUATE — bodies in concatenation order: plain bodies inline, externals
1732
+ // | as require(); a wrapped body stays behind its accessor
1733
+ // v
1734
+ // [10] RESULT — CodeGenerationResult { sources, data, runtimeRequirements }
1741
1735
  /**
1742
1736
  * Generates code and runtime requirements for this module.
1743
1737
  * @param {CodeGenerationContext} context context for code generation
@@ -2108,10 +2102,9 @@ class ConcatenatedModule extends Module {
2108
2102
  switch (info.type) {
2109
2103
  case "concatenated": {
2110
2104
  if (info.wrapped) {
2111
- // A wrapped module declares exactly one shared-scope name: the
2112
- // lazy wrapper accessor holding its body. [2] claimed every
2113
- // identifier of that body, so findNewName avoids the ones that
2114
- // would shadow the accessor from inside it.
2105
+ // A wrapped module declares one shared-scope name, the lazy accessor
2106
+ // holding its body. Stage 2 claimed that body's identifiers, so
2107
+ // findNewName avoids the ones that would shadow it from inside.
2115
2108
  const namespaceFnName = findNewName(
2116
2109
  "namespaceFn",
2117
2110
  allUsedNames,
@@ -2419,10 +2412,9 @@ class ConcatenatedModule extends Module {
2419
2412
  }
2420
2413
  // #endregion
2421
2414
 
2422
- // #region [5] COLLECT EXPORTS: split the root module's exports into used /
2423
- // unused / inlined. Used ones stay thunks — resolving one can still
2424
- // register a namespace object, which [7] must see
2425
- // Map with all root exposed used exports
2415
+ // #region [5] COLLECT EXPORTS: split the root module's exports into used,
2416
+ // unused and inlined. Used ones stay thunks, since resolving one can still
2417
+ // register a namespace object that stage 7 must see.
2426
2418
  /** @type {Map<string, (requestShortener: RequestShortener) => string>} */
2427
2419
  const exportsMap = new Map();
2428
2420
 
@@ -2500,6 +2492,8 @@ class ConcatenatedModule extends Module {
2500
2492
  shouldAddHarmonyFlag = true;
2501
2493
  }
2502
2494
 
2495
+ /** @type {string | undefined} */
2496
+ let onDemandExportsSource;
2503
2497
  // define exports
2504
2498
  if (exportsMap.size > 0) {
2505
2499
  /** @type {string[]} */
@@ -2530,17 +2524,10 @@ class ConcatenatedModule extends Module {
2530
2524
  this.exportsArgument
2531
2525
  }, {${definitions.join(",")}\n});\n`;
2532
2526
 
2533
- const { onDemandExportsGeneration } =
2534
- ConcatenatedModule.getCompilationHooks(this.compilation);
2535
-
2536
- if (
2537
- !onDemandExportsGeneration.call(
2538
- this,
2539
- runtimes,
2540
- `${harmonyFlagSource}${exportsSource}`,
2541
- exportsFinalName
2542
- )
2543
- ) {
2527
+ const meta = moduleGraph.getMetaIfExisting(this);
2528
+ if (meta !== undefined && meta.onDemandExports === true) {
2529
+ onDemandExportsSource = `${harmonyFlagSource}${exportsSource}`;
2530
+ } else {
2544
2531
  result.add(harmonyFlagSource);
2545
2532
  result.add(exportsSource);
2546
2533
  }
@@ -2562,13 +2549,12 @@ class ConcatenatedModule extends Module {
2562
2549
  // #endregion
2563
2550
 
2564
2551
  // #region [7] BUILD NS: namespace object sources are built as strings here
2565
- // and emitted by [8]; an external's is emitted next to its import variable
2566
- // or accessor instead, which is defined later.
2567
- //
2568
- // generate decoupled namespace objects for escaping mangled namespaces:
2569
- // same getters as the regular namespace object, but keyed by the original
2570
- // export names so untracked access by name keeps working. Done before the
2571
- // regular namespace objects so any nested namespace they pull in is built.
2552
+ // and emitted by stage 8; an external's goes next to its import variable or
2553
+ // accessor instead, defined later.
2554
+
2555
+ // Decoupled namespace objects for escaping mangled namespaces carry the same
2556
+ // getters keyed by the original export names, so untracked access by name
2557
+ // keeps working. Built first, so any nested namespace they pull in exists.
2572
2558
  /** @type {Map<ConcatenatedModuleInfo | ExternalModuleInfo, string>} */
2573
2559
  const escapeNamespaceObjectSources = new Map();
2574
2560
  for (const info of neededEscapeNamespaceObjects) {
@@ -2740,10 +2726,9 @@ ${defineGetters}`
2740
2726
  }) {\n`
2741
2727
  );
2742
2728
  result.add(/** @type {ReplaceSource} */ (info.source));
2743
- // A generated body (json, asset, html) binds its value to a local
2744
- // instead of writing exports; hand that local to the accessor. The
2745
- // name is verbatim: a wrapped body is not scope-analysed, so it keeps
2746
- // the reserved symbol the generator registered.
2729
+ // A generated body binds its value to a local rather than writing
2730
+ // exports, so hand that local to the accessor. The name is verbatim: a
2731
+ // wrapped body is not scope-analysed and keeps the reserved symbol.
2747
2732
  result.add(
2748
2733
  info.namespaceExportSymbol
2749
2734
  ? `\n${info.module.moduleArgument}.exports = ${info.namespaceExportSymbol};\n});\n`
@@ -2980,9 +2965,8 @@ ${defineGetters}`
2980
2965
  throw new Error(`Unsupported concatenation entry type ${info.type}`);
2981
2966
  }
2982
2967
  // Building a wrapped module's interop object here would evaluate its body
2983
- // at the top level and break require() cycles, so defer it behind a
2984
- // hoisted function. The memo lives on the function object: it keeps the
2985
- // identity stable without claiming a second top-level name.
2968
+ // at the top level and break require() cycles, so it is deferred behind a
2969
+ // hoisted function, memoized on the function object itself.
2986
2970
  /**
2987
2971
  * @param {string} interopName interop variable name
2988
2972
  * @param {string} expr interop object expression
@@ -3034,6 +3018,10 @@ ${defineGetters}`
3034
3018
  }
3035
3019
  data.set("topLevelDeclarations", topLevelDeclarations);
3036
3020
  data.set("freeNames", freeNames);
3021
+ if (onDemandExportsSource !== undefined) {
3022
+ data.set("exportsSource", onDemandExportsSource);
3023
+ data.set("exportsFinalName", exportsFinalName);
3024
+ }
3037
3025
 
3038
3026
  /** @type {CodeGenerationResult} */
3039
3027
  const resultEntry = {
@@ -3073,10 +3061,9 @@ ${defineGetters}`
3073
3061
  if (info.type === "concatenated") {
3074
3062
  const m = info.module;
3075
3063
  if (info.wrapped) {
3076
- // the wrapper isolates the body's top-level declarations, so no
3077
- // renaming is needed -- only a concatenation scope, to rewrite in-scope
3078
- // `require()` targets to accessor references. [2] claims its identifiers
3079
- // textually in place of the scope analysis skipped here.
3064
+ // the wrapper isolates the body's top-level declarations, so only a
3065
+ // concatenation scope is needed, rewriting in-scope `require()` targets.
3066
+ // Stage 2 claims its identifiers textually, in place of that analysis.
3080
3067
  const concatenationScope = new ConcatenationScope(
3081
3068
  modulesMap,
3082
3069
  info,
@@ -3349,12 +3336,6 @@ ${defineGetters}`
3349
3336
  ConcatenatedModule.getCompilationHooks = createHooksRegistry(
3350
3337
  () =>
3351
3338
  /** @type {ConcatenateModuleHooks} */ ({
3352
- onDemandExportsGeneration: new SyncBailHook([
3353
- "module",
3354
- "runtimes",
3355
- "exportsFinalName",
3356
- "exportsSource"
3357
- ]),
3358
3339
  concatenatedModuleInfo: new SyncBailHook([
3359
3340
  "updatedInfo",
3360
3341
  "concatenatedModuleInfo"
@@ -24,17 +24,9 @@ class FlagIncludedChunksPlugin {
24
24
  compilation.hooks.optimizeChunkIds.tap(PLUGIN_NAME, (chunks) => {
25
25
  const chunkGraph = compilation.chunkGraph;
26
26
 
27
- // prepare two bit integers for each module
28
- // 2^31 is the max number represented as SMI in v8
29
- // we want the bits distributed this way:
30
- // the bit 2^31 is pretty rar and only one module should get it
31
- // so it has a probability of 1 / modulesCount
32
- // the first bit (2^0) is the easiest and every module could get it
33
- // if it doesn't get a better bit
34
- // from bit 2^n to 2^(n+1) there is a probability of p
35
- // so 1 / modulesCount == p^31
36
- // <=> p = sqrt31(1 / modulesCount)
37
- // so we use a modulo of 1 / sqrt31(1 / modulesCount)
27
+ // Two bit integers per module, within v8's 2^31 SMI range. The bits are
28
+ // spread so 2^31 falls to about one module in `modulesCount` and 2^0 to
29
+ // any module missing a better one, which gives the modulo below.
38
30
  /** @type {WeakMap<Module, number>} */
39
31
  const moduleBits = new WeakMap();
40
32
  const modulesCount = compilation.modules.size;
@@ -122,10 +122,8 @@ class InnerGraphPlugin {
122
122
  // nodes that have a TopLevelSymbol assigned and
123
123
  // variables are tagged with the assigned TopLevelSymbol
124
124
 
125
- // We differ 3 types of nodes:
126
- // 1. full statements (export default, function declaration)
127
- // 2. classes (class declaration, class expression)
128
- // 3. variable declarators (const x = ...)
125
+ // Three kinds of node carry a symbol: a full statement, a class, and a
126
+ // variable declarator.
129
127
 
130
128
  /** @type {WeakMap<Node | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration, TopLevelSymbol>} */
131
129
  let statementWithTopLevelSymbol = new WeakMap();
@@ -360,16 +358,12 @@ class InnerGraphPlugin {
360
358
  // During real walking we set the TopLevelSymbol state to the assigned
361
359
  // TopLevelSymbol by using the fill datastructures.
362
360
 
363
- // In addition to tracking TopLevelSymbols, we sometimes need to
364
- // add a PureExpressionDependency. This is needed to skip execution
365
- // of pure expressions, even when they are not dropped due to
366
- // minimizing. Otherwise symbols used there might not exist anymore
367
- // as they are removed as unused by this optimization
361
+ // A `PureExpressionDependency` is sometimes added too, so a pure
362
+ // expression is skipped even where minimizing leaves it: the symbols it
363
+ // uses may have been removed as unused by this optimization.
368
364
 
369
- // When we find a reference to a TopLevelSymbol, we register a
370
- // TopLevelSymbol dependency from TopLevelSymbol in state to the
371
- // referenced TopLevelSymbol. This way we get a graph of all
372
- // TopLevelSymbols.
365
+ // A reference registers a dependency from the symbol in state to the one
366
+ // referenced, which is how the graph of all of them is built.
373
367
 
374
368
  // The following hooks are called during walking:
375
369
 
@@ -101,10 +101,8 @@ class LimitChunkCountPlugin {
101
101
  /** @type {Chunk[]} */
102
102
  const orderedChunks = [...chunks].sort(compareChunksWithGraph);
103
103
 
104
- // create a lazy sorted data structure to keep all combinations
105
- // this is large. Size = chunks * (chunks - 1) / 2
106
- // It uses a multi layer bucket sort plus normal sort in the last layer
107
- // It's also lazy so only accessed buckets are sorted
104
+ // All `chunks * (chunks - 1) / 2` combinations, held in a multi-layer
105
+ // bucket sort that sorts only the buckets actually reached.
108
106
  /** @type {LazyBucketSortedSet<ChunkCombination, number>} */
109
107
  const combinations = new LazyBucketSortedSet(
110
108
  // Layer 1: ordered by largest size benefit
@@ -214,10 +212,9 @@ class LimitChunkCountPlugin {
214
212
  for (const group of queue) {
215
213
  for (const mChunk of modifiedChunks) {
216
214
  if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) {
217
- // This is a potential pair which needs recalculation
218
- // We can't do that now, but it merge before following pairs
219
- // so we leave space for it, and consider chunks as modified
220
- // just for the worse case
215
+ // A pair needing recalculation, which cannot happen now yet may
216
+ // merge before the ones that follow, so room is left for it and
217
+ // the chunks count as modified for the worst case.
221
218
  remainingChunksToMerge--;
222
219
  if (remainingChunksToMerge <= 0) break loop;
223
220
  modifiedChunks.add(a);
@@ -60,10 +60,9 @@ const mangleExportsInfo = (deterministic, exportsInfo, isNamespace) => {
60
60
  /** @type {InstanceType<ExportInfo>[]} */
61
61
  const mangleableExports = [];
62
62
 
63
- // Avoid to renamed exports that are not provided when
64
- // 1. it's not a namespace export: non-provided exports can be found in prototype chain
65
- // 2. there are other provided exports and deterministic mode is chosen:
66
- // non-provided exports would break the determinism
63
+ // A non-provided export is left unmangled outside a namespace export, where the
64
+ // prototype chain may still carry it, and under deterministic mode beside other
65
+ // provided exports, where it would break the determinism.
67
66
  let avoidMangleNonProvided = !isNamespace;
68
67
  if (!avoidMangleNonProvided && deterministic) {
69
68
  for (const exportInfo of exportsInfo.ownedExports) {
@@ -478,10 +478,9 @@ class ModuleConcatenationPlugin {
478
478
  logger.debug(
479
479
  `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)`
480
480
  );
481
- // Create the largest configurations first: if a root also ended up inside
482
- // a bigger configuration, the bigger one wins (smaller skipped below).
483
- // Configurations can't be reused across roots: a module shared by several
484
- // chunks is concatenated into each consumer (module duplication).
481
+ // Largest configurations first, so a root that also landed inside a
482
+ // bigger one loses to it. None is reused across roots: a module shared by
483
+ // several chunks is concatenated into each consumer.
485
484
  logger.time("sort concat configurations");
486
485
  concatConfigurations.sort((a, b) => b.modules.size - a.modules.size);
487
486
  logger.timeEnd("sort concat configurations");
@@ -596,12 +596,8 @@ class SideEffectsFlagPlugin {
596
596
  pureFunctions.add(name);
597
597
  };
598
598
 
599
- // Detect on function declarations
600
- // Covers:
601
- // 1. function foo
602
- // 2. export function foo
603
- // 3. export default function foo
604
- // 4. export default function / export default () => {} (anonymous)
599
+ // Covers a plain `function foo`, an exported one, and an
600
+ // `export default` function whether named or anonymous.
605
601
  parser.hooks.preStatementByType
606
602
  .for("FunctionDeclaration")
607
603
  .tap(PLUGIN_NAME, (statement) => {
@@ -617,13 +613,10 @@ class SideEffectsFlagPlugin {
617
613
  markPure(name);
618
614
  return;
619
615
  }
620
- const commentsStart = parser.prevStatement
621
- ? /** @type {Range} */ (parser.prevStatement.range)[1]
622
- : 0;
623
616
  if (
624
617
  hasNoSideEffectsNotation(
625
618
  parser,
626
- commentsStart,
619
+ parser.getAttachedCommentsStart(statement),
627
620
  /** @type {Range} */ (statement.range)[0]
628
621
  )
629
622
  ) {
@@ -648,12 +641,9 @@ class SideEffectsFlagPlugin {
648
641
  let hasAnnotation = false;
649
642
  // Before the VariableDeclaration (only for const)
650
643
  if (statement.kind === "const") {
651
- const commentsStart = parser.prevStatement
652
- ? /** @type {Range} */ (parser.prevStatement.range)[1]
653
- : 0;
654
644
  hasAnnotation = hasNoSideEffectsNotation(
655
645
  parser,
656
- commentsStart,
646
+ parser.getAttachedCommentsStart(statement),
657
647
  /** @type {Range} */ (statement.range)[0]
658
648
  );
659
649
  }
@@ -901,11 +891,9 @@ class SideEffectsFlagPlugin {
901
891
  }
902
892
  if (!target) continue;
903
893
 
904
- // A deferred re-export must keep its side-effect-free
905
- // barrel: collapsing it here would turn the cached
906
- // deferred namespace (`.z`) into an eager import of the
907
- // source module, breaking deferred-namespace identity
908
- // and evaluation semantics.
894
+ // A deferred re-export keeps its side-effect-free barrel:
895
+ // collapsing it would turn the cached deferred namespace into
896
+ // an eager import, losing both identity and semantics.
909
897
  if (
910
898
  deferEnabled &&
911
899
  isDeferredTargetConnection(target.connection)
@@ -1390,10 +1390,8 @@ class SplitChunksPlugin {
1390
1390
  }
1391
1391
  }
1392
1392
  }
1393
- // Create key for maps
1394
- // When it has a name we use the name as key
1395
- // Otherwise we create the key from chunks and cache group key
1396
- // This automatically merges equal names
1393
+ // A named group keys on its name, which merges equal names by itself;
1394
+ // an unnamed one keys on its chunks and cache group.
1397
1395
  const key = name
1398
1396
  ? `${cacheGroup.key} name:${name}`
1399
1397
  : getUnnamedKey(cacheGroup, selectedChunksKey);
@@ -5,7 +5,7 @@
5
5
 
6
6
  "use strict";
7
7
 
8
- const ContextModule = require("../ContextModule");
8
+ const ContextModule = require("../context/ContextModule");
9
9
  const BroadContextsWarning = require("../errors/BroadContextsWarning");
10
10
  const { compareStrings } = require("../util/comparators");
11
11
  const getModuleSize = require("./getModuleSize");
@@ -83,10 +83,9 @@ class CacheEffectivenessPlugin {
83
83
 
84
84
  if (!warmRebuild && uncacheable === 0) return;
85
85
 
86
- // Most frequent first, and by reason where two are as frequent: the
87
- // map is keyed in the order the modules were walked, which is not the
88
- // same twice, and only three reasons are reported — so an unbroken tie
89
- // would vary which of them a build names at all.
86
+ // Most frequent first, then by reason: the map is keyed in walk order,
87
+ // which differs between builds, and only three reasons are reported, so
88
+ // an unbroken tie would vary which of them a build names.
90
89
  const sorted = [...modulesByReason].sort(
91
90
  (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
92
91
  );
@@ -269,10 +269,8 @@ module.exports = class SizeLimitsPlugin {
269
269
  }
270
270
 
271
271
  if (hints) {
272
- // 1. Individual Chunk: Size < 250kb
273
- // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb
274
- // 3. No Async Chunks
275
- // if !1, then 2, if !2 return
272
+ // Each asset is checked against the limit first, then each entrypoint's
273
+ // initial chunks together; async chunks count towards neither.
276
274
  if (assetsOverSizeLimit.length > 0) {
277
275
  addLargestModules(compilation, assetsOverSizeLimit);
278
276
  warnings.push(
@@ -83,10 +83,9 @@ class ChunkPrefetchPreloadPlugin {
83
83
  );
84
84
  }
85
85
  if (chunkMap.cssPreload) {
86
- // CSS-only preload (`parser.javascript.dynamicImportCssPreload`):
87
- // the trigger reaches the CSS `.s` handler itself
88
- // (`<link rel="preload" as="style">`), so it asks for the handlers
89
- // alone — nothing here calls the one that fans out over them.
86
+ // A CSS-only preload reaches the CSS handler itself, so it asks for
87
+ // the handlers alone: nothing here calls the function fanning out
88
+ // across them.
90
89
  set.add(RuntimeGlobals.preloadChunkHandlers);
91
90
  compilation.addLazyRuntimeModule(
92
91
  chunk,
@@ -96,10 +95,9 @@ class ChunkPrefetchPreloadPlugin {
96
95
  }
97
96
  }
98
97
  );
99
- // The handlers object is what carries the runtime module, so a chunk asking
100
- // only for it — a trigger that reaches one handler by name — ships no
101
- // fan-out function. Whether one is wanted is read here rather than in
102
- // `create`, which runs after the requirement pass is over.
98
+ // The handlers object carries the runtime module, so a chunk asking only for
99
+ // it ships no fan-out function. That is read here rather than in `create`,
100
+ // which runs once the requirement pass is over.
103
101
  for (const [type, fn, handlers] of /** @type {const} */ ([
104
102
  [
105
103
  "prefetch",