webpack 5.108.4 → 5.109.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/bin/webpack.js +12 -0
  2. package/lib/APIPlugin.js +48 -29
  3. package/lib/CacheFacade.js +8 -0
  4. package/lib/ChunkGraph.js +17 -15
  5. package/lib/ChunkGroup.js +1 -0
  6. package/lib/CompatibilityPlugin.js +62 -29
  7. package/lib/Compilation.js +58 -6
  8. package/lib/ConstPlugin.js +11 -11
  9. package/lib/ContextModule.js +239 -6
  10. package/lib/ContextModuleFactory.js +139 -14
  11. package/lib/DefinePlugin.js +433 -112
  12. package/lib/Entrypoint.js +1 -1
  13. package/lib/ExportsInfo.js +22 -5
  14. package/lib/ExportsInfoApiPlugin.js +2 -2
  15. package/lib/ExternalModule.js +107 -5
  16. package/lib/ExternalModuleFactoryPlugin.js +20 -1
  17. package/lib/FileSystemInfo.js +256 -100
  18. package/lib/FlagDependencyUsagePlugin.js +33 -12
  19. package/lib/HotModuleReplacementPlugin.js +18 -15
  20. package/lib/InitFragment.js +20 -32
  21. package/lib/Module.js +3 -0
  22. package/lib/ModuleFilenameHelpers.js +2 -2
  23. package/lib/ModuleTypeConstants.js +8 -1
  24. package/lib/MultiCompiler.js +13 -2
  25. package/lib/MultiWatching.js +1 -0
  26. package/lib/NodeStuffPlugin.js +51 -33
  27. package/lib/NormalModule.js +175 -401
  28. package/lib/NormalModuleFactory.js +76 -2
  29. package/lib/ProgressPlugin.js +211 -119
  30. package/lib/ProvidePlugin.js +2 -2
  31. package/lib/RuntimeGlobals.js +47 -0
  32. package/lib/RuntimePlugin.js +67 -107
  33. package/lib/RuntimeTemplate.js +304 -16
  34. package/lib/Template.js +23 -3
  35. package/lib/UseStrictPlugin.js +1 -1
  36. package/lib/WebpackIsIncludedPlugin.js +1 -1
  37. package/lib/WebpackOptionsApply.js +24 -19
  38. package/lib/asset/AssetGenerator.js +110 -28
  39. package/lib/asset/AssetModulesPlugin.js +92 -2
  40. package/lib/asset/WebManifestGenerator.js +164 -0
  41. package/lib/asset/WebManifestParser.js +130 -0
  42. package/lib/async-modules/AwaitDependenciesInitFragment.js +14 -4
  43. package/lib/async-modules/isGeneratorLowered.js +26 -0
  44. package/lib/cache/PackFileCacheStrategy.js +9 -3
  45. package/lib/config/browserslistTargetHandler.js +40 -0
  46. package/lib/config/defaults.js +219 -29
  47. package/lib/config/normalization.js +26 -0
  48. package/lib/config/target.js +9 -1
  49. package/lib/container/HoistContainerReferencesPlugin.js +47 -55
  50. package/lib/css/CssGenerator.js +40 -31
  51. package/lib/css/CssLoadingRuntimeModule.js +5 -1
  52. package/lib/css/CssModulesPlugin.js +13 -0
  53. package/lib/css/CssParser.js +729 -313
  54. package/lib/css/syntax.js +1371 -861
  55. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +6 -6
  56. package/lib/dependencies/AMDPlugin.js +2 -2
  57. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +13 -13
  58. package/lib/dependencies/CommonJsDependencyHelpers.js +39 -0
  59. package/lib/dependencies/CommonJsExportRequireDependency.js +19 -0
  60. package/lib/dependencies/CommonJsExportsDependency.js +47 -2
  61. package/lib/dependencies/CommonJsExportsParserPlugin.js +10 -10
  62. package/lib/dependencies/CommonJsImportsParserPlugin.js +18 -18
  63. package/lib/dependencies/CommonJsPlugin.js +2 -2
  64. package/lib/dependencies/CommonJsRequireDependency.js +26 -1
  65. package/lib/dependencies/CommonJsSelfReferenceDependency.js +32 -1
  66. package/lib/dependencies/ContextDependencyHelpers.js +3 -3
  67. package/lib/dependencies/CreateRequireParserPlugin.js +6 -6
  68. package/lib/dependencies/CssIcssExportDependency.js +162 -71
  69. package/lib/dependencies/CssUrlDependency.js +35 -4
  70. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +2 -2
  71. package/lib/dependencies/HarmonyCompatibilityDependency.js +32 -14
  72. package/lib/dependencies/HarmonyDetectionParserPlugin.js +43 -13
  73. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +2 -1
  74. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +7 -19
  75. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +17 -9
  76. package/lib/dependencies/HarmonyImportDependency.js +13 -2
  77. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +11 -11
  78. package/lib/dependencies/HarmonyImportSpecifierDependency.js +10 -7
  79. package/lib/dependencies/HarmonyModulesPlugin.js +6 -0
  80. package/lib/dependencies/HarmonyTopLevelThisParserPlugin.js +1 -1
  81. package/lib/dependencies/HtmlEntryDependency.js +797 -172
  82. package/lib/dependencies/HtmlSourceDependency.js +26 -0
  83. package/lib/dependencies/ImportDependency.js +43 -1
  84. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +31 -18
  85. package/lib/dependencies/ImportMetaContextPlugin.js +38 -7
  86. package/lib/dependencies/ImportMetaGlobDependency.js +81 -0
  87. package/lib/dependencies/ImportMetaGlobDependencyParserPlugin.js +78 -0
  88. package/lib/dependencies/ImportMetaGlobHelpers.js +660 -0
  89. package/lib/dependencies/ImportMetaPlugin.js +532 -180
  90. package/lib/dependencies/ImportMetaResolveDependency.js +90 -0
  91. package/lib/dependencies/ImportParserPlugin.js +80 -17
  92. package/lib/dependencies/ImportPhase.js +10 -8
  93. package/lib/dependencies/LoaderPlugin.js +5 -1
  94. package/lib/dependencies/RequireContextDependencyParserPlugin.js +1 -1
  95. package/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +3 -6
  96. package/lib/dependencies/RequireIncludeDependencyParserPlugin.js +4 -11
  97. package/lib/dependencies/SystemPlugin.js +2 -4
  98. package/lib/dependencies/TopLevelAwaitDependency.js +93 -0
  99. package/lib/dependencies/URLDependency.js +141 -21
  100. package/lib/dependencies/{WorkerPlugin.js → WorkerAndWorkletPlugin.js} +324 -112
  101. package/lib/dependencies/WorkerDependency.js +86 -18
  102. package/lib/dependencies/WorkletDependency.js +278 -0
  103. package/lib/dll/DelegatedModuleFactoryPlugin.js +19 -0
  104. package/lib/errors/EnvironmentNotSupportAsyncWarning.js +1 -1
  105. package/lib/errors/LoaderLoadingError.js +20 -0
  106. package/lib/errors/ModuleParseError.js +39 -22
  107. package/lib/errors/NodeStuffInWebError.js +1 -1
  108. package/lib/esm/ModuleChunkFormatPlugin.js +47 -14
  109. package/lib/esm/ModuleChunkLoadingPlugin.js +8 -1
  110. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +29 -1
  111. package/lib/hmr/lazyCompilationBackend.js +51 -12
  112. package/lib/html/HtmlGenerator.js +907 -15
  113. package/lib/html/HtmlModule.js +2 -2
  114. package/lib/html/HtmlModulesPlugin.js +610 -166
  115. package/lib/html/HtmlParser.js +603 -247
  116. package/lib/html/favicon.svg +1 -0
  117. package/lib/html/syntax.js +3451 -2762
  118. package/lib/ids/IdHelpers.js +25 -11
  119. package/lib/index.js +6 -0
  120. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +4 -5
  121. package/lib/javascript/BasicEvaluatedExpression.js +366 -48
  122. package/lib/javascript/JavascriptGenerator.js +197 -49
  123. package/lib/javascript/JavascriptModulesPlugin.js +178 -24
  124. package/lib/javascript/JavascriptParser.js +704 -355
  125. package/lib/javascript/JavascriptParserHelpers.js +3 -6
  126. package/lib/javascript/syntax.js +5037 -0
  127. package/lib/library/ModuleLibraryPlugin.js +38 -1
  128. package/lib/loaders/LoaderRunner.js +714 -0
  129. package/lib/loaders/loadLoader.js +100 -0
  130. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +29 -2
  131. package/lib/node/ReadFileCompileWasmPlugin.js +24 -2
  132. package/lib/optimize/AggressiveMergingPlugin.js +19 -15
  133. package/lib/optimize/ConcatenatedModule.js +139 -31
  134. package/lib/optimize/FlagIncludedChunksPlugin.js +13 -3
  135. package/lib/optimize/InnerGraphPlugin.js +50 -30
  136. package/lib/optimize/ModuleConcatenationPlugin.js +139 -24
  137. package/lib/optimize/SideEffectsFlagPlugin.js +86 -43
  138. package/lib/optimize/SplitChunksPlugin.js +146 -44
  139. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +15 -0
  140. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +24 -13
  141. package/lib/prefetch/ResourceHintPlugin.js +687 -0
  142. package/lib/prefetch/ResourceHintRuntimeModule.js +149 -0
  143. package/lib/prefetch/StartupAssetHintRuntimeModule.js +210 -0
  144. package/lib/prefetch/parseResourceHintOptions.js +103 -0
  145. package/lib/rules/RuleSetCompiler.js +114 -0
  146. package/lib/runtime/AsyncModuleGeneratorRuntimeModule.js +56 -0
  147. package/lib/runtime/AsyncModuleRuntimeModule.js +24 -8
  148. package/lib/runtime/AutoPublicPathRuntimeModule.js +7 -1
  149. package/lib/runtime/CommonJsWrapRuntimeModule.js +37 -0
  150. package/lib/runtime/GetWorkletBootstrapRuntimeModule.js +59 -0
  151. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +204 -8
  152. package/lib/runtime/SetAnonymousDefaultNameRuntimeModule.js +4 -1
  153. package/lib/schemes/HttpUriPlugin.js +40 -1
  154. package/lib/schemes/VirtualUrlPlugin.js +1 -2
  155. package/lib/serialization/BinaryMiddleware.js +270 -938
  156. package/lib/serialization/FileMiddleware.js +29 -3
  157. package/lib/stats/DefaultStatsFactoryPlugin.js +229 -194
  158. package/lib/stats/DefaultStatsPresetPlugin.js +2 -0
  159. package/lib/stats/DefaultStatsPrinterPlugin.js +36 -168
  160. package/lib/stats/StatsFactory.js +46 -17
  161. package/lib/url/URLParserPlugin.js +66 -13
  162. package/lib/util/AsyncQueue.js +122 -72
  163. package/lib/util/SetHelpers.js +1 -1
  164. package/lib/util/StackedMap.js +122 -48
  165. package/lib/util/binarySearchBounds.js +2 -2
  166. package/lib/util/concatenate.js +40 -14
  167. package/lib/util/createHooksRegistry.js +13 -5
  168. package/lib/util/dataURL.js +2 -2
  169. package/lib/util/deterministicGrouping.js +7 -5
  170. package/lib/util/formatSize.js +6 -2
  171. package/lib/util/globUtils.js +710 -0
  172. package/lib/util/identifier.js +23 -6
  173. package/lib/util/implicitTypeLoaderFallback.js +62 -0
  174. package/lib/util/internalSerializables.js +88 -71
  175. package/lib/util/magicComment.js +121 -25
  176. package/lib/util/numberHash.js +2 -2
  177. package/lib/wasm-async/AsyncWasmCompileRuntimeModule.js +24 -18
  178. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +33 -22
  179. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +79 -16
  180. package/lib/web/FetchCompileAsyncWasmPlugin.js +19 -0
  181. package/lib/web/FetchCompileWasmPlugin.js +14 -0
  182. package/lib/web/JsonpChunkLoadingRuntimeModule.js +2 -0
  183. package/lib/webpack.js +65 -0
  184. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +3 -0
  185. package/module.d.ts +21 -0
  186. package/package.json +12 -11
  187. package/schemas/WebpackOptions.check.js +1 -1
  188. package/schemas/WebpackOptions.json +759 -36
  189. package/schemas/plugins/HtmlParserOptions.check.js +1 -1
  190. package/schemas/plugins/ProgressPlugin.check.js +1 -1
  191. package/schemas/plugins/ProgressPlugin.json +17 -1
  192. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  193. package/schemas/plugins/container/ContainerReferencePlugin.json +1 -0
  194. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  195. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  196. package/schemas/plugins/container/ModuleFederationPlugin.json +1 -0
  197. package/schemas/plugins/css/CssAutoOrModuleParserOptions.check.js +1 -1
  198. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  199. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  200. package/types.d.ts +1212 -99
@@ -34,6 +34,7 @@ const {
34
34
  parseResource
35
35
  } = require("./util/identifier");
36
36
  const makeSerializable = require("./util/makeSerializable");
37
+ const { propertyAccess } = require("./util/property");
37
38
 
38
39
  /** @typedef {import("webpack-sources").Source} Source */
39
40
  /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
@@ -90,6 +91,11 @@ const makeSerializable = require("./util/makeSerializable");
90
91
  * @property {string | null=} layer
91
92
  * @property {ImportAttributes=} attributes
92
93
  * @property {ImportPhaseType=} phase
94
+ * @property {string[]=} patterns glob patterns for import.meta.glob
95
+ * @property {string=} requestContext importer context for import.meta.glob
96
+ * @property {string=} importName import selection for import.meta.glob
97
+ * @property {boolean=} exhaustive exhaustive mode for import.meta.glob
98
+ * @property {boolean=} caseSensitive case-sensitive matching for import.meta.glob
93
99
  */
94
100
 
95
101
  /**
@@ -226,7 +232,14 @@ class ContextModule extends Module {
226
232
  const str = stripSlash
227
233
  ? regexString.source + regexString.flags
228
234
  : `${regexString}`;
229
- return str.replace(/!/g, "%21").replace(/\|/g, "%7C");
235
+ // Escape chars that are structural in the identifier/source-name URL
236
+ // (`!`/`|` separators, `?` query, `#` fragment) so a regex like
237
+ // `(?:a|b)` isn't misread and truncated when it becomes a source name.
238
+ return str
239
+ .replace(/!/g, "%21")
240
+ .replace(/\|/g, "%7C")
241
+ .replace(/\?/g, "%3F")
242
+ .replace(/#/g, "%23");
230
243
  }
231
244
 
232
245
  _createIdentifier() {
@@ -253,6 +266,11 @@ class ContextModule extends Module {
253
266
  }
254
267
  if (this.options.regExp) {
255
268
  identifier += `|${this._prettyRegExp(this.options.regExp, false)}`;
269
+ } else if (this.options.patterns) {
270
+ identifier += `|patterns: ${this.options.patterns.join(", ")}`;
271
+ }
272
+ if (this.options.requestContext) {
273
+ identifier += `|requestContext: ${this.options.requestContext}`;
256
274
  }
257
275
  if (this.options.include) {
258
276
  identifier += `|include: ${this._prettyRegExp(
@@ -271,6 +289,15 @@ class ContextModule extends Module {
271
289
  this.options.referencedExports
272
290
  )}`;
273
291
  }
292
+ if (this.options.importName) {
293
+ identifier += `|import: ${this.options.importName}`;
294
+ }
295
+ if (this.options.exhaustive) {
296
+ identifier += "|exhaustive";
297
+ }
298
+ if (this.options.caseSensitive === false) {
299
+ identifier += "|case-insensitive";
300
+ }
274
301
  if (this.options.chunkName) {
275
302
  identifier += `|chunkName: ${this.options.chunkName}`;
276
303
  }
@@ -339,6 +366,17 @@ class ContextModule extends Module {
339
366
  }
340
367
  if (this.options.regExp) {
341
368
  identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
369
+ } else if (this.options.patterns) {
370
+ identifier += ` patterns: ${this.options.patterns.join(", ")}`;
371
+ }
372
+ if (this.options.requestContext) {
373
+ identifier += ` requestContext: ${this.options.requestContext}`;
374
+ }
375
+ if (this.options.exhaustive) {
376
+ identifier += " exhaustive";
377
+ }
378
+ if (this.options.caseSensitive === false) {
379
+ identifier += " case-insensitive";
342
380
  }
343
381
  if (this.options.include) {
344
382
  identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
@@ -418,6 +456,17 @@ class ContextModule extends Module {
418
456
  }
419
457
  if (this.options.regExp) {
420
458
  identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
459
+ } else if (this.options.patterns) {
460
+ identifier += ` patterns: ${this.options.patterns.join(", ")}`;
461
+ }
462
+ if (this.options.requestContext) {
463
+ identifier += ` requestContext: ${this.options.requestContext}`;
464
+ }
465
+ if (this.options.exhaustive) {
466
+ identifier += " exhaustive";
467
+ }
468
+ if (this.options.caseSensitive === false) {
469
+ identifier += " case-insensitive";
421
470
  }
422
471
  if (this.options.include) {
423
472
  identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
@@ -1184,7 +1233,8 @@ module.exports = webpackAsyncContext;`;
1184
1233
  }
1185
1234
 
1186
1235
  const chunksPosition = hasFakeMap ? 2 : 1;
1187
- const asyncDepsPosition = chunksPosition + 1;
1236
+ // No chunks slot is pushed when `hasNoChunk`, so `asyncDeps` sits at `chunksPosition`.
1237
+ const asyncDepsPosition = hasNoChunk ? chunksPosition : chunksPosition + 1;
1188
1238
  const requestPrefix = hasNoChunk
1189
1239
  ? "Promise.resolve()"
1190
1240
  : hasMultipleOrNoChunks
@@ -1278,13 +1328,196 @@ webpackEmptyAsyncContext.id = ${JSON.stringify(id)};
1278
1328
  module.exports = webpackEmptyAsyncContext;`;
1279
1329
  }
1280
1330
 
1331
+ /**
1332
+ * @returns {string | undefined} import property access
1333
+ */
1334
+ getImportPropertyAccess() {
1335
+ const importName = this.options.importName;
1336
+ if (!importName || importName === "*") return;
1337
+ return propertyAccess([importName]);
1338
+ }
1339
+
1340
+ /**
1341
+ * @param {number} index index
1342
+ * @param {string} userRequest user request
1343
+ * @param {string} value value expression
1344
+ * @param {string[]} entries entries
1345
+ * @returns {void}
1346
+ */
1347
+ appendGlobMapEntry(index, userRequest, value, entries) {
1348
+ entries.push(`\n ${JSON.stringify(userRequest)}: ${value}`);
1349
+ }
1350
+
1351
+ /**
1352
+ * @param {string} entries entries
1353
+ * @returns {string} object export source
1354
+ */
1355
+ getGlobObjectExportSource(entries) {
1356
+ return `\nmodule.exports = {${entries}\n};\n`;
1357
+ }
1358
+
1359
+ /**
1360
+ * @returns {string} empty object export source
1361
+ */
1362
+ getEmptyObjectExportSource() {
1363
+ return "\nmodule.exports = {};\n";
1364
+ }
1365
+
1366
+ /**
1367
+ * @param {AsyncDependenciesBlock[]} blocks blocks
1368
+ * @param {ImportPhaseType} phase import phase
1369
+ * @param {object} context context
1370
+ * @param {RuntimeTemplate} context.runtimeTemplate runtime template
1371
+ * @param {ChunkGraph} context.chunkGraph chunk graph
1372
+ * @param {RuntimeRequirements=} context.runtimeRequirements runtime requirements
1373
+ * @returns {string} glob lazy source
1374
+ */
1375
+ getGlobLazySource(
1376
+ blocks,
1377
+ phase,
1378
+ { runtimeTemplate, chunkGraph, runtimeRequirements }
1379
+ ) {
1380
+ if (!blocks || blocks.length === 0) {
1381
+ return this.getEmptyObjectExportSource();
1382
+ }
1383
+ const moduleGraph = chunkGraph.moduleGraph;
1384
+ const globImportAccess = this.getImportPropertyAccess();
1385
+ /** @type {RuntimeRequirements} */
1386
+ const localRuntimeRequirements = runtimeRequirements || new Set();
1387
+ /** @type {{ userRequest: string, block: AsyncDependenciesBlock, dependency: ContextElementDependency }[]} */
1388
+ const blockInfo = blocks
1389
+ .map((block) => {
1390
+ const dependency =
1391
+ /** @type {ContextElementDependency} */
1392
+ (block.dependencies[0]);
1393
+ return {
1394
+ userRequest: dependency.userRequest,
1395
+ block,
1396
+ dependency
1397
+ };
1398
+ })
1399
+ .sort((a, b) =>
1400
+ a.userRequest < b.userRequest
1401
+ ? -1
1402
+ : a.userRequest > b.userRequest
1403
+ ? 1
1404
+ : 0
1405
+ );
1406
+ /** @type {string[]} */
1407
+ const entries = [];
1408
+ for (let i = 0; i < blockInfo.length; i++) {
1409
+ const info = blockInfo[i];
1410
+ let importPromise = runtimeTemplate.moduleNamespacePromise({
1411
+ chunkGraph,
1412
+ block: info.block,
1413
+ module: /** @type {Module} */ (moduleGraph.getModule(info.dependency)),
1414
+ request: info.userRequest,
1415
+ message: "import.meta.glob",
1416
+ strict: this.options.namespaceObject === "strict",
1417
+ dependency: info.dependency,
1418
+ runtimeRequirements: localRuntimeRequirements
1419
+ });
1420
+ if (globImportAccess) {
1421
+ importPromise = `${importPromise}.then(function(m) { return m${globImportAccess}; })`;
1422
+ }
1423
+ this.appendGlobMapEntry(
1424
+ i,
1425
+ info.userRequest,
1426
+ `function() { return ${importPromise}; }`,
1427
+ entries
1428
+ );
1429
+ }
1430
+ return this.getGlobObjectExportSource(entries.join(","));
1431
+ }
1432
+
1433
+ /**
1434
+ * @param {Dependency[]} dependencies dependencies
1435
+ * @param {ChunkGraph} chunkGraph chunk graph
1436
+ * @param {RuntimeTemplate} runtimeTemplate runtime template
1437
+ * @returns {string} glob sync source
1438
+ */
1439
+ getGlobSyncSource(dependencies, chunkGraph, runtimeTemplate) {
1440
+ if (!dependencies || dependencies.length === 0) {
1441
+ return this.getEmptyObjectExportSource();
1442
+ }
1443
+ const moduleGraph = chunkGraph.moduleGraph;
1444
+ const fakeMap = this.getFakeMap(dependencies, chunkGraph);
1445
+ const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
1446
+ const globImportAccess = this.getImportPropertyAccess();
1447
+ const sortedDependencies =
1448
+ /** @type {import("./dependencies/ContextElementDependency")[]} */
1449
+ (dependencies).sort((a, b) =>
1450
+ a.userRequest < b.userRequest
1451
+ ? -1
1452
+ : a.userRequest > b.userRequest
1453
+ ? 1
1454
+ : 0
1455
+ );
1456
+ /** @type {string[]} */
1457
+ const entries = [];
1458
+ let index = 0;
1459
+ for (const dep of sortedDependencies) {
1460
+ const module = moduleGraph.getModule(dep);
1461
+ let moduleExpr;
1462
+ if (module) {
1463
+ const moduleId = chunkGraph.getModuleId(module);
1464
+ moduleExpr = `(function() { var id = ${JSON.stringify(moduleId)}; return ${returnModuleObject}; })()`;
1465
+ if (globImportAccess) {
1466
+ moduleExpr += globImportAccess;
1467
+ }
1468
+ } else {
1469
+ moduleExpr = `undefined /* ${JSON.stringify(dep.userRequest)} */`;
1470
+ }
1471
+ this.appendGlobMapEntry(index++, dep.userRequest, moduleExpr, entries);
1472
+ }
1473
+ const fakeMapInit = this.getFakeMapInitStatement(fakeMap, runtimeTemplate);
1474
+ return `${fakeMapInit}\n${this.getGlobObjectExportSource(entries.join(","))}`;
1475
+ }
1476
+
1281
1477
  /**
1282
1478
  * @param {string} asyncMode module mode
1283
1479
  * @param {ImportPhaseType} phase import phase
1284
1480
  * @param {CodeGenerationContext} context context info
1285
1481
  * @returns {string} the source code
1286
1482
  */
1287
- getSourceString(asyncMode, phase, { runtimeTemplate, chunkGraph }) {
1483
+ getGlobSourceString(asyncMode, phase, context) {
1484
+ if (asyncMode === "lazy") {
1485
+ if (this.blocks && this.blocks.length > 0) {
1486
+ return this.getGlobLazySource(this.blocks, phase, context);
1487
+ }
1488
+ return this.getEmptyObjectExportSource();
1489
+ }
1490
+ if (this.dependencies && this.dependencies.length > 0) {
1491
+ return this.getGlobSyncSource(
1492
+ this.dependencies,
1493
+ context.chunkGraph,
1494
+ context.runtimeTemplate
1495
+ );
1496
+ }
1497
+ return this.getEmptyObjectExportSource();
1498
+ }
1499
+
1500
+ /**
1501
+ * @param {string} asyncMode module mode
1502
+ * @param {ImportPhaseType} phase import phase
1503
+ * @param {CodeGenerationContext & { runtimeRequirements?: RuntimeRequirements }} context context info
1504
+ * @returns {string} the source code
1505
+ */
1506
+ getSourceString(asyncMode, phase, context) {
1507
+ if (this.options.patterns) {
1508
+ return this.getGlobSourceString(asyncMode, phase, context);
1509
+ }
1510
+ return this.getContextSourceString(asyncMode, phase, context);
1511
+ }
1512
+
1513
+ /**
1514
+ * @param {string} asyncMode module mode
1515
+ * @param {ImportPhaseType} phase import phase
1516
+ * @param {CodeGenerationContext & { runtimeRequirements?: RuntimeRequirements }} context context info
1517
+ * @returns {string} the source code
1518
+ */
1519
+ getContextSourceString(asyncMode, phase, context) {
1520
+ const { runtimeTemplate, chunkGraph } = context;
1288
1521
  const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this));
1289
1522
  if (asyncMode === "lazy") {
1290
1523
  if (this.blocks && this.blocks.length > 0) {
@@ -1373,6 +1606,8 @@ module.exports = webpackEmptyAsyncContext;`;
1373
1606
  codeGeneration(context) {
1374
1607
  const { chunkGraph, compilation } = context;
1375
1608
 
1609
+ /** @type {RuntimeRequirements} */
1610
+ const set = new Set();
1376
1611
  /** @type {Sources} */
1377
1612
  const sources = new Map();
1378
1613
  sources.set(
@@ -1381,13 +1616,11 @@ module.exports = webpackEmptyAsyncContext;`;
1381
1616
  this.getSourceString(
1382
1617
  this.options.mode,
1383
1618
  this.options.phase || ImportPhase.Evaluation,
1384
- context
1619
+ { ...context, runtimeRequirements: set }
1385
1620
  ),
1386
1621
  compilation
1387
1622
  )
1388
1623
  );
1389
- /** @type {RuntimeRequirements} */
1390
- const set = new Set();
1391
1624
  const allDeps =
1392
1625
  this.dependencies.length > 0
1393
1626
  ? /** @type {ContextElementDependency[]} */ [...this.dependencies]
@@ -14,7 +14,15 @@ const LazySet = require("./util/LazySet");
14
14
  const { cachedSetProperty } = require("./util/cleverMerge");
15
15
  const { createFakeHook } = require("./util/deprecation");
16
16
  const { join } = require("./util/fs");
17
-
17
+ const {
18
+ globPatternBaseReachesDir,
19
+ globUserRequest,
20
+ isNonExhaustiveImportMetaGlobSkippedDir,
21
+ resolveContextModuleGlobPattern
22
+ } = require("./util/globUtils");
23
+
24
+ /** @typedef {import("./util/globUtils").ResolvedContextModuleGlobPattern} ResolvedContextModuleGlobPattern */
25
+ /** @typedef {(context: string, subResource: string, callback: () => void, resolvedGlobPatterns?: ResolvedContextModuleGlobPattern[]) => void} AddSubDirectoryFn */
18
26
  /** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
19
27
  /** @typedef {import("./Compilation").FileSystemDependencies} FileSystemDependencies */
20
28
  /** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */
@@ -323,6 +331,10 @@ class ContextModuleFactory extends ModuleFactory {
323
331
  resourceFragment,
324
332
  recursive,
325
333
  regExp,
334
+ patterns,
335
+ requestContext,
336
+ exhaustive,
337
+ caseSensitive,
326
338
  include,
327
339
  exclude,
328
340
  referencedExports,
@@ -330,7 +342,8 @@ class ContextModuleFactory extends ModuleFactory {
330
342
  typePrefix,
331
343
  attributes
332
344
  } = options;
333
- if (!regExp || !resource) return callback(null, []);
345
+ const isImportMetaGlob = Boolean(patterns && requestContext);
346
+ if ((!regExp && !isImportMetaGlob) || !resource) return callback(null, []);
334
347
 
335
348
  /**
336
349
  * Adds directory checked.
@@ -338,8 +351,15 @@ class ContextModuleFactory extends ModuleFactory {
338
351
  * @param {string} directory directory
339
352
  * @param {Set<string>} visited visited
340
353
  * @param {ResolveDependenciesCallback} callback callback
354
+ * @param {ResolvedContextModuleGlobPattern[] | undefined} resolvedGlobPatterns resolved glob patterns
341
355
  */
342
- const addDirectoryChecked = (ctx, directory, visited, callback) => {
356
+ const addDirectoryChecked = (
357
+ ctx,
358
+ directory,
359
+ visited,
360
+ callback,
361
+ resolvedGlobPatterns
362
+ ) => {
343
363
  /** @type {NonNullable<InputFileSystem["realpath"]>} */
344
364
  (fs.realpath)(directory, (err, _realPath) => {
345
365
  if (err) return callback(err);
@@ -355,9 +375,16 @@ class ContextModuleFactory extends ModuleFactory {
355
375
  recursionStack = new Set(visited);
356
376
  recursionStack.add(realPath);
357
377
  }
358
- addDirectoryChecked(ctx, dir, recursionStack, callback);
378
+ addDirectoryChecked(
379
+ ctx,
380
+ dir,
381
+ recursionStack,
382
+ callback,
383
+ resolvedGlobPatterns
384
+ );
359
385
  },
360
- callback
386
+ callback,
387
+ resolvedGlobPatterns
361
388
  );
362
389
  });
363
390
  };
@@ -366,11 +393,18 @@ class ContextModuleFactory extends ModuleFactory {
366
393
  * Adds the provided ctx to the context module factory.
367
394
  * @param {string} ctx context
368
395
  * @param {string} directory directory
369
- * @param {(context: string, subResource: string, callback: () => void) => void} addSubDirectory addSubDirectoryFn
396
+ * @param {AddSubDirectoryFn} addSubDirectory addSubDirectoryFn
370
397
  * @param {ResolveDependenciesCallback} callback callback
398
+ * @param {ResolvedContextModuleGlobPattern[] | undefined} resolvedGlobPatterns resolved glob patterns
371
399
  * @returns {void}
372
400
  */
373
- const addDirectory = (ctx, directory, addSubDirectory, callback) => {
401
+ const addDirectory = (
402
+ ctx,
403
+ directory,
404
+ addSubDirectory,
405
+ callback,
406
+ resolvedGlobPatterns
407
+ ) => {
374
408
  fs.readdir(directory, (err, files) => {
375
409
  if (err) return callback(err);
376
410
  const processedFiles = cmf.hooks.contextModuleFiles.call(
@@ -381,8 +415,14 @@ class ContextModuleFactory extends ModuleFactory {
381
415
  }
382
416
  /** @type {ContextAlternativeRequest[]} */
383
417
  const fileObjs = [];
418
+ /** @type {ContextElementDependency[]} */
419
+ const globDeps = [];
420
+ /** @type {Set<string>} */
421
+ const globUserRequests = new Set();
384
422
  asyncLib.map(
385
- processedFiles.filter((p) => p.indexOf(".") !== 0),
423
+ isImportMetaGlob
424
+ ? processedFiles
425
+ : processedFiles.filter((p) => p.indexOf(".") !== 0),
386
426
  (segment, callback) => {
387
427
  const subResource = join(fs, directory, segment);
388
428
 
@@ -401,11 +441,65 @@ class ContextModuleFactory extends ModuleFactory {
401
441
 
402
442
  if (stat.isDirectory()) {
403
443
  if (!recursive) return callback();
404
- addSubDirectory(ctx, subResource, callback);
444
+ if (
445
+ isImportMetaGlob &&
446
+ !exhaustive &&
447
+ isNonExhaustiveImportMetaGlobSkippedDir(segment) &&
448
+ !(
449
+ resolvedGlobPatterns &&
450
+ globPatternBaseReachesDir(
451
+ resolvedGlobPatterns,
452
+ subResource
453
+ )
454
+ )
455
+ ) {
456
+ return callback();
457
+ }
458
+ addSubDirectory(
459
+ ctx,
460
+ subResource,
461
+ callback,
462
+ resolvedGlobPatterns
463
+ );
405
464
  } else if (
406
465
  stat.isFile() &&
407
466
  (!include || include.test(subResource))
408
467
  ) {
468
+ if (
469
+ isImportMetaGlob &&
470
+ patterns &&
471
+ requestContext &&
472
+ resolvedGlobPatterns
473
+ ) {
474
+ const relativePath = `.${subResource
475
+ .slice(ctx.length)
476
+ .replace(/\\/g, "/")}`;
477
+ const exposedUserRequest = globUserRequest(
478
+ resolvedGlobPatterns,
479
+ subResource,
480
+ exhaustive === true,
481
+ caseSensitive !== false
482
+ );
483
+ if (
484
+ exposedUserRequest &&
485
+ !globUserRequests.has(exposedUserRequest)
486
+ ) {
487
+ globUserRequests.add(exposedUserRequest);
488
+ const dep = new ContextElementDependency(
489
+ `${relativePath}${resourceQuery}${resourceFragment}`,
490
+ exposedUserRequest,
491
+ typePrefix,
492
+ /** @type {string} */
493
+ (category),
494
+ referencedExports,
495
+ ctx,
496
+ attributes
497
+ );
498
+ dep.optional = true;
499
+ globDeps.push(dep);
500
+ }
501
+ return callback();
502
+ }
409
503
  // Collect for a single batched alternativeRequests call
410
504
  // per directory below. Calling the hook once per file
411
505
  // would pay per-call overhead (closure, resolverFactory
@@ -436,6 +530,19 @@ class ContextModuleFactory extends ModuleFactory {
436
530
  }
437
531
  }
438
532
 
533
+ if (isImportMetaGlob) {
534
+ /** @type {Set<string>} */
535
+ const mergedUserRequests = new Set();
536
+ /** @type {ContextElementDependency[]} */
537
+ const merged = [];
538
+ for (const dep of [...flattenedResult, ...globDeps]) {
539
+ if (mergedUserRequests.has(dep.userRequest)) continue;
540
+ mergedUserRequests.add(dep.userRequest);
541
+ merged.push(dep);
542
+ }
543
+ return callback(null, merged);
544
+ }
545
+
439
546
  if (fileObjs.length === 0) {
440
547
  return callback(null, flattenedResult);
441
548
  }
@@ -448,7 +555,10 @@ class ContextModuleFactory extends ModuleFactory {
448
555
  for (const alt of /** @type {ContextAlternativeRequest[]} */ (
449
556
  alternatives
450
557
  )) {
451
- if (!regExp.test(/** @type {string} */ (alt.request))) {
558
+ if (
559
+ !(regExp instanceof RegExp) ||
560
+ !regExp.test(/** @type {string} */ (alt.request))
561
+ ) {
452
562
  continue;
453
563
  }
454
564
  const dep = new ContextElementDependency(
@@ -477,10 +587,11 @@ class ContextModuleFactory extends ModuleFactory {
477
587
  * @param {string} ctx context
478
588
  * @param {string} dir dir
479
589
  * @param {ResolveDependenciesCallback} callback callback
590
+ * @param {ResolvedContextModuleGlobPattern[] | undefined} resolvedGlobPatterns resolved glob patterns
480
591
  * @returns {void}
481
592
  */
482
- const addSubDirectory = (ctx, dir, callback) =>
483
- addDirectory(ctx, dir, addSubDirectory, callback);
593
+ const addSubDirectory = (ctx, dir, callback, resolvedGlobPatterns) =>
594
+ addDirectory(ctx, dir, addSubDirectory, callback, resolvedGlobPatterns);
484
595
 
485
596
  /**
486
597
  * Processes the provided resource.
@@ -488,16 +599,30 @@ class ContextModuleFactory extends ModuleFactory {
488
599
  * @param {ResolveDependenciesCallback} callback callback
489
600
  */
490
601
  const visitResource = (resource, callback) => {
602
+ /** @type {ResolvedContextModuleGlobPattern[] | undefined} */
603
+ const resolvedGlobPatterns =
604
+ isImportMetaGlob && patterns && requestContext
605
+ ? patterns.map((pattern) =>
606
+ resolveContextModuleGlobPattern(pattern, requestContext, resource)
607
+ )
608
+ : undefined;
491
609
  if (typeof fs.realpath === "function") {
492
610
  addDirectoryChecked(
493
611
  resource,
494
612
  resource,
495
613
  /** @type {Set<string>} */
496
614
  new Set(),
497
- callback
615
+ callback,
616
+ resolvedGlobPatterns
498
617
  );
499
618
  } else {
500
- addDirectory(resource, resource, addSubDirectory, callback);
619
+ addDirectory(
620
+ resource,
621
+ resource,
622
+ addSubDirectory,
623
+ callback,
624
+ resolvedGlobPatterns
625
+ );
501
626
  }
502
627
  };
503
628