Skip to content

Commit e9ecd4b

Browse files
committed
fix(provide): await asynchronous provided dependencies
1 parent 2b40c96 commit e9ecd4b

32 files changed

Lines changed: 379 additions & 136 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Await asynchronous dependencies injected by `ProvidePlugin`.

‎lib/async-modules/AsyncModuleHelpers.js‎

Lines changed: 122 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,17 @@
66
"use strict";
77

88
const isDependencyKind = require("../graph/isDependencyKind");
9+
const RuntimeGlobals = require("../runtime/RuntimeGlobals");
10+
const InitFragment = require("../template/InitFragment");
11+
const memoize = require("../util/memoize");
12+
const isGeneratorLowered = require("./isGeneratorLowered");
913

1014
/** @import ModuleGraph from "../graph/ModuleGraph" */
11-
/** @import Module from "../module/Module" */
15+
/** @import Module, { BuildMeta } from "../module/Module" */
16+
/** @import { GenerateContext } from "../module/Generator" */
17+
/** @import ChunkGraph, { ModuleId } from "../graph/ChunkGraph" */
18+
/** @import { DependencyTemplateContext } from "../template/DependencyTemplate" */
19+
/** @import { JavascriptModuleBuildInfo } from "../javascript/JavascriptModule" */
1220

1321
/** @typedef {Set<Module>} Modules */
1422

@@ -35,7 +43,12 @@ const getOutgoingAsyncModules = (moduleGraph, module) => {
3543
// Walk the imports in source order: the spec gathers these from
3644
// `[[RequestedModules]]`, and their evaluation order is observable.
3745
for (const dependency of module.dependencies) {
38-
if (!isDependencyKind(dependency, "esm-import")) continue;
46+
if (
47+
!isDependencyKind(dependency, "esm-import") &&
48+
!isDependencyKind(dependency, "provided")
49+
) {
50+
continue;
51+
}
3952
const referenced = moduleGraph.getModule(dependency);
4053
if (!referenced || seen.has(referenced)) continue;
4154
const connections = outgoingConnectionMap.get(referenced);
@@ -44,7 +57,8 @@ const getOutgoingAsyncModules = (moduleGraph, module) => {
4457
connections.some(
4558
(c) =>
4659
c.dependency !== null &&
47-
isDependencyKind(c.dependency, "esm-import") &&
60+
(isDependencyKind(c.dependency, "esm-import") ||
61+
isDependencyKind(c.dependency, "provided")) &&
4862
c.isTargetActive(undefined)
4963
)
5064
) {
@@ -58,3 +72,108 @@ const getOutgoingAsyncModules = (moduleGraph, module) => {
5872
};
5973

6074
module.exports.getOutgoingAsyncModules = getOutgoingAsyncModules;
75+
76+
// The deferred-namespace runtime imports dependency templates, so load it on demand.
77+
const getDeferredCycleHelpers = memoize(() =>
78+
require("../runtime/MakeDeferredNamespaceObjectRuntime")
79+
);
80+
81+
/**
82+
* Key shared by the async modules of one strongly-connected component. The spec
83+
* records one `[[EvaluationError]]` per component, so a member that already
84+
* fulfilled still has to report the root's error afterwards.
85+
* @param {ModuleGraph} moduleGraph the module graph
86+
* @param {ChunkGraph} chunkGraph the chunk graph
87+
* @param {Module} module the async module
88+
* @returns {ModuleId | null} the group key, or null when it is not in an async cycle
89+
*/
90+
const getAsyncCycleGroupId = (moduleGraph, chunkGraph, module) => {
91+
const { getDeferredCycleModules } = getDeferredCycleHelpers();
92+
const peers = getDeferredCycleModules(moduleGraph, module);
93+
if (peers === null) return null;
94+
// The component's smallest async member id names the group, so every member
95+
// emits the same key and none has to carry the whole peer list.
96+
let groupId = null;
97+
let asyncPeerCount = 0;
98+
for (const peer of peers) {
99+
if (!moduleGraph.isAsync(peer)) continue;
100+
asyncPeerCount++;
101+
const id = chunkGraph.getModuleId(peer);
102+
if (id !== null && (groupId === null || `${id}` < `${groupId}`)) {
103+
groupId = id;
104+
}
105+
}
106+
if (asyncPeerCount === 0) return null;
107+
const ownId = chunkGraph.getModuleId(module);
108+
if (ownId !== null && (groupId === null || `${ownId}` < `${groupId}`)) {
109+
groupId = ownId;
110+
}
111+
return groupId;
112+
};
113+
114+
/**
115+
* Wraps a module body so its imports can suspend evaluation.
116+
* @param {DependencyTemplateContext} templateContext template context
117+
* @param {boolean=} useModuleExports whether the body can replace CommonJS exports
118+
* @returns {InitFragment<GenerateContext>} async module boundary
119+
*/
120+
const createAsyncModuleInitFragment = (
121+
templateContext,
122+
useModuleExports = false
123+
) => {
124+
const {
125+
module,
126+
moduleGraph,
127+
chunkGraph,
128+
runtimeTemplate,
129+
runtimeRequirements
130+
} = templateContext;
131+
runtimeRequirements.add(RuntimeGlobals.module);
132+
runtimeRequirements.add(RuntimeGlobals.asyncModule);
133+
// Only strict error handling retains the shared evaluation error of a cycle.
134+
const cycleGroupId = runtimeTemplate.outputOptions.strictModuleErrorHandling
135+
? getAsyncCycleGroupId(moduleGraph, chunkGraph, module)
136+
: null;
137+
if (cycleGroupId !== null) runtimeRequirements.add(RuntimeGlobals.moduleId);
138+
const isAsyncBody = /** @type {BuildMeta} */ (module.buildMeta).async;
139+
const argumentsSuffix = useModuleExports
140+
? `, ${isAsyncBody ? 1 : 0}, ${cycleGroupId === null ? "undefined" : JSON.stringify(cycleGroupId)}, 1`
141+
: cycleGroupId === null
142+
? isAsyncBody
143+
? ", 1"
144+
: ""
145+
: `, ${isAsyncBody ? 1 : 0}, ${JSON.stringify(cycleGroupId)}`;
146+
// Disposal must finish before dependents can resume evaluation.
147+
const usesTopLevelUsingDeclaration =
148+
/** @type {JavascriptModuleBuildInfo} */ (module.buildInfo)
149+
.usesTopLevelUsingDeclaration;
150+
const blockStart = usesTopLevelUsingDeclaration ? " {" : "";
151+
const blockEnd = usesTopLevelUsingDeclaration ? "\n}" : "";
152+
const parameters = `__webpack_handle_async_dependencies__, __webpack_async_result__${useModuleExports ? ", __webpack_async_module__" : ""}`;
153+
const moduleAssignment = useModuleExports
154+
? `${module.moduleArgument} = __webpack_async_module__;\n`
155+
: "";
156+
const bindThis = useModuleExports ? ".bind(this)" : "";
157+
if (isGeneratorLowered(module, moduleGraph, runtimeTemplate)) {
158+
runtimeRequirements.add(RuntimeGlobals.asyncModuleGenerator);
159+
return new InitFragment(
160+
`${RuntimeGlobals.asyncModule}(${module.moduleArgument}, ${RuntimeGlobals.asyncModuleGenerator}(function* (${parameters}) { try {${blockStart}\n${moduleAssignment}`,
161+
InitFragment.STAGE_ASYNC_BOUNDARY,
162+
0,
163+
"async-module",
164+
`${blockEnd}\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } }${bindThis})${argumentsSuffix});`
165+
);
166+
}
167+
return new InitFragment(
168+
(runtimeTemplate.supportsArrowFunction()
169+
? `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async (${parameters}) => { try {${blockStart}\n`
170+
: `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async function (${parameters}) { try {${blockStart}\n`) +
171+
moduleAssignment,
172+
InitFragment.STAGE_ASYNC_BOUNDARY,
173+
0,
174+
"async-module",
175+
`${blockEnd}\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } }${runtimeTemplate.supportsArrowFunction() ? "" : bindThis}${argumentsSuffix});`
176+
);
177+
};
178+
179+
module.exports.createAsyncModuleInitFragment = createAsyncModuleInitFragment;

‎lib/async-modules/InferAsyncModulesPlugin.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ class InferAsyncModulesPlugin {
3939
connections.some(
4040
(c) =>
4141
c.dependency !== null &&
42-
isDependencyKind(c.dependency, "esm-import") &&
42+
(isDependencyKind(c.dependency, "esm-import") ||
43+
isDependencyKind(c.dependency, "provided")) &&
4344
c.isTargetActive(undefined)
4445
)
4546
) {

‎lib/dependencies/esm/ESMCompatibilityDependency.js‎

Lines changed: 7 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,17 @@
55

66
"use strict";
77

8-
const isGeneratorLowered = require("../../async-modules/isGeneratorLowered");
8+
const {
9+
createAsyncModuleInitFragment
10+
} = require("../../async-modules/AsyncModuleHelpers");
911
const { UsageState } = require("../../graph/ExportsInfo");
10-
const RuntimeGlobals = require("../../runtime/RuntimeGlobals");
1112
const InitFragment = require("../../template/InitFragment");
1213
const makeSerializable = require("../../util/makeSerializable");
13-
const memoize = require("../../util/memoize");
1414
const NullDependency = require("../core/NullDependency");
1515

16-
// Required here rather than at the top: the deferred-namespace runtime imports
17-
// dependencies from here.
18-
const getDeferredCycleHelpers = memoize(() =>
19-
require("../../runtime/MakeDeferredNamespaceObjectRuntime")
20-
);
21-
2216
/** @import { ReplaceSource } from "webpack-sources" */
2317
/** @import Dependency, { DependencyKinds } from "../../graph/Dependency" */
2418
/** @import { DependencyTemplateContext } from "../../template/DependencyTemplate" */
25-
/** @import Module, { BuildMeta } from "../../module/Module" */
26-
/** @import ModuleGraph from "../../graph/ModuleGraph" */
27-
/** @import ChunkGraph, { ModuleId } from "../../graph/ChunkGraph" */
28-
/**
29-
* @import {
30-
* JavascriptModuleBuildInfo
31-
* } from "../../javascript/JavascriptModule"
32-
*/
3319

3420
class ESMCompatibilityDependency extends NullDependency {
3521
get type() {
@@ -44,39 +30,6 @@ makeSerializable(ESMCompatibilityDependency, [
4430
"webpack/lib/dependencies/HarmonyCompatibilityDependency"
4531
]);
4632

47-
/**
48-
* Key shared by the async modules of one strongly-connected component. The spec
49-
* records one `[[EvaluationError]]` per component, so a member that already
50-
* fulfilled still has to report the root's error afterwards.
51-
* @param {ModuleGraph} moduleGraph the module graph
52-
* @param {ChunkGraph} chunkGraph the chunk graph
53-
* @param {Module} module the async module
54-
* @returns {ModuleId | null} the group key, or null when it is not in an async cycle
55-
*/
56-
const getAsyncCycleGroupId = (moduleGraph, chunkGraph, module) => {
57-
const { getDeferredCycleModules } = getDeferredCycleHelpers();
58-
const peers = getDeferredCycleModules(moduleGraph, module);
59-
if (peers === null) return null;
60-
// The component's smallest async member id names the group, so every member
61-
// emits the same key and none has to carry the whole peer list.
62-
let groupId = null;
63-
let asyncPeerCount = 0;
64-
for (const peer of peers) {
65-
if (!moduleGraph.isAsync(peer)) continue;
66-
asyncPeerCount++;
67-
const id = chunkGraph.getModuleId(peer);
68-
if (id !== null && (groupId === null || `${id}` < `${groupId}`)) {
69-
groupId = id;
70-
}
71-
}
72-
if (asyncPeerCount === 0) return null;
73-
const ownId = chunkGraph.getModuleId(module);
74-
if (ownId !== null && (groupId === null || `${ownId}` < `${groupId}`)) {
75-
groupId = ownId;
76-
}
77-
return groupId;
78-
};
79-
8033
ESMCompatibilityDependency.Template = class ESMExportDependencyTemplate extends (
8134
NullDependency.Template
8235
) {
@@ -87,21 +40,17 @@ ESMCompatibilityDependency.Template = class ESMExportDependencyTemplate extends
8740
* @param {DependencyTemplateContext} templateContext the context object
8841
* @returns {void}
8942
*/
90-
apply(
91-
dependency,
92-
source,
93-
{
43+
apply(dependency, source, templateContext) {
44+
const {
9445
module,
9546
runtimeTemplate,
9647
moduleGraph,
97-
chunkGraph,
9848
initFragments,
9949
runtimeRequirements,
10050
runtime,
10151
concatenationScope,
10252
getData
103-
}
104-
) {
53+
} = templateContext;
10554
// a wrapped module has a real exports object that still needs `__esModule`
10655
if (concatenationScope && !concatenationScope.isWrapped()) return;
10756
const exportsInfo = moduleGraph.getExportsInfo(module);
@@ -131,60 +80,7 @@ ESMCompatibilityDependency.Template = class ESMExportDependencyTemplate extends
13180
}
13281
}
13382
if (moduleGraph.isAsync(module)) {
134-
runtimeRequirements.add(RuntimeGlobals.module);
135-
// Only `strictModuleErrorHandling` keeps a recorded error for later
136-
// requires, so the component's peers are worth naming only then.
137-
const cycleGroupId = runtimeTemplate.outputOptions
138-
.strictModuleErrorHandling
139-
? getAsyncCycleGroupId(moduleGraph, chunkGraph, module)
140-
: null;
141-
// The group is keyed by module id, so the runtime needs `module.id`.
142-
if (cycleGroupId !== null) {
143-
runtimeRequirements.add(RuntimeGlobals.moduleId);
144-
}
145-
const isAsyncBody = /** @type {BuildMeta} */ (module.buildMeta).async;
146-
const hasAwait =
147-
cycleGroupId === null
148-
? isAsyncBody
149-
? ", 1"
150-
: ""
151-
: `, ${isAsyncBody ? 1 : 0}, ${JSON.stringify(cycleGroupId)}`;
152-
// A module-scope `await using` is disposed when its scope ends, so the body
153-
// needs a block that closes before the module reports completion —
154-
// otherwise dependents run before disposal is awaited.
155-
const usesTopLevelUsingDeclaration =
156-
/** @type {JavascriptModuleBuildInfo} */
157-
(module.buildInfo).usesTopLevelUsingDeclaration;
158-
const blockStart = usesTopLevelUsingDeclaration ? " {" : "";
159-
const blockEnd = usesTopLevelUsingDeclaration ? "\n}" : "";
160-
// Target has no `async`/`await` but has generators: drive the body as a
161-
// generator so `await` becomes `yield`, keeping the module in a single
162-
// scope (unlike a `.then` callback) without transpiling to a state machine.
163-
if (isGeneratorLowered(module, moduleGraph, runtimeTemplate)) {
164-
runtimeRequirements.add(RuntimeGlobals.asyncModuleGenerator);
165-
initFragments.push(
166-
new InitFragment(
167-
`${RuntimeGlobals.asyncModule}(${module.moduleArgument}, ${RuntimeGlobals.asyncModuleGenerator}(function* (__webpack_handle_async_dependencies__, __webpack_async_result__) { try {${blockStart}\n`,
168-
InitFragment.STAGE_ASYNC_BOUNDARY,
169-
0,
170-
undefined,
171-
`${blockEnd}\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } })${hasAwait});`
172-
)
173-
);
174-
} else {
175-
runtimeRequirements.add(RuntimeGlobals.asyncModule);
176-
initFragments.push(
177-
new InitFragment(
178-
runtimeTemplate.supportsArrowFunction()
179-
? `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {${blockStart}\n`
180-
: `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async function (__webpack_handle_async_dependencies__, __webpack_async_result__) { try {${blockStart}\n`,
181-
InitFragment.STAGE_ASYNC_BOUNDARY,
182-
0,
183-
undefined,
184-
`${blockEnd}\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } }${hasAwait});`
185-
)
186-
);
187-
}
83+
initFragments.push(createAsyncModuleInitFragment(templateContext));
18884
}
18985
}
19086
};

‎lib/graph/Dependency.js‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const memoize = require("../util/memoize");
2424
/** @import WebAssemblyExportImportedDependency from "../dependencies/wasm/WebAssemblyExportImportedDependency" */
2525
/** @import ConsumeSharedFallbackDependency from "../sharing/ConsumeSharedFallbackDependency" */
2626
/** @import ProvideForSharedDependency from "../sharing/ProvideForSharedDependency" */
27+
/** @import ProvidedDependency from "../provide/ProvidedDependency" */
2728
/** @import LocalModuleDependency from "../dependencies/amd/LocalModuleDependency" */
2829
/** @import StaticExportsDependency from "../dependencies/core/StaticExportsDependency" */
2930
/** @import LoaderImportDependency from "../loaders/LoaderImportDependency" */
@@ -168,6 +169,7 @@ const getIgnoredModule = memoize(() => {
168169
* @typedef {{
169170
* "module-dependency": ModuleDependency,
170171
* "esm-import": ESMImportDependency,
172+
* provided: ProvidedDependency,
171173
* "dynamic-import": ImportDependency,
172174
* "esm-reexport": ESMExportImportedSpecifierDependency,
173175
* "esm-side-effect-import": ESMImportSideEffectDependency,

0 commit comments

Comments
 (0)