@depup/webpack 5.109.0-depup.0 → 5.110.1-depup.0

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 (641) hide show
  1. package/README.md +7 -7
  2. package/bin/webpack.js +12 -0
  3. package/changes.json +10 -10
  4. package/lib/APIPlugin.js +123 -17
  5. package/lib/AsyncDependenciesBlock.js +10 -7
  6. package/lib/AutomaticPrefetchPlugin.js +1 -1
  7. package/lib/BannerPlugin.js +10 -6
  8. package/lib/CacheFacade.js +6 -6
  9. package/lib/Chunk.js +14 -11
  10. package/lib/ChunkGraph.js +43 -32
  11. package/lib/ChunkGroup.js +7 -7
  12. package/lib/ChunkTemplate.js +35 -44
  13. package/lib/CircularModulesPlugin.js +205 -28
  14. package/lib/CleanPlugin.js +15 -16
  15. package/lib/CodeGenerationResults.js +11 -8
  16. package/lib/CompatibilityPlugin.js +38 -7
  17. package/lib/Compilation.js +709 -414
  18. package/lib/Compiler.js +69 -42
  19. package/lib/ConcatenationScope.js +117 -8
  20. package/lib/ConditionalInitFragment.js +3 -3
  21. package/lib/ConstPlugin.js +13 -11
  22. package/lib/ContextExclusionPlugin.js +1 -1
  23. package/lib/ContextModule.js +146 -54
  24. package/lib/ContextModuleFactory.js +46 -14
  25. package/lib/ContextReplacementPlugin.js +12 -14
  26. package/lib/DefinePlugin.js +168 -57
  27. package/lib/DependenciesBlock.js +9 -6
  28. package/lib/Dependency.js +36 -16
  29. package/lib/DependencyTemplate.js +11 -12
  30. package/lib/DependencyTemplates.js +3 -3
  31. package/lib/DotenvPlugin.js +50 -13
  32. package/lib/DynamicEntryPlugin.js +8 -4
  33. package/lib/EntryOptionPlugin.js +8 -4
  34. package/lib/EntryPlugin.js +2 -2
  35. package/lib/Entrypoint.js +6 -2
  36. package/lib/EnvironmentPlugin.js +2 -2
  37. package/lib/EvalDevToolModulePlugin.js +8 -4
  38. package/lib/EvalSourceMapDevToolPlugin.js +15 -8
  39. package/lib/ExportsInfo.js +123 -19
  40. package/lib/ExportsInfoApiPlugin.js +2 -4
  41. package/lib/ExternalModule.js +242 -84
  42. package/lib/ExternalModuleFactoryPlugin.js +97 -38
  43. package/lib/ExternalsPlugin.js +10 -6
  44. package/lib/FileSystemInfo.js +116 -42
  45. package/lib/FlagAllModulesAsUsedPlugin.js +2 -3
  46. package/lib/FlagDependencyExportsPlugin.js +76 -19
  47. package/lib/FlagDependencyUsagePlugin.js +63 -57
  48. package/lib/FlagEntryExportAsUsedPlugin.js +1 -1
  49. package/lib/Generator.js +36 -15
  50. package/lib/HotModuleReplacementPlugin.js +16 -44
  51. package/lib/IgnorePlugin.js +8 -4
  52. package/lib/IgnoreWarningsPlugin.js +2 -2
  53. package/lib/InitFragment.js +28 -36
  54. package/lib/JavascriptMetaInfoPlugin.js +35 -4
  55. package/lib/LazyBarrel.js +3 -4
  56. package/lib/LibraryTemplatePlugin.js +10 -6
  57. package/lib/LoaderOptionsPlugin.js +7 -3
  58. package/lib/LoaderTargetPlugin.js +1 -1
  59. package/lib/MainTemplate.js +49 -42
  60. package/lib/ManifestPlugin.js +12 -11
  61. package/lib/Module.js +62 -33
  62. package/lib/ModuleFactory.js +3 -3
  63. package/lib/ModuleFilenameHelpers.js +22 -6
  64. package/lib/ModuleGraph.js +195 -21
  65. package/lib/ModuleGraphConnection.js +6 -13
  66. package/lib/ModuleInfoHeaderPlugin.js +8 -10
  67. package/lib/ModuleTemplate.js +62 -63
  68. package/lib/MultiCompiler.js +130 -64
  69. package/lib/MultiStats.js +40 -9
  70. package/lib/MultiWatching.js +3 -3
  71. package/lib/NoEmitOnErrorsPlugin.js +1 -1
  72. package/lib/NodeStuffPlugin.js +29 -19
  73. package/lib/NormalModule.js +221 -156
  74. package/lib/NormalModuleFactory.js +563 -112
  75. package/lib/NormalModuleReplacementPlugin.js +5 -8
  76. package/lib/NullFactory.js +6 -2
  77. package/lib/OptionsApply.js +7 -3
  78. package/lib/Parser.js +7 -3
  79. package/lib/PlatformPlugin.js +2 -2
  80. package/lib/PrefetchPlugin.js +1 -1
  81. package/lib/ProgressPlugin.js +16 -13
  82. package/lib/ProvidePlugin.js +3 -5
  83. package/lib/RawModule.js +25 -17
  84. package/lib/RecordIdsPlugin.js +3 -3
  85. package/lib/RequestShortener.js +1 -1
  86. package/lib/ResolverFactory.js +2 -2
  87. package/lib/RuntimeGlobals.js +22 -10
  88. package/lib/RuntimeModule.js +29 -19
  89. package/lib/RuntimePlugin.js +346 -256
  90. package/lib/RuntimeTemplate.js +2792 -352
  91. package/lib/SelfModuleFactory.js +7 -3
  92. package/lib/SourceMapDevToolModuleOptionsPlugin.js +6 -2
  93. package/lib/SourceMapDevToolPlugin.js +30 -20
  94. package/lib/Stats.js +3 -4
  95. package/lib/Template.js +55 -25
  96. package/lib/TemplatedPathPlugin.js +96 -14
  97. package/lib/UseStrictPlugin.js +4 -6
  98. package/lib/WarnCaseSensitiveModulesPlugin.js +4 -4
  99. package/lib/WarnDeprecatedOptionPlugin.js +1 -1
  100. package/lib/WarnNoModeSetPlugin.js +1 -1
  101. package/lib/WatchIgnorePlugin.js +8 -6
  102. package/lib/Watching.js +8 -8
  103. package/lib/WebpackIsIncludedPlugin.js +2 -4
  104. package/lib/WebpackOptionsApply.js +308 -18
  105. package/lib/WebpackOptionsDefaulter.js +6 -2
  106. package/lib/asset/AssetBytesGenerator.js +12 -10
  107. package/lib/asset/AssetBytesParser.js +2 -4
  108. package/lib/asset/AssetGenerator.js +188 -95
  109. package/lib/asset/AssetModule.js +7 -3
  110. package/lib/asset/AssetModulesPlugin.js +110 -38
  111. package/lib/asset/AssetParser.js +9 -7
  112. package/lib/asset/AssetSourceGenerator.js +60 -13
  113. package/lib/asset/AssetSourceParser.js +2 -4
  114. package/lib/asset/RawDataUrlModule.js +24 -16
  115. package/lib/asset/WebManifestGenerator.js +8 -10
  116. package/lib/asset/WebManifestParser.js +24 -10
  117. package/lib/async-modules/AsyncModuleHelpers.js +2 -2
  118. package/lib/async-modules/AwaitDependenciesInitFragment.js +2 -2
  119. package/lib/async-modules/InferAsyncModulesPlugin.js +2 -2
  120. package/lib/async-modules/isGeneratorLowered.js +4 -4
  121. package/lib/buildChunkGraph.js +36 -27
  122. package/lib/bun/BunTargetPlugin.js +1 -1
  123. package/lib/cache/AddBuildDependenciesPlugin.js +1 -1
  124. package/lib/cache/AddManagedPathsPlugin.js +1 -1
  125. package/lib/cache/IdleFileCachePlugin.js +2 -2
  126. package/lib/cache/MemoryCachePlugin.js +18 -10
  127. package/lib/cache/MemoryWithGcCachePlugin.js +34 -22
  128. package/lib/cache/PackFileCacheStrategy.js +289 -28
  129. package/lib/cache/ResolverCachePlugin.js +38 -18
  130. package/lib/cache/getLazyHashedEtag.js +1 -2
  131. package/lib/cache/mergeEtags.js +1 -1
  132. package/lib/cli.js +1 -3
  133. package/lib/config/browserslistTargetHandler.js +41 -5
  134. package/lib/config/defaults.js +282 -81
  135. package/lib/config/defineConfig.js +10 -2
  136. package/lib/config/getClaimedAssetTypes.js +65 -0
  137. package/lib/config/normalization.js +36 -16
  138. package/lib/config/target.js +46 -3
  139. package/lib/container/ContainerEntryDependency.js +1 -1
  140. package/lib/container/ContainerEntryModule.js +24 -15
  141. package/lib/container/ContainerEntryModuleFactory.js +7 -3
  142. package/lib/container/ContainerPlugin.js +9 -10
  143. package/lib/container/ContainerReferencePlugin.js +6 -2
  144. package/lib/container/FallbackDependency.js +1 -1
  145. package/lib/container/FallbackModule.js +24 -17
  146. package/lib/container/FallbackModuleFactory.js +7 -3
  147. package/lib/container/HoistContainerReferencesPlugin.js +53 -66
  148. package/lib/container/ModuleFederationPlugin.js +7 -18
  149. package/lib/container/RemoteModule.js +27 -19
  150. package/lib/container/RemoteRuntimeModule.js +10 -8
  151. package/lib/container/moduleFederationHooks.js +32 -0
  152. package/lib/css/CssGenerator.js +178 -44
  153. package/lib/css/CssInjectStyleRuntimeModule.js +7 -5
  154. package/lib/css/CssLoadingRuntimeModule.js +82 -36
  155. package/lib/css/CssModule.js +10 -7
  156. package/lib/css/CssModulesPlugin.js +197 -106
  157. package/lib/css/CssParser.js +1248 -618
  158. package/lib/css/CssServerStylesRuntimeModule.js +54 -0
  159. package/lib/css/cssMinify.js +168 -0
  160. package/lib/css/data.js +5324 -0
  161. package/lib/css/syntax.js +10396 -952
  162. package/lib/debug/ProfilingPlugin.js +14 -9
  163. package/lib/deno/DenoTargetPlugin.js +1 -1
  164. package/lib/dependencies/AMDDefineDependency.js +112 -87
  165. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +30 -17
  166. package/lib/dependencies/AMDPlugin.js +9 -7
  167. package/lib/dependencies/AMDRequireArrayDependency.js +5 -5
  168. package/lib/dependencies/AMDRequireContextDependency.js +2 -2
  169. package/lib/dependencies/AMDRequireDependenciesBlock.js +1 -1
  170. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +25 -14
  171. package/lib/dependencies/AMDRequireDependency.js +8 -7
  172. package/lib/dependencies/AMDRequireItemDependency.js +1 -1
  173. package/lib/dependencies/AMDRuntimeModules.js +21 -1
  174. package/lib/dependencies/BuildTimeConstDependency.js +102 -0
  175. package/lib/dependencies/CachedConstDependency.js +11 -8
  176. package/lib/dependencies/CommonJsDependencyHelpers.js +67 -46
  177. package/lib/dependencies/CommonJsExportRequireDependency.js +140 -45
  178. package/lib/dependencies/CommonJsExportsDependency.js +53 -49
  179. package/lib/dependencies/CommonJsExportsParserPlugin.js +207 -25
  180. package/lib/dependencies/CommonJsFullRequireDependency.js +140 -26
  181. package/lib/dependencies/CommonJsImportsParserPlugin.js +100 -48
  182. package/lib/dependencies/CommonJsObjectExportDependency.js +188 -0
  183. package/lib/dependencies/CommonJsPlugin.js +35 -6
  184. package/lib/dependencies/CommonJsRequireContextDependency.js +5 -6
  185. package/lib/dependencies/CommonJsRequireDependency.js +156 -27
  186. package/lib/dependencies/CommonJsSelfReferenceDependency.js +63 -38
  187. package/lib/dependencies/ConstDependency.js +8 -9
  188. package/lib/dependencies/ContextDependency.js +12 -8
  189. package/lib/dependencies/ContextDependencyHelpers.js +14 -9
  190. package/lib/dependencies/ContextDependencyTemplateAsId.js +4 -4
  191. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +4 -4
  192. package/lib/dependencies/ContextElementDependency.js +31 -12
  193. package/lib/dependencies/CreateRequireParserPlugin.js +12 -7
  194. package/lib/dependencies/CreateScriptUrlDependency.js +4 -4
  195. package/lib/dependencies/CssIcssExportDependency.js +56 -28
  196. package/lib/dependencies/CssIcssImportDependency.js +17 -13
  197. package/lib/dependencies/CssIcssSymbolDependency.js +9 -10
  198. package/lib/dependencies/CssImportDependency.js +18 -9
  199. package/lib/dependencies/CssUrlDependency.js +17 -13
  200. package/lib/dependencies/DllEntryDependency.js +1 -1
  201. package/lib/dependencies/DynamicExports.js +2 -2
  202. package/lib/dependencies/ExportBindingInitFragment.js +36 -9
  203. package/lib/dependencies/ExportsInfoDependency.js +7 -8
  204. package/lib/dependencies/ExternalModuleDependency.js +9 -5
  205. package/lib/dependencies/ExternalModuleInitFragment.js +2 -2
  206. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +8 -5
  207. package/lib/dependencies/HarmonyAcceptDependency.js +5 -5
  208. package/lib/dependencies/HarmonyCompatibilityDependency.js +52 -17
  209. package/lib/dependencies/HarmonyDetectionParserPlugin.js +11 -7
  210. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +15 -11
  211. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +78 -12
  212. package/lib/dependencies/HarmonyExportExpressionDependency.js +23 -18
  213. package/lib/dependencies/HarmonyExportHeaderDependency.js +7 -7
  214. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +159 -71
  215. package/lib/dependencies/HarmonyExportInitFragment.js +18 -6
  216. package/lib/dependencies/HarmonyExportSpecifierDependency.js +51 -14
  217. package/lib/dependencies/HarmonyExports.js +7 -4
  218. package/lib/dependencies/HarmonyImportDependency.js +28 -20
  219. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +31 -24
  220. package/lib/dependencies/HarmonyImportGuard.js +21 -30
  221. package/lib/dependencies/HarmonyImportSideEffectDependency.js +38 -9
  222. package/lib/dependencies/HarmonyImportSpecifierDependency.js +106 -55
  223. package/lib/dependencies/HarmonyModulesPlugin.js +7 -3
  224. package/lib/dependencies/HarmonyTopLevelThisParserPlugin.js +1 -3
  225. package/lib/dependencies/HtmlEntryDependency.js +37 -29
  226. package/lib/dependencies/HtmlInlineHtmlDependency.js +7 -8
  227. package/lib/dependencies/HtmlInlineScriptDependency.js +11 -8
  228. package/lib/dependencies/HtmlInlineStyleDependency.js +7 -10
  229. package/lib/dependencies/HtmlSourceDependency.js +22 -14
  230. package/lib/dependencies/ImportContextDependency.js +2 -2
  231. package/lib/dependencies/ImportDependency.js +24 -20
  232. package/lib/dependencies/ImportEagerDependency.js +6 -9
  233. package/lib/dependencies/ImportMetaContextDependency.js +2 -2
  234. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +14 -13
  235. package/lib/dependencies/ImportMetaContextPlugin.js +7 -3
  236. package/lib/dependencies/ImportMetaGlobDependency.js +2 -2
  237. package/lib/dependencies/ImportMetaGlobDependencyParserPlugin.js +2 -3
  238. package/lib/dependencies/ImportMetaGlobHelpers.js +19 -22
  239. package/lib/dependencies/ImportMetaHotAcceptDependency.js +1 -1
  240. package/lib/dependencies/ImportMetaHotDeclineDependency.js +1 -1
  241. package/lib/dependencies/ImportMetaPlugin.js +154 -71
  242. package/lib/dependencies/ImportMetaResolveDependency.js +3 -4
  243. package/lib/dependencies/ImportParserPlugin.js +49 -35
  244. package/lib/dependencies/ImportPhase.js +12 -5
  245. package/lib/dependencies/ImportPlugin.js +7 -3
  246. package/lib/dependencies/ImportWeakDependency.js +6 -9
  247. package/lib/dependencies/JsonExportsDependency.js +11 -7
  248. package/lib/dependencies/LoaderDependency.js +2 -2
  249. package/lib/dependencies/LoaderImportDependency.js +2 -2
  250. package/lib/dependencies/LoaderPlugin.js +11 -7
  251. package/lib/dependencies/LocalModuleDependency.js +5 -5
  252. package/lib/dependencies/LocalModulesHelpers.js +1 -1
  253. package/lib/dependencies/ModuleDecoratorDependency.js +6 -7
  254. package/lib/dependencies/ModuleDependency.js +9 -6
  255. package/lib/dependencies/ModuleDependencyTemplateAsId.js +4 -4
  256. package/lib/dependencies/ModuleDependencyTemplateAsRequireId.js +3 -3
  257. package/lib/dependencies/ModuleHotAcceptDependency.js +1 -1
  258. package/lib/dependencies/ModuleHotDeclineDependency.js +1 -1
  259. package/lib/dependencies/ModuleInitFragmentDependency.js +24 -10
  260. package/lib/dependencies/NullDependency.js +3 -3
  261. package/lib/dependencies/ProvidedDependency.js +14 -10
  262. package/lib/dependencies/PureExpressionDependency.js +9 -10
  263. package/lib/dependencies/RequireContextDependency.js +2 -2
  264. package/lib/dependencies/RequireContextDependencyParserPlugin.js +2 -4
  265. package/lib/dependencies/RequireContextPlugin.js +8 -4
  266. package/lib/dependencies/RequireEnsureDependenciesBlock.js +2 -2
  267. package/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +5 -8
  268. package/lib/dependencies/RequireEnsureDependency.js +8 -7
  269. package/lib/dependencies/RequireEnsurePlugin.js +7 -3
  270. package/lib/dependencies/RequireHeaderDependency.js +51 -12
  271. package/lib/dependencies/RequireIncludeDependency.js +6 -6
  272. package/lib/dependencies/RequireIncludeDependencyParserPlugin.js +2 -3
  273. package/lib/dependencies/RequireIncludePlugin.js +7 -3
  274. package/lib/dependencies/RequireJsStuffPlugin.js +7 -3
  275. package/lib/dependencies/RequireResolveContextDependency.js +2 -2
  276. package/lib/dependencies/RequireResolveDependency.js +4 -4
  277. package/lib/dependencies/RequireResolveHeaderDependency.js +4 -4
  278. package/lib/dependencies/RuntimeRequirementsDependency.js +5 -6
  279. package/lib/dependencies/StaticExportsDependency.js +2 -2
  280. package/lib/dependencies/SystemPlugin.js +10 -6
  281. package/lib/dependencies/SystemRuntimeModule.js +10 -0
  282. package/lib/dependencies/TopLevelAwaitDependency.js +11 -7
  283. package/lib/dependencies/URLContextDependency.js +2 -2
  284. package/lib/dependencies/URLDependency.js +110 -64
  285. package/lib/dependencies/URLPlugin.js +7 -3
  286. package/lib/dependencies/UnsupportedDependency.js +4 -4
  287. package/lib/dependencies/WebAssemblyExportImportedDependency.js +3 -4
  288. package/lib/dependencies/WebAssemblyImportDependency.js +5 -5
  289. package/lib/dependencies/WebpackIsIncludedDependency.js +6 -6
  290. package/lib/dependencies/WorkerAndWorkletPlugin.js +46 -28
  291. package/lib/dependencies/WorkerDependency.js +28 -22
  292. package/lib/dependencies/WorkletDependency.js +15 -14
  293. package/lib/dependencies/getFunctionExpression.js +8 -4
  294. package/lib/dependencies/processExportInfo.js +5 -5
  295. package/lib/dll/DelegatedModule.js +34 -22
  296. package/lib/dll/DelegatedModuleFactoryPlugin.js +15 -7
  297. package/lib/dll/DelegatedPlugin.js +2 -2
  298. package/lib/dll/DllEntryPlugin.js +2 -2
  299. package/lib/dll/DllModule.js +22 -15
  300. package/lib/dll/DllModuleFactory.js +7 -3
  301. package/lib/dll/DllPlugin.js +7 -5
  302. package/lib/dll/DllReferencePlugin.js +10 -7
  303. package/lib/dll/LibManifestPlugin.js +5 -5
  304. package/lib/electron/ElectronTargetPlugin.js +53 -49
  305. package/lib/errors/AsyncChunkWaterfallWarning.js +36 -0
  306. package/lib/errors/AsyncDependencyToInitialChunkError.js +2 -2
  307. package/lib/errors/BroadContextsWarning.js +43 -0
  308. package/lib/errors/BuildCycleError.js +1 -1
  309. package/lib/errors/CacheEffectivenessWarning.js +55 -0
  310. package/lib/errors/ChunkRenderError.js +1 -1
  311. package/lib/errors/CircularDependenciesWarning.js +38 -0
  312. package/lib/errors/CodeGenerationError.js +1 -1
  313. package/lib/errors/CommentCompilationWarning.js +1 -1
  314. package/lib/errors/ConflictingResourceHintsWarning.js +35 -0
  315. package/lib/errors/DuplicateModulesWarning.js +45 -0
  316. package/lib/errors/DynamicExportsWarning.js +30 -0
  317. package/lib/errors/EmbeddedSourceMapsWarning.js +25 -0
  318. package/lib/errors/EntrypointOverlapWarning.js +45 -0
  319. package/lib/errors/EnvironmentNotSupportAsyncWarning.js +2 -2
  320. package/lib/errors/EvalUsageWarning.js +28 -0
  321. package/lib/errors/HookWebpackError.js +5 -5
  322. package/lib/errors/HotspotsWarning.js +57 -0
  323. package/lib/errors/IgnoreErrorModuleFactory.js +7 -3
  324. package/lib/errors/InlinedAssetsWarning.js +36 -0
  325. package/lib/errors/InvalidDependenciesModuleWarning.js +1 -1
  326. package/lib/errors/LargeModulesWarning.js +45 -0
  327. package/lib/errors/LegacyJavascriptWarning.js +48 -0
  328. package/lib/errors/MissingSideEffectsWarning.js +36 -0
  329. package/lib/errors/MixedExportsWarning.js +41 -0
  330. package/lib/errors/ModuleDependencyError.js +13 -16
  331. package/lib/errors/ModuleDependencyWarning.js +5 -15
  332. package/lib/errors/ModuleHashingError.js +1 -1
  333. package/lib/errors/ModuleNotFoundError.js +2 -2
  334. package/lib/errors/ModuleParseError.js +1 -2
  335. package/lib/errors/ModuleRestoreError.js +1 -1
  336. package/lib/errors/ModuleStoreError.js +1 -1
  337. package/lib/errors/NodeStuffInWebError.js +1 -1
  338. package/lib/errors/OsDependentRuleWarning.js +31 -0
  339. package/lib/errors/PureAnnotationsWarning.js +36 -0
  340. package/lib/errors/RedundantDynamicImportWarning.js +31 -0
  341. package/lib/errors/ScopeHoistingBailoutsWarning.js +41 -0
  342. package/lib/errors/SplitChunksCappedWarning.js +41 -0
  343. package/lib/errors/TinyChunksWarning.js +40 -0
  344. package/lib/errors/TopLevelThisWarning.js +34 -0
  345. package/lib/errors/UnsplitVendorsWarning.js +42 -0
  346. package/lib/errors/UnsupportedFeatureWarning.js +1 -1
  347. package/lib/errors/UnusedAliasesWarning.js +29 -0
  348. package/lib/errors/UnusedDefinesWarning.js +29 -0
  349. package/lib/errors/UnusedExternalsWarning.js +29 -0
  350. package/lib/errors/UnusedReexportsWarning.js +42 -0
  351. package/lib/errors/UnusedRuleWarning.js +29 -0
  352. package/lib/errors/WebpackError.js +9 -5
  353. package/lib/errors/deriveStackFromNestedError.js +90 -0
  354. package/lib/esm/ExportWebpackRequireRuntimeModule.js +2 -0
  355. package/lib/esm/ModuleChunkFormatPlugin.js +37 -19
  356. package/lib/esm/ModuleChunkLoadingPlugin.js +89 -51
  357. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +170 -71
  358. package/lib/hmr/HotModuleReplacement.runtime.js +24 -5
  359. package/lib/hmr/HotModuleReplacementRuntimeModule.js +1 -1
  360. package/lib/hmr/LazyCompilationPlugin.js +45 -24
  361. package/lib/hmr/lazyCompilationBackend.js +28 -10
  362. package/lib/hmr/parserHooks.js +56 -0
  363. package/lib/html/HtmlGenerator.js +299 -79
  364. package/lib/html/HtmlModule.js +7 -3
  365. package/lib/html/HtmlModulesPlugin.js +312 -174
  366. package/lib/html/HtmlParser.js +31 -86
  367. package/lib/html/data.js +1928 -0
  368. package/lib/html/htmlMinify.js +288 -0
  369. package/lib/html/syntax.js +7819 -3331
  370. package/lib/ids/ChunkModuleIdRangePlugin.js +3 -3
  371. package/lib/ids/DeterministicChunkIdsPlugin.js +1 -1
  372. package/lib/ids/DeterministicModuleIdsPlugin.js +2 -2
  373. package/lib/ids/HashedModuleIdsPlugin.js +6 -2
  374. package/lib/ids/IdHelpers.js +31 -18
  375. package/lib/ids/NamedChunkIdsPlugin.js +1 -1
  376. package/lib/ids/NamedModuleIdsPlugin.js +1 -1
  377. package/lib/ids/NaturalChunkIdsPlugin.js +2 -2
  378. package/lib/ids/NaturalModuleIdsPlugin.js +1 -1
  379. package/lib/ids/OccurrenceChunkIdsPlugin.js +7 -3
  380. package/lib/ids/OccurrenceModuleIdsPlugin.js +7 -3
  381. package/lib/ids/SyncModuleIdsPlugin.js +4 -4
  382. package/lib/index.js +10 -0
  383. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +3 -3
  384. package/lib/javascript/BasicEvaluatedExpression.js +18 -14
  385. package/lib/javascript/ChunkFormatHelpers.js +6 -6
  386. package/lib/javascript/ChunkHelpers.js +1 -1
  387. package/lib/javascript/CommonJsChunkFormatPlugin.js +11 -5
  388. package/lib/javascript/EnableChunkLoadingPlugin.js +2 -2
  389. package/lib/javascript/JavascriptGenerator.js +65 -165
  390. package/lib/javascript/JavascriptModule.js +9 -3
  391. package/lib/javascript/JavascriptModulesPlugin.js +181 -162
  392. package/lib/javascript/JavascriptParser.js +291 -112
  393. package/lib/javascript/JavascriptParserHelpers.js +10 -7
  394. package/lib/javascript/ScopeAnalyzer.js +1094 -0
  395. package/lib/javascript/StartupHelpers.js +55 -9
  396. package/lib/javascript/syntax.js +3403 -300
  397. package/lib/json/JsonData.js +8 -4
  398. package/lib/json/JsonGenerator.js +38 -16
  399. package/lib/json/JsonModule.js +7 -3
  400. package/lib/json/JsonModulesPlugin.js +1 -1
  401. package/lib/json/JsonParser.js +5 -6
  402. package/lib/library/AbstractLibraryPlugin.js +20 -14
  403. package/lib/library/AmdLibraryPlugin.js +11 -7
  404. package/lib/library/AssignLibraryPlugin.js +19 -13
  405. package/lib/library/EnableLibraryPlugin.js +2 -2
  406. package/lib/library/ExportPropertyLibraryPlugin.js +15 -8
  407. package/lib/library/JsonpLibraryPlugin.js +11 -7
  408. package/lib/library/ModuleLibraryPlugin.js +256 -64
  409. package/lib/library/SystemLibraryPlugin.js +12 -8
  410. package/lib/library/UmdLibraryPlugin.js +62 -25
  411. package/lib/loaders/LoaderRunner.js +14 -1
  412. package/lib/loaders/loadLoader.js +8 -4
  413. package/lib/logging/createConsoleLogger.js +7 -4
  414. package/lib/node/CommonJsChunkLoadingPlugin.js +36 -22
  415. package/lib/node/NodeEnvironmentPlugin.js +17 -3
  416. package/lib/node/NodeSourcePlugin.js +1 -1
  417. package/lib/node/NodeTargetPlugin.js +4 -3
  418. package/lib/node/NodeTemplatePlugin.js +1 -1
  419. package/lib/node/NodeWatchFileSystem.js +70 -9
  420. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +35 -38
  421. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +81 -20
  422. package/lib/node/ReadFileCompileWasmPlugin.js +37 -17
  423. package/lib/node/RequireChunkLoadingRuntimeModule.js +35 -38
  424. package/lib/node/nodeConsole.js +7 -3
  425. package/lib/optimize/AggressiveMergingPlugin.js +21 -17
  426. package/lib/optimize/AggressiveSplittingPlugin.js +9 -6
  427. package/lib/optimize/ConcatenatedModule.js +996 -477
  428. package/lib/optimize/ConstExportsPlugin.js +11 -7
  429. package/lib/optimize/EnsureChunkConditionsPlugin.js +3 -3
  430. package/lib/optimize/FlagIncludedChunksPlugin.js +3 -4
  431. package/lib/optimize/InlineExports.js +9 -5
  432. package/lib/optimize/InnerGraph.js +28 -12
  433. package/lib/optimize/InnerGraphPlugin.js +23 -18
  434. package/lib/optimize/LimitChunkCountPlugin.js +7 -3
  435. package/lib/optimize/MangleExportsPlugin.js +7 -8
  436. package/lib/optimize/MergeDuplicateChunksPlugin.js +7 -3
  437. package/lib/optimize/MinChunkSizePlugin.js +7 -3
  438. package/lib/optimize/ModuleConcatenationPlugin.js +124 -59
  439. package/lib/optimize/RealContentHashPlugin.js +20 -13
  440. package/lib/optimize/RemoveEmptyChunksPlugin.js +2 -2
  441. package/lib/optimize/RemoveParentModulesPlugin.js +4 -4
  442. package/lib/optimize/RuntimeChunkPlugin.js +2 -2
  443. package/lib/optimize/SideEffectsFlagPlugin.js +262 -39
  444. package/lib/optimize/SplitChunksPlugin.js +232 -68
  445. package/lib/performance/AssetsOverSizeLimitWarning.js +10 -2
  446. package/lib/performance/AsyncChunkWaterfallsPlugin.js +136 -0
  447. package/lib/performance/BroadContextsPlugin.js +142 -0
  448. package/lib/performance/CacheEffectivenessPlugin.js +125 -0
  449. package/lib/performance/ConflictingResourceHintsPlugin.js +99 -0
  450. package/lib/performance/DuplicateModulesPlugin.js +93 -0
  451. package/lib/performance/DuplicatePackagesPlugin.js +119 -0
  452. package/lib/performance/DuplicatePackagesWarning.js +84 -0
  453. package/lib/performance/DynamicExportsPlugin.js +120 -0
  454. package/lib/performance/EmbeddedSourceMapsPlugin.js +71 -0
  455. package/lib/performance/EntrypointOverlapPlugin.js +122 -0
  456. package/lib/performance/EntrypointsOverSizeLimitWarning.js +1 -1
  457. package/lib/performance/EvalUsagePlugin.js +115 -0
  458. package/lib/performance/HotspotsPlugin.js +296 -0
  459. package/lib/performance/InlinedAssetsPlugin.js +99 -0
  460. package/lib/performance/LargeModulesPlugin.js +126 -0
  461. package/lib/performance/LegacyJavascriptPlugin.js +139 -0
  462. package/lib/performance/MissingSideEffectsPlugin.js +138 -0
  463. package/lib/performance/MixedExportsPlugin.js +136 -0
  464. package/lib/performance/OsDependentRuleWarningPlugin.js +178 -0
  465. package/lib/performance/PureAnnotationsPlugin.js +219 -0
  466. package/lib/performance/RedundantDynamicImportsPlugin.js +225 -0
  467. package/lib/performance/RuntimeInLargeChunkWarning.js +27 -0
  468. package/lib/performance/ScopeHoistingBailoutsPlugin.js +164 -0
  469. package/lib/performance/SizeLimitsPlugin.js +139 -7
  470. package/lib/performance/SplitChunksCappedPlugin.js +99 -0
  471. package/lib/performance/TinyChunksPlugin.js +128 -0
  472. package/lib/performance/TopLevelThisPlugin.js +208 -0
  473. package/lib/performance/UnsplitVendorsPlugin.js +112 -0
  474. package/lib/performance/UnusedAliasesPlugin.js +253 -0
  475. package/lib/performance/UnusedDefinesPlugin.js +87 -0
  476. package/lib/performance/UnusedExternalsPlugin.js +110 -0
  477. package/lib/performance/UnusedReexportsPlugin.js +159 -0
  478. package/lib/performance/UnusedRuleWarningPlugin.js +105 -0
  479. package/lib/performance/getModuleSize.js +22 -0
  480. package/lib/performance/getSourceModules.js +22 -0
  481. package/lib/performance/hasOnlyUnusedExports.js +40 -0
  482. package/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +24 -10
  483. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +63 -46
  484. package/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +2 -3
  485. package/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +2 -2
  486. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +2 -2
  487. package/lib/prefetch/ResourceHintPlugin.js +377 -136
  488. package/lib/prefetch/ResourceHintRuntimeModule.js +1 -21
  489. package/lib/prefetch/StartupAssetHintRuntimeModule.js +10 -133
  490. package/lib/prefetch/parseResourceHintOptions.js +31 -4
  491. package/lib/rules/BasicEffectRulePlugin.js +2 -2
  492. package/lib/rules/BasicMatcherRulePlugin.js +8 -4
  493. package/lib/rules/GlobMatcherRulePlugin.js +68 -0
  494. package/lib/rules/ObjectMatcherRulePlugin.js +12 -5
  495. package/lib/rules/RuleSetCompiler.js +146 -12
  496. package/lib/rules/UseEffectRulePlugin.js +18 -11
  497. package/lib/runtime/AsyncModuleGeneratorRuntimeModule.js +11 -1
  498. package/lib/runtime/AsyncModuleRuntimeModule.js +1 -1
  499. package/lib/runtime/AutoPublicPathRuntimeModule.js +15 -20
  500. package/lib/runtime/BaseUriRuntimeModule.js +33 -7
  501. package/lib/runtime/ChunkNameRuntimeModule.js +10 -0
  502. package/lib/runtime/CompatGetDefaultExportRuntimeModule.js +11 -1
  503. package/lib/runtime/CompatRuntimeModule.js +5 -3
  504. package/lib/runtime/ConcatenationWrapRuntimeModule.js +90 -0
  505. package/lib/runtime/ConstructRequireRuntimeModule.js +52 -0
  506. package/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +8 -6
  507. package/lib/runtime/CreateScriptRuntimeModule.js +11 -1
  508. package/lib/runtime/CreateScriptUrlRuntimeModule.js +11 -1
  509. package/lib/runtime/DefinePropertyGettersRuntimeModule.js +56 -38
  510. package/lib/runtime/EnsureChunkRuntimeModule.js +18 -2
  511. package/lib/runtime/GetChunkFilenameRuntimeModule.js +62 -37
  512. package/lib/runtime/GetFullHashRuntimeModule.js +12 -2
  513. package/lib/runtime/GetMainFilenameRuntimeModule.js +12 -2
  514. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +2 -2
  515. package/lib/runtime/GetWorkletBootstrapRuntimeModule.js +16 -3
  516. package/lib/runtime/GlobalRuntimeModule.js +18 -0
  517. package/lib/runtime/HasOwnPropertyRuntimeModule.js +12 -2
  518. package/lib/runtime/LoadScriptRuntimeModule.js +2 -2
  519. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +23 -6
  520. package/lib/runtime/MakeNamespaceObjectRuntimeModule.js +22 -6
  521. package/lib/runtime/NonceRuntimeModule.js +10 -0
  522. package/lib/runtime/OnChunksLoadedRuntimeModule.js +5 -3
  523. package/lib/runtime/PublicPathRuntimeModule.js +12 -2
  524. package/lib/runtime/RelativeUrlRuntimeModule.js +11 -1
  525. package/lib/runtime/RuntimeIdRuntimeModule.js +12 -2
  526. package/lib/runtime/SetAnonymousDefaultNameRuntimeModule.js +11 -1
  527. package/lib/runtime/StartupChunkDependenciesPlugin.js +18 -9
  528. package/lib/runtime/StartupChunkDependenciesRuntimeModule.js +3 -3
  529. package/lib/runtime/StartupEntrypointRuntimeModule.js +21 -4
  530. package/lib/runtime/SystemContextRuntimeModule.js +10 -0
  531. package/lib/runtime/ToBinaryRuntimeModule.js +1 -1
  532. package/lib/runtime/WorkerRuntimeModule.js +11 -1
  533. package/lib/runtime/baseUri.js +63 -0
  534. package/lib/schemes/DataUriPlugin.js +1 -1
  535. package/lib/schemes/FileUriPlugin.js +1 -1
  536. package/lib/schemes/HttpUriPlugin.js +24 -15
  537. package/lib/schemes/VirtualUrlPlugin.js +13 -7
  538. package/lib/serialization/AggregateErrorSerializer.js +1 -1
  539. package/lib/serialization/BinaryMiddleware.js +274 -942
  540. package/lib/serialization/ErrorObjectSerializer.js +1 -1
  541. package/lib/serialization/FileMiddleware.js +305 -66
  542. package/lib/serialization/ObjectMiddleware.js +139 -114
  543. package/lib/serialization/PlainObjectSerializer.js +19 -16
  544. package/lib/sharing/ConsumeSharedModule.js +30 -21
  545. package/lib/sharing/ConsumeSharedPlugin.js +18 -10
  546. package/lib/sharing/ConsumeSharedRuntimeModule.js +6 -9
  547. package/lib/sharing/ProvideSharedModule.js +25 -16
  548. package/lib/sharing/ProvideSharedModuleFactory.js +7 -3
  549. package/lib/sharing/ProvideSharedPlugin.js +8 -4
  550. package/lib/sharing/SharePlugin.js +17 -5
  551. package/lib/sharing/ShareRuntimeModule.js +4 -4
  552. package/lib/sharing/resolveMatchedConfigs.js +9 -6
  553. package/lib/sharing/utils.js +1 -3
  554. package/lib/stats/DefaultStatsFactoryPlugin.js +253 -226
  555. package/lib/stats/DefaultStatsPresetPlugin.js +17 -8
  556. package/lib/stats/DefaultStatsPrinterPlugin.js +60 -192
  557. package/lib/stats/StatsFactory.js +56 -35
  558. package/lib/stats/StatsPrinter.js +16 -12
  559. package/lib/typescript/TypeScriptPlugin.js +12 -14
  560. package/lib/url/URLParserPlugin.js +26 -13
  561. package/lib/util/AsyncQueue.js +4 -3
  562. package/lib/util/Hash.js +5 -1
  563. package/lib/util/LazySet.js +35 -22
  564. package/lib/util/LocConverter.js +36 -13
  565. package/lib/util/SourceProcessor.js +1050 -24
  566. package/lib/util/StringXor.js +1 -1
  567. package/lib/util/chainedImports.js +9 -5
  568. package/lib/util/cleverMerge.js +1 -1
  569. package/lib/util/comparators.js +45 -14
  570. package/lib/util/concatenate.js +203 -77
  571. package/lib/util/conventions.js +5 -1
  572. package/lib/util/createHash.js +2 -2
  573. package/lib/util/createHooksRegistry.js +8 -10
  574. package/lib/util/dataURL.js +225 -1
  575. package/lib/util/extractSourceMap.js +4 -3
  576. package/lib/util/findCaseMismatch.js +139 -0
  577. package/lib/util/formatLocation.js +1 -2
  578. package/lib/util/fs.js +22 -5
  579. package/lib/util/globUtils.js +298 -24
  580. package/lib/util/hash/BatchedHash.js +5 -1
  581. package/lib/util/hash/BulkUpdateHash.js +5 -1
  582. package/lib/util/hash/DebugHash.js +5 -1
  583. package/lib/util/hash/hash-digest.js +6 -2
  584. package/lib/util/identifier.js +25 -1
  585. package/lib/util/implicitTypeLoaderFallback.js +1 -1
  586. package/lib/util/internalSerializables.js +6 -0
  587. package/lib/util/lazyModule.js +56 -0
  588. package/lib/util/makeSerializable.js +7 -3
  589. package/lib/util/matchAlias.js +25 -0
  590. package/lib/util/mimeTypes.js +11 -5
  591. package/lib/util/nonNumericOnlyHash.js +4 -3
  592. package/lib/util/parseJson.js +5 -3
  593. package/lib/util/preloadModuleType.js +32 -0
  594. package/lib/util/registerExternalSerializer.js +7 -5
  595. package/lib/util/runtime.js +2 -2
  596. package/lib/util/semver.js +1 -1
  597. package/lib/util/serialization.js +28 -28
  598. package/lib/util/source.js +2 -2
  599. package/lib/util/traverseDestructuringAssignmentProperties.js +6 -2
  600. package/lib/wasm/EnableWasmLoadingPlugin.js +10 -8
  601. package/lib/wasm/wasmModuleFilename.js +54 -0
  602. package/lib/wasm-async/AsyncWasmCompileRuntimeModule.js +41 -21
  603. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +43 -21
  604. package/lib/wasm-async/AsyncWasmModule.js +3 -3
  605. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +4 -5
  606. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +57 -17
  607. package/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js +34 -18
  608. package/lib/wasm-async/AsyncWebAssemblyParser.js +9 -8
  609. package/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js +34 -8
  610. package/lib/wasm-sync/SyncWasmModule.js +2 -2
  611. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +18 -13
  612. package/lib/wasm-sync/WasmFinalizeExportsPlugin.js +4 -5
  613. package/lib/wasm-sync/WebAssemblyGenerator.js +18 -17
  614. package/lib/wasm-sync/WebAssemblyInInitialChunkError.js +4 -4
  615. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +7 -7
  616. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +24 -11
  617. package/lib/wasm-sync/WebAssemblyParser.js +4 -6
  618. package/lib/wasm-sync/WebAssemblyUtils.js +2 -2
  619. package/lib/web/FetchCompileAsyncWasmPlugin.js +101 -19
  620. package/lib/web/FetchCompileWasmPlugin.js +46 -16
  621. package/lib/web/JsonpChunkLoadingPlugin.js +47 -23
  622. package/lib/web/JsonpChunkLoadingRuntimeModule.js +50 -20
  623. package/lib/web/JsonpTemplatePlugin.js +2 -2
  624. package/lib/webpack.js +22 -11
  625. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +60 -26
  626. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +30 -32
  627. package/lib/webworker/WebWorkerTemplatePlugin.js +1 -1
  628. package/module.d.ts +1 -0
  629. package/package.json +37 -30
  630. package/schemas/WebpackOptions.check.js +1 -1
  631. package/schemas/WebpackOptions.json +780 -91
  632. package/schemas/plugins/HtmlParserOptions.check.js +1 -1
  633. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  634. package/schemas/plugins/container/ContainerPlugin.json +10 -0
  635. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  636. package/schemas/plugins/container/ModuleFederationPlugin.json +10 -0
  637. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.js +1 -1
  638. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  639. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  640. package/types.d.ts +4013 -738
  641. package/lib/runtime/CommonJsWrapRuntimeModule.js +0 -37
@@ -5,8 +5,6 @@
5
5
 
6
6
  "use strict";
7
7
 
8
- const eslintScope = require("eslint-scope");
9
- const Referencer = require("eslint-scope/lib/referencer");
10
8
  const { SyncBailHook } = require("tapable");
11
9
  const {
12
10
  CachedSource,
@@ -16,18 +14,23 @@ const {
16
14
  const ConcatenationScope = require("../ConcatenationScope");
17
15
  const Dependency = require("../Dependency");
18
16
  const { UsageState } = require("../ExportsInfo");
17
+ const ExternalModule = require("../ExternalModule");
19
18
  const Module = require("../Module");
20
19
  const {
21
20
  JAVASCRIPT_TYPE,
22
21
  JAVASCRIPT_TYPES
23
22
  } = require("../ModuleSourceTypeConstants");
24
23
  const { JAVASCRIPT_MODULE_TYPE_ESM } = require("../ModuleTypeConstants");
24
+ const NormalModule = require("../NormalModule");
25
25
  const RuntimeGlobals = require("../RuntimeGlobals");
26
26
  const Template = require("../Template");
27
27
  const { DEFAULTS } = require("../config/defaults");
28
+ const CommonJsExportRequireDependency = require("../dependencies/CommonJsExportRequireDependency");
29
+ const CommonJsFullRequireDependency = require("../dependencies/CommonJsFullRequireDependency");
30
+ const CommonJsRequireDependency = require("../dependencies/CommonJsRequireDependency");
28
31
  const { ImportPhaseUtils } = require("../dependencies/ImportPhase");
29
- const { isCommonJsWrapped } = require("../javascript/JavascriptGenerator");
30
32
  const JavascriptParser = require("../javascript/JavascriptParser");
33
+ const analyzeScope = require("../javascript/ScopeAnalyzer");
31
34
  const {
32
35
  getDeferredCycleModuleIds,
33
36
  getDeferredCycleModules,
@@ -36,14 +39,18 @@ const {
36
39
  } = require("../runtime/MakeDeferredNamespaceObjectRuntime");
37
40
  const { equals } = require("../util/ArrayHelpers");
38
41
  const LazySet = require("../util/LazySet");
39
- const { concatComparators } = require("../util/comparators");
42
+ const {
43
+ compareModulesByFullName,
44
+ concatComparators
45
+ } = require("../util/comparators");
40
46
  const {
41
47
  RESERVED_NAMES,
42
48
  addScopeSymbols,
43
49
  findNewName,
44
50
  getAllReferences,
45
51
  getPathInAst,
46
- getUsedNamesInScopeInfo
52
+ getUsedNamesInScopeInfo,
53
+ isCommonJsConcatenationEnabled
47
54
  } = require("../util/concatenate");
48
55
  const createHash = require("../util/createHash");
49
56
  const createHooksRegistry = require("../util/createHooksRegistry");
@@ -60,53 +67,71 @@ const {
60
67
  } = require("../util/runtime");
61
68
  const { InlinedUsedName } = require("./InlineExports");
62
69
 
63
- /** @typedef {import("webpack-sources").Source} Source */
64
- /** @typedef {import("../config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
65
- /** @typedef {import("../ChunkGraph")} ChunkGraph */
66
- /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
67
- /** @typedef {import("../Compilation")} Compilation */
68
- /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
69
- /** @typedef {import("../dependencies/ModuleDependency")} ModuleDependency */
70
- /** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */
71
- /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
72
- /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
73
- /** @typedef {import("../Module").BuildCallback} BuildCallback */
74
- /** @typedef {import("../Module").BuildInfo} BuildInfo */
75
- /** @typedef {import("../Module").FileSystemDependencies} FileSystemDependencies */
76
- /** @typedef {import("../Module").BuildMeta} BuildMeta */
77
- /** @typedef {import("../Module").ExportsType} ExportsType */
78
- /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
79
- /** @typedef {import("../Module").CodeGenerationResultData} CodeGenerationResultData */
80
- /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
81
- /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
82
- /** @typedef {import("../Module").LibIdent} LibIdent */
83
- /** @typedef {import("../Module").NameForCondition} NameForCondition */
84
- /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
85
- /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
86
- /** @typedef {import("../Module").SourceTypes} SourceTypes */
87
- /** @typedef {import("../ModuleGraph")} ModuleGraph */
88
- /** @typedef {import("../NormalModule")} NormalModule */
89
- /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
90
- /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */
91
- /** @typedef {import("../RequestShortener")} RequestShortener */
92
- /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
93
- /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
94
- /** @typedef {import("../javascript/JavascriptModule").JavascriptModuleBuildInfo} JavascriptModuleBuildInfo */
95
- /** @typedef {import("../javascript/JavascriptModule").JavascriptModuleBuildMeta} JavascriptModuleBuildMeta */
96
- /** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
97
- /** @typedef {import("../javascript/JavascriptModulesPlugin").Scope} Scope */
98
- /** @typedef {import("../javascript/JavascriptModulesPlugin").Reference} Reference */
99
- /** @typedef {import("../javascript/JavascriptModulesPlugin").Variable} Variable */
100
- /** @typedef {import("../javascript/JavascriptParser").Program} Program */
101
- /** @typedef {import("../javascript/JavascriptParser").Range} Range */
102
- /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
103
- /** @typedef {import("../util/Hash")} Hash */
104
- /** @typedef {import("../util/Hash").HashFunction} HashFunction */
105
- /** @typedef {import("../util/concatenate").UsedNames} UsedNames */
106
- /** @typedef {import("../util/concatenate").UsedNamesInScopeInfo} UsedNamesInScopeInfo */
107
- /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
108
- /** @typedef {import("../util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
109
- /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
70
+ /** @import { Source } from "webpack-sources" */
71
+ /**
72
+ * @import {
73
+ * WebpackOptionsNormalizedWithDefaults as WebpackOptions
74
+ * } from "../config/defaults"
75
+ */
76
+ /** @import ChunkGraph from "../ChunkGraph" */
77
+ /** @import CodeGenerationResults from "../CodeGenerationResults" */
78
+ /** @import Compilation, { FileSystemDependencies } from "../Compilation" */
79
+ /** @import { UpdateHashContext } from "../Dependency" */
80
+ /** @import HarmonyImportDependency from "../dependencies/HarmonyImportDependency" */
81
+ /** @import DependencyTemplates from "../DependencyTemplates" */
82
+ /** @import { ExportInfo } from "../ExportsInfo" */
83
+ /**
84
+ * @import {
85
+ * BuildCallback,
86
+ * BuildInfo,
87
+ * BuildMeta,
88
+ * ExportsType,
89
+ * CodeGenerationContext,
90
+ * CodeGenerationResultData,
91
+ * CodeGenerationResult,
92
+ * LibIdentOptions,
93
+ * LibIdent,
94
+ * NameForCondition,
95
+ * ReadOnlyRuntimeRequirements,
96
+ * RuntimeRequirements,
97
+ * SourceTypes
98
+ * } from "../Module"
99
+ */
100
+ /** @import ModuleGraph from "../ModuleGraph" */
101
+ /**
102
+ * @import ModuleGraphConnection, {
103
+ * ConnectionState
104
+ * } from "../ModuleGraphConnection"
105
+ */
106
+ /** @import RequestShortener from "../RequestShortener" */
107
+ /** @import { ResolverWithOptions } from "../ResolverFactory" */
108
+ /** @import RuntimeTemplate from "../RuntimeTemplate" */
109
+ /**
110
+ * @import {
111
+ * JavascriptModuleBuildInfo,
112
+ * JavascriptModuleBuildMeta
113
+ * } from "../javascript/JavascriptModule"
114
+ */
115
+ /**
116
+ * @import {
117
+ * ChunkRenderContext,
118
+ * Scope,
119
+ * Reference,
120
+ * Variable
121
+ * } from "../javascript/JavascriptModulesPlugin"
122
+ */
123
+ /** @import { Range } from "../javascript/JavascriptParser" */
124
+ /** @import { Identifier, Program } from "estree" */
125
+ /**
126
+ * @import {
127
+ * ObjectDeserializerContext
128
+ * } from "../serialization/ObjectMiddleware"
129
+ */
130
+ /** @import Hash, { HashFunction } from "../util/Hash" */
131
+ /** @import { UsedNames, UsedNamesInScopeInfo } from "../util/concatenate" */
132
+ /** @import { InputFileSystem } from "../util/fs" */
133
+ /** @import { AssociatedObjectForCache } from "../util/identifier" */
134
+ /** @import { RuntimeSpec } from "../util/runtime" */
110
135
  /**
111
136
  * @template T
112
137
  * @typedef {import("../InitFragment")<T>} InitFragment
@@ -117,13 +142,33 @@ const { InlinedUsedName } = require("./InlineExports");
117
142
  * @typedef {import("../util/comparators").Comparator<T>} Comparator
118
143
  */
119
144
 
120
- // fix eslint-scope to support class properties correctly
121
- // cspell:word Referencer
122
- const ReferencerClass = Referencer;
123
- if (!ReferencerClass.prototype.PropertyDefinition) {
124
- ReferencerClass.prototype.PropertyDefinition =
125
- ReferencerClass.prototype.Property;
126
- }
145
+ const IDENTIFIER_SCAN_REGEXP = /[$A-Za-z_][\w$]*/g;
146
+ const IDENTIFIER_SCAN_WHITESPACE = new Set([" ", "\t", "\n", "\r"]);
147
+
148
+ /**
149
+ * Finds every identifier a generated source could resolve against the enclosing
150
+ * concatenation scope. Property names are skipped; string and comment contents
151
+ * are not, which only over-reserves.
152
+ * @param {Source} source generated source
153
+ * @returns {ReadonlySet<string>} identifier names
154
+ */
155
+ const findIdentifiers = (source) => {
156
+ const code = source.source().toString();
157
+ /** @type {Set<string>} */
158
+ const result = new Set();
159
+ IDENTIFIER_SCAN_REGEXP.lastIndex = 0;
160
+ let match = IDENTIFIER_SCAN_REGEXP.exec(code);
161
+ while (match !== null) {
162
+ let i = match.index - 1;
163
+ while (i >= 0 && IDENTIFIER_SCAN_WHITESPACE.has(code[i])) i--;
164
+ // `a.b` can't bind to the outer scope, but the `b` of `...b` can
165
+ if (!(i >= 0 && code[i] === "." && code[i - 1] !== ".")) {
166
+ result.add(match[0]);
167
+ }
168
+ match = IDENTIFIER_SCAN_REGEXP.exec(code);
169
+ }
170
+ return result;
171
+ };
127
172
 
128
173
  /** @typedef {RawBinding | SymbolBinding} Binding */
129
174
 
@@ -155,20 +200,23 @@ if (!ReferencerClass.prototype.PropertyDefinition) {
155
200
  /**
156
201
  * @typedef {object} ConcatenatedModuleInfo
157
202
  * @property {"concatenated"} type
203
+ * @property {boolean} wrapped the body renders inside the lazy CJS wrapper with real module/exports instead of being scope-hoisted into the shared scope
204
+ * @property {boolean} eager a wrapped body reached by an eager import edge, so its accessor is called at its own slot in evaluation order
158
205
  * @property {Module} module
159
206
  * @property {number} index
160
- * @property {boolean=} cjsWrapped a "weird" CommonJS module executed via the CJS wrapper runtime helper with real module/exports objects
161
207
  * @property {Program | undefined} ast
162
208
  * @property {Source | undefined} internalSource
163
209
  * @property {ReplaceSource | undefined} source
164
210
  * @property {InitFragment<ChunkRenderContext>[]=} chunkInitFragments
165
211
  * @property {ReadOnlyRuntimeRequirements | undefined} runtimeRequirements
166
212
  * @property {Scope | undefined} globalScope
213
+ * @property {Reference[] | undefined} unresolvedReferences the module's free references
167
214
  * @property {Scope | undefined} moduleScope
168
215
  * @property {Map<string, string>} internalNames
169
216
  * @property {ExportMap | undefined} exportMap
170
217
  * @property {ExportMap | undefined} rawExportMap
171
218
  * @property {string=} namespaceExportSymbol
219
+ * @property {string | undefined} namespaceFnName name of the lazy wrapper accessor function (calling it evaluates the module and returns its exports)
172
220
  * @property {string | undefined} namespaceObjectName
173
221
  * @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
174
222
  * @property {ConcatenationScope | undefined} concatenationScope
@@ -185,11 +233,14 @@ if (!ReferencerClass.prototype.PropertyDefinition) {
185
233
  /**
186
234
  * @typedef {object} ExternalModuleInfo
187
235
  * @property {"external"} type
236
+ * @property {boolean} wrapped the module's `require()` call is deferred behind an accessor instead of running at its own slot; unlike a wrapped concatenated member there is no body and no CJS wrapper, so any external may be wrapped
237
+ * @property {boolean} eager a wrapped module reached by an eager import edge, so its accessor is called at its own slot in evaluation order
188
238
  * @property {Module} module
189
239
  * @property {RuntimeSpec | boolean} runtimeCondition
190
240
  * @property {NonDeferAccess} nonDeferAccess
191
241
  * @property {number} index
192
242
  * @property {string | undefined} name module.exports / harmony namespace object
243
+ * @property {string | undefined} namespaceFnName lazy module accessor
193
244
  * @property {string | undefined} escapeNamespaceObjectName decoupled namespace object that keeps original export names when the exports are mangled
194
245
  * @property {string | undefined} deferredName deferred module.exports / harmony namespace object
195
246
  * @property {boolean} deferred the module is deferred at least once
@@ -289,11 +340,36 @@ const subtractNonDeferAccess = (a, b) => a && !b;
289
340
  /**
290
341
  * @typedef {object} ConcatenationEntry
291
342
  * @property {"concatenated" | "external"} type
343
+ * @property {boolean} wrapped evaluation is deferred behind an accessor: a "concatenated" entry renders its body inside the lazy CJS wrapper instead of being scope-hoisted, an "external" entry only defers its `require()` call
292
344
  * @property {Module} module
293
345
  * @property {RuntimeSpec | boolean} runtimeCondition
294
346
  * @property {NonDeferAccess} nonDeferAccess
295
347
  */
296
348
 
349
+ /**
350
+ * Whether a member runs inside the lazy CJS wrapper or is scope-hoisted. Only a
351
+ * NormalModule can carry a CJS body; an ESM member starts out hoisted and is
352
+ * downgraded by {@link ConcatenatedModule._createConcatenationList}.
353
+ * @param {Module} module a module taking part in the concatenation
354
+ * @returns {boolean} true, when the module renders wrapped
355
+ */
356
+ const needWrapped = (module) =>
357
+ module instanceof NormalModule &&
358
+ module.type.startsWith("javascript/") &&
359
+ module.buildMeta !== undefined &&
360
+ module.buildMeta.exportsType !== "namespace";
361
+
362
+ /**
363
+ * Whether a hoisted member can move into the lazy wrapper instead.
364
+ * @param {ConcatenationEntry} entry a member of the concatenation
365
+ * @returns {boolean} true, when it may be wrapped
366
+ */
367
+ const entryCanBeWrapped = (entry) =>
368
+ (entry.module instanceof NormalModule &&
369
+ !entry.module.type.startsWith("css/")) ||
370
+ (entry.module instanceof ExternalModule &&
371
+ entry.module.canBeWrappedInConcatenation());
372
+
297
373
  /** @typedef {Set<ConcatenatedModuleInfo>} NeededNamespaceObjects */
298
374
 
299
375
  /** @typedef {Map<Module, ModuleInfo>} ModuleToInfoMap */
@@ -319,6 +395,40 @@ const getExportsType = (moduleGraph, info, strict) => {
319
395
  return info.exportsTypeNonStrict;
320
396
  };
321
397
 
398
+ /**
399
+ * @param {ExternalModuleInfo} info module info
400
+ * @returns {string} module exports expression
401
+ */
402
+ const getExternalModuleExpr = (info) =>
403
+ info.wrapped
404
+ ? `${
405
+ /** @type {NonNullable<ExternalModuleInfo["namespaceFnName"]>} */
406
+ (info.namespaceFnName)
407
+ }()`
408
+ : /** @type {NonNullable<ExternalModuleInfo["name"]>} */ (info.name);
409
+
410
+ /**
411
+ * A wrapped module's interop object is declared as a lazy accessor, so reading
412
+ * it is a call. See `declareInterop`.
413
+ * @param {ModuleInfo} info module info
414
+ * @param {string | undefined} interopName interop variable name
415
+ * @returns {string} interop object expression
416
+ */
417
+ const getInteropExpr = (info, interopName) =>
418
+ info.wrapped ? `${interopName}()` : /** @type {string} */ (interopName);
419
+
420
+ /**
421
+ * Expression for an export that is not used. A hoisted body runs at its own
422
+ * slot, but a wrapped one only runs when its accessor is called, so dropping
423
+ * the reference would drop the module's side effects with it.
424
+ * @param {ConcatenatedModuleInfo} info module info
425
+ * @returns {string} expression evaluating to undefined
426
+ */
427
+ const getUnusedExportExpr = (info) =>
428
+ info.wrapped
429
+ ? `/* unused export */ (${info.namespaceObjectName}, undefined)`
430
+ : "/* unused export */ undefined";
431
+
322
432
  /**
323
433
  * @param {ModuleGraph} moduleGraph the module graph
324
434
  * @param {ModuleInfo} info module info
@@ -332,7 +442,8 @@ const getExportsType = (moduleGraph, info, strict) => {
332
442
  * @param {boolean} depDeferred the dependency is deferred
333
443
  * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
334
444
  * @param {boolean | undefined} asiSafe asiSafe
335
- * @param {Set<ExportInfo>=} alreadyVisited alreadyVisited
445
+ * @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
446
+ * @param {Set<InstanceType<ExportInfo>>=} alreadyVisited alreadyVisited
336
447
  * @returns {Binding} the final variable
337
448
  */
338
449
  const getFinalBinding = (
@@ -348,6 +459,7 @@ const getFinalBinding = (
348
459
  depDeferred,
349
460
  strictHarmonyModule,
350
461
  asiSafe,
462
+ moduleExportsAccess,
351
463
  alreadyVisited
352
464
  ) => {
353
465
  const exportsType = getExportsType(moduleGraph, info, strictHarmonyModule);
@@ -356,35 +468,57 @@ const getFinalBinding = (
356
468
  info.deferred &&
357
469
  !(/** @type {BuildMeta} */ (info.module.buildMeta).async);
358
470
  const deferred = depDeferred && moduleDeferred;
471
+
472
+ if (moduleExportsAccess && info.type === "concatenated") {
473
+ neededNamespaceObjects.add(info);
474
+ // ids arrive as declared names and the rendered exports object is keyed by
475
+ // used ones, so resolve here — the same way `case "external"` does below.
476
+ // Resolving in the caller instead would mangle twice.
477
+ const usedName =
478
+ exportName.length === 0
479
+ ? exportName
480
+ : moduleGraph
481
+ .getExportsInfo(info.module)
482
+ .getUsedName(exportName, runtime);
483
+ if (!usedName) {
484
+ return {
485
+ info,
486
+ rawName: getUnusedExportExpr(info),
487
+ ids: [],
488
+ exportName
489
+ };
490
+ }
491
+ return {
492
+ info,
493
+ rawName:
494
+ /** @type {NonNullable<ConcatenatedModuleInfo["namespaceObjectName"]>} */
495
+ (info.namespaceObjectName),
496
+ ids: /** @type {ExportName} */ (usedName),
497
+ exportName
498
+ };
499
+ }
500
+
359
501
  if (exportName.length === 0) {
360
502
  switch (exportsType) {
361
503
  case "default-only":
362
- // a concatenated CommonJS module has no runtime exports object;
363
- // its fake namespace is built over the generated namespace object
364
- if (info.type === "concatenated") neededNamespaceObjects.add(info);
365
504
  if (deferred) info.deferredNamespaceObjectUsed = true;
366
505
  else info.interopNamespaceObject2Used = true;
367
506
  return {
368
507
  info,
369
- rawName: /** @type {string} */ (
370
- deferred
371
- ? info.deferredNamespaceObjectName
372
- : info.interopNamespaceObject2Name
373
- ),
508
+ rawName: deferred
509
+ ? /** @type {string} */ (info.deferredNamespaceObjectName)
510
+ : getInteropExpr(info, info.interopNamespaceObject2Name),
374
511
  ids: exportName,
375
512
  exportName
376
513
  };
377
514
  case "default-with-named":
378
- if (info.type === "concatenated") neededNamespaceObjects.add(info);
379
515
  if (deferred) info.deferredNamespaceObjectUsed = true;
380
516
  else info.interopNamespaceObjectUsed = true;
381
517
  return {
382
518
  info,
383
- rawName: /** @type {string} */ (
384
- deferred
385
- ? info.deferredNamespaceObjectName
386
- : info.interopNamespaceObjectName
387
- ),
519
+ rawName: deferred
520
+ ? /** @type {string} */ (info.deferredNamespaceObjectName)
521
+ : getInteropExpr(info, info.interopNamespaceObjectName),
388
522
  ids: exportName,
389
523
  exportName
390
524
  };
@@ -475,19 +609,23 @@ const getFinalBinding = (
475
609
  if (moduleDeferred) {
476
610
  return {
477
611
  info,
478
- rawName: /** @type {string} */ (info.name),
612
+ rawName: getExternalModuleExpr(info),
479
613
  ids: exportName,
480
614
  exportName
481
615
  };
482
616
  }
483
617
  info.interopDefaultAccessUsed = true;
618
+ const accessor = getInteropExpr(
619
+ info,
620
+ info.interopDefaultAccessName
621
+ );
484
622
  const defaultExport = asCall
485
- ? `${info.interopDefaultAccessName}()`
623
+ ? `${accessor}()`
486
624
  : asiSafe
487
- ? `(${info.interopDefaultAccessName}())`
625
+ ? `(${accessor}())`
488
626
  : asiSafe === false
489
- ? `;(${info.interopDefaultAccessName}())`
490
- : `${info.interopDefaultAccessName}.a`;
627
+ ? `;(${accessor}())`
628
+ : `${accessor}.a`;
491
629
  return {
492
630
  info,
493
631
  rawName: defaultExport,
@@ -508,6 +646,7 @@ const getFinalBinding = (
508
646
  throw new Error(`Unexpected exportsType ${exportsType}`);
509
647
  }
510
648
  }
649
+
511
650
  if (exportName.length === 0) {
512
651
  switch (info.type) {
513
652
  case "concatenated":
@@ -532,9 +671,7 @@ const getFinalBinding = (
532
671
  }
533
672
  return {
534
673
  info,
535
- rawName:
536
- /** @type {NonNullable<ExternalModuleInfo["name"]>} */
537
- (info.name),
674
+ rawName: getExternalModuleExpr(info),
538
675
  ids: exportName,
539
676
  exportName
540
677
  };
@@ -663,19 +800,41 @@ const getFinalBinding = (
663
800
  /** @type {BuildMeta} */
664
801
  (info.module.buildMeta).strictHarmonyModule,
665
802
  asiSafe,
803
+ false,
666
804
  alreadyVisited
667
805
  );
668
806
  }
669
807
  // A wrapped module resolves every export through its live exports
670
808
  // alias (namespaceObjectName), same as namespaceExportSymbol modules.
671
- if (info.namespaceExportSymbol || info.cjsWrapped) {
672
- const usedName = /** @type {ExportName} */ (
673
- exportsInfo.getUsedName(exportName, runtime)
674
- );
809
+ if (info.namespaceExportSymbol || info.wrapped) {
810
+ const usedName = exportsInfo.getUsedName(exportName, runtime);
811
+ if (!usedName) {
812
+ return {
813
+ info,
814
+ rawName: "/* unused export */ undefined",
815
+ ids: exportName.slice(1),
816
+ exportName
817
+ };
818
+ }
819
+ // an inlined export never reaches the exports object, so render the
820
+ // literal instead of reading the namespace
821
+ if (usedName instanceof InlinedUsedName) {
822
+ return {
823
+ info,
824
+ // Literal only; suffix is appended once via `ids` (see directExport branch).
825
+ rawName: usedName.render(
826
+ Template.toNormalComment(
827
+ `inlined export ${propertyAccess(exportName)}`
828
+ )
829
+ ),
830
+ ids: usedName.suffix,
831
+ exportName
832
+ };
833
+ }
675
834
  return {
676
835
  info,
677
836
  rawName: /** @type {string} */ (info.namespaceObjectName),
678
- ids: usedName,
837
+ ids: /** @type {ExportName} */ (usedName),
679
838
  exportName
680
839
  };
681
840
  }
@@ -716,8 +875,7 @@ const getFinalBinding = (
716
875
  return {
717
876
  info,
718
877
  rawName:
719
- (deferred ? info.deferredName : info.name) +
720
- (deferred ? ".a" : "") +
878
+ (deferred ? `${info.deferredName}.a` : getExternalModuleExpr(info)) +
721
879
  comment,
722
880
  ids: usedName,
723
881
  exportName
@@ -740,6 +898,7 @@ const getFinalBinding = (
740
898
  * @param {boolean | undefined} callContext callContext
741
899
  * @param {boolean | undefined} strictHarmonyModule strictHarmonyModule
742
900
  * @param {boolean | undefined} asiSafe asiSafe
901
+ * @param {boolean=} moduleExportsAccess resolve to the module's own exports value with plain property access, skipping ESM interop
743
902
  * @returns {string} the final name
744
903
  */
745
904
  const getFinalName = (
@@ -755,7 +914,8 @@ const getFinalName = (
755
914
  depDeferred,
756
915
  callContext,
757
916
  strictHarmonyModule,
758
- asiSafe
917
+ asiSafe,
918
+ moduleExportsAccess
759
919
  ) => {
760
920
  const binding = getFinalBinding(
761
921
  moduleGraph,
@@ -769,7 +929,8 @@ const getFinalName = (
769
929
  asCall,
770
930
  depDeferred,
771
931
  strictHarmonyModule,
772
- asiSafe
932
+ asiSafe,
933
+ moduleExportsAccess
773
934
  );
774
935
  {
775
936
  const { ids, comment } = binding;
@@ -798,13 +959,19 @@ const getFinalName = (
798
959
  reference = `${name}${comment || ""}${propertyAccess(ids)}`;
799
960
  isPropertyAccess = ids.length > 1;
800
961
  }
801
- if (isPropertyAccess && asCall && callContext === false) {
802
- return asiSafe
803
- ? `(0,${reference})`
804
- : asiSafe === false
805
- ? `;(0,${reference})`
806
- : `/*#__PURE__*/Object(${reference})`;
962
+
963
+ if (isPropertyAccess) {
964
+ if (asCall && callContext === false) {
965
+ return asiSafe
966
+ ? `(0,${reference})`
967
+ : asiSafe === false
968
+ ? `;(0,${reference})`
969
+ : `/*#__PURE__*/Object(${reference})`;
970
+ } else if (binding.info.wrapped) {
971
+ return asiSafe === false ? `;(${reference})` : `(${reference})`;
972
+ }
807
973
  }
974
+
808
975
  return reference;
809
976
  }
810
977
  };
@@ -972,6 +1139,9 @@ class ConcatenatedModule extends Module {
972
1139
  */
973
1140
  build(options, compilation, resolver, fs, callback) {
974
1141
  const { rootModule } = this;
1142
+ const concatenateCommonJsModules = isCommonJsConcatenationEnabled(
1143
+ options.optimization.concatenateModules
1144
+ );
975
1145
  const { moduleArgument, exportsArgument } =
976
1146
  /** @type {BuildInfo} */
977
1147
  (rootModule.buildInfo);
@@ -1011,16 +1181,17 @@ class ConcatenatedModule extends Module {
1011
1181
  }
1012
1182
  }
1013
1183
 
1014
- // populate dependencies
1015
- for (const d of m.dependencies.filter(
1016
- (dep) =>
1017
- !Dependency.canConcatenate(dep) ||
1184
+ // populate dependencies — keep only deps that leave the concat set
1185
+ for (const d of m.dependencies) {
1186
+ if (
1187
+ !Dependency.canConcatenate(d, concatenateCommonJsModules) ||
1018
1188
  !this._modules.has(
1019
1189
  /** @type {Module} */
1020
- (compilation.moduleGraph.getModule(dep))
1190
+ (compilation.moduleGraph.getModule(d))
1021
1191
  )
1022
- )) {
1023
- this.dependencies.push(d);
1192
+ ) {
1193
+ this.dependencies.push(d);
1194
+ }
1024
1195
  }
1025
1196
  // populate codeGenerationDependencies — the inner modules'
1026
1197
  // templates are applied during ConcatenatedModule.codeGeneration,
@@ -1125,11 +1296,19 @@ class ConcatenatedModule extends Module {
1125
1296
  * @returns {ConcatenationEntry[]} concatenation list
1126
1297
  */
1127
1298
  _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) {
1299
+ const concatenateCommonJsModules = isCommonJsConcatenationEnabled(
1300
+ this.compilation.options.optimization.concatenateModules
1301
+ );
1128
1302
  /** @type {ConcatenationEntry[]} */
1129
1303
  const list = [];
1130
1304
  /** @type {Map<Module, { runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} */
1131
1305
  const existingEntries = new Map();
1132
1306
 
1307
+ /** @type {Map<Module, Module[]>} */
1308
+ const importConnections = new Map();
1309
+ /** @type {Set<Module>} */
1310
+ const wrappedModules = new Set();
1311
+
1133
1312
  /**
1134
1313
  * @param {Module} module a module
1135
1314
  * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} imported modules in order
@@ -1148,7 +1327,10 @@ class ConcatenatedModule extends Module {
1148
1327
  .filter((connection) => {
1149
1328
  if (
1150
1329
  !connection.dependency ||
1151
- !Dependency.canConcatenate(connection.dependency)
1330
+ !Dependency.canConcatenate(
1331
+ connection.dependency,
1332
+ concatenateCommonJsModules
1333
+ )
1152
1334
  ) {
1153
1335
  return false;
1154
1336
  }
@@ -1170,7 +1352,12 @@ class ConcatenatedModule extends Module {
1170
1352
  (connection.dependency);
1171
1353
  return {
1172
1354
  connection,
1173
- sourceOrder: /** @type {number} */ (dep.sourceOrder),
1355
+ // A require() edge carries no sourceOrder; Infinity sorts it last,
1356
+ // matching the low-priority sentinel. NaN must not be used here:
1357
+ // compareNumbers returns 0 against every number, which makes the
1358
+ // comparator non-transitive and the order depend on insertion order.
1359
+ sourceOrder:
1360
+ typeof dep.sourceOrder === "number" ? dep.sourceOrder : Infinity,
1174
1361
  rangeStart: dep.range && dep.range[0],
1175
1362
  defer: ImportPhaseUtils.isDefer(dep.phase)
1176
1363
  };
@@ -1194,6 +1381,8 @@ class ConcatenatedModule extends Module {
1194
1381
  references.sort(concatComparators(bySourceOrder, byRangeStart));
1195
1382
  /** @type {Map<Module, { connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true, nonDeferAccess: NonDeferAccess }>} */
1196
1383
  const referencesMap = new Map();
1384
+ /** @type {Module[] | undefined} */
1385
+ let targets;
1197
1386
  for (const { connection, defer } of references) {
1198
1387
  const runtimeCondition = filterRuntime(runtime, (r) =>
1199
1388
  connection.isTargetActive(r)
@@ -1201,6 +1390,17 @@ class ConcatenatedModule extends Module {
1201
1390
  if (runtimeCondition === false) continue;
1202
1391
  const nonDeferAccess = !defer;
1203
1392
  const module = connection.module;
1393
+ if (targets === undefined) targets = [module];
1394
+ else if (!targets.includes(module)) targets.push(module);
1395
+ if (
1396
+ [
1397
+ CommonJsRequireDependency,
1398
+ CommonJsFullRequireDependency,
1399
+ CommonJsExportRequireDependency
1400
+ ].some((Dep) => connection.dependency instanceof Dep)
1401
+ ) {
1402
+ wrappedModules.add(module);
1403
+ }
1204
1404
  const entry = referencesMap.get(module);
1205
1405
  if (entry === undefined) {
1206
1406
  referencesMap.set(module, {
@@ -1220,6 +1420,7 @@ class ConcatenatedModule extends Module {
1220
1420
  nonDeferAccess
1221
1421
  );
1222
1422
  }
1423
+ if (targets !== undefined) importConnections.set(module, targets);
1223
1424
  return referencesMap.values();
1224
1425
  };
1225
1426
 
@@ -1267,6 +1468,7 @@ class ConcatenatedModule extends Module {
1267
1468
  }
1268
1469
  list.push({
1269
1470
  type: "concatenated",
1471
+ wrapped: needWrapped(module),
1270
1472
  module: connection.module,
1271
1473
  runtimeCondition,
1272
1474
  nonDeferAccess
@@ -1333,6 +1535,7 @@ class ConcatenatedModule extends Module {
1333
1535
  }
1334
1536
  list.push({
1335
1537
  type: "external",
1538
+ wrapped: wrappedModules.has(connection.module),
1336
1539
  get module() {
1337
1540
  // We need to use a getter here, because the module in the dependency
1338
1541
  // could be replaced by some other process (i. e. also replaced with a
@@ -1355,11 +1558,39 @@ class ConcatenatedModule extends Module {
1355
1558
  }
1356
1559
  list.push({
1357
1560
  type: "concatenated",
1561
+ wrapped: needWrapped(rootModule),
1358
1562
  module: rootModule,
1359
1563
  runtimeCondition: true,
1360
1564
  nonDeferAccess: true
1361
1565
  });
1362
1566
 
1567
+ // A lazily evaluated member may only depend on lazily evaluated members,
1568
+ // so wrapping propagates forward from every `require()` target along all
1569
+ // import edges, ESM included.
1570
+ /** @type {Set<Module>} */
1571
+ const modules = new Set(wrappedModules);
1572
+ for (const entry of list) {
1573
+ if (entry.wrapped) modules.add(entry.module);
1574
+ }
1575
+ const queue = [...modules];
1576
+ for (let i = 0; i < queue.length; i++) {
1577
+ const targets = importConnections.get(queue[i]);
1578
+ if (targets === undefined) continue;
1579
+ for (const target of targets) {
1580
+ if (modules.has(target)) continue;
1581
+ modules.add(target);
1582
+ queue.push(target);
1583
+ }
1584
+ }
1585
+ for (const entry of list) {
1586
+ if (
1587
+ !entry.wrapped &&
1588
+ modules.has(entry.module) &&
1589
+ entryCanBeWrapped(entry)
1590
+ ) {
1591
+ entry.wrapped = true;
1592
+ }
1593
+ }
1363
1594
  return list;
1364
1595
  }
1365
1596
 
@@ -1414,6 +1645,40 @@ class ConcatenatedModule extends Module {
1414
1645
  }
1415
1646
  }
1416
1647
 
1648
+ /*
1649
+ * How the inner modules become one flat source. Stages [1]-[5] only mutate the
1650
+ * per-module info records (names, ReplaceSource patches); stages [6]-[9] append
1651
+ * to the single output ConcatSource, in exactly the order shown.
1652
+ *
1653
+ * _getModulesWithInfo() — ordered concatenation list + one info per module
1654
+ * | (concatenated [+wrapped] | external | reference)
1655
+ * v
1656
+ * [1] ANALYSE — inner codeGeneration() per module, into a ConcatenationScope
1657
+ * | plain -> ReplaceSource + ast + scope analysis
1658
+ * | wrapped -> ReplaceSource only, body kept verbatim
1659
+ * | external -> nothing yet, rendered as a require() below
1660
+ * [2] RESERVE — free globals of the analysed bodies enter allUsedNames, so
1661
+ * | renaming in [3] can't shadow them (a wrapped body is not analysed;
1662
+ * | the reserved `__webpack_` prefix protects it)
1663
+ * [3] RENAME — module-scope variables renamed inside the ReplaceSource, then
1664
+ * | the generated names allocated: wrapper accessor, namespace object,
1665
+ * | interop helpers, external import variable
1666
+ * [4] LINK — __WEBPACK_MODULE_REFERENCE__ tokens replaced by their final
1667
+ * | binding; through the ast for analysed bodies, textually for wrapped
1668
+ * [5] COLLECT EXPORTS — root exports split into used / unused / inlined
1669
+ * v
1670
+ * ---- from here on everything is appended to the result ConcatSource ----
1671
+ * |
1672
+ * [6] EMIT EXPORTS — __esModule flag + exports getters, UNUSED/INLINED lists
1673
+ * [7] BUILD NS — namespace object sources built as strings (not emitted yet)
1674
+ * [8] DEFINE — everything that must exist before any body runs: namespace
1675
+ * | objects, wrapper accessors (wrapped modules and wrapped externals),
1676
+ * | deferred external loaders
1677
+ * [9] EVALUATE — bodies in concatenation order: plain bodies inline, externals
1678
+ * | as require(); a wrapped body stays behind its accessor
1679
+ * v
1680
+ * [10] RESULT — CodeGenerationResult { sources, data, runtimeRequirements }
1681
+ */
1417
1682
  /**
1418
1683
  * Generates code and runtime requirements for this module.
1419
1684
  * @param {CodeGenerationContext} context context for code generation
@@ -1437,12 +1702,39 @@ class ConcatenatedModule extends Module {
1437
1702
  const runtime = intersectRuntime(generationRuntime, this._runtime);
1438
1703
 
1439
1704
  const requestShortener = runtimeTemplate.requestShortener;
1440
- // Meta info for each module
1705
+ // Meta info for each module, in evaluation order (repeats become references)
1441
1706
  const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo(
1442
1707
  moduleGraph,
1443
1708
  runtime
1444
1709
  );
1445
1710
 
1711
+ // This module's body is the root's body, so a wrapped root still evaluates
1712
+ // at its slot. No import edge inside the concatenation expresses that.
1713
+ const rootModuleInfo = moduleToInfoMap.get(this.rootModule);
1714
+ if (rootModuleInfo !== undefined) rootModuleInfo.eager = true;
1715
+
1716
+ // State shared by all stages below, in the order they are filled
1717
+
1718
+ // List of all used names to avoid conflicts
1719
+ const allUsedNames = new Set(RESERVED_NAMES);
1720
+
1721
+ // Updated Top level declarations are created by renaming
1722
+ /** @type {TopLevelDeclarations} */
1723
+ const topLevelDeclarations = new Set();
1724
+
1725
+ // Free names remaining in the rendered source (runtime globals are
1726
+ // tracked by runtimeRequirements instead)
1727
+ /** @type {Set<string>} */
1728
+ const freeNames = new Set();
1729
+
1730
+ // List of additional names in scope for module references
1731
+ /** @type {UsedNamesInScopeInfo} */
1732
+ const usedNamesInScopeInfo = new Map();
1733
+
1734
+ // Set of already checked scopes
1735
+ /** @type {Set<Scope>} */
1736
+ const ignoredScopes = new Set();
1737
+
1446
1738
  // Set with modules that need a generated namespace object
1447
1739
  /** @type {NeededNamespaceObjects} */
1448
1740
  const neededNamespaceObjects = new Set();
@@ -1452,11 +1744,8 @@ class ConcatenatedModule extends Module {
1452
1744
  /** @type {Set<ConcatenatedModuleInfo | ExternalModuleInfo>} */
1453
1745
  const neededEscapeNamespaceObjects = new Set();
1454
1746
 
1455
- // List of all used names to avoid conflicts
1456
- const allUsedNames = new Set(RESERVED_NAMES);
1457
-
1458
- // Generate source code and analyse scopes
1459
- // Prepare a ReplaceSource for the final source
1747
+ // #region [1] ANALYSE: run each inner module's own codeGeneration; a
1748
+ // non-wrapped body is parsed and scope-analysed so [3] can rename its locals
1460
1749
  for (const info of moduleToInfoMap.values()) {
1461
1750
  this._analyseModule(
1462
1751
  moduleToInfoMap,
@@ -1472,23 +1761,7 @@ class ConcatenatedModule extends Module {
1472
1761
  allUsedNames
1473
1762
  );
1474
1763
  }
1475
-
1476
- // Updated Top level declarations are created by renaming
1477
- /** @type {TopLevelDeclarations} */
1478
- const topLevelDeclarations = new Set();
1479
-
1480
- // Free names remaining in the rendered source (runtime globals are
1481
- // tracked by runtimeRequirements instead)
1482
- /** @type {Set<string>} */
1483
- const freeNames = new Set();
1484
-
1485
- // List of additional names in scope for module references
1486
- /** @type {UsedNamesInScopeInfo} */
1487
- const usedNamesInScopeInfo = new Map();
1488
-
1489
- // Set of already checked scopes
1490
- /** @type {Set<Scope>} */
1491
- const ignoredScopes = new Set();
1764
+ // #endregion
1492
1765
 
1493
1766
  /**
1494
1767
  * Lazily allocates a decoupled namespace object for a concatenated module
@@ -1499,12 +1772,22 @@ class ConcatenatedModule extends Module {
1499
1772
  * @returns {string | undefined} the escape namespace object name
1500
1773
  */
1501
1774
  const getEscapeNamespaceObjectName = (info) => {
1502
- if (info.type === "concatenated" && info.namespaceExportSymbol) {
1775
+ // Only a hoisted member's namespaceExportSymbol is a real variable
1776
+ // holding the original names; a wrapped one reuses the field for its
1777
+ // `X_namespaceFn()` call, which exposes the mangled keys
1778
+ if (
1779
+ info.type === "concatenated" &&
1780
+ !info.wrapped &&
1781
+ info.namespaceExportSymbol
1782
+ ) {
1503
1783
  return undefined;
1504
1784
  }
1785
+
1505
1786
  // Deferred external modules keep their special deferred namespace object
1506
1787
  // and are rendered through a different path that wouldn't emit ours.
1507
- if (info.type === "external" && info.deferred) return undefined;
1788
+ if (info.type === "external" && info.deferred) {
1789
+ return undefined;
1790
+ }
1508
1791
  // Only real ES module namespaces are decoupled; non-harmony modules use
1509
1792
  // their interop/fake namespace object as before.
1510
1793
  const buildMeta = /** @type {BuildMeta} */ (info.module.buildMeta);
@@ -1537,118 +1820,129 @@ class ConcatenatedModule extends Module {
1537
1820
  return name;
1538
1821
  };
1539
1822
 
1540
- // get all global names
1823
+ // #region [2] RESERVE: the free globals of every analysed body. Claiming
1824
+ // them up front is what lets [3] rename without shadowing any of them
1541
1825
  for (const info of modulesWithInfo) {
1542
- if (info.type === "concatenated" && !info.cjsWrapped) {
1543
- // ignore symbols from moduleScope
1544
- if (info.moduleScope) {
1545
- ignoredScopes.add(info.moduleScope);
1546
- }
1547
-
1548
- // The super class expression in class scopes behaves weird
1549
- // We get ranges of all super class expressions to make
1550
- // renaming to work correctly
1551
- /** @typedef {{ range: Range, variables: Variable[] }} ClassInfo */
1552
- /** @type {WeakMap<Scope, ClassInfo[]>} */
1553
- const superClassCache = new WeakMap();
1554
- /**
1555
- * @param {Scope} scope scope
1556
- * @returns {ClassInfo[]} result
1557
- */
1558
- const getSuperClassExpressions = (scope) => {
1559
- const cacheEntry = superClassCache.get(scope);
1560
- if (cacheEntry !== undefined) return cacheEntry;
1561
- /** @type {ClassInfo[]} */
1562
- const superClassExpressions = [];
1563
- for (const childScope of scope.childScopes) {
1564
- if (childScope.type !== "class") continue;
1565
- const block = childScope.block;
1826
+ if (info.type === "concatenated") {
1827
+ if (info.wrapped) {
1828
+ // The body is emitted verbatim and never renamed, so every identifier
1829
+ // in it is claimed: its declarations must not shadow a name [3]
1830
+ // generates, and its free globals must not be captured by one.
1831
+ for (const name of findIdentifiers(
1832
+ /** @type {Source} */ (info.internalSource)
1833
+ )) {
1834
+ allUsedNames.add(name);
1835
+ }
1836
+ // A wrapped body has no scope analysis, so its references are found
1837
+ // textually. They still have to be resolved here: binding one is what
1838
+ // flags the interop objects it needs, and [3] allocates their names.
1839
+ /** @type {Set<string>} */
1840
+ const visitedReferences = new Set();
1841
+ for (const reference of ConcatenationScope.findModuleReferences(
1842
+ /** @type {Source} */ (info.internalSource)
1843
+ )) {
1844
+ if (visitedReferences.has(reference.name)) continue;
1845
+ visitedReferences.add(reference.name);
1846
+ const match = ConcatenationScope.matchModuleReference(
1847
+ reference.name
1848
+ );
1849
+ if (!match) continue;
1850
+ const referencedInfo = modulesWithInfo[match.index];
1851
+ if (referencedInfo.type === "reference") {
1852
+ throw new Error("Module reference can't point to a reference");
1853
+ }
1566
1854
  if (
1567
- (block.type === "ClassDeclaration" ||
1568
- block.type === "ClassExpression") &&
1569
- block.superClass
1855
+ match.mangleableNamespace &&
1856
+ match.ids.length === 0 &&
1857
+ getEscapeNamespaceObjectName(referencedInfo) !== undefined
1570
1858
  ) {
1571
- superClassExpressions.push({
1572
- range: /** @type {Range} */ (block.superClass.range),
1573
- variables: childScope.variables
1574
- });
1859
+ continue;
1575
1860
  }
1861
+ getFinalBinding(
1862
+ moduleGraph,
1863
+ referencedInfo,
1864
+ match.ids,
1865
+ moduleToInfoMap,
1866
+ runtime,
1867
+ requestShortener,
1868
+ runtimeTemplate,
1869
+ neededNamespaceObjects,
1870
+ match.call,
1871
+ match.deferredImport,
1872
+ /** @type {BuildMeta} */
1873
+ (info.module.buildMeta).strictHarmonyModule,
1874
+ match.asiSafe,
1875
+ match.moduleExportsAccess
1876
+ );
1877
+ }
1878
+ } else {
1879
+ // ignore symbols from moduleScope
1880
+ if (info.moduleScope) {
1881
+ ignoredScopes.add(info.moduleScope);
1576
1882
  }
1577
- superClassCache.set(scope, superClassExpressions);
1578
- return superClassExpressions;
1579
- };
1580
1883
 
1581
- // add global symbols
1582
- if (info.globalScope) {
1583
- for (const reference of info.globalScope.through) {
1584
- const name = reference.identifier.name;
1585
- if (ConcatenationScope.isModuleReference(name)) {
1586
- const match = ConcatenationScope.matchModuleReference(name);
1587
- if (!match) continue;
1588
- const referencedInfo = modulesWithInfo[match.index];
1589
- if (referencedInfo.type === "reference") {
1590
- throw new Error("Module reference can't point to a reference");
1591
- }
1592
- // An escaping mangled namespace resolves to its own decoupled
1593
- // namespace object (a unique top-level name), so it neither needs
1594
- // the regular namespace object nor super-class scope handling.
1595
- if (
1596
- match.mangleableNamespace &&
1597
- match.ids.length === 0 &&
1598
- (referencedInfo.type === "concatenated" ||
1599
- referencedInfo.type === "external") &&
1600
- getEscapeNamespaceObjectName(referencedInfo) !== undefined
1601
- ) {
1602
- continue;
1603
- }
1604
- const binding = getFinalBinding(
1605
- moduleGraph,
1606
- referencedInfo,
1607
- match.ids,
1608
- moduleToInfoMap,
1609
- runtime,
1610
- requestShortener,
1611
- runtimeTemplate,
1612
- neededNamespaceObjects,
1613
- false,
1614
- match.deferredImport,
1615
- /** @type {BuildMeta} */
1616
- (info.module.buildMeta).strictHarmonyModule,
1617
- true
1618
- );
1619
- if (!binding.ids) continue;
1620
- const { usedNames, alreadyCheckedScopes } =
1621
- getUsedNamesInScopeInfo(
1622
- usedNamesInScopeInfo,
1623
- binding.info.module.identifier(),
1624
- "name" in binding ? binding.name : ""
1625
- );
1626
- for (const expr of getSuperClassExpressions(reference.from)) {
1884
+ // add global symbols
1885
+ if (info.unresolvedReferences) {
1886
+ for (const reference of info.unresolvedReferences) {
1887
+ const name = reference.identifier.name;
1888
+ if (ConcatenationScope.isModuleReference(name)) {
1889
+ const match = ConcatenationScope.matchModuleReference(name);
1890
+ if (!match) continue;
1891
+ const referencedInfo = modulesWithInfo[match.index];
1892
+ if (referencedInfo.type === "reference") {
1893
+ throw new Error(
1894
+ "Module reference can't point to a reference"
1895
+ );
1896
+ }
1897
+ // An escaping mangled namespace resolves to its own decoupled
1898
+ // namespace object (a unique top-level name), so it neither needs
1899
+ // the regular namespace object nor super-class scope handling.
1627
1900
  if (
1628
- expr.range[0] <=
1629
- /** @type {Range} */ (reference.identifier.range)[0] &&
1630
- expr.range[1] >=
1631
- /** @type {Range} */ (reference.identifier.range)[1]
1901
+ match.mangleableNamespace &&
1902
+ match.ids.length === 0 &&
1903
+ getEscapeNamespaceObjectName(referencedInfo) !== undefined
1632
1904
  ) {
1633
- for (const variable of expr.variables) {
1634
- usedNames.add(variable.name);
1635
- }
1905
+ continue;
1636
1906
  }
1907
+ const binding = getFinalBinding(
1908
+ moduleGraph,
1909
+ referencedInfo,
1910
+ match.ids,
1911
+ moduleToInfoMap,
1912
+ runtime,
1913
+ requestShortener,
1914
+ runtimeTemplate,
1915
+ neededNamespaceObjects,
1916
+ false,
1917
+ match.deferredImport,
1918
+ /** @type {BuildMeta} */
1919
+ (info.module.buildMeta).strictHarmonyModule,
1920
+ true,
1921
+ match.moduleExportsAccess
1922
+ );
1923
+ if (!binding.ids) continue;
1924
+ const { usedNames, alreadyCheckedScopes } =
1925
+ getUsedNamesInScopeInfo(
1926
+ usedNamesInScopeInfo,
1927
+ binding.info.module.identifier(),
1928
+ "name" in binding ? binding.name : ""
1929
+ );
1930
+ addScopeSymbols(
1931
+ reference.from,
1932
+ usedNames,
1933
+ alreadyCheckedScopes,
1934
+ ignoredScopes
1935
+ );
1936
+ } else {
1937
+ allUsedNames.add(name);
1938
+ freeNames.add(name);
1637
1939
  }
1638
- addScopeSymbols(
1639
- reference.from,
1640
- usedNames,
1641
- alreadyCheckedScopes,
1642
- ignoredScopes
1643
- );
1644
- } else {
1645
- allUsedNames.add(name);
1646
- freeNames.add(name);
1647
1940
  }
1648
1941
  }
1649
1942
  }
1650
1943
  }
1651
1944
  }
1945
+ // #endregion
1652
1946
 
1653
1947
  /**
1654
1948
  * @param {string} name the name to find a new name for
@@ -1720,7 +2014,9 @@ class ConcatenatedModule extends Module {
1720
2014
  }
1721
2015
  };
1722
2016
 
1723
- // generate names for symbols
2017
+ // #region [3] RENAME: rename every module-scope variable inside its
2018
+ // ReplaceSource, then allocate the generated names (wrapper accessor,
2019
+ // namespace object, interop helpers, external import variable)
1724
2020
  for (const info of moduleToInfoMap.values()) {
1725
2021
  const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo(
1726
2022
  usedNamesInScopeInfo,
@@ -1729,80 +2025,85 @@ class ConcatenatedModule extends Module {
1729
2025
  );
1730
2026
  switch (info.type) {
1731
2027
  case "concatenated": {
1732
- if (info.cjsWrapped) {
1733
- // Wrapped modules expose one shared-scope name: the final
1734
- // exports object used as the namespace.
1735
- const namespaceObjectName = findNewName(
1736
- "namespaceObject",
2028
+ if (info.wrapped) {
2029
+ // A wrapped module declares exactly one shared-scope name: the
2030
+ // lazy wrapper accessor holding its body. [2] claimed every
2031
+ // identifier of that body, so findNewName avoids the ones that
2032
+ // would shadow the accessor from inside it.
2033
+ const namespaceFnName = findNewName(
2034
+ "namespaceFn",
1737
2035
  allUsedNames,
1738
2036
  namespaceObjectUsedNames,
1739
2037
  info.module.readableIdentifier(requestShortener)
1740
2038
  );
1741
- allUsedNames.add(namespaceObjectName);
1742
- topLevelDeclarations.add(namespaceObjectName);
1743
- info.namespaceObjectName = namespaceObjectName;
1744
- // Route every binding to the live exports alias and skip the
1745
- // materialized namespace object generated for other modules.
1746
- info.namespaceExportSymbol = namespaceObjectName;
1747
- break;
1748
- }
1749
- const variables = /** @type {Scope} */ (info.moduleScope).variables;
1750
- for (const variable of variables) {
1751
- const name = variable.name;
1752
- const references = getAllReferences(variable);
1753
- const newName = _findNewName(name, info, references);
1754
- if (newName) {
1755
- const source = /** @type {ReplaceSource} */ (info.source);
1756
- const allIdentifiers = new Set([
1757
- ...references.map((r) => r.identifier),
1758
- ...variable.identifiers
1759
- ]);
1760
- for (const identifier of allIdentifiers) {
1761
- const r = /** @type {Range} */ (identifier.range);
1762
- const path = getPathInAst(
1763
- /** @type {NonNullable<ConcatenatedModuleInfo["ast"]>} */
1764
- (info.ast),
1765
- identifier
1766
- );
1767
- if (path && path.length > 1) {
1768
- const maybeProperty =
1769
- path[1].type === "AssignmentPattern" &&
1770
- path[1].left === path[0]
1771
- ? path[2]
1772
- : path[1];
1773
- if (
1774
- maybeProperty.type === "Property" &&
1775
- maybeProperty.shorthand
1776
- ) {
1777
- source.insert(r[1], `: ${newName}`);
1778
- continue;
2039
+ allUsedNames.add(namespaceFnName);
2040
+ topLevelDeclarations.add(namespaceFnName);
2041
+ info.namespaceFnName = namespaceFnName;
2042
+ // Every reference — `require()` and ESM import alike — reads the
2043
+ // live exports object through the accessor, so the namespace is
2044
+ // the call itself, not a variable. Not a declared name.
2045
+ info.namespaceObjectName = `${namespaceFnName}()`;
2046
+ } else {
2047
+ const variables = /** @type {Scope} */ (info.moduleScope).variables;
2048
+ for (const variable of variables) {
2049
+ const name = variable.name;
2050
+ const references = getAllReferences(variable);
2051
+ const newName = _findNewName(name, info, references);
2052
+ if (newName) {
2053
+ const source = /** @type {ReplaceSource} */ (info.source);
2054
+ /** @type {Set<Identifier>} */
2055
+ const allIdentifiers = new Set();
2056
+ for (const r of references) allIdentifiers.add(r.identifier);
2057
+ for (const identifier of variable.identifiers) {
2058
+ allIdentifiers.add(identifier);
2059
+ }
2060
+ for (const identifier of allIdentifiers) {
2061
+ const r = /** @type {Range} */ (identifier.range);
2062
+ const path = getPathInAst(
2063
+ /** @type {NonNullable<ConcatenatedModuleInfo["ast"]>} */
2064
+ (info.ast),
2065
+ identifier
2066
+ );
2067
+ if (path && path.length > 1) {
2068
+ const maybeProperty =
2069
+ path[1].type === "AssignmentPattern" &&
2070
+ path[1].left === path[0]
2071
+ ? path[2]
2072
+ : path[1];
2073
+ if (
2074
+ maybeProperty.type === "Property" &&
2075
+ maybeProperty.shorthand
2076
+ ) {
2077
+ source.insert(r[1], `: ${newName}`);
2078
+ continue;
2079
+ }
1779
2080
  }
2081
+ source.replace(r[0], r[1] - 1, newName);
1780
2082
  }
1781
- source.replace(r[0], r[1] - 1, newName);
2083
+ } else {
2084
+ allUsedNames.add(name);
2085
+ info.internalNames.set(name, name);
2086
+ topLevelDeclarations.add(name);
1782
2087
  }
2088
+ }
2089
+ /** @type {string} */
2090
+ let namespaceObjectName;
2091
+ if (info.namespaceExportSymbol) {
2092
+ namespaceObjectName =
2093
+ /** @type {string} */
2094
+ (info.internalNames.get(info.namespaceExportSymbol));
1783
2095
  } else {
1784
- allUsedNames.add(name);
1785
- info.internalNames.set(name, name);
1786
- topLevelDeclarations.add(name);
2096
+ namespaceObjectName = findNewName(
2097
+ "namespaceObject",
2098
+ allUsedNames,
2099
+ namespaceObjectUsedNames,
2100
+ info.module.readableIdentifier(requestShortener)
2101
+ );
2102
+ allUsedNames.add(namespaceObjectName);
1787
2103
  }
2104
+ info.namespaceObjectName = namespaceObjectName;
2105
+ topLevelDeclarations.add(namespaceObjectName);
1788
2106
  }
1789
- /** @type {string} */
1790
- let namespaceObjectName;
1791
- if (info.namespaceExportSymbol) {
1792
- namespaceObjectName =
1793
- /** @type {string} */
1794
- (info.internalNames.get(info.namespaceExportSymbol));
1795
- } else {
1796
- namespaceObjectName = findNewName(
1797
- "namespaceObject",
1798
- allUsedNames,
1799
- namespaceObjectUsedNames,
1800
- info.module.readableIdentifier(requestShortener)
1801
- );
1802
- allUsedNames.add(namespaceObjectName);
1803
- }
1804
- info.namespaceObjectName = namespaceObjectName;
1805
- topLevelDeclarations.add(namespaceObjectName);
1806
2107
  break;
1807
2108
  }
1808
2109
  case "external": {
@@ -1816,6 +2117,18 @@ class ConcatenatedModule extends Module {
1816
2117
  info.name = externalName;
1817
2118
  topLevelDeclarations.add(externalName);
1818
2119
 
2120
+ if (info.wrapped) {
2121
+ const namespaceFnName = findNewName(
2122
+ "namespaceFn",
2123
+ allUsedNames,
2124
+ namespaceObjectUsedNames,
2125
+ info.module.readableIdentifier(requestShortener)
2126
+ );
2127
+ allUsedNames.add(namespaceFnName);
2128
+ info.namespaceFnName = namespaceFnName;
2129
+ topLevelDeclarations.add(namespaceFnName);
2130
+ }
2131
+
1819
2132
  if (info.deferred) {
1820
2133
  const externalName = findNewName(
1821
2134
  "deferred",
@@ -1879,21 +2192,26 @@ class ConcatenatedModule extends Module {
1879
2192
  topLevelDeclarations.add(externalNameInterop);
1880
2193
  }
1881
2194
  }
2195
+ // #endregion
1882
2196
 
1883
- // Find and replace references to modules
2197
+ // #region [4] LINK: resolve each cross-module reference token to the final
2198
+ // name picked in [3] and patch it in. Must run after [3] — a reference can
2199
+ // only be resolved once its target has been named
1884
2200
  for (const info of moduleToInfoMap.values()) {
1885
- if (info.type === "concatenated" && !info.cjsWrapped) {
1886
- const globalScope = /** @type {Scope} */ (info.globalScope);
2201
+ if (info.type !== "concatenated") continue;
2202
+ if (!info.wrapped) {
1887
2203
  // group references by name
1888
2204
  /** @type {Map<string, Reference[]>} */
1889
2205
  const referencesByName = new Map();
1890
- for (const reference of globalScope.through) {
2206
+ for (const reference of /** @type {Reference[]} */ (
2207
+ info.unresolvedReferences
2208
+ )) {
1891
2209
  const name = reference.identifier.name;
1892
- if (!referencesByName.has(name)) {
1893
- referencesByName.set(name, []);
2210
+ let references = referencesByName.get(name);
2211
+ if (references === undefined) {
2212
+ referencesByName.set(name, (references = []));
1894
2213
  }
1895
- /** @type {Reference[]} */
1896
- (referencesByName.get(name)).push(reference);
2214
+ references.push(reference);
1897
2215
  }
1898
2216
  for (const [name, references] of referencesByName) {
1899
2217
  const match = ConcatenationScope.matchModuleReference(name);
@@ -1932,10 +2250,7 @@ class ConcatenatedModule extends Module {
1932
2250
  // are mangled, point it at a decoupled namespace object that keeps
1933
2251
  // the original names so untracked access keeps working.
1934
2252
  const escapeName =
1935
- match.mangleableNamespace &&
1936
- match.ids.length === 0 &&
1937
- (referencedInfo.type === "concatenated" ||
1938
- referencedInfo.type === "external")
2253
+ match.mangleableNamespace && match.ids.length === 0
1939
2254
  ? getEscapeNamespaceObjectName(referencedInfo)
1940
2255
  : undefined;
1941
2256
  const finalName =
@@ -1955,7 +2270,8 @@ class ConcatenatedModule extends Module {
1955
2270
  !match.directImport,
1956
2271
  /** @type {BuildMeta} */
1957
2272
  (info.module.buildMeta).strictHarmonyModule,
1958
- match.asiSafe
2273
+ match.asiSafe,
2274
+ match.moduleExportsAccess
1959
2275
  );
1960
2276
 
1961
2277
  for (const reference of references) {
@@ -1966,9 +2282,64 @@ class ConcatenatedModule extends Module {
1966
2282
  }
1967
2283
  }
1968
2284
  }
2285
+ } else {
2286
+ // Wrapped bodies are not re-parsed: find their reference tokens
2287
+ // textually. [2] scanned the same source, so this reuses its result.
2288
+ /** @type {Map<string, string>} */
2289
+ const finalNames = new Map();
2290
+ const source = /** @type {ReplaceSource} */ (info.source);
2291
+ for (const reference of ConcatenationScope.findModuleReferences(
2292
+ /** @type {Source} */ (info.internalSource)
2293
+ )) {
2294
+ let finalName = finalNames.get(reference.name);
2295
+ if (finalName === undefined) {
2296
+ const match = ConcatenationScope.matchModuleReference(
2297
+ reference.name
2298
+ );
2299
+ if (!match) continue;
2300
+ const referencedInfo = modulesWithInfo[match.index];
2301
+ if (referencedInfo.type === "reference") {
2302
+ throw new Error("Module reference can't point to a reference");
2303
+ }
2304
+ // Same escaping whole-namespace rule as the hoisted branch above: a
2305
+ // wrapped target resolves to its `X_namespaceFn()` exports object,
2306
+ // whose keys are the mangled ones.
2307
+ const escapeName =
2308
+ match.mangleableNamespace && match.ids.length === 0
2309
+ ? getEscapeNamespaceObjectName(referencedInfo)
2310
+ : undefined;
2311
+ finalName =
2312
+ escapeName !== undefined
2313
+ ? escapeName
2314
+ : getFinalName(
2315
+ moduleGraph,
2316
+ referencedInfo,
2317
+ match.ids,
2318
+ moduleToInfoMap,
2319
+ runtime,
2320
+ requestShortener,
2321
+ runtimeTemplate,
2322
+ neededNamespaceObjects,
2323
+ match.call,
2324
+ match.deferredImport,
2325
+ !match.directImport,
2326
+ /** @type {BuildMeta} */
2327
+ (info.module.buildMeta).strictHarmonyModule,
2328
+ match.asiSafe,
2329
+ match.moduleExportsAccess
2330
+ );
2331
+ finalNames.set(reference.name, finalName);
2332
+ }
2333
+ // token end is extended by 2 chars to cover the appended "._"
2334
+ source.replace(reference.start, reference.end + 1, finalName);
2335
+ }
1969
2336
  }
1970
2337
  }
2338
+ // #endregion
1971
2339
 
2340
+ // #region [5] COLLECT EXPORTS: split the root module's exports into used /
2341
+ // unused / inlined. Used ones stay thunks — resolving one can still
2342
+ // register a namespace object, which [7] must see
1972
2343
  // Map with all root exposed used exports
1973
2344
  /** @type {Map<string, (requestShortener: RequestShortener) => string>} */
1974
2345
  const exportsMap = new Map();
@@ -2030,7 +2401,10 @@ class ConcatenatedModule extends Module {
2030
2401
  }
2031
2402
  });
2032
2403
  }
2404
+ // #endregion
2033
2405
 
2406
+ // #region [6] EMIT EXPORTS: first thing in the output — the exports getters
2407
+ // must exist before any body runs, so circular importers see them
2034
2408
  const result = new ConcatSource();
2035
2409
 
2036
2410
  // add harmony compatibility flag (must be first because of possible circular dependencies)
@@ -2059,15 +2433,14 @@ class ConcatenatedModule extends Module {
2059
2433
  runtimeRequirements.add(RuntimeGlobals.exports);
2060
2434
  runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
2061
2435
 
2062
- if (shouldAddHarmonyFlag) {
2063
- result.add("// ESM COMPAT FLAG\n");
2064
- result.add(
2065
- runtimeTemplate.defineEsModuleFlagStatement({
2436
+ // Goes with the definitions below: whoever takes those over emits both,
2437
+ // and the marker has to stay in front of them.
2438
+ const harmonyFlagSource = shouldAddHarmonyFlag
2439
+ ? `// ESM COMPAT FLAG\n${runtimeTemplate.defineEsModuleFlagStatement({
2066
2440
  exportsArgument: this.exportsArgument,
2067
2441
  runtimeRequirements
2068
- })
2069
- );
2070
- }
2442
+ })}`
2443
+ : "";
2071
2444
 
2072
2445
  const exportsSource =
2073
2446
  "\n// EXPORTS\n" +
@@ -2082,10 +2455,11 @@ class ConcatenatedModule extends Module {
2082
2455
  !onDemandExportsGeneration.call(
2083
2456
  this,
2084
2457
  runtimes,
2085
- exportsSource,
2458
+ `${harmonyFlagSource}${exportsSource}`,
2086
2459
  exportsFinalName
2087
2460
  )
2088
2461
  ) {
2462
+ result.add(harmonyFlagSource);
2089
2463
  result.add(exportsSource);
2090
2464
  }
2091
2465
  }
@@ -2103,7 +2477,12 @@ class ConcatenatedModule extends Module {
2103
2477
  `\n// INLINED EXPORTS: ${joinIterableWithComma(inlinedExports)}\n`
2104
2478
  );
2105
2479
  }
2480
+ // #endregion
2106
2481
 
2482
+ // #region [7] BUILD NS: namespace object sources are built as strings here
2483
+ // and emitted by [8]; an external's is emitted next to its import variable
2484
+ // or accessor instead, which is defined later.
2485
+ //
2107
2486
  // generate decoupled namespace objects for escaping mangled namespaces:
2108
2487
  // same getters as the regular namespace object, but keyed by the original
2109
2488
  // export names so untracked access by name keeps working. Done before the
@@ -2135,9 +2514,7 @@ class ConcatenatedModule extends Module {
2135
2514
  // import variable; concatenated ones resolve to an internal binding.
2136
2515
  const finalName =
2137
2516
  info.type === "external"
2138
- ? `${/** @type {string} */ (info.name)}${propertyAccess([
2139
- usedName
2140
- ])}`
2517
+ ? `${getExternalModuleExpr(info)}${propertyAccess([usedName])}`
2141
2518
  : getFinalName(
2142
2519
  moduleGraph,
2143
2520
  info,
@@ -2188,50 +2565,41 @@ ${defineGetters}`
2188
2565
  /** @type {Map<ConcatenatedModuleInfo, string>} */
2189
2566
  const namespaceObjectSources = new Map();
2190
2567
  for (const info of neededNamespaceObjects) {
2191
- if (info.namespaceExportSymbol) continue;
2568
+ if (
2569
+ info.namespaceExportSymbol ||
2570
+ // Skip constructing namespace object generated for wrapped module
2571
+ info.wrapped
2572
+ ) {
2573
+ continue;
2574
+ }
2192
2575
  /** @type {string[]} */
2193
2576
  const nsObj = [];
2194
2577
  const exportsInfo = moduleGraph.getExportsInfo(info.module);
2195
2578
  for (const exportInfo of exportsInfo.orderedExports) {
2196
2579
  if (exportInfo.provided === false) continue;
2197
2580
  const usedName = exportInfo.getUsedName(undefined, runtime);
2198
- if (usedName) {
2199
- // TODO: Replace with the inlined value directly at the call site
2200
- if (usedName instanceof InlinedUsedName) {
2201
- nsObj.push(
2202
- `\n ${propertyName(
2203
- exportInfo.name
2204
- )}: ${runtimeTemplate.returningFunction(
2205
- usedName.render(
2206
- Template.toNormalComment(
2207
- `inlined export ${propertyAccess([exportInfo.name])}`
2208
- )
2209
- )
2210
- )}`
2211
- );
2212
- } else {
2213
- const finalName = getFinalName(
2214
- moduleGraph,
2215
- info,
2216
- [exportInfo.name],
2217
- moduleToInfoMap,
2218
- runtime,
2219
- requestShortener,
2220
- runtimeTemplate,
2221
- neededNamespaceObjects,
2222
- false,
2223
- false,
2224
- undefined,
2225
- /** @type {BuildMeta} */
2226
- (info.module.buildMeta).strictHarmonyModule,
2227
- true
2228
- );
2229
- nsObj.push(
2230
- `\n ${propertyName(
2231
- usedName
2232
- )}: ${runtimeTemplate.returningFunction(finalName)}`
2233
- );
2234
- }
2581
+ if (usedName && !(usedName instanceof InlinedUsedName)) {
2582
+ const finalName = getFinalName(
2583
+ moduleGraph,
2584
+ info,
2585
+ [exportInfo.name],
2586
+ moduleToInfoMap,
2587
+ runtime,
2588
+ requestShortener,
2589
+ runtimeTemplate,
2590
+ neededNamespaceObjects,
2591
+ false,
2592
+ false,
2593
+ undefined,
2594
+ /** @type {BuildMeta} */
2595
+ (info.module.buildMeta).strictHarmonyModule,
2596
+ true
2597
+ );
2598
+ nsObj.push(
2599
+ `\n ${propertyName(
2600
+ usedName
2601
+ )}: ${runtimeTemplate.returningFunction(finalName)}`
2602
+ );
2235
2603
  }
2236
2604
  }
2237
2605
  const name = info.namespaceObjectName;
@@ -2254,20 +2622,92 @@ ${defineGetters}`
2254
2622
  );
2255
2623
  runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
2256
2624
  }
2625
+ // #endregion
2257
2626
 
2258
- // define required namespace objects (must be before evaluation modules)
2627
+ // #region [8] DEFINE: define required namespace objects and wrapper
2628
+ // (must be before evaluation modules — a cycle member calls another's
2629
+ // accessor before that module's own position in the order)
2630
+
2631
+ // wrapper accessors are only called later, so their definitions may be
2632
+ // emitted in a stable order of their own instead of concatenation order
2633
+ /** @type {(ConcatenatedModuleInfo | ExternalModuleInfo)[]} */
2634
+ const wrappedInfos = [];
2259
2635
  for (const info of modulesWithInfo) {
2636
+ if (
2637
+ (info.type === "concatenated" || info.type === "external") &&
2638
+ info.wrapped
2639
+ ) {
2640
+ wrappedInfos.push(info);
2641
+ }
2642
+ }
2643
+ const compareWrappedModules = compareModulesByFullName(
2644
+ runtimeTemplate.compilation.compiler
2645
+ );
2646
+ wrappedInfos.sort((a, b) => compareWrappedModules(a.module, b.module));
2647
+
2648
+ for (const info of wrappedInfos) {
2260
2649
  if (info.type === "concatenated") {
2261
- const source = namespaceObjectSources.get(info);
2262
- if (source) result.add(source);
2263
- const escapeSource = escapeNamespaceObjectSources.get(
2264
- /** @type {ConcatenatedModuleInfo} */ (info)
2650
+ runtimeRequirements.add(RuntimeGlobals.concatenationWrap);
2651
+ result.add(
2652
+ `\n// MODULE: ${info.module.readableIdentifier(
2653
+ requestShortener
2654
+ )}\nvar ${info.namespaceFnName} = /*#__PURE__*/${
2655
+ RuntimeGlobals.concatenationWrap
2656
+ }(function(${info.module.moduleArgument}, ${
2657
+ info.module.exportsArgument
2658
+ }) {\n`
2659
+ );
2660
+ result.add(/** @type {ReplaceSource} */ (info.source));
2661
+ // A generated body (json, asset, html) binds its value to a local
2662
+ // instead of writing exports; hand that local to the accessor. The
2663
+ // name is verbatim: a wrapped body is not scope-analysed, so it keeps
2664
+ // the reserved symbol the generator registered.
2665
+ result.add(
2666
+ info.namespaceExportSymbol
2667
+ ? `\n${info.module.moduleArgument}.exports = ${info.namespaceExportSymbol};\n});\n`
2668
+ : "\n});\n"
2669
+ );
2670
+ // its getters call the accessor lazily, so this may sit right after it
2671
+ const escapeSource = escapeNamespaceObjectSources.get(info);
2672
+ if (escapeSource) result.add(escapeSource);
2673
+ } else if (info.type === "external") {
2674
+ runtimeRequirements.add(RuntimeGlobals.require);
2675
+ const { runtimeCondition } = info;
2676
+ const condition = runtimeTemplate.runtimeConditionExpression({
2677
+ chunkGraph,
2678
+ runtimeCondition,
2679
+ runtime,
2680
+ runtimeRequirements
2681
+ });
2682
+ const moduleId = JSON.stringify(chunkGraph.getModuleId(info.module));
2683
+ const body =
2684
+ condition === "true"
2685
+ ? `return ${RuntimeGlobals.require}(${moduleId});`
2686
+ : `if (${condition}) return ${RuntimeGlobals.require}(${moduleId});`;
2687
+ result.add(
2688
+ `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
2689
+ requestShortener
2690
+ )}\nvar ${info.namespaceFnName} = ${runtimeTemplate.basicFunction(
2691
+ "",
2692
+ body
2693
+ )};\n`
2265
2694
  );
2695
+ const escapeSource = escapeNamespaceObjectSources.get(info);
2266
2696
  if (escapeSource) result.add(escapeSource);
2267
- if (!source && !escapeSource) continue;
2268
2697
  }
2698
+ }
2269
2699
 
2270
- if (info.type === "external" && info.deferred) {
2700
+ for (const info of modulesWithInfo) {
2701
+ if (info.type === "concatenated") {
2702
+ if (!info.wrapped) {
2703
+ const source = namespaceObjectSources.get(info);
2704
+ if (source) result.add(source);
2705
+ const escapeSource = escapeNamespaceObjectSources.get(
2706
+ /** @type {ConcatenatedModuleInfo} */ (info)
2707
+ );
2708
+ if (escapeSource) result.add(escapeSource);
2709
+ }
2710
+ } else if (info.type === "external" && info.deferred) {
2271
2711
  const moduleId = JSON.stringify(chunkGraph.getModuleId(info.module));
2272
2712
  const loader = getOptimizedDeferredModule(
2273
2713
  moduleId,
@@ -2312,10 +2752,13 @@ ${defineGetters}`
2312
2752
  }
2313
2753
  }
2314
2754
 
2755
+ // #endregion
2756
+
2757
+ // #region [9] EVALUATE: emit the bodies in concatenation order and collect
2758
+ // what they need — runtime requirements, chunk init fragments, interop
2315
2759
  /** @type {InitFragment<ChunkRenderContext>[]} */
2316
2760
  const chunkInitFragments = [];
2317
2761
 
2318
- // evaluate modules in order
2319
2762
  for (const rawInfo of modulesWithInfo) {
2320
2763
  /** @type {undefined | string} */
2321
2764
  let name;
@@ -2323,35 +2766,47 @@ ${defineGetters}`
2323
2766
  const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo;
2324
2767
  switch (info.type) {
2325
2768
  case "concatenated": {
2326
- result.add(
2327
- `\n;// ${info.module.readableIdentifier(requestShortener)}\n`
2328
- );
2329
- if (info.cjsWrapped) {
2330
- // Real CommonJS semantics via the runtime helper: it calls the
2331
- // body with this = exports and returns the final module.exports.
2332
- runtimeRequirements.add(RuntimeGlobals.commonJsWrap);
2769
+ name = info.namespaceObjectName;
2770
+ // wrapped bodies are emitted above, evaluated at their call sites
2771
+ if (info.wrapped && info.eager) {
2772
+ // This slot is the module's place in evaluation order; calling from
2773
+ // the importing body would run it too late.
2333
2774
  result.add(
2334
- `var ${info.namespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.commonJsWrap}(function(${info.module.moduleArgument}, ${info.module.exportsArgument}) {\n`
2775
+ `\n;// ${info.module.readableIdentifier(
2776
+ requestShortener
2777
+ )}\n${info.namespaceFnName}();\n`
2778
+ );
2779
+ } else if (!info.wrapped) {
2780
+ result.add(
2781
+ `\n;// ${info.module.readableIdentifier(requestShortener)}\n`
2335
2782
  );
2336
- result.add(/** @type {ReplaceSource} */ (info.source));
2337
- result.add("\n});\n");
2338
- } else {
2339
2783
  result.add(/** @type {ReplaceSource} */ (info.source));
2340
2784
  }
2785
+
2341
2786
  if (info.chunkInitFragments) {
2342
2787
  for (const f of info.chunkInitFragments) chunkInitFragments.push(f);
2343
2788
  }
2344
2789
  if (info.runtimeRequirements) {
2345
2790
  for (const r of info.runtimeRequirements) {
2791
+ // Wrapped module supplies module/exports/this itself
2792
+ if (
2793
+ info.wrapped &&
2794
+ (r === RuntimeGlobals.module ||
2795
+ r === RuntimeGlobals.exports ||
2796
+ r === RuntimeGlobals.thisAsExports)
2797
+ ) {
2798
+ continue;
2799
+ }
2346
2800
  runtimeRequirements.add(r);
2347
2801
  }
2348
2802
  }
2349
- name = info.namespaceObjectName;
2803
+
2350
2804
  break;
2351
2805
  }
2352
2806
  case "external": {
2353
- // deferred case is handled in the "const info of modulesWithInfo" loop above
2354
- if (!info.deferred) {
2807
+ name = getExternalModuleExpr(info);
2808
+ // deferred and wrapped cases are handled in the "const info of modulesWithInfo" loop above
2809
+ if (!info.deferred && !info.wrapped) {
2355
2810
  result.add(
2356
2811
  `\n// EXTERNAL MODULE: ${info.module.readableIdentifier(
2357
2812
  requestShortener
@@ -2378,11 +2833,17 @@ ${defineGetters}`
2378
2833
  // runtime-condition `if` blocks but referenced outside,
2379
2834
  // so they must remain function-scoped (`var`).
2380
2835
  result.add(`var ${info.name} = __webpack_require__(${moduleId});`);
2381
- name = info.name;
2836
+
2382
2837
  // Decoupled namespace object for an escaping mangled external
2383
2838
  // module must come after its import variable is defined.
2384
2839
  const escapeSource = escapeNamespaceObjectSources.get(info);
2385
2840
  if (escapeSource) result.add(escapeSource);
2841
+ } else if (info.wrapped && info.eager) {
2842
+ result.add(
2843
+ `\n;// EXTERNAL MODULE: ${info.module.readableIdentifier(
2844
+ requestShortener
2845
+ )}\n${info.namespaceFnName}();\n`
2846
+ );
2386
2847
  }
2387
2848
  // If a module is deferred in other places, but used as non-deferred here,
2388
2849
  // the module itself will be emitted as mod_deferred (in the case "external"),
@@ -2390,7 +2851,7 @@ ${defineGetters}`
2390
2851
  const { nonDeferAccess } =
2391
2852
  /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */
2392
2853
  (rawInfo);
2393
- if (info.deferred && nonDeferAccess) {
2854
+ if (info.deferred && nonDeferAccess && !info.wrapped) {
2394
2855
  result.add(
2395
2856
  `\n// non-deferred import to a deferred module (${info.module.readableIdentifier(
2396
2857
  requestShortener
@@ -2403,29 +2864,54 @@ ${defineGetters}`
2403
2864
  // @ts-expect-error never is expected here
2404
2865
  throw new Error(`Unsupported concatenation entry type ${info.type}`);
2405
2866
  }
2867
+ // Building a wrapped module's interop object here would evaluate its body
2868
+ // at the top level and break require() cycles, so defer it behind a
2869
+ // hoisted function. The memo lives on the function object: it keeps the
2870
+ // identity stable without claiming a second top-level name.
2871
+ /**
2872
+ * @param {string} interopName interop variable name
2873
+ * @param {string} expr interop object expression
2874
+ * @returns {string} the declaration
2875
+ */
2876
+ const declareInterop = (interopName, expr) =>
2877
+ info.wrapped
2878
+ ? `\nfunction ${interopName}() { return ${interopName}.c || (${interopName}.c = ${expr}); }`
2879
+ : `\nvar ${interopName} = /*#__PURE__*/${expr};`;
2406
2880
  if (info.interopNamespaceObjectUsed) {
2407
2881
  runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
2408
2882
  result.add(
2409
- `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);`
2883
+ declareInterop(
2884
+ /** @type {string} */ (info.interopNamespaceObjectName),
2885
+ `${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2)`
2886
+ )
2410
2887
  );
2411
2888
  }
2412
2889
  if (info.interopNamespaceObject2Used) {
2413
2890
  runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
2414
2891
  result.add(
2415
- `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});`
2892
+ declareInterop(
2893
+ /** @type {string} */ (info.interopNamespaceObject2Name),
2894
+ `${RuntimeGlobals.createFakeNamespaceObject}(${name})`
2895
+ )
2416
2896
  );
2417
2897
  }
2418
2898
  if (info.interopDefaultAccessUsed) {
2419
2899
  runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
2420
2900
  result.add(
2421
- `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});`
2901
+ declareInterop(
2902
+ /** @type {string} */ (info.interopDefaultAccessName),
2903
+ `${RuntimeGlobals.compatGetDefaultExport}(${name})`
2904
+ )
2422
2905
  );
2423
2906
  }
2424
2907
  if (isConditional) {
2425
2908
  result.add("\n}");
2426
2909
  }
2427
2910
  }
2911
+ // #endregion
2428
2912
 
2913
+ // #region [10] RESULT: topLevelDeclarations and freeNames let consumers
2914
+ // (mangling, an outer concatenation) reason about this source unparsed
2429
2915
  /** @type {CodeGenerationResultData} */
2430
2916
  const data = new Map();
2431
2917
  if (chunkInitFragments.length > 0) {
@@ -2440,6 +2926,7 @@ ${defineGetters}`
2440
2926
  data,
2441
2927
  runtimeRequirements
2442
2928
  };
2929
+ // #endregion
2443
2930
 
2444
2931
  return resultEntry;
2445
2932
  }
@@ -2470,43 +2957,17 @@ ${defineGetters}`
2470
2957
  ) {
2471
2958
  if (info.type === "concatenated") {
2472
2959
  const m = info.module;
2473
- try {
2474
- if (info.cjsWrapped) {
2475
- // A wrapped module renders its normal module source (real
2476
- // module/exports objects, own module ids) inside an IIFE, so it
2477
- // needs no concatenation scope, reference rewriting, or scope
2478
- // analysis — the wrapper isolates its top-level declarations.
2479
- const codeGenResult = m.codeGeneration({
2480
- dependencyTemplates,
2481
- runtimeTemplate,
2482
- moduleGraph,
2483
- chunkGraph,
2484
- runtime,
2485
- runtimes,
2486
- codeGenerationResults,
2487
- sourceTypes: JAVASCRIPT_TYPES
2488
- });
2489
- const source =
2490
- /** @type {Source} */
2491
- (codeGenResult.sources.get(JAVASCRIPT_TYPE));
2492
- const data = codeGenResult.data;
2493
- info.runtimeRequirements =
2494
- /** @type {ReadOnlyRuntimeRequirements} */
2495
- (codeGenResult.runtimeRequirements);
2496
- info.internalSource = source;
2497
- info.source = new ReplaceSource(source);
2498
- info.chunkInitFragments = data && data.get("chunkInitFragments");
2499
- return;
2500
- }
2501
- // Create a concatenation scope to track and capture information
2960
+ if (info.wrapped) {
2961
+ // the wrapper isolates the body's top-level declarations, so no
2962
+ // renaming is needed -- only a concatenation scope, to rewrite in-scope
2963
+ // `require()` targets to accessor references. [2] claims its identifiers
2964
+ // textually in place of the scope analysis skipped here.
2502
2965
  const concatenationScope = new ConcatenationScope(
2503
2966
  modulesMap,
2504
2967
  info,
2505
2968
  usedNames
2506
2969
  );
2507
-
2508
- // Not cached: Compilation memoizes the outer codeGeneration per
2509
- // (module, runtime), so inner generation never recomputes usefully.
2970
+ info.concatenationScope = concatenationScope;
2510
2971
  const codeGenResult = m.codeGeneration({
2511
2972
  dependencyTemplates,
2512
2973
  runtimeTemplate,
@@ -2522,69 +2983,95 @@ ${defineGetters}`
2522
2983
  /** @type {Source} */
2523
2984
  (codeGenResult.sources.get(JAVASCRIPT_TYPE));
2524
2985
  const data = codeGenResult.data;
2525
- const chunkInitFragments = data && data.get("chunkInitFragments");
2526
- const code = source.source().toString();
2527
-
2528
- /** @type {Program} */
2529
- let ast;
2530
-
2531
- try {
2532
- const { experiments } = this.compilation.options;
2533
-
2534
- ({ ast } = JavascriptParser._parse(
2535
- code,
2536
- {
2537
- sourceType: "module",
2538
- ranges: true,
2539
- // generated code contains phase imports when the experiments are on
2540
- importPhases: Boolean(
2541
- experiments.deferImport || experiments.sourceImport
2542
- )
2543
- },
2544
- JavascriptParser._getModuleParseFunction(this.compilation, m)
2545
- ));
2546
- } catch (_err) {
2547
- const err =
2548
- /** @type {Error & { loc?: { line: number, column: number } }} */
2549
- (_err);
2550
- if (
2551
- err.loc &&
2552
- typeof err.loc === "object" &&
2553
- typeof err.loc.line === "number"
2554
- ) {
2555
- const lineNumber = err.loc.line;
2556
- const lines = code.split("\n");
2557
- err.message += `\n| ${lines
2558
- .slice(Math.max(0, lineNumber - 3), lineNumber + 2)
2559
- .join("\n| ")}`;
2560
- }
2561
- throw err;
2562
- }
2563
- const scopeManager = eslintScope.analyze(ast, {
2564
- ecmaVersion: 6,
2565
- sourceType: "module",
2566
- optimistic: true,
2567
- ignoreEval: true,
2568
- impliedStrict: true
2569
- });
2570
- const globalScope = /** @type {Scope} */ (scopeManager.acquire(ast));
2571
- const moduleScope = globalScope.childScopes[0];
2572
- const resultSource = new ReplaceSource(source);
2573
2986
  info.runtimeRequirements =
2574
2987
  /** @type {ReadOnlyRuntimeRequirements} */
2575
2988
  (codeGenResult.runtimeRequirements);
2576
- info.ast = ast;
2577
2989
  info.internalSource = source;
2578
- info.source = resultSource;
2579
- info.chunkInitFragments = chunkInitFragments;
2580
- info.globalScope = globalScope;
2581
- info.moduleScope = moduleScope;
2582
- info.concatenationScope = concatenationScope;
2583
- } catch (err) {
2584
- /** @type {Error} */
2585
- (err).message +=
2586
- `\nwhile analyzing module ${m.identifier()} for concatenation`;
2587
- throw err;
2990
+ info.source = new ReplaceSource(source);
2991
+ info.chunkInitFragments = data && data.get("chunkInitFragments");
2992
+ } else {
2993
+ try {
2994
+ // Create a concatenation scope to track and capture information
2995
+ const concatenationScope = new ConcatenationScope(
2996
+ modulesMap,
2997
+ info,
2998
+ usedNames
2999
+ );
3000
+
3001
+ // Not cached: Compilation memoizes the outer codeGeneration per
3002
+ // (module, runtime), so inner generation never recomputes usefully.
3003
+ const codeGenResult = m.codeGeneration({
3004
+ dependencyTemplates,
3005
+ runtimeTemplate,
3006
+ moduleGraph,
3007
+ chunkGraph,
3008
+ runtime,
3009
+ runtimes,
3010
+ concatenationScope,
3011
+ codeGenerationResults,
3012
+ sourceTypes: JAVASCRIPT_TYPES
3013
+ });
3014
+ const source =
3015
+ /** @type {Source} */
3016
+ (codeGenResult.sources.get(JAVASCRIPT_TYPE));
3017
+ const data = codeGenResult.data;
3018
+ const chunkInitFragments = data && data.get("chunkInitFragments");
3019
+ const code = source.source().toString();
3020
+
3021
+ /** @type {Program} */
3022
+ let ast;
3023
+
3024
+ try {
3025
+ const { experiments } = this.compilation.options;
3026
+
3027
+ ({ ast } = JavascriptParser._parse(
3028
+ code,
3029
+ {
3030
+ sourceType: "module",
3031
+ ranges: true,
3032
+ // generated code contains phase imports when the experiments are on
3033
+ importPhases: Boolean(
3034
+ experiments.deferImport || experiments.sourceImport
3035
+ )
3036
+ },
3037
+ JavascriptParser._getModuleParseFunction(this.compilation, m)
3038
+ ));
3039
+ } catch (_err) {
3040
+ const err =
3041
+ /** @type {Error & { loc?: { line: number, column: number } }} */
3042
+ (_err);
3043
+ if (
3044
+ err.loc &&
3045
+ typeof err.loc === "object" &&
3046
+ typeof err.loc.line === "number"
3047
+ ) {
3048
+ const lineNumber = err.loc.line;
3049
+ const lines = code.split("\n");
3050
+ err.message += `\n| ${lines
3051
+ .slice(Math.max(0, lineNumber - 3), lineNumber + 2)
3052
+ .join("\n| ")}`;
3053
+ }
3054
+ throw err;
3055
+ }
3056
+ const analysis = analyzeScope(ast);
3057
+ const resultSource = new ReplaceSource(source);
3058
+ info.runtimeRequirements =
3059
+ /** @type {ReadOnlyRuntimeRequirements} */
3060
+ (codeGenResult.runtimeRequirements);
3061
+ info.ast = ast;
3062
+ info.internalSource = source;
3063
+ info.source = resultSource;
3064
+ info.chunkInitFragments = chunkInitFragments;
3065
+ info.globalScope = analysis.globalScope;
3066
+ info.moduleScope = analysis.moduleScope;
3067
+ info.unresolvedReferences = analysis.unresolvedReferences;
3068
+ info.concatenationScope = concatenationScope;
3069
+ } catch (err) {
3070
+ /** @type {Error} */
3071
+ (err).message +=
3072
+ `\nwhile analyzing module ${m.identifier()} for concatenation`;
3073
+ throw err;
3074
+ }
2588
3075
  }
2589
3076
  }
2590
3077
  }
@@ -2610,17 +3097,18 @@ ${defineGetters}`
2610
3097
  case "concatenated":
2611
3098
  item = {
2612
3099
  type: "concatenated",
3100
+ wrapped: info.wrapped,
3101
+ eager: false,
2613
3102
  module: info.module,
2614
3103
  index,
2615
- cjsWrapped: isCommonJsWrapped(
2616
- /** @type {NormalModule} */ (info.module)
2617
- ),
3104
+ namespaceFnName: undefined,
2618
3105
  ast: undefined,
2619
3106
  chunkInitFragments: undefined,
2620
3107
  internalSource: undefined,
2621
3108
  runtimeRequirements: undefined,
2622
3109
  source: undefined,
2623
3110
  globalScope: undefined,
3111
+ unresolvedReferences: undefined,
2624
3112
  moduleScope: undefined,
2625
3113
  internalNames: new Map(),
2626
3114
  exportMap: undefined,
@@ -2642,11 +3130,14 @@ ${defineGetters}`
2642
3130
  case "external":
2643
3131
  item = {
2644
3132
  type: "external",
3133
+ wrapped: info.wrapped,
3134
+ eager: false,
2645
3135
  module: info.module,
2646
3136
  runtimeCondition: info.runtimeCondition,
2647
3137
  nonDeferAccess: info.nonDeferAccess,
2648
3138
  index,
2649
3139
  name: undefined,
3140
+ namespaceFnName: undefined,
2650
3141
  escapeNamespaceObjectName: undefined,
2651
3142
  deferredName: undefined,
2652
3143
  interopNamespaceObjectUsed: false,
@@ -2757,4 +3248,32 @@ ConcatenatedModule.getCompilationHooks = createHooksRegistry(
2757
3248
 
2758
3249
  makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule");
2759
3250
 
3251
+ /** @type {WeakMap<Compilation, WeakMap<Module, ConcatenatedModule>>} */
3252
+ const absorbedBy = new WeakMap();
3253
+
3254
+ /**
3255
+ * The module the chunk graph holds for `module`: concatenation replaces every module
3256
+ * it absorbs with one `ConcatenatedModule`, so an absorbed module is itself in no
3257
+ * chunk and no runtime, and asking the chunk graph about it answers about nothing.
3258
+ * @param {Compilation} compilation the compilation
3259
+ * @param {Module} module a module, possibly absorbed by concatenation
3260
+ * @returns {Module} the module the chunk graph holds, or `module` itself
3261
+ */
3262
+ ConcatenatedModule.getChunkGraphModule = (compilation, module) => {
3263
+ let map = absorbedBy.get(compilation);
3264
+ if (map === undefined) {
3265
+ map = new WeakMap();
3266
+ for (const candidate of compilation.modules) {
3267
+ if (candidate instanceof ConcatenatedModule) {
3268
+ for (const inner of candidate._modules) {
3269
+ map.set(inner, candidate);
3270
+ }
3271
+ }
3272
+ }
3273
+ absorbedBy.set(compilation, map);
3274
+ }
3275
+ const outer = map.get(module);
3276
+ return outer === undefined ? module : outer;
3277
+ };
3278
+
2760
3279
  module.exports = ConcatenatedModule;