webpack 5.59.0 → 5.76.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.

Potentially problematic release.


This version of webpack might be problematic. Click here for more details.

Files changed (236) hide show
  1. package/README.md +22 -24
  2. package/bin/webpack.js +0 -0
  3. package/hot/dev-server.js +17 -4
  4. package/hot/lazy-compilation-node.js +3 -1
  5. package/hot/poll.js +1 -1
  6. package/hot/signal.js +1 -1
  7. package/lib/APIPlugin.js +33 -0
  8. package/lib/BannerPlugin.js +13 -5
  9. package/lib/Cache.js +1 -1
  10. package/lib/CacheFacade.js +4 -11
  11. package/lib/Chunk.js +6 -3
  12. package/lib/ChunkGraph.js +94 -8
  13. package/lib/ChunkGroup.js +1 -1
  14. package/lib/CleanPlugin.js +81 -20
  15. package/lib/Compilation.js +188 -93
  16. package/lib/Compiler.js +87 -18
  17. package/lib/ConstPlugin.js +2 -2
  18. package/lib/ContextModule.js +142 -51
  19. package/lib/ContextModuleFactory.js +65 -25
  20. package/lib/DelegatedModule.js +1 -1
  21. package/lib/DelegatedModuleFactoryPlugin.js +1 -1
  22. package/lib/Dependency.js +17 -0
  23. package/lib/DependencyTemplate.js +9 -0
  24. package/lib/DependencyTemplates.js +1 -1
  25. package/lib/DllModule.js +1 -1
  26. package/lib/DllReferencePlugin.js +1 -1
  27. package/lib/EntryOptionPlugin.js +2 -0
  28. package/lib/ErrorHelpers.js +2 -2
  29. package/lib/EvalDevToolModulePlugin.js +16 -1
  30. package/lib/EvalSourceMapDevToolPlugin.js +25 -4
  31. package/lib/ExportsInfo.js +5 -5
  32. package/lib/ExternalModule.js +94 -54
  33. package/lib/ExternalModuleFactoryPlugin.js +5 -5
  34. package/lib/FileSystemInfo.js +124 -58
  35. package/lib/Generator.js +3 -0
  36. package/lib/HookWebpackError.js +1 -1
  37. package/lib/HotModuleReplacementPlugin.js +3 -1
  38. package/lib/LoaderOptionsPlugin.js +1 -1
  39. package/lib/Module.js +28 -4
  40. package/lib/ModuleFilenameHelpers.js +8 -4
  41. package/lib/ModuleHashingError.js +29 -0
  42. package/lib/MultiCompiler.js +1 -1
  43. package/lib/MultiWatching.js +1 -1
  44. package/lib/NodeStuffPlugin.js +13 -3
  45. package/lib/NormalModule.js +51 -33
  46. package/lib/NormalModuleFactory.js +42 -37
  47. package/lib/ProgressPlugin.js +4 -5
  48. package/lib/RawModule.js +1 -1
  49. package/lib/RuntimeGlobals.js +29 -1
  50. package/lib/RuntimeModule.js +1 -1
  51. package/lib/RuntimePlugin.js +84 -1
  52. package/lib/RuntimeTemplate.js +114 -2
  53. package/lib/Template.js +3 -2
  54. package/lib/TemplatedPathPlugin.js +48 -23
  55. package/lib/WatchIgnorePlugin.js +19 -7
  56. package/lib/Watching.js +33 -19
  57. package/lib/WebpackOptionsApply.js +79 -11
  58. package/lib/asset/AssetGenerator.js +228 -71
  59. package/lib/asset/AssetModulesPlugin.js +3 -0
  60. package/lib/asset/AssetParser.js +1 -0
  61. package/lib/asset/AssetSourceGenerator.js +31 -6
  62. package/lib/asset/AssetSourceParser.js +1 -0
  63. package/lib/asset/RawDataUrlModule.js +148 -0
  64. package/lib/async-modules/AwaitDependenciesInitFragment.js +4 -4
  65. package/lib/buildChunkGraph.js +38 -7
  66. package/lib/cache/PackFileCacheStrategy.js +15 -8
  67. package/lib/cache/ResolverCachePlugin.js +90 -29
  68. package/lib/cli.js +44 -3
  69. package/lib/config/browserslistTargetHandler.js +41 -6
  70. package/lib/config/defaults.js +123 -19
  71. package/lib/config/normalization.js +10 -2
  72. package/lib/config/target.js +10 -0
  73. package/lib/container/ContainerEntryModule.js +8 -5
  74. package/lib/container/FallbackModule.js +4 -4
  75. package/lib/container/ModuleFederationPlugin.js +2 -0
  76. package/lib/container/RemoteModule.js +4 -2
  77. package/lib/container/RemoteRuntimeModule.js +8 -7
  78. package/lib/css/CssExportsGenerator.js +139 -0
  79. package/lib/css/CssGenerator.js +109 -0
  80. package/lib/css/CssLoadingRuntimeModule.js +442 -0
  81. package/lib/css/CssModulesPlugin.js +462 -0
  82. package/lib/css/CssParser.js +618 -0
  83. package/lib/css/walkCssTokens.js +659 -0
  84. package/lib/debug/ProfilingPlugin.js +24 -21
  85. package/lib/dependencies/AMDRequireDependency.js +6 -6
  86. package/lib/dependencies/CommonJsExportsParserPlugin.js +1 -2
  87. package/lib/dependencies/CommonJsFullRequireDependency.js +5 -1
  88. package/lib/dependencies/CommonJsImportsParserPlugin.js +344 -61
  89. package/lib/dependencies/CommonJsRequireContextDependency.js +6 -2
  90. package/lib/dependencies/CommonJsRequireDependency.js +2 -1
  91. package/lib/dependencies/ContextDependency.js +16 -2
  92. package/lib/dependencies/ContextDependencyHelpers.js +21 -8
  93. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +4 -1
  94. package/lib/dependencies/ContextElementDependency.js +25 -3
  95. package/lib/dependencies/CreateScriptUrlDependency.js +12 -0
  96. package/lib/dependencies/CssExportDependency.js +85 -0
  97. package/lib/dependencies/CssImportDependency.js +75 -0
  98. package/lib/dependencies/CssLocalIdentifierDependency.js +119 -0
  99. package/lib/dependencies/CssSelfLocalIdentifierDependency.js +101 -0
  100. package/lib/dependencies/CssUrlDependency.js +132 -0
  101. package/lib/dependencies/ExportsInfoDependency.js +6 -0
  102. package/lib/dependencies/HarmonyAcceptImportDependency.js +5 -3
  103. package/lib/dependencies/HarmonyCompatibilityDependency.js +5 -5
  104. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +127 -0
  105. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +12 -3
  106. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +25 -17
  107. package/lib/dependencies/HarmonyExportInitFragment.js +4 -1
  108. package/lib/dependencies/HarmonyImportDependency.js +23 -0
  109. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +142 -45
  110. package/lib/dependencies/HarmonyImportSpecifierDependency.js +46 -22
  111. package/lib/dependencies/HarmonyModulesPlugin.js +10 -0
  112. package/lib/dependencies/ImportContextDependency.js +0 -2
  113. package/lib/dependencies/ImportMetaContextDependency.js +35 -0
  114. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +252 -0
  115. package/lib/dependencies/ImportMetaContextPlugin.js +59 -0
  116. package/lib/dependencies/ImportMetaPlugin.js +22 -3
  117. package/lib/dependencies/ImportParserPlugin.js +35 -29
  118. package/lib/dependencies/JsonExportsDependency.js +17 -21
  119. package/lib/dependencies/LoaderDependency.js +13 -0
  120. package/lib/dependencies/LoaderImportDependency.js +13 -0
  121. package/lib/dependencies/LoaderPlugin.js +4 -2
  122. package/lib/dependencies/ModuleDependency.js +11 -1
  123. package/lib/dependencies/ProvidedDependency.js +31 -8
  124. package/lib/dependencies/RequireContextDependency.js +0 -16
  125. package/lib/dependencies/RequireEnsureDependency.js +2 -2
  126. package/lib/dependencies/RequireResolveContextDependency.js +2 -2
  127. package/lib/dependencies/RequireResolveDependency.js +2 -1
  128. package/lib/dependencies/URLDependency.js +3 -8
  129. package/lib/dependencies/URLPlugin.js +22 -1
  130. package/lib/dependencies/WorkerPlugin.js +2 -0
  131. package/lib/esm/ModuleChunkFormatPlugin.js +74 -49
  132. package/lib/esm/ModuleChunkLoadingPlugin.js +3 -1
  133. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +25 -9
  134. package/lib/hmr/HotModuleReplacement.runtime.js +29 -14
  135. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +4 -3
  136. package/lib/hmr/LazyCompilationPlugin.js +54 -26
  137. package/lib/hmr/lazyCompilationBackend.js +51 -12
  138. package/lib/ids/DeterministicModuleIdsPlugin.js +55 -35
  139. package/lib/ids/HashedModuleIdsPlugin.js +11 -14
  140. package/lib/ids/IdHelpers.js +26 -12
  141. package/lib/ids/NamedModuleIdsPlugin.js +6 -9
  142. package/lib/ids/NaturalModuleIdsPlugin.js +10 -13
  143. package/lib/ids/OccurrenceModuleIdsPlugin.js +13 -10
  144. package/lib/ids/SyncModuleIdsPlugin.js +140 -0
  145. package/lib/index.js +20 -0
  146. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +2 -2
  147. package/lib/javascript/BasicEvaluatedExpression.js +5 -2
  148. package/lib/javascript/ChunkHelpers.js +33 -0
  149. package/lib/javascript/JavascriptGenerator.js +1 -0
  150. package/lib/javascript/JavascriptModulesPlugin.js +27 -2
  151. package/lib/javascript/JavascriptParser.js +143 -73
  152. package/lib/javascript/StartupHelpers.js +7 -30
  153. package/lib/json/JsonData.js +8 -0
  154. package/lib/json/JsonParser.js +4 -6
  155. package/lib/library/AssignLibraryPlugin.js +39 -15
  156. package/lib/library/EnableLibraryPlugin.js +11 -0
  157. package/lib/library/UmdLibraryPlugin.js +5 -3
  158. package/lib/node/NodeTargetPlugin.js +3 -0
  159. package/lib/node/NodeWatchFileSystem.js +85 -31
  160. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +23 -8
  161. package/lib/node/RequireChunkLoadingRuntimeModule.js +24 -9
  162. package/lib/optimize/ConcatenatedModule.js +62 -26
  163. package/lib/optimize/ModuleConcatenationPlugin.js +26 -4
  164. package/lib/optimize/RealContentHashPlugin.js +45 -15
  165. package/lib/optimize/SplitChunksPlugin.js +8 -1
  166. package/lib/runtime/AsyncModuleRuntimeModule.js +50 -66
  167. package/lib/runtime/BaseUriRuntimeModule.js +31 -0
  168. package/lib/runtime/CreateScriptRuntimeModule.js +36 -0
  169. package/lib/runtime/CreateScriptUrlRuntimeModule.js +9 -34
  170. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +76 -0
  171. package/lib/runtime/LoadScriptRuntimeModule.js +11 -9
  172. package/lib/runtime/NonceRuntimeModule.js +24 -0
  173. package/lib/schemes/HttpUriPlugin.js +77 -14
  174. package/lib/serialization/FileMiddleware.js +44 -9
  175. package/lib/sharing/ConsumeSharedModule.js +8 -2
  176. package/lib/sharing/ConsumeSharedRuntimeModule.js +26 -5
  177. package/lib/sharing/ProvideSharedModule.js +4 -2
  178. package/lib/sharing/ProvideSharedPlugin.js +1 -2
  179. package/lib/sharing/ShareRuntimeModule.js +1 -1
  180. package/lib/sharing/utils.js +1 -1
  181. package/lib/stats/DefaultStatsFactoryPlugin.js +113 -68
  182. package/lib/stats/DefaultStatsPrinterPlugin.js +90 -25
  183. package/lib/util/ArrayHelpers.js +30 -0
  184. package/lib/util/AsyncQueue.js +1 -1
  185. package/lib/util/compileBooleanMatcher.js +1 -1
  186. package/lib/util/create-schema-validation.js +9 -2
  187. package/lib/util/createHash.js +12 -0
  188. package/lib/util/deprecation.js +10 -2
  189. package/lib/util/deterministicGrouping.js +1 -1
  190. package/lib/util/extractUrlAndGlobal.js +3 -0
  191. package/lib/util/fs.js +11 -0
  192. package/lib/util/hash/BatchedHash.js +7 -4
  193. package/lib/util/hash/md4.js +20 -0
  194. package/lib/util/hash/wasm-hash.js +163 -0
  195. package/lib/util/hash/xxhash64.js +5 -139
  196. package/lib/util/identifier.js +65 -44
  197. package/lib/util/internalSerializables.js +15 -0
  198. package/lib/util/nonNumericOnlyHash.js +22 -0
  199. package/lib/util/semver.js +17 -10
  200. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +9 -3
  201. package/lib/wasm-sync/WebAssemblyParser.js +1 -1
  202. package/lib/web/JsonpChunkLoadingRuntimeModule.js +31 -18
  203. package/lib/webpack.js +10 -3
  204. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +3 -11
  205. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +33 -22
  206. package/module.d.ts +215 -0
  207. package/package.json +28 -32
  208. package/schemas/WebpackOptions.check.js +1 -1
  209. package/schemas/WebpackOptions.json +321 -30
  210. package/schemas/plugins/BannerPlugin.check.js +1 -1
  211. package/schemas/plugins/BannerPlugin.json +4 -0
  212. package/schemas/plugins/DllReferencePlugin.check.js +1 -1
  213. package/schemas/plugins/HashedModuleIdsPlugin.check.js +1 -1
  214. package/schemas/plugins/ProgressPlugin.check.js +1 -1
  215. package/schemas/plugins/asset/AssetGeneratorOptions.check.js +1 -1
  216. package/schemas/plugins/asset/AssetParserOptions.check.js +1 -1
  217. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js +1 -1
  218. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  219. package/schemas/plugins/container/ContainerPlugin.json +2 -1
  220. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  221. package/schemas/plugins/container/ContainerReferencePlugin.json +1 -0
  222. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  223. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  224. package/schemas/plugins/container/ModuleFederationPlugin.json +3 -1
  225. package/schemas/plugins/css/CssGeneratorOptions.check.d.ts +7 -0
  226. package/schemas/plugins/css/CssGeneratorOptions.check.js +6 -0
  227. package/schemas/plugins/css/CssGeneratorOptions.json +3 -0
  228. package/schemas/plugins/css/CssParserOptions.check.d.ts +7 -0
  229. package/schemas/plugins/css/CssParserOptions.check.js +6 -0
  230. package/schemas/plugins/css/CssParserOptions.json +3 -0
  231. package/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js +1 -1
  232. package/schemas/plugins/optimize/LimitChunkCountPlugin.check.js +1 -1
  233. package/schemas/plugins/optimize/MinChunkSizePlugin.check.js +1 -1
  234. package/schemas/plugins/schemes/HttpUriPlugin.check.js +1 -1
  235. package/schemas/plugins/schemes/HttpUriPlugin.json +4 -0
  236. package/types.d.ts +869 -296
@@ -10,7 +10,7 @@ const HelperRuntimeModule = require("./HelperRuntimeModule");
10
10
 
11
11
  class CreateScriptUrlRuntimeModule extends HelperRuntimeModule {
12
12
  constructor() {
13
- super("trusted types");
13
+ super("trusted types script url");
14
14
  }
15
15
 
16
16
  /**
@@ -22,39 +22,14 @@ class CreateScriptUrlRuntimeModule extends HelperRuntimeModule {
22
22
  const { trustedTypes } = outputOptions;
23
23
  const fn = RuntimeGlobals.createScriptUrl;
24
24
 
25
- if (!trustedTypes) {
26
- // Skip Trusted Types logic.
27
- return Template.asString([
28
- `${fn} = ${runtimeTemplate.returningFunction("url", "url")};`
29
- ]);
30
- }
31
-
32
- return Template.asString([
33
- "var policy;",
34
- `${fn} = ${runtimeTemplate.basicFunction("url", [
35
- "// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.",
36
- "if (policy === undefined) {",
37
- Template.indent([
38
- "policy = {",
39
- Template.indent([
40
- `createScriptURL: ${runtimeTemplate.returningFunction(
41
- "url",
42
- "url"
43
- )}`
44
- ]),
45
- "};",
46
- 'if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {',
47
- Template.indent([
48
- `policy = trustedTypes.createPolicy(${JSON.stringify(
49
- trustedTypes.policyName
50
- )}, policy);`
51
- ]),
52
- "}"
53
- ]),
54
- "}",
55
- "return policy.createScriptURL(url);"
56
- ])};`
57
- ]);
25
+ return Template.asString(
26
+ `${fn} = ${runtimeTemplate.returningFunction(
27
+ trustedTypes
28
+ ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScriptURL(url)`
29
+ : "url",
30
+ "url"
31
+ )};`
32
+ );
58
33
  }
59
34
  }
60
35
 
@@ -0,0 +1,76 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ */
4
+
5
+ "use strict";
6
+
7
+ const RuntimeGlobals = require("../RuntimeGlobals");
8
+ const Template = require("../Template");
9
+ const HelperRuntimeModule = require("./HelperRuntimeModule");
10
+
11
+ class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule {
12
+ /**
13
+ * @param {Set<string>} runtimeRequirements runtime requirements
14
+ */
15
+ constructor(runtimeRequirements) {
16
+ super("trusted types policy");
17
+ this.runtimeRequirements = runtimeRequirements;
18
+ }
19
+
20
+ /**
21
+ * @returns {string} runtime code
22
+ */
23
+ generate() {
24
+ const { compilation } = this;
25
+ const { runtimeTemplate, outputOptions } = compilation;
26
+ const { trustedTypes } = outputOptions;
27
+ const fn = RuntimeGlobals.getTrustedTypesPolicy;
28
+
29
+ return Template.asString([
30
+ "var policy;",
31
+ `${fn} = ${runtimeTemplate.basicFunction("", [
32
+ "// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.",
33
+ "if (policy === undefined) {",
34
+ Template.indent([
35
+ "policy = {",
36
+ Template.indent(
37
+ [
38
+ ...(this.runtimeRequirements.has(RuntimeGlobals.createScript)
39
+ ? [
40
+ `createScript: ${runtimeTemplate.returningFunction(
41
+ "script",
42
+ "script"
43
+ )}`
44
+ ]
45
+ : []),
46
+ ...(this.runtimeRequirements.has(RuntimeGlobals.createScriptUrl)
47
+ ? [
48
+ `createScriptURL: ${runtimeTemplate.returningFunction(
49
+ "url",
50
+ "url"
51
+ )}`
52
+ ]
53
+ : [])
54
+ ].join(",\n")
55
+ ),
56
+ "};",
57
+ ...(trustedTypes
58
+ ? [
59
+ 'if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {',
60
+ Template.indent([
61
+ `policy = trustedTypes.createPolicy(${JSON.stringify(
62
+ trustedTypes.policyName
63
+ )}, policy);`
64
+ ]),
65
+ "}"
66
+ ]
67
+ : [])
68
+ ]),
69
+ "}",
70
+ "return policy;"
71
+ ])};`
72
+ ]);
73
+ }
74
+ }
75
+
76
+ module.exports = GetTrustedTypesPolicyRuntimeModule;
@@ -87,13 +87,15 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule {
87
87
  : "url"
88
88
  };`,
89
89
  crossOriginLoading
90
- ? Template.asString([
91
- "if (script.src.indexOf(window.location.origin + '/') !== 0) {",
92
- Template.indent(
93
- `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
94
- ),
95
- "}"
96
- ])
90
+ ? crossOriginLoading === "use-credentials"
91
+ ? 'script.crossOrigin = "use-credentials";'
92
+ : Template.asString([
93
+ "if (script.src.indexOf(window.location.origin + '/') !== 0) {",
94
+ Template.indent(
95
+ `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
96
+ ),
97
+ "}"
98
+ ])
97
99
  : ""
98
100
  ]);
99
101
 
@@ -144,8 +146,8 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule {
144
146
  )});`,
145
147
  "if(prev) return prev(event);"
146
148
  ])
147
- ),
148
- ";",
149
+ ) +
150
+ ";",
149
151
  `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`,
150
152
  "script.onerror = onScriptComplete.bind(null, script.onerror);",
151
153
  "script.onload = onScriptComplete.bind(null, script.onload);",
@@ -0,0 +1,24 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Ivan Kopeykin @vankop
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const RuntimeGlobals = require("../RuntimeGlobals");
9
+ const RuntimeModule = require("../RuntimeModule");
10
+
11
+ class NonceRuntimeModule extends RuntimeModule {
12
+ constructor() {
13
+ super("nonce", RuntimeModule.STAGE_ATTACH);
14
+ }
15
+
16
+ /**
17
+ * @returns {string} runtime code
18
+ */
19
+ generate() {
20
+ return `${RuntimeGlobals.scriptNonce} = undefined;`;
21
+ }
22
+ }
23
+
24
+ module.exports = NonceRuntimeModule;
@@ -5,6 +5,7 @@
5
5
 
6
6
  "use strict";
7
7
 
8
+ const EventEmitter = require("events");
8
9
  const { extname, basename } = require("path");
9
10
  const { URL } = require("url");
10
11
  const { createGunzip, createBrotliDecompress, createInflate } = require("zlib");
@@ -19,6 +20,44 @@ const memoize = require("../util/memoize");
19
20
 
20
21
  const getHttp = memoize(() => require("http"));
21
22
  const getHttps = memoize(() => require("https"));
23
+ const proxyFetch = (request, proxy) => (url, options, callback) => {
24
+ const eventEmitter = new EventEmitter();
25
+ const doRequest = socket =>
26
+ request
27
+ .get(url, { ...options, ...(socket && { socket }) }, callback)
28
+ .on("error", eventEmitter.emit.bind(eventEmitter, "error"));
29
+
30
+ if (proxy) {
31
+ const { hostname: host, port } = new URL(proxy);
32
+
33
+ getHttp()
34
+ .request({
35
+ host, // IP address of proxy server
36
+ port, // port of proxy server
37
+ method: "CONNECT",
38
+ path: url.host
39
+ })
40
+ .on("connect", (res, socket) => {
41
+ if (res.statusCode === 200) {
42
+ // connected to proxy server
43
+ doRequest(socket);
44
+ }
45
+ })
46
+ .on("error", err => {
47
+ eventEmitter.emit(
48
+ "error",
49
+ new Error(
50
+ `Failed to connect to proxy server "${proxy}": ${err.message}`
51
+ )
52
+ );
53
+ })
54
+ .end();
55
+ } else {
56
+ doRequest();
57
+ }
58
+
59
+ return eventEmitter;
60
+ };
22
61
 
23
62
  /** @type {(() => void)[] | undefined} */
24
63
  let inProgressWrite = undefined;
@@ -166,7 +205,7 @@ class Lockfile {
166
205
  /**
167
206
  * @template R
168
207
  * @param {function(function(Error=, R=): void): void} fn function
169
- * @returns {function(function(Error=, R=): void): void} cached function
208
+ * @returns {function(function((Error | null)=, R=): void): void} cached function
170
209
  */
171
210
  const cachedWithoutKey = fn => {
172
211
  let inFlight = false;
@@ -201,10 +240,10 @@ const cachedWithoutKey = fn => {
201
240
  * @template R
202
241
  * @param {function(T, function(Error=, R=): void): void} fn function
203
242
  * @param {function(T, function(Error=, R=): void): void=} forceFn function for the second try
204
- * @returns {(function(T, function(Error=, R=): void): void) & { force: function(T, function(Error=, R=): void): void }} cached function
243
+ * @returns {(function(T, function((Error | null)=, R=): void): void) & { force: function(T, function((Error | null)=, R=): void): void }} cached function
205
244
  */
206
245
  const cachedWithKey = (fn, forceFn = fn) => {
207
- /** @typedef {{ result?: R, error?: Error, callbacks?: (function(Error=, R=): void)[], force?: true }} CacheEntry */
246
+ /** @typedef {{ result?: R, error?: Error, callbacks?: (function((Error | null)=, R=): void)[], force?: true }} CacheEntry */
208
247
  /** @type {Map<T, CacheEntry>} */
209
248
  const cache = new Map();
210
249
  const resultFn = (arg, callback) => {
@@ -274,6 +313,7 @@ class HttpUriPlugin {
274
313
  this._upgrade = options.upgrade;
275
314
  this._frozen = options.frozen;
276
315
  this._allowedUris = options.allowedUris;
316
+ this._proxy = options.proxy;
277
317
  }
278
318
 
279
319
  /**
@@ -282,15 +322,16 @@ class HttpUriPlugin {
282
322
  * @returns {void}
283
323
  */
284
324
  apply(compiler) {
325
+ const proxy =
326
+ this._proxy || process.env["http_proxy"] || process.env["HTTP_PROXY"];
285
327
  const schemes = [
286
328
  {
287
329
  scheme: "http",
288
- fetch: (url, options, callback) => getHttp().get(url, options, callback)
330
+ fetch: proxyFetch(getHttp(), proxy)
289
331
  },
290
332
  {
291
333
  scheme: "https",
292
- fetch: (url, options, callback) =>
293
- getHttps().get(url, options, callback)
334
+ fetch: proxyFetch(getHttps(), proxy)
294
335
  }
295
336
  ];
296
337
  let lockfileCache;
@@ -358,7 +399,7 @@ class HttpUriPlugin {
358
399
 
359
400
  const getLockfile = cachedWithoutKey(
360
401
  /**
361
- * @param {function(Error=, Lockfile=): void} callback callback
402
+ * @param {function((Error | null)=, Lockfile=): void} callback callback
362
403
  * @returns {void}
363
404
  */
364
405
  callback => {
@@ -465,7 +506,7 @@ class HttpUriPlugin {
465
506
  *
466
507
  * @param {string} url URL
467
508
  * @param {string} integrity integrity
468
- * @param {function(Error=, { entry: LockfileEntry, content: Buffer, storeLock: boolean }=): void} callback callback
509
+ * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer, storeLock: boolean }=): void} callback callback
469
510
  */
470
511
  const resolveContent = (url, integrity, callback) => {
471
512
  const handleResult = (err, result) => {
@@ -509,8 +550,8 @@ class HttpUriPlugin {
509
550
 
510
551
  /**
511
552
  * @param {string} url URL
512
- * @param {FetchResult} cachedResult result from cache
513
- * @param {function(Error=, FetchResult=): void} callback callback
553
+ * @param {FetchResult | RedirectFetchResult} cachedResult result from cache
554
+ * @param {function((Error | null)=, FetchResult=): void} callback callback
514
555
  * @returns {void}
515
556
  */
516
557
  const fetchContentRaw = (url, cachedResult, callback) => {
@@ -603,9 +644,30 @@ class HttpUriPlugin {
603
644
  res.statusCode >= 301 &&
604
645
  res.statusCode <= 308
605
646
  ) {
606
- return finishWith({
647
+ const result = {
607
648
  location: new URL(location, url).href
608
- });
649
+ };
650
+ if (
651
+ !cachedResult ||
652
+ !("location" in cachedResult) ||
653
+ cachedResult.location !== result.location ||
654
+ cachedResult.validUntil < validUntil ||
655
+ cachedResult.storeLock !== storeLock ||
656
+ cachedResult.storeCache !== storeCache ||
657
+ cachedResult.etag !== etag
658
+ ) {
659
+ return finishWith(result);
660
+ } else {
661
+ logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`);
662
+ return callback(null, {
663
+ ...result,
664
+ fresh: true,
665
+ storeLock,
666
+ storeCache,
667
+ validUntil,
668
+ etag
669
+ });
670
+ }
609
671
  }
610
672
  const contentType = res.headers["content-type"] || "";
611
673
  const bufferArr = [];
@@ -662,7 +724,7 @@ class HttpUriPlugin {
662
724
  const fetchContent = cachedWithKey(
663
725
  /**
664
726
  * @param {string} url URL
665
- * @param {function(Error=, { validUntil: number, etag?: string, entry: LockfileEntry, content: Buffer, fresh: boolean } | { validUntil: number, etag?: string, location: string, fresh: boolean }=): void} callback callback
727
+ * @param {function((Error | null)=, { validUntil: number, etag?: string, entry: LockfileEntry, content: Buffer, fresh: boolean } | { validUntil: number, etag?: string, location: string, fresh: boolean }=): void} callback callback
666
728
  * @returns {void}
667
729
  */ (url, callback) => {
668
730
  cache.get(url, null, (err, cachedResult) => {
@@ -693,7 +755,7 @@ class HttpUriPlugin {
693
755
  const getInfo = cachedWithKey(
694
756
  /**
695
757
  * @param {string} url the url
696
- * @param {function(Error=, { entry: LockfileEntry, content: Buffer }=): void} callback callback
758
+ * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer }=): void} callback callback
697
759
  * @returns {void}
698
760
  */
699
761
  (url, callback) => {
@@ -1044,6 +1106,7 @@ Run build with un-frozen lockfile to automatically fix lockfile.`
1044
1106
  inProgressWrite.push(runWrite);
1045
1107
  } else {
1046
1108
  inProgressWrite = [];
1109
+ runWrite();
1047
1110
  }
1048
1111
  }
1049
1112
  );
@@ -40,6 +40,8 @@ Section -> Buffer
40
40
 
41
41
  // "wpc" + 1 in little-endian
42
42
  const VERSION = 0x01637077;
43
+ const WRITE_LIMIT_TOTAL = 0x7fff0000;
44
+ const WRITE_LIMIT_CHUNK = 511 * 1024 * 1024;
43
45
 
44
46
  /**
45
47
  * @param {Buffer[]} buffers buffers
@@ -87,7 +89,7 @@ const readUInt64LE = Buffer.prototype.readBigUInt64LE
87
89
  * @param {FileMiddleware} middleware this
88
90
  * @param {BufferSerializableType[] | Promise<BufferSerializableType[]>} data data to be serialized
89
91
  * @param {string | boolean} name file base name
90
- * @param {function(string | false, Buffer[]): Promise<void>} writeFile writes a file
92
+ * @param {function(string | false, Buffer[], number): Promise<void>} writeFile writes a file
91
93
  * @param {string | Hash} hashFunction hash function to use
92
94
  * @returns {Promise<SerializeResult>} resulting file pointer and promise
93
95
  */
@@ -212,9 +214,9 @@ const serialize = async (
212
214
  if (name === true) {
213
215
  name = hashForName(buf, hashFunction);
214
216
  }
215
- backgroundJobs.push(writeFile(name, buf));
216
217
  let size = 0;
217
218
  for (const b of buf) size += b.length;
219
+ backgroundJobs.push(writeFile(name, buf, size));
218
220
  return {
219
221
  size,
220
222
  name,
@@ -422,7 +424,7 @@ class FileMiddleware extends SerializerMiddleware {
422
424
  // It's important that we don't touch existing files during serialization
423
425
  // because serialize may read existing files (when deserializing)
424
426
  const allWrittenFiles = new Set();
425
- const writeFile = async (name, content) => {
427
+ const writeFile = async (name, content, size) => {
426
428
  const file = name
427
429
  ? join(this.fs, filename, `../${name}${extension}`)
428
430
  : filename;
@@ -441,10 +443,7 @@ class FileMiddleware extends SerializerMiddleware {
441
443
  [zConstants.BROTLI_PARAM_MODE]: zConstants.BROTLI_MODE_TEXT,
442
444
  [zConstants.BROTLI_PARAM_QUALITY]: 2,
443
445
  [zConstants.BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING]: true,
444
- [zConstants.BROTLI_PARAM_SIZE_HINT]: content.reduce(
445
- (size, b) => size + b.length,
446
- 0
447
- )
446
+ [zConstants.BROTLI_PARAM_SIZE_HINT]: size
448
447
  }
449
448
  });
450
449
  }
@@ -456,8 +455,44 @@ class FileMiddleware extends SerializerMiddleware {
456
455
  stream.on("error", err => reject(err));
457
456
  stream.on("finish", () => resolve());
458
457
  }
459
- for (const b of content) stream.write(b);
460
- stream.end();
458
+ // split into chunks for WRITE_LIMIT_CHUNK size
459
+ const chunks = [];
460
+ for (const b of content) {
461
+ if (b.length < WRITE_LIMIT_CHUNK) {
462
+ chunks.push(b);
463
+ } else {
464
+ for (let i = 0; i < b.length; i += WRITE_LIMIT_CHUNK) {
465
+ chunks.push(b.slice(i, i + WRITE_LIMIT_CHUNK));
466
+ }
467
+ }
468
+ }
469
+
470
+ const len = chunks.length;
471
+ let i = 0;
472
+ const batchWrite = err => {
473
+ // will be handled in "on" error handler
474
+ if (err) return;
475
+
476
+ if (i === len) {
477
+ stream.end();
478
+ return;
479
+ }
480
+
481
+ // queue up a batch of chunks up to the write limit
482
+ // end is exclusive
483
+ let end = i;
484
+ let sum = chunks[end++].length;
485
+ while (end < len) {
486
+ sum += chunks[end].length;
487
+ if (sum > WRITE_LIMIT_TOTAL) break;
488
+ end++;
489
+ }
490
+ while (i < end - 1) {
491
+ stream.write(chunks[i++]);
492
+ }
493
+ stream.write(chunks[i++], batchWrite);
494
+ };
495
+ batchWrite();
461
496
  });
462
497
  if (name) allWrittenFiles.add(file);
463
498
  };
@@ -101,14 +101,16 @@ class ConsumeSharedModule extends Module {
101
101
  */
102
102
  libIdent(options) {
103
103
  const { shareKey, shareScope, import: request } = this.options;
104
- return `webpack/sharing/consume/${shareScope}/${shareKey}${
104
+ return `${
105
+ this.layer ? `(${this.layer})/` : ""
106
+ }webpack/sharing/consume/${shareScope}/${shareKey}${
105
107
  request ? `/${request}` : ""
106
108
  }`;
107
109
  }
108
110
 
109
111
  /**
110
112
  * @param {NeedBuildContext} context context info
111
- * @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
113
+ * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
112
114
  * @returns {void}
113
115
  */
114
116
  needBuild(context, callback) {
@@ -210,6 +212,10 @@ class ConsumeSharedModule extends Module {
210
212
  }
211
213
  args.push(stringifyHoley(requiredVersion));
212
214
  fn += "VersionCheck";
215
+ } else {
216
+ if (singleton) {
217
+ fn += "Singleton";
218
+ }
213
219
  }
214
220
  if (fallbackCode) {
215
221
  fn += "Fallback";
@@ -103,9 +103,16 @@ class ConsumeSharedRuntimeModule extends RuntimeModule {
103
103
  ]
104
104
  )};`,
105
105
  `var getInvalidSingletonVersionMessage = ${runtimeTemplate.basicFunction(
106
- "key, version, requiredVersion",
106
+ "scope, key, version, requiredVersion",
107
107
  [
108
- `return "Unsatisfied version " + version + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"`
108
+ `return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"`
109
+ ]
110
+ )};`,
111
+ `var getSingleton = ${runtimeTemplate.basicFunction(
112
+ "scope, scopeName, key, requiredVersion",
113
+ [
114
+ "var version = findSingletonVersionKey(scope, key);",
115
+ "return get(scope[key][version]);"
109
116
  ]
110
117
  )};`,
111
118
  `var getSingletonVersion = ${runtimeTemplate.basicFunction(
@@ -113,7 +120,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule {
113
120
  [
114
121
  "var version = findSingletonVersionKey(scope, key);",
115
122
  "if (!satisfy(requiredVersion, version)) " +
116
- 'typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(key, version, requiredVersion));',
123
+ 'typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));',
117
124
  "return get(scope[key][version]);"
118
125
  ]
119
126
  )};`,
@@ -122,7 +129,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule {
122
129
  [
123
130
  "var version = findSingletonVersionKey(scope, key);",
124
131
  "if (!satisfy(requiredVersion, version)) " +
125
- "throw new Error(getInvalidSingletonVersionMessage(key, version, requiredVersion));",
132
+ "throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));",
126
133
  "return get(scope[key][version]);"
127
134
  ]
128
135
  )};`,
@@ -202,6 +209,13 @@ class ConsumeSharedRuntimeModule extends RuntimeModule {
202
209
  "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));"
203
210
  ]
204
211
  )});`,
212
+ `var loadSingleton = /*#__PURE__*/ init(${runtimeTemplate.basicFunction(
213
+ "scopeName, scope, key",
214
+ [
215
+ "ensureExistence(scopeName, key);",
216
+ "return getSingleton(scope, scopeName, key);"
217
+ ]
218
+ )});`,
205
219
  `var loadSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction(
206
220
  "scopeName, scope, key, version",
207
221
  [
@@ -230,6 +244,13 @@ class ConsumeSharedRuntimeModule extends RuntimeModule {
230
244
  "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));"
231
245
  ]
232
246
  )});`,
247
+ `var loadSingletonFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction(
248
+ "scopeName, scope, key, fallback",
249
+ [
250
+ `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`,
251
+ "return getSingleton(scope, scopeName, key);"
252
+ ]
253
+ )});`,
233
254
  `var loadSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction(
234
255
  "scopeName, scope, key, version, fallback",
235
256
  [
@@ -320,7 +341,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule {
320
341
  "var promise = moduleToHandlerMapping[id]();",
321
342
  "if(promise.then) {",
322
343
  Template.indent(
323
- `promises.push(installedModules[id] = promise.then(onFactory).catch(onError));`
344
+ "promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));"
324
345
  ),
325
346
  "} else onFactory(promise);"
326
347
  ]),
@@ -67,12 +67,14 @@ class ProvideSharedModule extends Module {
67
67
  * @returns {string | null} an identifier for library inclusion
68
68
  */
69
69
  libIdent(options) {
70
- return `webpack/sharing/provide/${this._shareScope}/${this._name}`;
70
+ return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${
71
+ this._shareScope
72
+ }/${this._name}`;
71
73
  }
72
74
 
73
75
  /**
74
76
  * @param {NeedBuildContext} context context info
75
- * @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
77
+ * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
76
78
  * @returns {void}
77
79
  */
78
80
  needBuild(context, callback) {
@@ -129,8 +129,7 @@ class ProvideSharedPlugin {
129
129
  details =
130
130
  "No description file (usually package.json) found. Add description file with name and version, or manually specify version in shared config.";
131
131
  } else if (!descriptionFileData.version) {
132
- details =
133
- "No version in description file (usually package.json). Add version to description file, or manually specify version in shared config.";
132
+ details = `No version in description file (usually package.json). Add version to description file ${resourceResolveData.descriptionFilePath}, or manually specify version in shared config.`;
134
133
  } else {
135
134
  version = descriptionFileData.version;
136
135
  }
@@ -105,7 +105,7 @@ class ShareRuntimeModule extends RuntimeModule {
105
105
  )}`,
106
106
  "if(module.then) return promises.push(module.then(initFn, handleError));",
107
107
  "var initResult = initFn(module);",
108
- "if(initResult && initResult.then) return promises.push(initResult.catch(handleError));"
108
+ "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));"
109
109
  ]),
110
110
  "} catch(err) { handleError(err); }"
111
111
  ])}`,
@@ -22,7 +22,7 @@ exports.isRequiredVersion = str => {
22
22
  * @param {InputFileSystem} fs file system
23
23
  * @param {string} directory directory to start looking into
24
24
  * @param {string[]} descriptionFiles possible description filenames
25
- * @param {function(Error=, {data: object, path: string}=): void} callback callback
25
+ * @param {function((Error | null)=, {data: object, path: string}=): void} callback callback
26
26
  */
27
27
  const getDescriptionFile = (fs, directory, descriptionFiles, callback) => {
28
28
  let i = 0;