-
Notifications
You must be signed in to change notification settings - Fork 47.4k
/
Copy pathReactFlightClientConfigBundlerWebpack.js
234 lines (217 loc) · 7.44 KB
/
ReactFlightClientConfigBundlerWebpack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {
Thenable,
FulfilledThenable,
RejectedThenable,
} from 'shared/ReactTypes';
import type {
ImportMetadata,
ImportManifestEntry,
} from './shared/ReactFlightImportMetadata';
import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig';
import {
ID,
CHUNKS,
NAME,
isAsyncImport,
} from './shared/ReactFlightImportMetadata';
import {prepareDestinationWithChunks} from 'react-client/src/ReactFlightClientConfig';
import {loadChunk} from 'react-client/src/ReactFlightClientConfig';
export type SSRModuleMap = null | {
[clientId: string]: {
[clientExportName: string]: ClientReferenceManifestEntry,
},
};
export type ServerManifest = {
[id: string]: ImportManifestEntry,
};
export type ServerReferenceId = string;
export opaque type ClientReferenceManifestEntry = ImportManifestEntry;
export opaque type ClientReferenceMetadata = ImportMetadata;
// eslint-disable-next-line no-unused-vars
export opaque type ClientReference<T> = ClientReferenceMetadata;
// The reason this function needs to defined here in this file instead of just
// being exported directly from the WebpackDestination... file is because the
// ClientReferenceMetadata is opaque and we can't unwrap it there.
// This should get inlined and we could also just implement an unwrapping function
// though that risks it getting used in places it shouldn't be. This is unfortunate
// but currently it seems to be the best option we have.
export function prepareDestinationForModule(
moduleLoading: ModuleLoading,
nonce: ?string,
metadata: ClientReferenceMetadata,
) {
prepareDestinationWithChunks(moduleLoading, metadata[CHUNKS], nonce);
}
export function resolveClientReference<T>(
bundlerConfig: SSRModuleMap,
metadata: ClientReferenceMetadata,
): ClientReference<T> {
if (bundlerConfig) {
const moduleExports = bundlerConfig[metadata[ID]];
let resolvedModuleData = moduleExports[metadata[NAME]];
let name;
if (resolvedModuleData) {
// The potentially aliased name.
name = resolvedModuleData.name;
} else {
// If we don't have this specific name, we might have the full module.
resolvedModuleData = moduleExports['*'];
if (!resolvedModuleData) {
throw new Error(
'Could not find the module "' +
metadata[ID] +
'" in the React SSR Manifest. ' +
'This is probably a bug in the React Server Components bundler.',
);
}
name = metadata[NAME];
}
if (isAsyncImport(metadata)) {
return [
resolvedModuleData.id,
resolvedModuleData.chunks,
name,
1 /* async */,
];
} else {
return [resolvedModuleData.id, resolvedModuleData.chunks, name];
}
}
return metadata;
}
export function resolveServerReference<T>(
bundlerConfig: ServerManifest,
id: ServerReferenceId,
): ClientReference<T> {
let name = '';
let resolvedModuleData = bundlerConfig[id];
if (resolvedModuleData) {
// The potentially aliased name.
name = resolvedModuleData.name;
} else {
// We didn't find this specific export name but we might have the * export
// which contains this name as well.
// TODO: It's unfortunate that we now have to parse this string. We should
// probably go back to encoding path and name separately on the client reference.
const idx = id.lastIndexOf('#');
if (idx !== -1) {
name = id.slice(idx + 1);
resolvedModuleData = bundlerConfig[id.slice(0, idx)];
}
if (!resolvedModuleData) {
throw new Error(
'Could not find the module "' +
id +
'" in the React Server Manifest. ' +
'This is probably a bug in the React Server Components bundler.',
);
}
}
// TODO: This needs to return async: true if it's an async module.
return [resolvedModuleData.id, resolvedModuleData.chunks, name];
}
// The chunk cache contains all the chunks we've preloaded so far.
// If they're still pending they're a thenable. This map also exists
// in Webpack but unfortunately it's not exposed so we have to
// replicate it in user space. null means that it has already loaded.
const chunkCache: Map<string, null | Promise<any>> = new Map();
function requireAsyncModule(id: string): null | Thenable<any> {
// We've already loaded all the chunks. We can require the module.
const promise = __webpack_require__(id);
if (typeof promise.then !== 'function') {
// This wasn't a promise after all.
return null;
} else if (promise.status === 'fulfilled') {
// This module was already resolved earlier.
return null;
} else {
// Instrument the Promise to stash the result.
promise.then(
value => {
const fulfilledThenable: FulfilledThenable<mixed> = (promise: any);
fulfilledThenable.status = 'fulfilled';
fulfilledThenable.value = value;
},
reason => {
const rejectedThenable: RejectedThenable<mixed> = (promise: any);
rejectedThenable.status = 'rejected';
rejectedThenable.reason = reason;
},
);
return promise;
}
}
function ignoreReject() {
// We rely on rejected promises to be handled by another listener.
}
// Start preloading the modules since we might need them soon.
// This function doesn't suspend.
export function preloadModule<T>(
metadata: ClientReference<T>,
): null | Thenable<any> {
const chunks = metadata[CHUNKS];
const promises = [];
let i = 0;
while (i < chunks.length) {
const chunkId = chunks[i++];
const chunkFilename = chunks[i++];
const entry = chunkCache.get(chunkId);
if (entry === undefined) {
const thenable = loadChunk(chunkId, chunkFilename);
promises.push(thenable);
// $FlowFixMe[method-unbinding]
const resolve = chunkCache.set.bind(chunkCache, chunkId, null);
thenable.then(resolve, ignoreReject);
chunkCache.set(chunkId, thenable);
} else if (entry !== null) {
promises.push(entry);
}
}
if (isAsyncImport(metadata)) {
if (promises.length === 0) {
return requireAsyncModule(metadata[ID]);
} else {
return Promise.all(promises).then(() => {
return requireAsyncModule(metadata[ID]);
});
}
} else if (promises.length > 0) {
return Promise.all(promises);
} else {
return null;
}
}
// Actually require the module or suspend if it's not yet ready.
// Increase priority if necessary.
export function requireModule<T>(metadata: ClientReference<T>): T {
let moduleExports = __webpack_require__(metadata[ID]);
if (isAsyncImport(metadata)) {
if (typeof moduleExports.then !== 'function') {
// This wasn't a promise after all.
} else if (moduleExports.status === 'fulfilled') {
// This Promise should've been instrumented by preloadModule.
moduleExports = moduleExports.value;
} else {
throw moduleExports.reason;
}
}
if (metadata[NAME] === '*') {
// This is a placeholder value that represents that the caller imported this
// as a CommonJS module as is.
return moduleExports;
}
if (metadata[NAME] === '') {
// This is a placeholder value that represents that the caller accessed the
// default property of this if it was an ESM interop module.
return moduleExports.__esModule ? moduleExports.default : moduleExports;
}
return moduleExports[metadata[NAME]];
}