rsbuild-plugin-react-router 0.0.5 → 0.1.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.
- package/README.md +228 -3
- package/dist/906.js +1 -0
- package/dist/946.js +1 -0
- package/dist/babel.d.ts +2 -2
- package/dist/build-manifest.d.ts +19 -0
- package/dist/constants.d.ts +10 -3
- package/dist/export-utils.d.ts +7 -0
- package/dist/index.cjs +1824 -645
- package/dist/index.js +1594 -483
- package/dist/manifest.d.ts +18 -1
- package/dist/modify-browser-manifest.d.ts +7 -1
- package/dist/plugin-utils.d.ts +2 -0
- package/dist/prerender.d.ts +16 -0
- package/dist/react-router-config.d.ts +51 -0
- package/dist/route-chunks.d.ts +32 -0
- package/dist/route-config.d.ts +13 -0
- package/dist/rslib-runtime.js +23 -0
- package/dist/server-utils.d.ts +22 -6
- package/dist/ssr-externals.d.ts +1 -0
- package/dist/templates/entry.client.cjs +5 -7
- package/dist/templates/entry.client.js +5 -5
- package/dist/templates/entry.server.cjs +7 -6
- package/dist/templates/entry.server.js +10 -11
- package/dist/types.d.ts +6 -0
- package/dist/validation/validate-plugin-order.d.ts +9 -0
- package/dist/warnings/warn-on-client-source-maps.d.ts +6 -0
- package/package.json +46 -47
- package/dist/transform-route-federation.d.ts +0 -6
package/dist/index.js
CHANGED
|
@@ -1,333 +1,988 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import * as
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
import
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
var module = __webpack_module_cache__[moduleId] = {
|
|
26
|
-
exports: {}
|
|
27
|
-
};
|
|
28
|
-
return __webpack_modules__[moduleId](module, module.exports, __webpack_require__), module.exports;
|
|
29
|
-
}
|
|
30
|
-
let traverse = __webpack_require__("@babel/traverse").default, generate = __webpack_require__("@babel/generator").default, JS_EXTENSIONS = [
|
|
1
|
+
let lexer_C;
|
|
2
|
+
import { fileURLToPath as __rspack_fileURLToPath, pathToFileURL } from "node:url";
|
|
3
|
+
import { dirname as __rspack_dirname, sep } from "node:path";
|
|
4
|
+
import * as __rspack_external__babel_types_69e65b52 from "@babel/types";
|
|
5
|
+
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
6
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
7
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import fs_extra from "fs-extra";
|
|
10
|
+
import { createJiti } from "jiti";
|
|
11
|
+
import jsesc from "jsesc";
|
|
12
|
+
import { basename as external_pathe_basename, dirname, extname, isAbsolute, normalize, relative, resolve } from "pathe";
|
|
13
|
+
import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
|
|
14
|
+
import { parse } from "@babel/parser";
|
|
15
|
+
import { deadCodeElimination, findReferencedIdentifiers } from "babel-dead-code-elimination";
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
import { transform } from "esbuild";
|
|
18
|
+
import { rspack } from "@rsbuild/core";
|
|
19
|
+
import { createRequestHandler, matchRoutes } from "./906.js";
|
|
20
|
+
let generator_namespaceObject = require("@babel/generator");
|
|
21
|
+
var A, A1, ImportType, generator_default = __webpack_require__.n(generator_namespaceObject);
|
|
22
|
+
let traverse_namespaceObject = require("@babel/traverse");
|
|
23
|
+
var traverse_default = __webpack_require__.n(traverse_namespaceObject);
|
|
24
|
+
let traverse = traverse_default().default ?? traverse_default(), generate = generator_default().default ?? generator_default(), PLUGIN_NAME = 'rsbuild:react-router', JS_EXTENSIONS = [
|
|
31
25
|
'.tsx',
|
|
32
26
|
'.ts',
|
|
33
27
|
'.jsx',
|
|
34
28
|
'.js',
|
|
35
|
-
'.mjs'
|
|
29
|
+
'.mjs',
|
|
30
|
+
'.mts'
|
|
36
31
|
], JS_LOADERS = {
|
|
37
32
|
'.ts': 'ts',
|
|
38
33
|
'.tsx': 'tsx',
|
|
39
34
|
'.js': 'js',
|
|
40
|
-
'.jsx': 'jsx'
|
|
41
|
-
|
|
35
|
+
'.jsx': 'jsx',
|
|
36
|
+
'.mjs': 'js',
|
|
37
|
+
'.mts': 'ts'
|
|
38
|
+
}, BUILD_CLIENT_ROUTE_QUERY_STRING = '?__react-router-build-client-route', SERVER_ONLY_ROUTE_EXPORTS = [
|
|
42
39
|
'loader',
|
|
43
40
|
'action',
|
|
41
|
+
'middleware',
|
|
44
42
|
'headers'
|
|
43
|
+
], CLIENT_ROUTE_EXPORTS = [
|
|
44
|
+
'clientAction',
|
|
45
|
+
'clientLoader',
|
|
46
|
+
'clientMiddleware',
|
|
47
|
+
'handle',
|
|
48
|
+
'meta',
|
|
49
|
+
'links',
|
|
50
|
+
'shouldRevalidate',
|
|
51
|
+
'default',
|
|
52
|
+
'ErrorBoundary',
|
|
53
|
+
'HydrateFallback',
|
|
54
|
+
'Layout'
|
|
45
55
|
], NAMED_COMPONENT_EXPORTS = [
|
|
46
56
|
'HydrateFallback',
|
|
47
57
|
'ErrorBoundary'
|
|
48
|
-
]
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
58
|
+
];
|
|
59
|
+
function generateServerBuild(routes, options) {
|
|
60
|
+
let manifestId;
|
|
61
|
+
return manifestId = options.serverManifestId ?? 'virtual/react-router/server-manifest', `
|
|
62
|
+
import * as entryServer from ${JSON.stringify(options.entryServerPath)};
|
|
63
|
+
${Object.keys(routes).map((key, index)=>{
|
|
64
|
+
let route = routes[key];
|
|
65
|
+
return `import * as route${index} from ${JSON.stringify(`${resolve(options.appDirectory, route.file)}?react-router-route`)};`;
|
|
66
|
+
}).join('\n')}
|
|
67
|
+
|
|
68
|
+
export { default as assets } from ${JSON.stringify(manifestId)};
|
|
69
|
+
export const assetsBuildDirectory = ${JSON.stringify(options.assetsBuildDirectory)};
|
|
70
|
+
export const basename = ${JSON.stringify(options.basename)};
|
|
71
|
+
export const future = ${JSON.stringify(options.future ?? {})};
|
|
72
|
+
export const isSpaMode = ${!options.ssr};
|
|
73
|
+
export const ssr = ${options.ssr};
|
|
74
|
+
export const routeDiscovery = ${JSON.stringify(options.routeDiscovery)};
|
|
75
|
+
export const prerender = ${JSON.stringify(options.prerender ?? [])};
|
|
76
|
+
export const publicPath = ${JSON.stringify(options.publicPath ?? '/')};
|
|
77
|
+
export const entry = { module: entryServer };
|
|
78
|
+
export const allowedActionOrigins = ${JSON.stringify(options.allowedActionOrigins)};
|
|
79
|
+
export var routes = {};
|
|
80
|
+
${Object.keys(routes).map((key, index)=>{
|
|
81
|
+
let route = routes[key];
|
|
82
|
+
return `routes[${JSON.stringify(key)}] = {
|
|
83
|
+
id: ${JSON.stringify(route.id)},
|
|
84
|
+
parentId: ${JSON.stringify(route.parentId)},
|
|
85
|
+
path: ${JSON.stringify(route.path)},
|
|
86
|
+
index: ${JSON.stringify(route.index)},
|
|
87
|
+
caseSensitive: ${JSON.stringify(route.caseSensitive)},
|
|
88
|
+
module: route${index}
|
|
89
|
+
};`;
|
|
90
|
+
}).join('\n ')}
|
|
91
|
+
`;
|
|
92
|
+
}
|
|
93
|
+
let RESOLVABLE_BUILD_EXPORTS = new Set([
|
|
94
|
+
'allowedActionOrigins',
|
|
95
|
+
'assets',
|
|
96
|
+
'assetsBuildDirectory',
|
|
97
|
+
'basename',
|
|
98
|
+
'entry',
|
|
99
|
+
'future',
|
|
100
|
+
'isSpaMode',
|
|
101
|
+
'prerender',
|
|
102
|
+
'publicPath',
|
|
103
|
+
'routeDiscovery',
|
|
104
|
+
'routes',
|
|
105
|
+
'ssr'
|
|
106
|
+
]), isPromiseLike = (value)=>'function' == typeof value?.then, normalizeBuildModule = (build)=>build && 'object' == typeof build && 'default' in build && 1 === Object.keys(build).length && 'object' == typeof build.default && build.default ? build.default : build, resolveBuildExports = async (build)=>{
|
|
107
|
+
let resolved = {
|
|
108
|
+
...build
|
|
66
109
|
};
|
|
110
|
+
for (let key of Object.keys(build)){
|
|
111
|
+
if (!RESOLVABLE_BUILD_EXPORTS.has(key)) continue;
|
|
112
|
+
let value = build[key];
|
|
113
|
+
if ('function' == typeof value && 0 === value.length) {
|
|
114
|
+
let result = value();
|
|
115
|
+
resolved[key] = isPromiseLike(result) ? await result : result;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
isPromiseLike(value) && (resolved[key] = await value);
|
|
119
|
+
}
|
|
120
|
+
return resolved;
|
|
121
|
+
};
|
|
67
122
|
function invalidDestructureError(name) {
|
|
68
123
|
return Error(`Cannot remove destructured export "${name}"`);
|
|
69
124
|
}
|
|
70
125
|
function toFunctionExpression(decl) {
|
|
71
|
-
return
|
|
126
|
+
return __rspack_external__babel_types_69e65b52.functionExpression(decl.id, decl.params, decl.body, decl.generator, decl.async);
|
|
72
127
|
}
|
|
73
128
|
function combineURLs(baseURL, relativeURL) {
|
|
74
129
|
return relativeURL ? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}` : baseURL;
|
|
75
130
|
}
|
|
131
|
+
function normalizeAssetPrefix(assetPrefix) {
|
|
132
|
+
return assetPrefix && 'auto' !== assetPrefix ? assetPrefix.endsWith('/') ? assetPrefix : `${assetPrefix}/` : '/';
|
|
133
|
+
}
|
|
76
134
|
function findEntryFile(basePath) {
|
|
77
135
|
for (let ext of JS_EXTENSIONS){
|
|
78
136
|
let filePath = `${basePath}${ext}`;
|
|
79
|
-
if (
|
|
137
|
+
if (existsSync(filePath)) return filePath;
|
|
80
138
|
}
|
|
81
139
|
return `${basePath}.tsx`;
|
|
82
140
|
}
|
|
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
|
-
|
|
141
|
+
function isNamedComponentExport(name) {
|
|
142
|
+
return NAMED_COMPONENT_EXPORTS.includes(name);
|
|
143
|
+
}
|
|
144
|
+
let normalizePath = (value)=>value.replace(/\/\/+/g, '/').replace(/(.+)\/$/, '$1'), resolvePrerenderPaths = async (prerender, ssr, routes, options = {})=>{
|
|
145
|
+
let pathsConfig, paths, paramRoutes, recurse;
|
|
146
|
+
if (null == prerender || !1 === prerender || !1 === (pathsConfig = 'object' == typeof prerender && null !== prerender && 'paths' in prerender ? prerender?.paths : prerender)) return [];
|
|
147
|
+
let { paths: paths1, paramRoutes: paramRoutes1 } = (paths = [
|
|
148
|
+
'/'
|
|
149
|
+
], paramRoutes = [], (recurse = (entries, prefix = '', hasDynamicParent = !1)=>{
|
|
150
|
+
for (let route of entries){
|
|
151
|
+
let routePath = route.path ?? '', hasDynamicSegment = routePath.split('/').filter(Boolean).some((segment)=>segment.startsWith(':') || '*' === segment) || '*' === routePath, nextHasDynamic = hasDynamicParent || hasDynamicSegment;
|
|
152
|
+
if (routePath) {
|
|
153
|
+
let fullPath = normalizePath([
|
|
154
|
+
prefix,
|
|
155
|
+
routePath
|
|
156
|
+
].join('/'));
|
|
157
|
+
nextHasDynamic ? paramRoutes.push(fullPath) : paths.push(fullPath);
|
|
158
|
+
}
|
|
159
|
+
if (route.children) {
|
|
160
|
+
let newPrefix = routePath ? normalizePath([
|
|
161
|
+
prefix,
|
|
162
|
+
routePath
|
|
163
|
+
].join('/')) : prefix;
|
|
164
|
+
recurse(route.children, newPrefix, nextHasDynamic);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
})(routes), {
|
|
168
|
+
paths: paths.map(normalizePath),
|
|
169
|
+
paramRoutes: paramRoutes.map(normalizePath)
|
|
170
|
+
});
|
|
171
|
+
if (!0 === pathsConfig) return options.logWarning && !ssr && paramRoutes1.length > 0 && (options.warn ?? ((message)=>{
|
|
172
|
+
console.warn(message);
|
|
173
|
+
}))([
|
|
174
|
+
'Warning: Paths with dynamic/splat params cannot be prerendered when using `prerender: true`.',
|
|
175
|
+
'You may want to use the `prerender()` API to prerender the following paths:',
|
|
176
|
+
...paramRoutes1.map((path)=>` - ${path}`)
|
|
177
|
+
].join('\n')), paths1;
|
|
178
|
+
if ('function' == typeof pathsConfig) {
|
|
179
|
+
let resolved = await pathsConfig({
|
|
180
|
+
getStaticPaths: ()=>paths1
|
|
181
|
+
});
|
|
182
|
+
return !0 === resolved ? paths1 : !1 === resolved || null == resolved ? [] : resolved;
|
|
183
|
+
}
|
|
184
|
+
return pathsConfig ?? [];
|
|
185
|
+
}, isValidPrerenderPathsConfig = (value)=>'boolean' == typeof value || 'function' == typeof value || Array.isArray(value), DEFAULT_CONFIG = {
|
|
186
|
+
appDirectory: 'app',
|
|
187
|
+
basename: '/',
|
|
188
|
+
buildDirectory: 'build',
|
|
189
|
+
serverBuildFile: 'index.js',
|
|
190
|
+
serverModuleFormat: 'esm',
|
|
191
|
+
ssr: !0,
|
|
192
|
+
future: {
|
|
193
|
+
unstable_optimizeDeps: !1,
|
|
194
|
+
unstable_subResourceIntegrity: !1,
|
|
195
|
+
unstable_trailingSlashAwareDataRequests: !1,
|
|
196
|
+
v8_middleware: !1,
|
|
197
|
+
v8_splitRouteModules: !1,
|
|
198
|
+
v8_viteEnvironmentApi: !1
|
|
199
|
+
},
|
|
200
|
+
routeDiscovery: void 0,
|
|
201
|
+
prerender: void 0,
|
|
202
|
+
serverBundles: void 0,
|
|
203
|
+
buildEnd: void 0,
|
|
204
|
+
allowedActionOrigins: !1,
|
|
205
|
+
routes: {},
|
|
206
|
+
unstable_routeConfig: []
|
|
207
|
+
}, resolveReactRouterConfig = async (reactRouterUserConfig)=>{
|
|
208
|
+
let userAndPresetConfigs = ((...configs)=>configs.reduce((configA, configB)=>{
|
|
209
|
+
let mergeRequired = (key)=>void 0 !== configA[key] && void 0 !== configB[key];
|
|
210
|
+
return {
|
|
211
|
+
...configA,
|
|
212
|
+
...configB,
|
|
213
|
+
...mergeRequired('buildEnd') ? {
|
|
214
|
+
buildEnd: async (...args)=>{
|
|
215
|
+
await Promise.all([
|
|
216
|
+
configA.buildEnd?.(...args),
|
|
217
|
+
configB.buildEnd?.(...args)
|
|
218
|
+
]);
|
|
219
|
+
}
|
|
220
|
+
} : {},
|
|
221
|
+
...mergeRequired('future') ? {
|
|
222
|
+
future: {
|
|
223
|
+
...configA.future,
|
|
224
|
+
...configB.future
|
|
225
|
+
}
|
|
226
|
+
} : {},
|
|
227
|
+
...mergeRequired('presets') ? {
|
|
228
|
+
presets: [
|
|
229
|
+
...configA.presets ?? [],
|
|
230
|
+
...configB.presets ?? []
|
|
231
|
+
]
|
|
232
|
+
} : {}
|
|
233
|
+
};
|
|
234
|
+
}, {}))(...(await Promise.all((reactRouterUserConfig.presets ?? []).map(async (preset)=>{
|
|
235
|
+
if (!preset.name) throw Error('React Router presets must have a `name` property defined.');
|
|
236
|
+
if (!preset.reactRouterConfig) return null;
|
|
237
|
+
let { buildEnd: _buildEnd, ...reactRouterUserConfigForPreset } = reactRouterUserConfig, presetConfig = await preset.reactRouterConfig({
|
|
238
|
+
reactRouterUserConfig: reactRouterUserConfigForPreset
|
|
239
|
+
});
|
|
240
|
+
if (!presetConfig) return null;
|
|
241
|
+
let { presets: _presets, ...rest } = presetConfig;
|
|
242
|
+
return rest;
|
|
243
|
+
}))).filter(Boolean), reactRouterUserConfig), resolvedFuture = {
|
|
244
|
+
...DEFAULT_CONFIG.future,
|
|
245
|
+
...userAndPresetConfigs.future ?? {}
|
|
246
|
+
}, resolved = {
|
|
247
|
+
...DEFAULT_CONFIG,
|
|
248
|
+
...userAndPresetConfigs,
|
|
249
|
+
future: resolvedFuture,
|
|
250
|
+
allowedActionOrigins: userAndPresetConfigs.allowedActionOrigins ?? DEFAULT_CONFIG.allowedActionOrigins,
|
|
251
|
+
routes: DEFAULT_CONFIG.routes,
|
|
252
|
+
unstable_routeConfig: DEFAULT_CONFIG.unstable_routeConfig,
|
|
253
|
+
serverBundles: DEFAULT_CONFIG.serverBundles
|
|
254
|
+
};
|
|
255
|
+
return resolved.ssr || (resolved = {
|
|
256
|
+
...resolved,
|
|
257
|
+
serverBundles: void 0
|
|
258
|
+
}), {
|
|
259
|
+
resolved,
|
|
260
|
+
presets: reactRouterUserConfig.presets ?? []
|
|
261
|
+
};
|
|
262
|
+
}, routeChunkExportNames = [
|
|
263
|
+
'clientAction',
|
|
264
|
+
'clientLoader',
|
|
265
|
+
'clientMiddleware',
|
|
266
|
+
'HydrateFallback'
|
|
267
|
+
];
|
|
268
|
+
[
|
|
269
|
+
...routeChunkExportNames
|
|
270
|
+
];
|
|
271
|
+
let routeChunkQueryStringPrefix = '?route-chunk=', routeChunkQueryStrings = {
|
|
272
|
+
main: `${routeChunkQueryStringPrefix}main`,
|
|
273
|
+
clientAction: `${routeChunkQueryStringPrefix}clientAction`,
|
|
274
|
+
clientLoader: `${routeChunkQueryStringPrefix}clientLoader`,
|
|
275
|
+
clientMiddleware: `${routeChunkQueryStringPrefix}clientMiddleware`,
|
|
276
|
+
HydrateFallback: `${routeChunkQueryStringPrefix}HydrateFallback`
|
|
277
|
+
}, routeChunkEntrySuffix = {
|
|
278
|
+
clientAction: 'client-action',
|
|
279
|
+
clientLoader: 'client-loader',
|
|
280
|
+
clientMiddleware: 'client-middleware',
|
|
281
|
+
HydrateFallback: 'hydrate-fallback'
|
|
282
|
+
}, invariant = (value, message)=>{
|
|
283
|
+
if (!value) throw Error(message);
|
|
284
|
+
}, getOrSetFromCache = (cache, key, version, getValue)=>{
|
|
285
|
+
if (!cache) return getValue();
|
|
286
|
+
let entry = cache.get(key);
|
|
287
|
+
if (entry?.version === version) return entry.value;
|
|
288
|
+
let value = getValue();
|
|
289
|
+
return cache.set(key, {
|
|
290
|
+
value,
|
|
291
|
+
version
|
|
292
|
+
}), value;
|
|
293
|
+
}, codeToAst = (code, cache, cacheKey)=>structuredClone(getOrSetFromCache(cache, `${cacheKey}::codeToAst`, code, ()=>parse(code, {
|
|
294
|
+
sourceType: 'module'
|
|
295
|
+
}))), isNodePathWithNode = (path)=>!(!path || 'object' != typeof path || Array.isArray(path)) && 'node' in path && !!path.node, assertNodePathIsVariableDeclarator = (path)=>{
|
|
296
|
+
invariant(path && !Array.isArray(path) && __rspack_external__babel_types_69e65b52.isVariableDeclarator(path.node), `Expected a VariableDeclarator path, but got ${Array.isArray(path) ? 'an array' : path?.node?.type}`);
|
|
297
|
+
}, assertNodePathIsPattern = (path)=>{
|
|
298
|
+
invariant(path && !Array.isArray(path) && __rspack_external__babel_types_69e65b52.isPattern(path.node), `Expected a Pattern path, but got ${Array.isArray(path) ? 'an array' : path?.node?.type}`);
|
|
299
|
+
}, getExportDependencies = (code, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::getExportDependencies`, code, ()=>{
|
|
300
|
+
let exportDependencies = new Map();
|
|
301
|
+
function handleExport(exportName, exportPath, identifiersPath = exportPath) {
|
|
302
|
+
let identifiers = getDependentIdentifiersForPath(identifiersPath), topLevelStatements = new Set([
|
|
303
|
+
exportPath.node,
|
|
304
|
+
...getTopLevelStatementsForPaths(identifiers)
|
|
305
|
+
]), topLevelNonModuleStatements = new Set(Array.from(topLevelStatements).filter((statement)=>!__rspack_external__babel_types_69e65b52.isImportDeclaration(statement) && !__rspack_external__babel_types_69e65b52.isExportDeclaration(statement))), importedIdentifierNames = new Set();
|
|
306
|
+
for (let identifier of identifiers)__rspack_external__babel_types_69e65b52.isIdentifier(identifier.node) && identifier.parentPath?.parentPath?.isImportDeclaration() && importedIdentifierNames.add(identifier.node.name);
|
|
307
|
+
let exportedVariableDeclarators = new Set();
|
|
308
|
+
for (let identifier of identifiers){
|
|
309
|
+
if (identifier.parentPath?.isVariableDeclarator()) {
|
|
310
|
+
let parentPath = identifier.parentPath;
|
|
311
|
+
if (parentPath.parentPath?.parentPath?.isExportNamedDeclaration()) {
|
|
312
|
+
exportedVariableDeclarators.add(parentPath.node);
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
109
315
|
}
|
|
110
|
-
if ((
|
|
111
|
-
let
|
|
112
|
-
|
|
316
|
+
if (identifier.findParent((path)=>!!(path.isPattern() && path.parentPath?.isVariableDeclarator() && path.parentPath.parentPath?.parentPath?.isExportNamedDeclaration()))) {
|
|
317
|
+
let currentPath = identifier;
|
|
318
|
+
for(; currentPath;){
|
|
319
|
+
if (currentPath.parentPath?.isVariableDeclarator() && 'id' === currentPath.parentKey) {
|
|
320
|
+
exportedVariableDeclarators.add(currentPath.parentPath.node);
|
|
321
|
+
break;
|
|
322
|
+
}
|
|
323
|
+
currentPath = currentPath.parentPath;
|
|
324
|
+
}
|
|
113
325
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
326
|
+
}
|
|
327
|
+
exportDependencies.set(exportName, {
|
|
328
|
+
topLevelStatements,
|
|
329
|
+
topLevelNonModuleStatements,
|
|
330
|
+
importedIdentifierNames,
|
|
331
|
+
exportedVariableDeclarators
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
return traverse(codeToAst(code, cache, cacheKey), {
|
|
335
|
+
ExportDeclaration (exportPath) {
|
|
336
|
+
let { node } = exportPath;
|
|
337
|
+
if (__rspack_external__babel_types_69e65b52.isExportAllDeclaration(node)) return;
|
|
338
|
+
if (__rspack_external__babel_types_69e65b52.isExportDefaultDeclaration(node)) return void handleExport('default', exportPath);
|
|
339
|
+
let { declaration } = node;
|
|
340
|
+
if (__rspack_external__babel_types_69e65b52.isVariableDeclaration(declaration)) {
|
|
341
|
+
let { declarations } = declaration;
|
|
342
|
+
for(let i = 0; i < declarations.length; i++){
|
|
343
|
+
let declarator = declarations[i];
|
|
344
|
+
if (__rspack_external__babel_types_69e65b52.isIdentifier(declarator.id)) {
|
|
345
|
+
let declaratorPath = exportPath.get(`declaration.declarations.${i}`);
|
|
346
|
+
assertNodePathIsVariableDeclarator(declaratorPath), handleExport(declarator.id.name, exportPath, declaratorPath);
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
if (__rspack_external__babel_types_69e65b52.isPattern(declarator.id)) {
|
|
350
|
+
let exportedPatternPath = exportPath.get(`declaration.declarations.${i}.id`);
|
|
351
|
+
for (let identifier of (assertNodePathIsPattern(exportedPatternPath), getIdentifiersForPatternPath(exportedPatternPath)))__rspack_external__babel_types_69e65b52.isIdentifier(identifier.node) && handleExport(identifier.node.name, exportPath, identifier);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (__rspack_external__babel_types_69e65b52.isFunctionDeclaration(declaration) || __rspack_external__babel_types_69e65b52.isClassDeclaration(declaration)) {
|
|
357
|
+
invariant(declaration.id, 'Expected exported function or class declaration to have a name when not the default export'), handleExport(declaration.id.name, exportPath);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (__rspack_external__babel_types_69e65b52.isExportNamedDeclaration(node)) {
|
|
361
|
+
for (let specifier of node.specifiers)if (__rspack_external__babel_types_69e65b52.isIdentifier(specifier.exported)) {
|
|
362
|
+
let name = specifier.exported.name, specifierPath = exportPath.get('specifiers').find((path)=>path.node === specifier);
|
|
363
|
+
invariant(specifierPath, `Expected to find specifier path for ${name}`), handleExport(name, exportPath, specifierPath);
|
|
364
|
+
}
|
|
365
|
+
return;
|
|
117
366
|
}
|
|
367
|
+
throw Error('Unknown export node type');
|
|
368
|
+
}
|
|
369
|
+
}), exportDependencies;
|
|
370
|
+
}), getDependentIdentifiersForPath = (path, state)=>{
|
|
371
|
+
let { visited, identifiers } = state ?? {
|
|
372
|
+
visited: new Set(),
|
|
373
|
+
identifiers: new Set()
|
|
374
|
+
};
|
|
375
|
+
if (visited.has(path)) return identifiers;
|
|
376
|
+
visited.add(path), path.traverse({
|
|
377
|
+
Identifier (pathInner) {
|
|
378
|
+
if (identifiers.has(pathInner)) return;
|
|
379
|
+
identifiers.add(pathInner);
|
|
380
|
+
let binding = pathInner.scope.getBinding(pathInner.node.name);
|
|
381
|
+
if (binding) {
|
|
382
|
+
for (let reference of (getDependentIdentifiersForPath(binding.path, {
|
|
383
|
+
visited,
|
|
384
|
+
identifiers
|
|
385
|
+
}), binding.referencePaths))reference.isExportNamedDeclaration() || getDependentIdentifiersForPath(reference, {
|
|
386
|
+
visited,
|
|
387
|
+
identifiers
|
|
388
|
+
});
|
|
389
|
+
for (let constantViolation of binding.constantViolations)getDependentIdentifiersForPath(constantViolation, {
|
|
390
|
+
visited,
|
|
391
|
+
identifiers
|
|
392
|
+
});
|
|
118
393
|
}
|
|
119
|
-
'ExportDefaultDeclaration' === path.node.type && exportsToRemove.includes('default') && markedForRemoval.add(path);
|
|
120
394
|
}
|
|
121
|
-
})
|
|
122
|
-
|
|
123
|
-
|
|
395
|
+
});
|
|
396
|
+
let topLevelStatement = getTopLevelStatementPathForPath(path), withinImportStatement = topLevelStatement.isImportDeclaration(), withinExportStatement = topLevelStatement.isExportDeclaration();
|
|
397
|
+
if (withinImportStatement || withinExportStatement || getDependentIdentifiersForPath(topLevelStatement, {
|
|
398
|
+
visited,
|
|
399
|
+
identifiers
|
|
400
|
+
}), withinExportStatement && path.isIdentifier() && (__rspack_external__babel_types_69e65b52.isPattern(path.parentPath.node) || __rspack_external__babel_types_69e65b52.isPattern(path.parentPath.parentPath?.node))) {
|
|
401
|
+
let variableDeclarator = path.findParent((p)=>p.isVariableDeclarator());
|
|
402
|
+
variableDeclarator && (invariant(variableDeclarator && !Array.isArray(variableDeclarator), `Expected a Path, but got ${Array.isArray(variableDeclarator) ? 'an array' : variableDeclarator}`), getDependentIdentifiersForPath(variableDeclarator, {
|
|
403
|
+
visited,
|
|
404
|
+
identifiers
|
|
405
|
+
}));
|
|
124
406
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
407
|
+
return identifiers;
|
|
408
|
+
}, getTopLevelStatementPathForPath = (path)=>{
|
|
409
|
+
let ancestry = path.getAncestry(), topLevelStatement = ancestry[ancestry.length - 2];
|
|
410
|
+
return invariant(topLevelStatement && !Array.isArray(topLevelStatement) && __rspack_external__babel_types_69e65b52.isStatement(topLevelStatement.node), `Expected a Statement path, but got ${Array.isArray(topLevelStatement) ? 'an array' : topLevelStatement?.node?.type}`), topLevelStatement;
|
|
411
|
+
}, getTopLevelStatementsForPaths = (paths)=>{
|
|
412
|
+
let topLevelStatements = new Set();
|
|
413
|
+
for (let path of paths){
|
|
414
|
+
let topLevelStatement = getTopLevelStatementPathForPath(path);
|
|
415
|
+
topLevelStatements.add(topLevelStatement.node);
|
|
133
416
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
417
|
+
return topLevelStatements;
|
|
418
|
+
}, getIdentifiersForPatternPath = (patternPath, identifiers = new Set())=>(!function walk(currentPath) {
|
|
419
|
+
if (currentPath.isIdentifier()) return void identifiers.add(currentPath);
|
|
420
|
+
if (currentPath.isObjectPattern()) {
|
|
421
|
+
let { properties } = currentPath.node;
|
|
422
|
+
for(let i = 0; i < properties.length; i++){
|
|
423
|
+
let property = properties[i];
|
|
424
|
+
if (__rspack_external__babel_types_69e65b52.isObjectProperty(property)) {
|
|
425
|
+
let valuePath = currentPath.get(`properties.${i}.value`);
|
|
426
|
+
isNodePathWithNode(valuePath) && walk(valuePath);
|
|
427
|
+
} else if (__rspack_external__babel_types_69e65b52.isRestElement(property)) {
|
|
428
|
+
let argumentPath = currentPath.get(`properties.${i}.argument`);
|
|
429
|
+
isNodePathWithNode(argumentPath) && walk(argumentPath);
|
|
143
430
|
}
|
|
144
|
-
return;
|
|
145
431
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if (!expr || !id.isIdentifier()) return;
|
|
152
|
-
let { name } = id.node;
|
|
153
|
-
if (!isNamedComponentExport(name)) return;
|
|
154
|
-
let uid = getHocUid(path, `with${name}Props`);
|
|
155
|
-
init.replaceWith(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.callExpression(uid, [
|
|
156
|
-
expr
|
|
157
|
-
]));
|
|
158
|
-
});
|
|
159
|
-
return;
|
|
160
|
-
}
|
|
161
|
-
if (decl.isFunctionDeclaration()) {
|
|
162
|
-
let { id } = decl.node;
|
|
163
|
-
if (!id) return;
|
|
164
|
-
let { name } = id;
|
|
165
|
-
if (!isNamedComponentExport(name)) return;
|
|
166
|
-
let uid = getHocUid(path, `with${name}Props`);
|
|
167
|
-
decl.replaceWith(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.variableDeclaration('const', [
|
|
168
|
-
__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.variableDeclarator(__WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.identifier(name), __WEBPACK_EXTERNAL_MODULE__babel_types_69e65b52__.callExpression(uid, [
|
|
169
|
-
toFunctionExpression(decl.node)
|
|
170
|
-
]))
|
|
171
|
-
]));
|
|
172
|
-
}
|
|
432
|
+
} else if (currentPath.isArrayPattern()) {
|
|
433
|
+
let { elements } = currentPath.node;
|
|
434
|
+
for(let i = 0; i < elements.length; i++)if (elements[i]) {
|
|
435
|
+
let elementPath = currentPath.get(`elements.${i}`);
|
|
436
|
+
isNodePathWithNode(elementPath) && walk(elementPath);
|
|
173
437
|
}
|
|
438
|
+
} else if (currentPath.isRestElement()) {
|
|
439
|
+
let argumentPath = currentPath.get('argument');
|
|
440
|
+
isNodePathWithNode(argumentPath) && walk(argumentPath);
|
|
174
441
|
}
|
|
175
|
-
}),
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
return
|
|
442
|
+
}(patternPath), identifiers), getExportedName = (exported)=>__rspack_external__babel_types_69e65b52.isIdentifier(exported) ? exported.name : exported.value, setsIntersect = (set1, set2)=>{
|
|
443
|
+
let smallerSet = set1, largerSet = set2;
|
|
444
|
+
for (let element of (set1.size > set2.size && (smallerSet = set2, largerSet = set1), smallerSet))if (largerSet.has(element)) return !0;
|
|
445
|
+
return !1;
|
|
446
|
+
}, hasChunkableExport = (code, exportName, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::hasChunkableExport::${exportName}`, code, ()=>{
|
|
447
|
+
let exportDependencies = getExportDependencies(code, cache, cacheKey), dependencies = exportDependencies.get(exportName);
|
|
448
|
+
if (!dependencies) return !1;
|
|
449
|
+
for (let [currentExportName, currentDependencies] of exportDependencies)if (currentExportName !== exportName && setsIntersect(currentDependencies.topLevelNonModuleStatements, dependencies.topLevelNonModuleStatements)) return !1;
|
|
450
|
+
if (dependencies.exportedVariableDeclarators.size > 1) return !1;
|
|
451
|
+
if (dependencies.exportedVariableDeclarators.size > 0) {
|
|
452
|
+
for (let [currentExportName, currentDependencies] of exportDependencies)if (currentExportName !== exportName && setsIntersect(currentDependencies.exportedVariableDeclarators, dependencies.exportedVariableDeclarators)) return !1;
|
|
453
|
+
}
|
|
454
|
+
return !0;
|
|
455
|
+
}), getRouteChunkModuleId = (filePath, chunkName)=>`${filePath}${routeChunkQueryStrings[chunkName]}`, normalizeRelativeFilePath = (file, appDirectory)=>{
|
|
456
|
+
let fullPath = resolve(appDirectory, file);
|
|
457
|
+
return normalize(relative(appDirectory, fullPath)).split('?')[0];
|
|
458
|
+
}, isRootRouteModuleId = (config, id)=>normalizeRelativeFilePath(id, config.appDirectory) === config.rootRouteFile, detectRouteChunksIfEnabled = async (cache, config, id, code)=>{
|
|
459
|
+
let hasRouteChunkByExportName, chunkedExports;
|
|
460
|
+
if (!config.splitRouteModules || isRootRouteModuleId(config, id) || !routeChunkExportNames.some((exportName)=>code.includes(exportName))) return {
|
|
461
|
+
chunkedExports: [],
|
|
462
|
+
hasRouteChunks: !1,
|
|
463
|
+
hasRouteChunkByExportName: {
|
|
464
|
+
clientAction: !1,
|
|
465
|
+
clientLoader: !1,
|
|
466
|
+
clientMiddleware: !1,
|
|
467
|
+
HydrateFallback: !1
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
let cacheKey = normalizeRelativeFilePath(id, config.appDirectory);
|
|
471
|
+
return {
|
|
472
|
+
hasRouteChunks: (chunkedExports = Object.entries(hasRouteChunkByExportName = Object.fromEntries(routeChunkExportNames.map((exportName)=>[
|
|
473
|
+
exportName,
|
|
474
|
+
hasChunkableExport(code, exportName, cache, cacheKey)
|
|
475
|
+
]))).filter(([, isChunked])=>isChunked).map(([exportName])=>exportName)).length > 0,
|
|
476
|
+
hasRouteChunkByExportName,
|
|
477
|
+
chunkedExports
|
|
478
|
+
};
|
|
479
|
+
}, getRouteChunkIfEnabled = async (cache, config, id, chunkName, code)=>{
|
|
480
|
+
if (!config.splitRouteModules) return null;
|
|
481
|
+
let cacheKey = normalizeRelativeFilePath(id, config.appDirectory);
|
|
482
|
+
return ('main' === chunkName ? ((code, exportNames, generateOptions = {}, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::omitChunkedExports::${exportNames.join(',')}::${JSON.stringify(generateOptions)}`, code, ()=>{
|
|
483
|
+
let isOmitted = (exportName)=>exportNames.includes(exportName) && hasChunkableExport(code, exportName, cache, cacheKey), exportDependencies = getExportDependencies(code, cache, cacheKey), allExportNames = Array.from(exportDependencies.keys()), omittedExportNames = allExportNames.filter(isOmitted), retainedExportNames = allExportNames.filter((exportName)=>!isOmitted(exportName)), omittedStatements = new Set(), omittedExportedVariableDeclarators = new Set();
|
|
484
|
+
for (let omittedExportName of omittedExportNames){
|
|
485
|
+
let dependencies = exportDependencies.get(omittedExportName);
|
|
486
|
+
for (let statement of (invariant(dependencies, `Expected dependencies for ${omittedExportName}`), dependencies.topLevelNonModuleStatements))omittedStatements.add(statement);
|
|
487
|
+
for (let declarator of dependencies.exportedVariableDeclarators)omittedExportedVariableDeclarators.add(declarator);
|
|
488
|
+
}
|
|
489
|
+
let ast = codeToAst(code, cache, cacheKey), omittedStatementsArray = Array.from(omittedStatements), omittedExportedVariableDeclaratorsArray = Array.from(omittedExportedVariableDeclarators);
|
|
490
|
+
if (ast.program.body = ast.program.body.filter((node)=>omittedStatementsArray.every((statement)=>!__rspack_external__babel_types_69e65b52.isNodesEquivalent(node, statement))).map((node)=>__rspack_external__babel_types_69e65b52.isImportDeclaration(node) && 0 !== node.specifiers.length && (node.specifiers = node.specifiers.filter((specifier)=>{
|
|
491
|
+
let importedName = specifier.local.name;
|
|
492
|
+
for (let retainedExportName of retainedExportNames){
|
|
493
|
+
let dependencies = exportDependencies.get(retainedExportName);
|
|
494
|
+
if (dependencies?.importedIdentifierNames?.has(importedName)) return !0;
|
|
495
|
+
}
|
|
496
|
+
for (let omittedExportName of omittedExportNames){
|
|
497
|
+
let dependencies = exportDependencies.get(omittedExportName);
|
|
498
|
+
if (dependencies?.importedIdentifierNames?.has(importedName)) return !1;
|
|
499
|
+
}
|
|
500
|
+
return !0;
|
|
501
|
+
}), 0 === node.specifiers.length) ? null : node).map((node)=>{
|
|
502
|
+
if (!__rspack_external__babel_types_69e65b52.isExportDeclaration(node) || __rspack_external__babel_types_69e65b52.isExportAllDeclaration(node)) return node;
|
|
503
|
+
if (__rspack_external__babel_types_69e65b52.isExportDefaultDeclaration(node)) return isOmitted('default') ? null : node;
|
|
504
|
+
if (__rspack_external__babel_types_69e65b52.isVariableDeclaration(node.declaration)) return (node.declaration.declarations = node.declaration.declarations.filter((declarationNode)=>omittedExportedVariableDeclaratorsArray.every((declarator)=>!__rspack_external__babel_types_69e65b52.isNodesEquivalent(declarationNode, declarator))), 0 === node.declaration.declarations.length) ? null : node;
|
|
505
|
+
if (__rspack_external__babel_types_69e65b52.isFunctionDeclaration(node.declaration) || __rspack_external__babel_types_69e65b52.isClassDeclaration(node.declaration)) {
|
|
506
|
+
let declarationId = node.declaration.id;
|
|
507
|
+
return invariant(declarationId, 'Expected exported function or class declaration to have a name when not the default export'), isOmitted(declarationId.name) ? null : node;
|
|
508
|
+
}
|
|
509
|
+
if (__rspack_external__babel_types_69e65b52.isExportNamedDeclaration(node)) return 0 === node.specifiers.length ? node : (node.specifiers = node.specifiers.filter((specifier)=>!isOmitted(getExportedName(specifier.exported))), 0 === node.specifiers.length) ? null : node;
|
|
510
|
+
throw Error('Unknown node type');
|
|
511
|
+
}).filter(Boolean), 0 !== ast.program.body.length) return generate(ast, generateOptions).code;
|
|
512
|
+
}))(code, routeChunkExportNames, {}, cache, cacheKey) : ((code, exportName, generateOptions = {}, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::getChunkedExport::${exportName}::${JSON.stringify(generateOptions)}`, code, ()=>{
|
|
513
|
+
if (!hasChunkableExport(code, exportName, cache, cacheKey)) return;
|
|
514
|
+
let dependencies = getExportDependencies(code, cache, cacheKey).get(exportName);
|
|
515
|
+
invariant(dependencies, 'Expected export to have dependencies');
|
|
516
|
+
let topLevelStatementsArray = Array.from(dependencies.topLevelStatements), exportedVariableDeclaratorsArray = Array.from(dependencies.exportedVariableDeclarators), ast = codeToAst(code, cache, cacheKey);
|
|
517
|
+
return ast.program.body = ast.program.body.filter((node)=>topLevelStatementsArray.some((statement)=>__rspack_external__babel_types_69e65b52.isNodesEquivalent(node, statement))).map((node)=>__rspack_external__babel_types_69e65b52.isImportDeclaration(node) ? 0 === dependencies.importedIdentifierNames.size ? null : (node.specifiers = node.specifiers.filter((specifier)=>dependencies.importedIdentifierNames.has(specifier.local.name)), invariant(node.specifiers.length > 0, 'Expected import statement to have used specifiers'), node) : node).map((node)=>{
|
|
518
|
+
if (!__rspack_external__babel_types_69e65b52.isExportDeclaration(node)) return node;
|
|
519
|
+
if (__rspack_external__babel_types_69e65b52.isExportAllDeclaration(node)) return null;
|
|
520
|
+
if (__rspack_external__babel_types_69e65b52.isExportDefaultDeclaration(node)) return 'default' === exportName ? node : null;
|
|
521
|
+
let { declaration } = node;
|
|
522
|
+
if (__rspack_external__babel_types_69e65b52.isVariableDeclaration(declaration)) return (declaration.declarations = declaration.declarations.filter((declarationNode)=>exportedVariableDeclaratorsArray.some((declarator)=>__rspack_external__babel_types_69e65b52.isNodesEquivalent(declarationNode, declarator))), 0 === declaration.declarations.length) ? null : node;
|
|
523
|
+
if (__rspack_external__babel_types_69e65b52.isFunctionDeclaration(node.declaration) || __rspack_external__babel_types_69e65b52.isClassDeclaration(node.declaration)) return node.declaration.id?.name === exportName ? node : null;
|
|
524
|
+
if (__rspack_external__babel_types_69e65b52.isExportNamedDeclaration(node)) return 0 === node.specifiers.length || (node.specifiers = node.specifiers.filter((specifier)=>getExportedName(specifier.exported) === exportName), 0 === node.specifiers.length) ? null : node;
|
|
525
|
+
throw Error('Unknown export node type');
|
|
526
|
+
}).filter(Boolean), generate(ast, generateOptions).code;
|
|
527
|
+
}))(code, chunkName, {}, cache, cacheKey)) ?? null;
|
|
528
|
+
}, validateRouteChunks = ({ config, id, valid })=>{
|
|
529
|
+
if (isRootRouteModuleId(config, id)) return;
|
|
530
|
+
let invalidChunks = Object.entries(valid).filter(([, isValid])=>!isValid).map(([chunkName])=>chunkName);
|
|
531
|
+
if (0 === invalidChunks.length) return;
|
|
532
|
+
let plural = invalidChunks.length > 1;
|
|
533
|
+
throw Error([
|
|
534
|
+
`Error splitting route module: ${normalizeRelativeFilePath(id, config.appDirectory)}`,
|
|
535
|
+
invalidChunks.map((name)=>`- ${name}`).join('\n'),
|
|
536
|
+
`${plural ? 'These exports' : 'This export'} could not be split into ${plural ? 'their own chunks' : 'its own chunk'} because ${plural ? 'they share' : 'it shares'} code with other exports. You should extract any shared code into its own module and then import it within the route module.`
|
|
537
|
+
].join('\n\n'));
|
|
538
|
+
}, getRouteChunkEntryName = (routeId, chunkName)=>`${routeId}-${routeChunkEntrySuffix[chunkName]}`;
|
|
539
|
+
(A = ImportType || (ImportType = {}))[A.Static = 1] = "Static", A[A.Dynamic = 2] = "Dynamic", A[A.ImportMeta = 3] = "ImportMeta", A[A.StaticSourcePhase = 4] = "StaticSourcePhase", A[A.DynamicSourcePhase = 5] = "DynamicSourcePhase", A[A.StaticDeferPhase = 6] = "StaticDeferPhase", A[A.DynamicDeferPhase = 7] = "DynamicDeferPhase";
|
|
540
|
+
let lexer_A = 1 === new Uint8Array(new Uint16Array([
|
|
541
|
+
1
|
|
542
|
+
]).buffer)[0];
|
|
543
|
+
function lexer_parse(E, g = "@") {
|
|
544
|
+
if (!lexer_C) return lexer_init.then(()=>lexer_parse(E));
|
|
545
|
+
let I = E.length + 1, w = (lexer_C.__heap_base.value || lexer_C.__heap_base) + 4 * I - lexer_C.memory.buffer.byteLength;
|
|
546
|
+
w > 0 && lexer_C.memory.grow(Math.ceil(w / 65536));
|
|
547
|
+
let K = lexer_C.sa(I - 1);
|
|
548
|
+
if ((lexer_A ? function(A, Q) {
|
|
549
|
+
let B = A.length, C = 0;
|
|
550
|
+
for(; C < B;)Q[C] = A.charCodeAt(C++);
|
|
551
|
+
} : function(A, Q) {
|
|
552
|
+
let B = A.length, C = 0;
|
|
553
|
+
for(; C < B;){
|
|
554
|
+
let B = A.charCodeAt(C);
|
|
555
|
+
Q[C++] = (255 & B) << 8 | B >>> 8;
|
|
556
|
+
}
|
|
557
|
+
})(E, new Uint16Array(lexer_C.memory.buffer, K, I)), !lexer_C.parse()) throw Object.assign(Error(`Parse error ${g}:${E.slice(0, lexer_C.e()).split("\n").length}:${lexer_C.e() - E.lastIndexOf("\n", lexer_C.e() - 1)}`), {
|
|
558
|
+
idx: lexer_C.e()
|
|
559
|
+
});
|
|
560
|
+
let o = [], D = [];
|
|
561
|
+
for(; lexer_C.ri();){
|
|
562
|
+
let D, A = lexer_C.is(), Q = lexer_C.ie(), B = lexer_C.it(), g = lexer_C.ai(), I = lexer_C.id(), w = lexer_C.ss(), K = lexer_C.se();
|
|
563
|
+
lexer_C.ip() && (D = k(E.slice(-1 === I ? A - 1 : A, -1 === I ? Q + 1 : Q))), o.push({
|
|
564
|
+
n: D,
|
|
565
|
+
t: B,
|
|
566
|
+
s: A,
|
|
567
|
+
e: Q,
|
|
568
|
+
ss: w,
|
|
569
|
+
se: K,
|
|
570
|
+
d: I,
|
|
571
|
+
a: g
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
for(; lexer_C.re();){
|
|
575
|
+
let A = lexer_C.es(), Q = lexer_C.ee(), B = lexer_C.els(), g = lexer_C.ele(), I = E.slice(A, Q), w = I[0], K = B < 0 ? void 0 : E.slice(B, g), o = K ? K[0] : "";
|
|
576
|
+
D.push({
|
|
577
|
+
s: A,
|
|
578
|
+
e: Q,
|
|
579
|
+
ls: B,
|
|
580
|
+
le: g,
|
|
581
|
+
n: '"' === w || "'" === w ? k(I) : I,
|
|
582
|
+
ln: '"' === o || "'" === o ? k(K) : K
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
function k(A) {
|
|
586
|
+
try {
|
|
587
|
+
return (0, eval)(A);
|
|
588
|
+
} catch (A) {}
|
|
589
|
+
}
|
|
590
|
+
return [
|
|
591
|
+
o,
|
|
592
|
+
D,
|
|
593
|
+
!!lexer_C.f(),
|
|
594
|
+
!!lexer_C.ms()
|
|
595
|
+
];
|
|
179
596
|
}
|
|
180
|
-
async function getReactRouterManifestForDev(routes, options, clientStats, context) {
|
|
181
|
-
|
|
182
|
-
|
|
597
|
+
let lexer_init = WebAssembly.compile((A1 = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgIC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BuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "u" > typeof Buffer ? Buffer.from(A1, "base64") : Uint8Array.from(atob(A1), (A)=>A.charCodeAt(0)))).then(WebAssembly.instantiate).then(({ exports: A })=>{
|
|
598
|
+
lexer_C = A;
|
|
599
|
+
}), transformToEsm = async (code, resourcePath)=>(await transform(code, {
|
|
600
|
+
jsx: 'automatic',
|
|
601
|
+
format: 'esm',
|
|
602
|
+
platform: 'neutral',
|
|
603
|
+
loader: JS_LOADERS[extname(resourcePath)] ?? 'js'
|
|
604
|
+
})).code, getExportNames = async (code)=>{
|
|
605
|
+
await lexer_init;
|
|
606
|
+
let [, exportSpecifiers] = await lexer_parse(code);
|
|
607
|
+
return Array.from(new Set(exportSpecifiers.map((specifier)=>specifier.n).filter(Boolean)));
|
|
608
|
+
}, getExportNamesAndExportAll = async (code)=>{
|
|
609
|
+
await lexer_init;
|
|
610
|
+
let [imports, exportSpecifiers] = await lexer_parse(code), exportNames = new Set();
|
|
611
|
+
for (let specifier of exportSpecifiers)specifier.n && exportNames.add(specifier.n);
|
|
612
|
+
let exportAllModules = [];
|
|
613
|
+
for (let entry of imports){
|
|
614
|
+
if (!entry.n) continue;
|
|
615
|
+
let statement = code.slice(entry.ss, entry.se);
|
|
616
|
+
/^\s*export\s*\*\s*from\s*['"]/.test(statement) && exportAllModules.push(entry.n);
|
|
617
|
+
}
|
|
618
|
+
return {
|
|
619
|
+
exportNames: Array.from(exportNames),
|
|
620
|
+
exportAllModules
|
|
621
|
+
};
|
|
622
|
+
}, getRouteModuleExports = async (resourcePath)=>{
|
|
623
|
+
let source = await readFile(resourcePath, 'utf8');
|
|
624
|
+
return getExportNames(await transformToEsm(source, resourcePath));
|
|
625
|
+
}, DEFAULT_MANIFEST_DIR = 'static/js', getReactRouterManifestPath = ({ version, isBuild, entryModulePath })=>{
|
|
626
|
+
if (!isBuild) return 'static/js/virtual/react-router/browser-manifest.js';
|
|
627
|
+
let dir = ((entryModulePath)=>{
|
|
628
|
+
if (!entryModulePath) return DEFAULT_MANIFEST_DIR;
|
|
629
|
+
let dir = dirname(entryModulePath);
|
|
630
|
+
return '.' === dir ? DEFAULT_MANIFEST_DIR : dir;
|
|
631
|
+
})(entryModulePath);
|
|
632
|
+
return `${dir}/manifest-${version}.js`;
|
|
633
|
+
};
|
|
634
|
+
async function getReactRouterManifestForDev(routes, options, clientStats, context, assetPrefix = '/', routeChunkOptions) {
|
|
635
|
+
let result = {}, splitRouteModules = routeChunkOptions?.splitRouteModules ?? !1, enforceSplitRouteModules = 'enforce' === splitRouteModules, isBuild = routeChunkOptions?.isBuild ?? !1, routeChunkConfig = splitRouteModules && routeChunkOptions?.rootRouteFile ? {
|
|
636
|
+
splitRouteModules,
|
|
637
|
+
appDirectory: context,
|
|
638
|
+
rootRouteFile: routeChunkOptions.rootRouteFile
|
|
639
|
+
} : null, getAssetsForChunk = (chunkName)=>{
|
|
640
|
+
let assets = clientStats?.assetsByChunkName?.[chunkName];
|
|
641
|
+
return assets ? Array.isArray(assets) ? assets : [
|
|
642
|
+
assets
|
|
643
|
+
] : [];
|
|
644
|
+
}, getModulePathForChunk = (chunkName)=>{
|
|
645
|
+
let jsAssets = getAssetsForChunk(chunkName).filter((asset)=>asset.endsWith('.js'));
|
|
646
|
+
return jsAssets[0] ? combineURLs(assetPrefix, jsAssets[0]) : void 0;
|
|
647
|
+
};
|
|
183
648
|
for (let [key, route] of Object.entries(routes)){
|
|
184
|
-
let assets =
|
|
649
|
+
let assets = getAssetsForChunk(route.id), jsAssets = assets.filter((asset)=>asset.endsWith('.js')) || [], cssAssets = assets.filter((asset)=>asset.endsWith('.css')) || [], routeFilePath = resolve(context, route.file), exports = new Set(), hasRouteChunkByExportName = {
|
|
650
|
+
clientAction: !1,
|
|
651
|
+
clientLoader: !1,
|
|
652
|
+
clientMiddleware: !1,
|
|
653
|
+
HydrateFallback: !1
|
|
654
|
+
};
|
|
185
655
|
try {
|
|
186
|
-
let
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
write: !1,
|
|
192
|
-
metafile: !0,
|
|
193
|
-
jsx: 'automatic',
|
|
194
|
-
format: 'esm',
|
|
195
|
-
platform: 'neutral',
|
|
196
|
-
loader: JS_LOADERS
|
|
197
|
-
}), entryPoint = Object.values(buildResult.metafile.outputs)[0];
|
|
198
|
-
(null == entryPoint ? void 0 : entryPoint.exports) && (exports = new Set(entryPoint.exports));
|
|
656
|
+
let source = await readFile(routeFilePath, 'utf8'), code = await transformToEsm(source, routeFilePath);
|
|
657
|
+
if (exports = new Set(await getExportNames(code)), isBuild && routeChunkConfig) {
|
|
658
|
+
let { hasRouteChunkByExportName: chunkInfo } = await detectRouteChunksIfEnabled(routeChunkOptions?.cache, routeChunkConfig, routeFilePath, code);
|
|
659
|
+
hasRouteChunkByExportName = chunkInfo;
|
|
660
|
+
}
|
|
199
661
|
} catch (error) {
|
|
200
662
|
console.error(`Failed to analyze route file ${routeFilePath}:`, error);
|
|
201
663
|
}
|
|
202
|
-
|
|
664
|
+
let hasClientAction = exports.has('clientAction'), hasClientLoader = exports.has('clientLoader'), hasClientMiddleware = exports.has('clientMiddleware'), hasHydrateFallback = exports.has('HydrateFallback'), hasDefaultExport = exports.has('default');
|
|
665
|
+
isBuild && enforceSplitRouteModules && routeChunkConfig && validateRouteChunks({
|
|
666
|
+
config: routeChunkConfig,
|
|
667
|
+
id: routeFilePath,
|
|
668
|
+
valid: {
|
|
669
|
+
clientAction: !hasClientAction || hasRouteChunkByExportName.clientAction,
|
|
670
|
+
clientLoader: !hasClientLoader || hasRouteChunkByExportName.clientLoader,
|
|
671
|
+
clientMiddleware: !hasClientMiddleware || hasRouteChunkByExportName.clientMiddleware,
|
|
672
|
+
HydrateFallback: !hasHydrateFallback || hasRouteChunkByExportName.HydrateFallback
|
|
673
|
+
}
|
|
674
|
+
}), result[key] = {
|
|
203
675
|
id: route.id,
|
|
204
676
|
parentId: route.parentId,
|
|
205
677
|
path: route.path,
|
|
206
678
|
index: route.index,
|
|
207
679
|
caseSensitive: route.caseSensitive,
|
|
208
|
-
module: combineURLs(
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
680
|
+
module: combineURLs(assetPrefix, jsAssets[0] || ''),
|
|
681
|
+
clientActionModule: isBuild && hasRouteChunkByExportName.clientAction ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'clientAction')) : void 0,
|
|
682
|
+
clientLoaderModule: isBuild && hasRouteChunkByExportName.clientLoader ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'clientLoader')) : void 0,
|
|
683
|
+
clientMiddlewareModule: isBuild && hasRouteChunkByExportName.clientMiddleware ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'clientMiddleware')) : void 0,
|
|
684
|
+
hydrateFallbackModule: isBuild && hasRouteChunkByExportName.HydrateFallback ? getModulePathForChunk(getRouteChunkEntryName(route.id, 'HydrateFallback')) : void 0,
|
|
685
|
+
hasAction: exports.has('action'),
|
|
686
|
+
hasLoader: exports.has('loader'),
|
|
687
|
+
hasClientAction,
|
|
688
|
+
hasClientLoader,
|
|
689
|
+
hasClientMiddleware,
|
|
690
|
+
hasDefaultExport,
|
|
691
|
+
hasErrorBoundary: exports.has('ErrorBoundary'),
|
|
692
|
+
imports: jsAssets.map((asset)=>combineURLs(assetPrefix, asset)),
|
|
693
|
+
css: cssAssets.map((asset)=>combineURLs(assetPrefix, asset))
|
|
216
694
|
};
|
|
217
695
|
}
|
|
218
|
-
let entryAssets =
|
|
219
|
-
return {
|
|
220
|
-
version: String(Math.random()),
|
|
221
|
-
url: '/static/js/virtual/react-router/browser-manifest.js',
|
|
696
|
+
let entryAssets = clientStats?.assetsByChunkName?.['entry.client'], entryJsAssets = entryAssets?.filter((asset)=>asset.endsWith('.js')) || [], entryCssAssets = entryAssets?.filter((asset)=>asset.endsWith('.css')) || [], fingerprintedValues = {
|
|
222
697
|
entry: {
|
|
223
|
-
module: combineURLs(
|
|
224
|
-
imports: entryJsAssets.map((asset)=>combineURLs(
|
|
225
|
-
css: entryCssAssets.map((asset)=>combineURLs(
|
|
698
|
+
module: combineURLs(assetPrefix, entryJsAssets[0] || ''),
|
|
699
|
+
imports: entryJsAssets.map((asset)=>combineURLs(assetPrefix, asset)),
|
|
700
|
+
css: entryCssAssets.map((asset)=>combineURLs(assetPrefix, asset))
|
|
226
701
|
},
|
|
227
702
|
routes: result
|
|
703
|
+
}, version = isBuild ? createHash('md5').update(JSON.stringify(fingerprintedValues)).digest('hex').slice(0, 8) : String(Math.random()), manifestPath = getReactRouterManifestPath({
|
|
704
|
+
version,
|
|
705
|
+
isBuild,
|
|
706
|
+
entryModulePath: entryJsAssets[0]
|
|
707
|
+
});
|
|
708
|
+
return {
|
|
709
|
+
version,
|
|
710
|
+
url: combineURLs(assetPrefix, manifestPath),
|
|
711
|
+
hmr: void 0,
|
|
712
|
+
entry: fingerprintedValues.entry,
|
|
713
|
+
sri: void 0,
|
|
714
|
+
routes: result
|
|
228
715
|
};
|
|
229
716
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
plugins: [
|
|
237
|
-
"typescript",
|
|
238
|
-
'jsx'
|
|
239
|
-
]
|
|
240
|
-
});
|
|
241
|
-
args.environment && 'web' === args.environment.name && removeExports(ast, [
|
|
242
|
-
...SERVER_ONLY_ROUTE_EXPORTS
|
|
243
|
-
]), transformRoute(ast);
|
|
244
|
-
let transformedCode = generate(ast, {
|
|
245
|
-
sourceMaps: !0,
|
|
246
|
-
filename: args.resource,
|
|
247
|
-
sourceFileName: args.resourcePath,
|
|
248
|
-
retainLines: !0,
|
|
249
|
-
compact: !1,
|
|
250
|
-
concise: !1
|
|
251
|
-
}).code, output = (await __WEBPACK_EXTERNAL_MODULE_esbuild__.build({
|
|
252
|
-
bundle: !1,
|
|
253
|
-
write: !1,
|
|
254
|
-
metafile: !0,
|
|
255
|
-
jsx: 'automatic',
|
|
256
|
-
format: 'esm',
|
|
257
|
-
platform: 'neutral',
|
|
258
|
-
loader: {
|
|
259
|
-
'.ts': 'ts',
|
|
260
|
-
'.tsx': 'tsx'
|
|
261
|
-
},
|
|
262
|
-
stdin: {
|
|
263
|
-
contents: transformedCode,
|
|
264
|
-
resolveDir: args.context || void 0,
|
|
265
|
-
sourcefile: args.resourcePath
|
|
266
|
-
}
|
|
267
|
-
})).metafile.outputs['stdin.js'];
|
|
268
|
-
return (null === (_args_environment = args.environment) || void 0 === _args_environment ? void 0 : _args_environment.name) === 'node' ? `
|
|
269
|
-
let cache;
|
|
270
|
-
const loadRoute = async (exportName)=>{
|
|
271
|
-
if(cache !== undefined) {
|
|
272
|
-
return cache[exportName];
|
|
273
|
-
}
|
|
274
|
-
let exp = await import('${args.resourcePath}?react-router-route');
|
|
275
|
-
cache = exp;
|
|
276
|
-
return exp[exportName]
|
|
717
|
+
let isPlainObject = (value)=>'object' == typeof value && null !== value, validateEntry = (entry, path, issues)=>isPlainObject(entry) && 'then' in entry && 'catch' in entry ? (issues.push(`${path}\nInvalid type: Expected object but received a promise. Did you forget to await?`), !1) : isPlainObject(entry) ? ('string' != typeof entry.file && issues.push(`${path}.file\nInvalid type: Expected string.`), 'id' in entry && 'root' === entry.id && issues.push(`${path}.id\nA route cannot use the reserved id 'root'.`), 'path' in entry && void 0 !== entry.path && 'string' != typeof entry.path && issues.push(`${path}.path\nInvalid type: Expected string.`), 'index' in entry && void 0 !== entry.index && 'boolean' != typeof entry.index && issues.push(`${path}.index\nInvalid type: Expected boolean.`), 'caseSensitive' in entry && void 0 !== entry.caseSensitive && 'boolean' != typeof entry.caseSensitive && issues.push(`${path}.caseSensitive\nInvalid type: Expected boolean.`), 'children' in entry && void 0 !== entry.children && (Array.isArray(entry.children) ? entry.children.forEach((child, index)=>validateEntry(child, `${path}.children.${index}`, issues)) : issues.push(`${path}.children\nInvalid type: Expected array.`)), 0 === issues.length) : (issues.push(`${path}\nInvalid type: Expected object.`), !1), getRouteBranch = (routes, routeId)=>{
|
|
718
|
+
let branch = [], current = routeId;
|
|
719
|
+
for(; current;){
|
|
720
|
+
let route = routes[current];
|
|
721
|
+
if (!route) throw Error(`Missing route for ${current}`);
|
|
722
|
+
branch.push(route), current = route.parentId || '';
|
|
277
723
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
724
|
+
return branch.reverse();
|
|
725
|
+
}, getBuildManifest = async ({ reactRouterConfig, routes, rootDirectory })=>{
|
|
726
|
+
let { serverBundles, appDirectory, buildDirectory, serverBuildFile, future } = reactRouterConfig;
|
|
727
|
+
if (!serverBundles) return {
|
|
728
|
+
routes
|
|
729
|
+
};
|
|
730
|
+
let rootRelativeRoutes = Object.fromEntries(Object.entries(routes).map(([id, route])=>{
|
|
731
|
+
let filePath = resolve(appDirectory, route.file);
|
|
732
|
+
return [
|
|
733
|
+
id,
|
|
734
|
+
{
|
|
735
|
+
...route,
|
|
736
|
+
file: relative(rootDirectory, filePath).replace(/\\/g, '/')
|
|
737
|
+
}
|
|
738
|
+
];
|
|
739
|
+
})), serverBuildDirectory = resolve(buildDirectory, 'server'), buildManifest = {
|
|
740
|
+
routes: rootRelativeRoutes,
|
|
741
|
+
serverBundles: {},
|
|
742
|
+
routeIdToServerBundleId: {}
|
|
743
|
+
};
|
|
744
|
+
return await Promise.all(((routes)=>{
|
|
745
|
+
let nonAddressableIds = new Set();
|
|
746
|
+
for(let id in routes){
|
|
747
|
+
let route = routes[id];
|
|
748
|
+
if (route.index) {
|
|
749
|
+
if (!route.parentId) continue;
|
|
750
|
+
nonAddressableIds.add(route.parentId);
|
|
751
|
+
}
|
|
752
|
+
'string' == typeof route.path || route.index || nonAddressableIds.add(id);
|
|
753
|
+
}
|
|
754
|
+
return Object.values(routes).filter((route)=>!nonAddressableIds.has(route.id));
|
|
755
|
+
})(routes).map(async (route)=>{
|
|
756
|
+
let branch = getRouteBranch(routes, route.id), serverBundleId = await serverBundles({
|
|
757
|
+
branch: branch.map((branchRoute)=>{
|
|
758
|
+
let route;
|
|
759
|
+
return {
|
|
760
|
+
id: (route = {
|
|
761
|
+
...branchRoute,
|
|
762
|
+
file: resolve(appDirectory, branchRoute.file)
|
|
763
|
+
}).id,
|
|
764
|
+
path: route.path,
|
|
765
|
+
file: route.file,
|
|
766
|
+
index: route.index
|
|
767
|
+
};
|
|
768
|
+
})
|
|
769
|
+
});
|
|
770
|
+
if ('string' != typeof serverBundleId) throw Error('The "serverBundles" function must return a string');
|
|
771
|
+
if (future?.v8_viteEnvironmentApi) {
|
|
772
|
+
if (!/^[a-zA-Z0-9_]+$/.test(serverBundleId)) throw Error('The "serverBundles" function must only return strings containing alphanumeric characters and underscores.');
|
|
773
|
+
} else if (!/^[a-zA-Z0-9-_]+$/.test(serverBundleId)) throw Error('The "serverBundles" function must only return strings containing alphanumeric characters, hyphens and underscores.');
|
|
774
|
+
buildManifest.routeIdToServerBundleId[route.id] = serverBundleId, buildManifest.serverBundles[serverBundleId] ??= {
|
|
775
|
+
id: serverBundleId,
|
|
776
|
+
file: relative(rootDirectory, resolve(serverBuildDirectory, serverBundleId, serverBuildFile)).replace(/\\/g, '/')
|
|
777
|
+
};
|
|
778
|
+
})), buildManifest;
|
|
779
|
+
};
|
|
780
|
+
function getDevtoolFromRspackConfig(config) {
|
|
781
|
+
if (config && 'function' != typeof config && 'object' == typeof config) return config.devtool;
|
|
782
|
+
}
|
|
783
|
+
function pluginId(name) {
|
|
784
|
+
return `rsbuild:${name}`;
|
|
284
785
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
786
|
+
function indexOfPlugin(plugins, names) {
|
|
787
|
+
return plugins.findIndex((p)=>!!p?.name && names.includes(p.name));
|
|
788
|
+
}
|
|
789
|
+
let REACT_ROUTER_EXTERNALS = [
|
|
790
|
+
'react-router',
|
|
791
|
+
'react-router-dom',
|
|
792
|
+
'@react-router/architect',
|
|
793
|
+
'@react-router/cloudflare',
|
|
794
|
+
'@react-router/dev',
|
|
795
|
+
'@react-router/express',
|
|
796
|
+
'@react-router/node',
|
|
797
|
+
'@react-router/serve'
|
|
798
|
+
], requireFromHere = createRequire(import.meta.url);
|
|
799
|
+
var src_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
800
|
+
let redirectStatusCodes = new Set([
|
|
801
|
+
301,
|
|
802
|
+
302,
|
|
803
|
+
303,
|
|
804
|
+
307,
|
|
805
|
+
308
|
|
806
|
+
]), pluginReactRouter = (options = {})=>({
|
|
807
|
+
name: PLUGIN_NAME,
|
|
288
808
|
async setup (api) {
|
|
289
|
-
|
|
290
|
-
let clientStats;
|
|
291
|
-
let pluginOptions = {
|
|
809
|
+
let routeDiscovery, clientStats, pluginOptions = {
|
|
292
810
|
customServer: !1,
|
|
293
811
|
serverOutput: 'module',
|
|
294
812
|
...options
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
813
|
+
}, nodeExternals = Array.from(new Set([
|
|
814
|
+
'express',
|
|
815
|
+
...function(rootDirectory) {
|
|
816
|
+
let externals = [];
|
|
817
|
+
for (let name of REACT_ROUTER_EXTERNALS){
|
|
818
|
+
let resolved = function(name, rootDirectory) {
|
|
819
|
+
try {
|
|
820
|
+
return requireFromHere.resolve(`${name}/package.json`, {
|
|
821
|
+
paths: [
|
|
822
|
+
rootDirectory
|
|
823
|
+
]
|
|
824
|
+
});
|
|
825
|
+
} catch {
|
|
826
|
+
return null;
|
|
827
|
+
}
|
|
828
|
+
}(name, rootDirectory);
|
|
829
|
+
resolved && ((function(pathname) {
|
|
830
|
+
try {
|
|
831
|
+
return realpathSync(pathname);
|
|
832
|
+
} catch {
|
|
833
|
+
return pathname;
|
|
834
|
+
}
|
|
835
|
+
})(resolved).split(sep).includes('node_modules') || externals.push(name));
|
|
836
|
+
}
|
|
837
|
+
return externals;
|
|
838
|
+
}(process.cwd())
|
|
839
|
+
])), assetPrefix = '/';
|
|
840
|
+
api.modifyRsbuildConfig({
|
|
841
|
+
order: 'pre',
|
|
842
|
+
handler (config) {
|
|
843
|
+
let plugins, issues, rrIndex, mdxIndex, hasReact;
|
|
844
|
+
for (let issue of (plugins = function flattenPlugins(input) {
|
|
845
|
+
if (!Array.isArray(input)) return [];
|
|
846
|
+
let out = [];
|
|
847
|
+
for (let item of input)if (item) {
|
|
848
|
+
if (Array.isArray(item)) {
|
|
849
|
+
out.push(...flattenPlugins(item));
|
|
850
|
+
continue;
|
|
851
|
+
}
|
|
852
|
+
'function' != typeof item?.then && 'object' == typeof item && out.push(item);
|
|
853
|
+
}
|
|
854
|
+
return out;
|
|
855
|
+
}(config.plugins), issues = [], rrIndex = indexOfPlugin(plugins, [
|
|
856
|
+
'rsbuild:react-router'
|
|
857
|
+
]), mdxIndex = indexOfPlugin(plugins, [
|
|
858
|
+
pluginId('mdx')
|
|
859
|
+
]), rrIndex >= 0 && mdxIndex >= 0 && mdxIndex > rrIndex && issues.push({
|
|
860
|
+
kind: 'error',
|
|
861
|
+
message: 'The "rsbuild:mdx" plugin should be placed before the React Router plugin in your Rsbuild config. This ensures route modules authored in MDX are compiled before React Router inspects route exports.'
|
|
862
|
+
}), hasReact = plugins.some((p)=>p?.name === pluginId('react')), rrIndex >= 0 && !hasReact && issues.push({
|
|
863
|
+
kind: 'warn',
|
|
864
|
+
message: 'React Router plugin detected without "rsbuild:react". If you are using JSX/TSX route modules, add "@rsbuild/plugin-react" to your plugins list.'
|
|
865
|
+
}), issues)){
|
|
866
|
+
if ('error' === issue.kind) throw Error(issue.message);
|
|
867
|
+
api.logger.warn(issue.message);
|
|
868
|
+
}
|
|
869
|
+
return assetPrefix = normalizeAssetPrefix(config.output?.assetPrefix), config;
|
|
870
|
+
}
|
|
871
|
+
}), api.onBeforeBuild(()=>{
|
|
872
|
+
!function(normalized, warn, clientEnvName = 'web') {
|
|
873
|
+
if ('production' !== normalized.mode && 'production' !== process.env.NODE_ENV) return;
|
|
874
|
+
let sourceMapSetting = function(normalized, clientEnvName = 'web') {
|
|
875
|
+
return normalized.environments?.[clientEnvName]?.output?.sourceMap ?? normalized.output?.sourceMap;
|
|
876
|
+
}(normalized, clientEnvName), devtoolSetting = function(normalized, clientEnvName = 'web') {
|
|
877
|
+
let envTools = normalized.environments?.[clientEnvName]?.tools?.rspack, rootTools = normalized.tools?.rspack;
|
|
878
|
+
return getDevtoolFromRspackConfig(envTools) ?? getDevtoolFromRspackConfig(rootTools);
|
|
879
|
+
}(normalized, clientEnvName);
|
|
880
|
+
(!0 === sourceMapSetting || !1 !== sourceMapSetting && null != sourceMapSetting && ('string' == typeof sourceMapSetting || 'object' == typeof sourceMapSetting && sourceMapSetting.js) || !0 === devtoolSetting || null != devtoolSetting && !1 !== devtoolSetting && ('string' == typeof devtoolSetting ? devtoolSetting.includes('source-map') : 'object' == typeof devtoolSetting)) && warn("\n WARNING: Source maps are enabled in production\n This makes your server code publicly visible in the browser.\n This is highly discouraged! If you insist, ensure that you are using\n environment variables for secrets and not hard-coding them in your source code.\n");
|
|
881
|
+
}(api.getNormalizedConfig(), (msg)=>api.logger.warn(msg), 'web');
|
|
306
882
|
}), api.onBeforeStartDevServer(async ()=>{
|
|
307
|
-
let {
|
|
308
|
-
|
|
883
|
+
let { execa } = await import("execa");
|
|
884
|
+
execa('npx', [
|
|
885
|
+
'--yes',
|
|
886
|
+
'react-router',
|
|
887
|
+
'typegen',
|
|
888
|
+
'--watch'
|
|
889
|
+
], {
|
|
890
|
+
stdio: 'inherit',
|
|
891
|
+
detached: !1,
|
|
892
|
+
cleanup: !0
|
|
893
|
+
}).catch(()=>{});
|
|
309
894
|
}), api.onBeforeBuild(async ()=>{
|
|
310
|
-
let {
|
|
311
|
-
|
|
895
|
+
let { execa } = await import("execa");
|
|
896
|
+
await execa('npx', [
|
|
897
|
+
'--yes',
|
|
898
|
+
'react-router',
|
|
899
|
+
'typegen'
|
|
900
|
+
], {
|
|
901
|
+
stdio: 'inherit'
|
|
902
|
+
});
|
|
312
903
|
});
|
|
313
|
-
let jiti =
|
|
314
|
-
|
|
315
|
-
|
|
904
|
+
let jiti = createJiti(process.cwd()), configPath = findEntryFile(resolve('react-router.config')), configExists = existsSync(configPath), reactRouterUserConfig = {};
|
|
905
|
+
if (configExists) {
|
|
906
|
+
let displayPath = relative(process.cwd(), configPath);
|
|
907
|
+
try {
|
|
908
|
+
let imported = await jiti.import(configPath, {
|
|
909
|
+
default: !0
|
|
910
|
+
});
|
|
911
|
+
if (void 0 === imported) throw Error(`${displayPath} must provide a default export`);
|
|
912
|
+
if ('object' != typeof imported) throw Error(`${displayPath} must export a config`);
|
|
913
|
+
reactRouterUserConfig = imported;
|
|
914
|
+
} catch (error) {
|
|
915
|
+
throw Error(`Error loading ${displayPath}: ${error}`);
|
|
916
|
+
}
|
|
917
|
+
} else console.warn('No react-router.config found, using default configuration.');
|
|
918
|
+
let { resolved: resolvedConfig, presets: configPresets } = await resolveReactRouterConfig(reactRouterUserConfig), { appDirectory, basename, buildDirectory, future, allowedActionOrigins, routeDiscovery: userRouteDiscovery, ssr, prerender: prerenderConfig, serverBuildFile, serverModuleFormat, serverBundles, buildEnd } = resolvedConfig, hasExplicitServerOutput = Object.prototype.hasOwnProperty.call(options, 'serverOutput'), resolvedServerOutput = hasExplicitServerOutput ? options.serverOutput : 'cjs' === serverModuleFormat ? 'commonjs' : 'module';
|
|
919
|
+
if (hasExplicitServerOutput && serverModuleFormat && ('commonjs' === options.serverOutput ? 'cjs' : 'esm') !== serverModuleFormat && api.logger.warn(`[${PLUGIN_NAME}] Both \`serverOutput\` and \`serverModuleFormat\` are set. Using \`serverOutput=${options.serverOutput}\` and ignoring \`serverModuleFormat=${serverModuleFormat}\`.`), serverBuildFile && !serverBuildFile.endsWith('.js')) throw Error('The `serverBuildFile` config must end in `.js`.');
|
|
920
|
+
if ('esm' !== serverModuleFormat && 'cjs' !== serverModuleFormat) throw Error('The `serverModuleFormat` config must be "esm" or "cjs".');
|
|
921
|
+
serverBundles && api.logger.warn(`[${PLUGIN_NAME}] \`serverBundles\` is configured. Rsbuild currently emits a single server bundle, but the build manifest will include the server bundle mapping for compatibility.`);
|
|
922
|
+
let prerenderConfigError = ((prerender)=>{
|
|
923
|
+
if (!prerender) return null;
|
|
924
|
+
if (!(isValidPrerenderPathsConfig('object' == typeof prerender && null !== prerender && 'paths' in prerender ? prerender?.paths : prerender) || 'object' == typeof prerender && null !== prerender && 'paths' in prerender && isValidPrerenderPathsConfig(prerender?.paths))) return 'The `prerender`/`prerender.paths` config must be a boolean, an array of string paths, or a function returning a boolean or array of string paths.';
|
|
925
|
+
let concurrency = 'object' == typeof prerender && null !== prerender && 'unstable_concurrency' in prerender ? prerender?.unstable_concurrency : void 0;
|
|
926
|
+
return void 0 !== concurrency && (!Number.isInteger(concurrency) || concurrency <= 0) ? 'The `prerender.unstable_concurrency` config must be a positive integer if specified.' : null;
|
|
927
|
+
})(prerenderConfig);
|
|
928
|
+
if (prerenderConfigError) throw Error(prerenderConfigError);
|
|
929
|
+
if (userRouteDiscovery) {
|
|
930
|
+
if ('initial' === userRouteDiscovery.mode) routeDiscovery = userRouteDiscovery;
|
|
931
|
+
else if ('lazy' === userRouteDiscovery.mode) {
|
|
932
|
+
if (!ssr) throw Error('The `routeDiscovery.mode` config cannot be set to "lazy" when setting `ssr:false`');
|
|
933
|
+
let manifestPath = userRouteDiscovery.manifestPath;
|
|
934
|
+
if (manifestPath && !manifestPath.startsWith('/')) throw Error('The `routeDiscovery.manifestPath` config must be a root-relative pathname beginning with a slash (i.e., "/__manifest")');
|
|
935
|
+
routeDiscovery = userRouteDiscovery;
|
|
936
|
+
}
|
|
937
|
+
} else routeDiscovery = ssr ? {
|
|
938
|
+
mode: 'lazy',
|
|
939
|
+
manifestPath: '/__manifest'
|
|
940
|
+
} : {
|
|
941
|
+
mode: 'initial'
|
|
942
|
+
};
|
|
943
|
+
globalThis.__reactRouterAppDirectory = resolve(appDirectory);
|
|
944
|
+
let routesPath = findEntryFile(resolve(appDirectory, 'routes'));
|
|
945
|
+
if (!existsSync(routesPath)) throw Error(`Route config file not found at "${relative(process.cwd(), routesPath)}".`);
|
|
946
|
+
let routeConfigExport = await jiti.import(routesPath, {
|
|
316
947
|
default: !0
|
|
317
|
-
})
|
|
948
|
+
}), routeConfigValue = await routeConfigExport, validation = (({ routeConfigFile, routeConfig })=>{
|
|
949
|
+
if (!routeConfig) return {
|
|
950
|
+
valid: !1,
|
|
951
|
+
message: `Route config must be the default export in "${routeConfigFile}".`
|
|
952
|
+
};
|
|
953
|
+
if (!Array.isArray(routeConfig)) return {
|
|
954
|
+
valid: !1,
|
|
955
|
+
message: `Route config in "${routeConfigFile}" must be an array.`
|
|
956
|
+
};
|
|
957
|
+
let issues = [];
|
|
958
|
+
return (routeConfig.forEach((entry, index)=>validateEntry(entry, `routes.${index}`, issues)), issues.length > 0) ? {
|
|
959
|
+
valid: !1,
|
|
960
|
+
message: [
|
|
961
|
+
`Route config in "${routeConfigFile}" is invalid.`,
|
|
962
|
+
issues.join('\n\n')
|
|
963
|
+
].join('\n\n')
|
|
964
|
+
} : {
|
|
965
|
+
valid: !0,
|
|
966
|
+
routeConfig: routeConfig
|
|
967
|
+
};
|
|
968
|
+
})({
|
|
969
|
+
routeConfigFile: relative(process.cwd(), routesPath),
|
|
970
|
+
routeConfig: routeConfigValue
|
|
971
|
+
});
|
|
972
|
+
if (!validation.valid) throw Error(validation.message);
|
|
973
|
+
let routeConfig = validation.routeConfig, entryClientPath = findEntryFile(resolve(appDirectory, 'entry.client')), entryServerPath = findEntryFile(resolve(appDirectory, 'entry.server')), serverAppPath = findEntryFile(resolve(appDirectory, '../server/index')), hasServerApp = existsSync(serverAppPath), templateDir = resolve(src_dirname, 'templates'), templateClientPath = resolve(templateDir, 'entry.client.js'), templateServerPath = resolve(templateDir, 'entry.server.js'), finalEntryClientPath = existsSync(entryClientPath) ? entryClientPath : templateClientPath, finalEntryServerPath = existsSync(entryServerPath) ? entryServerPath : templateServerPath, rootRoutePath = findEntryFile(resolve(appDirectory, 'root')), rootRouteFile = relative(appDirectory, rootRoutePath), routes = {
|
|
318
974
|
root: {
|
|
319
975
|
path: '',
|
|
320
976
|
id: 'root',
|
|
321
|
-
file:
|
|
977
|
+
file: rootRouteFile
|
|
322
978
|
},
|
|
323
979
|
...function(appDirectory, routes, rootId = 'root') {
|
|
324
980
|
let routeManifest = {};
|
|
325
981
|
for (let route of routes)!function walk(route, parentId) {
|
|
326
|
-
|
|
327
|
-
let id = route.id || (file = route.file, (0, __WEBPACK_EXTERNAL_MODULE_pathe__.normalize)(file.replace(/\.[^/.]+$/, ''))), manifestItem = {
|
|
982
|
+
let id = route.id || normalize(route.file.replace(/\.[^/.]+$/, '')), manifestItem = {
|
|
328
983
|
id,
|
|
329
984
|
parentId,
|
|
330
|
-
file:
|
|
985
|
+
file: isAbsolute(route.file) ? relative(appDirectory, route.file) : route.file,
|
|
331
986
|
path: route.path,
|
|
332
987
|
index: route.index,
|
|
333
988
|
caseSensitive: route.caseSensitive
|
|
@@ -337,142 +992,271 @@ let pluginReactRouter = (options = {})=>({
|
|
|
337
992
|
}(route, rootId);
|
|
338
993
|
return routeManifest;
|
|
339
994
|
}(appDirectory, routeConfig)
|
|
340
|
-
},
|
|
995
|
+
}, resolvedConfigWithRoutes = {
|
|
996
|
+
...resolvedConfig,
|
|
997
|
+
appDirectory: resolve(appDirectory),
|
|
998
|
+
buildDirectory: resolve(buildDirectory),
|
|
999
|
+
routeDiscovery,
|
|
1000
|
+
prerender: prerenderConfig,
|
|
1001
|
+
routes,
|
|
1002
|
+
unstable_routeConfig: routeConfig,
|
|
1003
|
+
allowedActionOrigins: allowedActionOrigins ?? !1
|
|
1004
|
+
}, { buildEnd: _buildEnd, ...resolvedConfigForPreset } = resolvedConfigWithRoutes;
|
|
1005
|
+
for (let preset of configPresets)await preset.reactRouterConfigResolved?.({
|
|
1006
|
+
reactRouterConfig: resolvedConfigForPreset
|
|
1007
|
+
});
|
|
1008
|
+
let isBuild = 'build' === api.context.action, splitRouteModules = future?.v8_splitRouteModules ?? !1, enforceSplitRouteModules = 'enforce' === splitRouteModules, routeChunkConfig = {
|
|
1009
|
+
splitRouteModules,
|
|
1010
|
+
appDirectory,
|
|
1011
|
+
rootRouteFile
|
|
1012
|
+
}, routeChunkCache = new Map(), routeChunkOptions = {
|
|
1013
|
+
splitRouteModules,
|
|
1014
|
+
rootRouteFile,
|
|
1015
|
+
isBuild,
|
|
1016
|
+
cache: routeChunkCache
|
|
1017
|
+
}, latestServerManifest = null, latestServerManifestsByBundleId = {}, routeByFilePath = new Map(Object.values(routes).map((route)=>[
|
|
1018
|
+
resolve(appDirectory, route.file),
|
|
1019
|
+
route
|
|
1020
|
+
])), routeExportsCache = new Map(), getCachedRouteExports = async (filePath)=>{
|
|
1021
|
+
if (routeExportsCache.has(filePath)) return routeExportsCache.get(filePath);
|
|
1022
|
+
let exports = await getRouteModuleExports(filePath);
|
|
1023
|
+
return routeExportsCache.set(filePath, exports), exports;
|
|
1024
|
+
}, webRouteEntries = Object.values(routes).reduce((acc, route)=>{
|
|
1025
|
+
let entryName = route.file.slice(0, route.file.lastIndexOf('.')), routeFilePath = resolve(appDirectory, route.file);
|
|
1026
|
+
if (acc[entryName] = {
|
|
1027
|
+
import: `${routeFilePath}${BUILD_CLIENT_ROUTE_QUERY_STRING}`
|
|
1028
|
+
}, isBuild && splitRouteModules && 'root' !== route.id) {
|
|
1029
|
+
let source = '';
|
|
1030
|
+
try {
|
|
1031
|
+
source = readFileSync(routeFilePath, 'utf8');
|
|
1032
|
+
} catch {
|
|
1033
|
+
source = '';
|
|
1034
|
+
}
|
|
1035
|
+
if (source) for (let exportName of routeChunkExportNames)source.includes(exportName) && (acc[getRouteChunkEntryName(route.id, exportName)] = {
|
|
1036
|
+
import: getRouteChunkModuleId(routeFilePath, exportName)
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
return acc;
|
|
1040
|
+
}, {}), routesByServerBundleId = ((buildManifest)=>{
|
|
1041
|
+
if (!buildManifest || !('routeIdToServerBundleId' in buildManifest)) return {};
|
|
1042
|
+
let routesByServerBundleId = {};
|
|
1043
|
+
for (let [routeId, serverBundleId] of Object.entries(buildManifest.routeIdToServerBundleId))for (let route of (routesByServerBundleId[serverBundleId] ??= {}, getRouteBranch(buildManifest.routes, routeId)))routesByServerBundleId[serverBundleId][route.id] = route;
|
|
1044
|
+
return routesByServerBundleId;
|
|
1045
|
+
})(await getBuildManifest({
|
|
1046
|
+
reactRouterConfig: resolvedConfigWithRoutes,
|
|
1047
|
+
routes,
|
|
1048
|
+
rootDirectory: process.cwd()
|
|
1049
|
+
})), outputClientPath = resolve(buildDirectory, 'client'), assetsBuildDirectory = relative(process.cwd(), outputClientPath);
|
|
341
1050
|
api.onAfterEnvironmentCompile(({ stats, environment })=>{
|
|
342
|
-
if ('web' === environment.name && (clientStats =
|
|
343
|
-
let serverBuildDir =
|
|
344
|
-
if (
|
|
345
|
-
let ssrDir =
|
|
346
|
-
|
|
1051
|
+
if ('web' === environment.name && (clientStats = stats?.toJson()), pluginOptions.federation && ssr) {
|
|
1052
|
+
let serverBuildDir = resolve(buildDirectory, 'server'), clientBuildDir = resolve(buildDirectory, 'client');
|
|
1053
|
+
if (existsSync(serverBuildDir)) {
|
|
1054
|
+
let ssrDir = resolve(clientBuildDir, 'static');
|
|
1055
|
+
fs_extra.copySync(serverBuildDir, ssrDir);
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
let prerenderPaths = await resolvePrerenderPaths(prerenderConfig, ssr, routeConfig, {
|
|
1060
|
+
logWarning: !0,
|
|
1061
|
+
warn: (message)=>api.logger.warn(message)
|
|
1062
|
+
}), isPrerenderEnabled = void 0 !== prerenderConfig && !1 !== prerenderConfig, isSpaMode = !ssr && !isPrerenderEnabled, groupRoutesByParentId = (manifest)=>{
|
|
1063
|
+
let grouped = {};
|
|
1064
|
+
return Object.values(manifest).forEach((route)=>{
|
|
1065
|
+
if (!route) return;
|
|
1066
|
+
let parentId = route.parentId || '';
|
|
1067
|
+
grouped[parentId] || (grouped[parentId] = []), grouped[parentId].push(route);
|
|
1068
|
+
}), grouped;
|
|
1069
|
+
}, createPrerenderRoutes = (manifest, parentId = '', grouped = groupRoutesByParentId(manifest))=>(grouped[parentId] || []).map((route)=>{
|
|
1070
|
+
let common = {
|
|
1071
|
+
id: route.id,
|
|
1072
|
+
path: route.path
|
|
1073
|
+
};
|
|
1074
|
+
return route.index ? {
|
|
1075
|
+
index: !0,
|
|
1076
|
+
...common
|
|
1077
|
+
} : {
|
|
1078
|
+
...common,
|
|
1079
|
+
children: createPrerenderRoutes(manifest, route.id, grouped)
|
|
1080
|
+
};
|
|
1081
|
+
}), normalizePrerenderMatchPath = (path)=>`/${path}/`.replace(/^\/\/+/, '/'), prerenderData = async (handler, prerenderPath, onlyRoutes, clientBuildDir, requestInit)=>{
|
|
1082
|
+
let dataRequestPath;
|
|
1083
|
+
dataRequestPath = future?.unstable_trailingSlashAwareDataRequests ? prerenderPath.endsWith('/') ? `${prerenderPath}_.data` : `${prerenderPath}.data` : '/' === prerenderPath ? '/_root.data' : `${prerenderPath.replace(/\/$/, '')}.data`;
|
|
1084
|
+
let normalizedPath = `${basename}${dataRequestPath}`.replace(/\/\/+/g, '/'), url = new URL(`http://localhost${normalizedPath}`);
|
|
1085
|
+
onlyRoutes?.length && url.searchParams.set('_routes', onlyRoutes.join(','));
|
|
1086
|
+
let request = new Request(url, requestInit), response = await handler(request), data = await response.text();
|
|
1087
|
+
if (200 !== response.status && 202 !== response.status) throw Error(`Prerender (data): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${prerenderPath}\` path.\n${normalizedPath}`);
|
|
1088
|
+
let outputPath = resolve(clientBuildDir, ...normalizedPath.split('/'));
|
|
1089
|
+
return await mkdir(dirname(outputPath), {
|
|
1090
|
+
recursive: !0
|
|
1091
|
+
}), await writeFile(outputPath, data), api.logger.info(`Prerender (data): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`), data;
|
|
1092
|
+
}, prerenderRoute = async (handler, prerenderPath, clientBuildDir, requestInit)=>{
|
|
1093
|
+
let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/'), request = new Request(`http://localhost${normalizedPath}`, requestInit), response = await handler(request), html = await response.text();
|
|
1094
|
+
if (redirectStatusCodes.has(response.status)) {
|
|
1095
|
+
let location = response.headers.get('Location'), delay = 2 * (302 === response.status);
|
|
1096
|
+
html = `<!doctype html>
|
|
1097
|
+
<head>
|
|
1098
|
+
<title>Redirecting to: ${location}</title>
|
|
1099
|
+
<meta http-equiv="refresh" content="${delay};url=${location}">
|
|
1100
|
+
<meta name="robots" content="noindex">
|
|
1101
|
+
</head>
|
|
1102
|
+
<body>
|
|
1103
|
+
\t<a href="${location}">
|
|
1104
|
+
Redirecting from <code>${normalizedPath}</code> to <code>${location}</code>
|
|
1105
|
+
</a>
|
|
1106
|
+
</body>
|
|
1107
|
+
</html>`;
|
|
1108
|
+
} else if (200 !== response.status) throw Error(`Prerender (html): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + html);
|
|
1109
|
+
let outputPath = resolve(clientBuildDir, ...normalizedPath.split('/'), 'index.html');
|
|
1110
|
+
await mkdir(dirname(outputPath), {
|
|
1111
|
+
recursive: !0
|
|
1112
|
+
}), await writeFile(outputPath, html), api.logger.info(`Prerender (html): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
|
|
1113
|
+
}, prerenderResourceRoute = async (handler, prerenderPath, clientBuildDir, requestInit)=>{
|
|
1114
|
+
let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/').replace(/\/$/g, ''), request = new Request(`http://localhost${normalizedPath}`, requestInit), response = await handler(request), content = Buffer.from(await response.arrayBuffer());
|
|
1115
|
+
if (200 !== response.status) throw Error(`Prerender (resource): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + content.toString('utf8'));
|
|
1116
|
+
let outputPath = resolve(clientBuildDir, ...normalizedPath.split('/'));
|
|
1117
|
+
await mkdir(dirname(outputPath), {
|
|
1118
|
+
recursive: !0
|
|
1119
|
+
}), await writeFile(outputPath, content), api.logger.info(`Prerender (resource): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
|
|
1120
|
+
}, handleSpaMode = async (handler, build, clientBuildDir)=>{
|
|
1121
|
+
let request = new Request(`http://localhost${basename}`, {
|
|
1122
|
+
headers: {
|
|
1123
|
+
'X-React-Router-SPA-Mode': 'yes'
|
|
1124
|
+
}
|
|
1125
|
+
}), response = await handler(request), html = await response.text(), isPrerenderSpaFallback = build.prerender?.includes('/'), filename = isPrerenderSpaFallback ? '__spa-fallback.html' : 'index.html';
|
|
1126
|
+
if (200 !== response.status) {
|
|
1127
|
+
if (isPrerenderSpaFallback) throw Error(`Prerender: Received a ${response.status} status code from \`entry.server.tsx\` while prerendering your \`${filename}\` file.\n` + html);
|
|
1128
|
+
throw Error(`SPA Mode: Received a ${response.status} status code from \`entry.server.tsx\` while prerendering your \`${filename}\` file.\n` + html);
|
|
1129
|
+
}
|
|
1130
|
+
if (!html.includes('window.__reactRouterContext =') || !html.includes('window.__reactRouterRouteModules =')) throw Error("SPA Mode: Did you forget to include `<Scripts/>` in your root route? Your pre-rendered HTML cannot hydrate without `<Scripts />`.");
|
|
1131
|
+
let outputPath = resolve(clientBuildDir, filename);
|
|
1132
|
+
await writeFile(outputPath, html);
|
|
1133
|
+
let prettyPath = relative(process.cwd(), outputPath);
|
|
1134
|
+
build.prerender?.length ? api.logger.info(`Prerender (html): SPA Fallback -> ${prettyPath}`) : api.logger.info(`SPA Mode: Generated ${prettyPath}`);
|
|
1135
|
+
}, validateSsrFalsePrerenderExports = async (manifest, prerenderList)=>{
|
|
1136
|
+
if (0 === prerenderList.length) return;
|
|
1137
|
+
let prerenderRoutes = createPrerenderRoutes(routes), prerenderedRoutes = new Set();
|
|
1138
|
+
for (let path of prerenderList){
|
|
1139
|
+
let matches = matchRoutes(prerenderRoutes, normalizePrerenderMatchPath(path));
|
|
1140
|
+
if (!matches) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
|
|
1141
|
+
matches.forEach((match)=>prerenderedRoutes.add(match.route.id));
|
|
1142
|
+
}
|
|
1143
|
+
let routeExports = {};
|
|
1144
|
+
for (let route of Object.values(routes)){
|
|
1145
|
+
let filePath = resolve(appDirectory, route.file);
|
|
1146
|
+
routeExports[route.id] = await getRouteModuleExports(filePath);
|
|
1147
|
+
}
|
|
1148
|
+
let errors = [];
|
|
1149
|
+
for (let [routeId, route] of Object.entries(manifest.routes)){
|
|
1150
|
+
let exports = routeExports[routeId] ?? [], invalidApis = [];
|
|
1151
|
+
if (exports.includes('headers') && invalidApis.push('headers'), exports.includes('action') && invalidApis.push('action'), invalidApis.length > 0 && errors.push(`Prerender: ${invalidApis.length} invalid route export(s) in \`${routeId}\` when pre-rendering with \`ssr:false\`: ${invalidApis.map((api)=>`\`${api}\``).join(', ')}. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), !prerenderedRoutes.has(routeId)) {
|
|
1152
|
+
exports.includes('loader') && errors.push(`Prerender: 1 invalid route export in \`${routeId}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`);
|
|
1153
|
+
let parentRoute = route.parentId && manifest.routes[route.parentId] ? manifest.routes[route.parentId] : null;
|
|
1154
|
+
for(; parentRoute && 'root' !== parentRoute.id;)parentRoute.hasLoader && !parentRoute.hasClientLoader && errors.push(`Prerender: 1 invalid route export in \`${parentRoute.id}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), parentRoute = parentRoute.parentId && 'root' !== parentRoute.parentId ? manifest.routes[parentRoute.parentId] : null;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
if (errors.length > 0) throw api.logger.error(errors.join('\n')), Error('Invalid route exports found when prerendering with `ssr:false`');
|
|
1158
|
+
};
|
|
1159
|
+
api.onAfterBuild(async ({ environments })=>{
|
|
1160
|
+
if (!environments.web) return;
|
|
1161
|
+
let serverBuildDir = resolve(buildDirectory, 'server'), defaultServerBuildFile = 'static/js/app.js', configuredServerBuildFile = serverBuildFile || 'index.js', configuredServerBuildPath = resolve(serverBuildDir, configuredServerBuildFile), defaultServerBuildPath = resolve(serverBuildDir, defaultServerBuildFile);
|
|
1162
|
+
configuredServerBuildFile !== defaultServerBuildFile && existsSync(defaultServerBuildPath) && !existsSync(configuredServerBuildPath) && (await mkdir(dirname(configuredServerBuildPath), {
|
|
1163
|
+
recursive: !0
|
|
1164
|
+
}), await fs_extra.copy(defaultServerBuildPath, configuredServerBuildPath));
|
|
1165
|
+
let serverBuildPath = existsSync(configuredServerBuildPath) ? configuredServerBuildPath : defaultServerBuildPath, clientBuildDir = resolve(buildDirectory, 'client');
|
|
1166
|
+
if (!existsSync(serverBuildPath)) return void console.warn(`[${PLUGIN_NAME}] Server build not found at ${serverBuildPath}. Skipping prerendering.`);
|
|
1167
|
+
if (await mkdir(clientBuildDir, {
|
|
1168
|
+
recursive: !0
|
|
1169
|
+
}), !ssr || isPrerenderEnabled) {
|
|
1170
|
+
process.env.IS_RR_BUILD_REQUEST = 'yes';
|
|
1171
|
+
let normalizedBuild = normalizeBuildModule(await import(pathToFileURL(serverBuildPath).toString())), build = await resolveBuildExports(normalizedBuild), requestHandler = createRequestHandler(build, 'production');
|
|
1172
|
+
if (isPrerenderEnabled) {
|
|
1173
|
+
let manifest = await getReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory, assetPrefix, routeChunkOptions);
|
|
1174
|
+
ssr || await validateSsrFalsePrerenderExports(manifest, prerenderPaths);
|
|
1175
|
+
let routeTree = createPrerenderRoutes(routes);
|
|
1176
|
+
for (let path of prerenderPaths)if (!matchRoutes(routeTree, normalizePrerenderMatchPath(path))) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
|
|
1177
|
+
prerenderPaths.length > 0 && api.logger.info(`Prerender (html): ${prerenderPaths.length} path(s)...`);
|
|
1178
|
+
let buildRoutes = createPrerenderRoutes(build.routes), concurrency = ((prerender)=>{
|
|
1179
|
+
if ('object' == typeof prerender && null !== prerender && 'unstable_concurrency' in prerender) {
|
|
1180
|
+
let value = prerender?.unstable_concurrency;
|
|
1181
|
+
if ('number' == typeof value && Number.isInteger(value) && value > 0) return value;
|
|
1182
|
+
}
|
|
1183
|
+
return 1;
|
|
1184
|
+
})(prerenderConfig), pending = new Set(), enqueue = async (path)=>{
|
|
1185
|
+
let matches = matchRoutes(buildRoutes, normalizePrerenderMatchPath(path));
|
|
1186
|
+
if (!matches) return;
|
|
1187
|
+
let leafRoute = matches[matches.length - 1]?.route, manifestRoute = leafRoute ? build.routes?.[leafRoute.id]?.module : null;
|
|
1188
|
+
if (!manifestRoute || manifestRoute.default || manifestRoute.ErrorBoundary) {
|
|
1189
|
+
let data;
|
|
1190
|
+
matches.some((match)=>{
|
|
1191
|
+
let routeId = match.route.id;
|
|
1192
|
+
return !!routeId && build.assets?.routes?.[routeId]?.hasLoader;
|
|
1193
|
+
}) && (data = await prerenderData(requestHandler, path, null, clientBuildDir)), await prerenderRoute(requestHandler, path, clientBuildDir, data ? {
|
|
1194
|
+
headers: {
|
|
1195
|
+
'X-React-Router-Prerender-Data': encodeURI(data)
|
|
1196
|
+
}
|
|
1197
|
+
} : void 0);
|
|
1198
|
+
} else manifestRoute.loader ? (await prerenderData(requestHandler, path, [
|
|
1199
|
+
leafRoute.id
|
|
1200
|
+
], clientBuildDir), await prerenderResourceRoute(requestHandler, path, clientBuildDir)) : api.logger.warn(`⚠️ Skipping prerendering for resource route without a loader: ${leafRoute?.id}`);
|
|
1201
|
+
};
|
|
1202
|
+
for (let path of prerenderPaths){
|
|
1203
|
+
let task = enqueue(path);
|
|
1204
|
+
pending.add(task), task.finally(()=>pending.delete(task)), pending.size >= concurrency && await Promise.race(pending);
|
|
1205
|
+
}
|
|
1206
|
+
await Promise.all(pending);
|
|
347
1207
|
}
|
|
1208
|
+
ssr || await handleSpaMode(requestHandler, build, clientBuildDir);
|
|
1209
|
+
}
|
|
1210
|
+
if (ssr || (await fs_extra.remove(serverBuildDir), api.logger.info(`[${PLUGIN_NAME}] Removed server build (static deployment)`)), buildEnd) {
|
|
1211
|
+
let buildManifest = await getBuildManifest({
|
|
1212
|
+
reactRouterConfig: resolvedConfigWithRoutes,
|
|
1213
|
+
routes,
|
|
1214
|
+
rootDirectory: process.cwd()
|
|
1215
|
+
});
|
|
1216
|
+
await buildEnd({
|
|
1217
|
+
buildManifest,
|
|
1218
|
+
reactRouterConfig: resolvedConfigWithRoutes,
|
|
1219
|
+
viteConfig: api.getNormalizedConfig()
|
|
1220
|
+
});
|
|
348
1221
|
}
|
|
349
1222
|
});
|
|
350
|
-
let
|
|
1223
|
+
let allowedActionOriginsForBuild = !1 === allowedActionOrigins ? void 0 : allowedActionOrigins, bundleVirtualModules = Object.fromEntries(Object.entries(routesByServerBundleId).map(([bundleId, bundleRoutes])=>[
|
|
1224
|
+
`virtual/react-router/server-build-${bundleId}`,
|
|
1225
|
+
generateServerBuild(bundleRoutes, {
|
|
1226
|
+
entryServerPath: finalEntryServerPath,
|
|
1227
|
+
assetsBuildDirectory,
|
|
1228
|
+
basename,
|
|
1229
|
+
appDirectory,
|
|
1230
|
+
ssr,
|
|
1231
|
+
federation: options.federation,
|
|
1232
|
+
future,
|
|
1233
|
+
allowedActionOrigins: allowedActionOriginsForBuild,
|
|
1234
|
+
prerender: prerenderPaths,
|
|
1235
|
+
routeDiscovery,
|
|
1236
|
+
publicPath: assetPrefix,
|
|
1237
|
+
serverManifestId: `virtual/react-router/server-manifest-${bundleId}`
|
|
1238
|
+
})
|
|
1239
|
+
])), bundleManifestModules = Object.fromEntries(Object.entries(routesByServerBundleId).filter(([, bundleRoutes])=>bundleRoutes && Object.keys(bundleRoutes).length > 0).map(([bundleId])=>[
|
|
1240
|
+
`virtual/react-router/server-manifest-${bundleId}`,
|
|
1241
|
+
'export default {};'
|
|
1242
|
+
])), vmodTempDir = `rspack-virtual-module-${process.pid}-${Math.random().toString(16).slice(2)}`, vmodPlugin = new RspackVirtualModulePlugin({
|
|
351
1243
|
'virtual/react-router/browser-manifest': 'export default {};',
|
|
352
1244
|
'virtual/react-router/server-manifest': 'export default {};',
|
|
353
|
-
'virtual/react-router/server-build': (
|
|
1245
|
+
'virtual/react-router/server-build': generateServerBuild(routes, {
|
|
354
1246
|
entryServerPath: finalEntryServerPath,
|
|
355
1247
|
assetsBuildDirectory,
|
|
356
1248
|
basename,
|
|
357
1249
|
appDirectory,
|
|
358
1250
|
ssr,
|
|
359
1251
|
federation: options.federation,
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
// Function to ensure the module is loaded
|
|
369
|
-
const ensureEntryServerLoaded = async () => {
|
|
370
|
-
if (!entryServerModule) {
|
|
371
|
-
entryServerModule = await import(${JSON.stringify(options1.entryServerPath)});
|
|
372
|
-
}
|
|
373
|
-
return entryServerModule;
|
|
374
|
-
};
|
|
375
|
-
|
|
376
|
-
// Helper function to create async handlers
|
|
377
|
-
const createAsyncHandler = (exportName) => {
|
|
378
|
-
return async (...args) => {
|
|
379
|
-
const module = await ensureEntryServerLoaded();
|
|
380
|
-
const handler = module[exportName];
|
|
381
|
-
return typeof handler === 'function' ? handler(...args) : handler;
|
|
382
|
-
};
|
|
383
|
-
};
|
|
384
|
-
|
|
385
|
-
// Helper function to create sync handlers
|
|
386
|
-
const createSyncHandler = (exportName) => {
|
|
387
|
-
return (...args) => {
|
|
388
|
-
if (!entryServerModule) {
|
|
389
|
-
throw new Error('Entry server module not loaded yet. Call an async method first or await ensureEntryServerLoaded()');
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
const handler = entryServerModule[exportName];
|
|
393
|
-
return typeof handler === 'function' ? handler(...args) : handler;
|
|
394
|
-
};
|
|
395
|
-
};
|
|
396
|
-
|
|
397
|
-
// Create a proxy for the entryServer exports
|
|
398
|
-
const entryServer = new Proxy({}, {
|
|
399
|
-
get: (target, prop) => {
|
|
400
|
-
|
|
401
|
-
if (entryServerModule) {
|
|
402
|
-
return entryServerModule[prop];
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
if (prop === 'handleDataRequest' || prop === 'handleRequest' || prop === 'default') {
|
|
406
|
-
return createAsyncHandler(prop);
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
});
|
|
411
|
-
|
|
412
|
-
// Preload the entry server module
|
|
413
|
-
ensureEntryServerLoaded().catch(console.error);
|
|
414
|
-
|
|
415
|
-
${Object.keys(routes).map((key, index)=>{
|
|
416
|
-
let route = routes[key];
|
|
417
|
-
return `import * as route${index} from ${JSON.stringify(`${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(options1.appDirectory, route.file)}?react-router-route`)};`;
|
|
418
|
-
}).join('\n')}
|
|
419
|
-
|
|
420
|
-
export { default as assets } from "virtual/react-router/server-manifest";
|
|
421
|
-
export const assetsBuildDirectory = ${JSON.stringify(options1.assetsBuildDirectory)};
|
|
422
|
-
export const basename = ${JSON.stringify(options1.basename)};
|
|
423
|
-
export const future = ${JSON.stringify({})};
|
|
424
|
-
export const isSpaMode = ${!options1.ssr};
|
|
425
|
-
export const ssr = ${options1.ssr};
|
|
426
|
-
export const routeDiscovery = ${JSON.stringify(options1.routeDiscovery)};
|
|
427
|
-
export const publicPath = "/";
|
|
428
|
-
export const prerender = [];
|
|
429
|
-
export const entry = { module: entryServer };
|
|
430
|
-
export const routes = {
|
|
431
|
-
${Object.keys(routes).map((key, index)=>{
|
|
432
|
-
let route = routes[key];
|
|
433
|
-
return `${JSON.stringify(key)}: {
|
|
434
|
-
id: ${JSON.stringify(route.id)},
|
|
435
|
-
parentId: ${JSON.stringify(route.parentId)},
|
|
436
|
-
path: ${JSON.stringify(route.path)},
|
|
437
|
-
index: ${JSON.stringify(route.index)},
|
|
438
|
-
caseSensitive: ${JSON.stringify(route.caseSensitive)},
|
|
439
|
-
module: route${index}
|
|
440
|
-
}
|
|
441
|
-
`;
|
|
442
|
-
}).join(',\n ')}
|
|
443
|
-
};
|
|
444
|
-
` : `
|
|
445
|
-
import * as entryServer from ${JSON.stringify(options1.entryServerPath)};
|
|
446
|
-
${Object.keys(routes).map((key, index)=>{
|
|
447
|
-
let route = routes[key];
|
|
448
|
-
return `import * as route${index} from ${JSON.stringify(`${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(options1.appDirectory, route.file)}?react-router-route`)};`;
|
|
449
|
-
}).join('\n')}
|
|
450
|
-
|
|
451
|
-
export { default as assets } from "virtual/react-router/server-manifest";
|
|
452
|
-
export const assetsBuildDirectory = ${JSON.stringify(options1.assetsBuildDirectory)};
|
|
453
|
-
export const basename = ${JSON.stringify(options1.basename)};
|
|
454
|
-
export const future = ${JSON.stringify({})};
|
|
455
|
-
export const isSpaMode = ${!options1.ssr};
|
|
456
|
-
export const ssr = ${options1.ssr};
|
|
457
|
-
export const routeDiscovery = ${JSON.stringify(options1.routeDiscovery)};
|
|
458
|
-
export const prerender = [];
|
|
459
|
-
export const publicPath = "/";
|
|
460
|
-
export const entry = { module: entryServer };
|
|
461
|
-
export const routes = {
|
|
462
|
-
${Object.keys(routes).map((key, index)=>{
|
|
463
|
-
let route = routes[key];
|
|
464
|
-
return `${JSON.stringify(key)}: {
|
|
465
|
-
id: ${JSON.stringify(route.id)},
|
|
466
|
-
parentId: ${JSON.stringify(route.parentId)},
|
|
467
|
-
path: ${JSON.stringify(route.path)},
|
|
468
|
-
index: ${JSON.stringify(route.index)},
|
|
469
|
-
caseSensitive: ${JSON.stringify(route.caseSensitive)},
|
|
470
|
-
module: route${index}
|
|
471
|
-
}
|
|
472
|
-
`;
|
|
473
|
-
}).join(',\n ')}
|
|
474
|
-
};
|
|
475
|
-
`,
|
|
1252
|
+
future,
|
|
1253
|
+
allowedActionOrigins: allowedActionOriginsForBuild,
|
|
1254
|
+
prerender: prerenderPaths,
|
|
1255
|
+
routeDiscovery,
|
|
1256
|
+
publicPath: assetPrefix
|
|
1257
|
+
}),
|
|
1258
|
+
...bundleVirtualModules,
|
|
1259
|
+
...bundleManifestModules,
|
|
476
1260
|
'virtual/react-router/with-props': `
|
|
477
1261
|
import { createElement as h } from "react";
|
|
478
1262
|
import { useActionData, useLoaderData, useMatches, useParams, useRouteError } from "react-router";
|
|
@@ -510,20 +1294,46 @@ let pluginReactRouter = (options = {})=>({
|
|
|
510
1294
|
};
|
|
511
1295
|
}
|
|
512
1296
|
`
|
|
513
|
-
});
|
|
1297
|
+
}, vmodTempDir);
|
|
514
1298
|
api.modifyRsbuildConfig(async (config, { mergeRsbuildConfig })=>{
|
|
515
|
-
|
|
1299
|
+
assetPrefix = normalizeAssetPrefix(config.output?.assetPrefix);
|
|
1300
|
+
let useAsyncNodeChunkLoading = options.federation && 'commonjs' === resolvedServerOutput, nodeChunkLoading = 'module' === resolvedServerOutput ? 'import' : useAsyncNodeChunkLoading ? 'async-node' : 'require', serverBuildFileBase = (serverBuildFile || 'index.js').replace(/\.js$/, ''), nodeEntries = {
|
|
1301
|
+
...hasServerApp ? {
|
|
1302
|
+
'static/js/app': serverAppPath
|
|
1303
|
+
} : {
|
|
1304
|
+
'static/js/app': 'virtual/react-router/server-build'
|
|
1305
|
+
},
|
|
1306
|
+
'static/js/entry.server': finalEntryServerPath
|
|
1307
|
+
};
|
|
1308
|
+
for (let [bundleId, bundleRoutes] of Object.entries(routesByServerBundleId))bundleRoutes && 0 !== Object.keys(bundleRoutes).length && (nodeEntries[`${bundleId}/${serverBuildFileBase}`] = `virtual/react-router/server-build-${bundleId}`);
|
|
516
1309
|
return mergeRsbuildConfig(config, {
|
|
517
1310
|
output: {
|
|
518
|
-
assetPrefix:
|
|
1311
|
+
assetPrefix: config.output?.assetPrefix || '/'
|
|
519
1312
|
},
|
|
520
1313
|
dev: {
|
|
521
1314
|
writeToDisk: !0,
|
|
522
|
-
|
|
523
|
-
liveReload: !0,
|
|
524
|
-
setupMiddlewares: pluginOptions.customServer ? [] : [
|
|
1315
|
+
setupMiddlewares: pluginOptions.customServer || !ssr ? [] : [
|
|
525
1316
|
(middlewares, server)=>{
|
|
526
|
-
middlewares.push(
|
|
1317
|
+
middlewares.push(async (req, res, next)=>{
|
|
1318
|
+
try {
|
|
1319
|
+
let tryLoadBundle = async (entryName)=>{
|
|
1320
|
+
try {
|
|
1321
|
+
return await server.environments.node.loadBundle(entryName);
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
if (error instanceof Error && error.message.includes("Can't find entry")) return null;
|
|
1324
|
+
throw error;
|
|
1325
|
+
}
|
|
1326
|
+
}, bundle = await tryLoadBundle('static/js/app') ?? await tryLoadBundle('app');
|
|
1327
|
+
if (!bundle || !bundle.routes) throw Error('Server bundle not found or invalid');
|
|
1328
|
+
let rr = await import("react-router"), nfs = await import("@remix-run/node-fetch-server");
|
|
1329
|
+
if ('function' != typeof rr.createRequestHandler) throw Error('[rsbuild-plugin-react-router] Missing `createRequestHandler` export from `react-router`');
|
|
1330
|
+
if ('function' != typeof nfs.createRequestListener) throw Error('[rsbuild-plugin-react-router] Missing `createRequestListener` export from `@remix-run/node-fetch-server`');
|
|
1331
|
+
let normalizedBuild = normalizeBuildModule(bundle), build = await resolveBuildExports(normalizedBuild), requestHandler = rr.createRequestHandler(build, 'development'), listener = nfs.createRequestListener((request)=>requestHandler(request));
|
|
1332
|
+
await listener(req, res);
|
|
1333
|
+
} catch (error) {
|
|
1334
|
+
console.error('SSR Error:', error), next(error);
|
|
1335
|
+
}
|
|
1336
|
+
});
|
|
527
1337
|
}
|
|
528
1338
|
]
|
|
529
1339
|
},
|
|
@@ -538,11 +1348,9 @@ let pluginReactRouter = (options = {})=>({
|
|
|
538
1348
|
web: {
|
|
539
1349
|
source: {
|
|
540
1350
|
entry: {
|
|
541
|
-
'entry.client': finalEntryClientPath
|
|
1351
|
+
'entry.client': finalEntryClientPath,
|
|
542
1352
|
'virtual/react-router/browser-manifest': 'virtual/react-router/browser-manifest',
|
|
543
|
-
...
|
|
544
|
-
import: `${(0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(appDirectory, route.file)}?${options.federation ? 'react-router-route-federation' : 'react-router-route'}`
|
|
545
|
-
}, acc), {})
|
|
1353
|
+
...webRouteEntries
|
|
546
1354
|
}
|
|
547
1355
|
},
|
|
548
1356
|
output: {
|
|
@@ -560,6 +1368,11 @@ let pluginReactRouter = (options = {})=>({
|
|
|
560
1368
|
topLevelAwait: !0,
|
|
561
1369
|
outputModule: !0
|
|
562
1370
|
},
|
|
1371
|
+
...options.federation ? {
|
|
1372
|
+
output: {
|
|
1373
|
+
chunkLoading: 'import'
|
|
1374
|
+
}
|
|
1375
|
+
} : {},
|
|
563
1376
|
externalsType: 'module',
|
|
564
1377
|
output: {
|
|
565
1378
|
chunkFormat: 'module',
|
|
@@ -577,113 +1390,159 @@ let pluginReactRouter = (options = {})=>({
|
|
|
577
1390
|
}
|
|
578
1391
|
}
|
|
579
1392
|
},
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
app: serverAppPath + (options.federation ? '?react-router-route-federation' : '')
|
|
585
|
-
} : {
|
|
586
|
-
app: 'virtual/react-router/server-build' + (options.federation ? '?react-router-route-federation' : '')
|
|
587
|
-
},
|
|
588
|
-
'entry.server': finalEntryServerPath + (options.federation ? '?react-router-route-federation' : '')
|
|
589
|
-
}
|
|
590
|
-
},
|
|
591
|
-
output: {
|
|
592
|
-
distPath: {
|
|
593
|
-
root: (0, __WEBPACK_EXTERNAL_MODULE_pathe__.resolve)(buildDirectory, 'server')
|
|
1393
|
+
...{
|
|
1394
|
+
node: {
|
|
1395
|
+
source: {
|
|
1396
|
+
entry: nodeEntries
|
|
594
1397
|
},
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
}
|
|
599
|
-
},
|
|
600
|
-
tools: {
|
|
601
|
-
rspack: {
|
|
602
|
-
target: options.federation ? 'async-node' : 'node',
|
|
603
|
-
externals: [
|
|
604
|
-
'express'
|
|
605
|
-
],
|
|
606
|
-
dependencies: [
|
|
607
|
-
'web'
|
|
608
|
-
],
|
|
609
|
-
experiments: {
|
|
610
|
-
outputModule: 'module' === pluginOptions.serverOutput
|
|
1398
|
+
output: {
|
|
1399
|
+
distPath: {
|
|
1400
|
+
root: resolve(buildDirectory, 'server')
|
|
611
1401
|
},
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
1402
|
+
target: config.environments?.node?.output?.target || 'node',
|
|
1403
|
+
filename: {
|
|
1404
|
+
js: '[name].js'
|
|
1405
|
+
}
|
|
1406
|
+
},
|
|
1407
|
+
tools: {
|
|
1408
|
+
rspack: {
|
|
1409
|
+
target: options.federation ? 'async-node' : 'node',
|
|
1410
|
+
externals: nodeExternals,
|
|
1411
|
+
dependencies: [
|
|
1412
|
+
'web'
|
|
1413
|
+
],
|
|
1414
|
+
experiments: {
|
|
1415
|
+
outputModule: 'module' === resolvedServerOutput,
|
|
1416
|
+
...options.federation ? {
|
|
1417
|
+
asyncStartup: !0
|
|
1418
|
+
} : {}
|
|
620
1419
|
},
|
|
621
|
-
|
|
1420
|
+
externalsType: resolvedServerOutput,
|
|
1421
|
+
output: {
|
|
1422
|
+
chunkFormat: resolvedServerOutput,
|
|
1423
|
+
chunkLoading: nodeChunkLoading,
|
|
1424
|
+
workerChunkLoading: nodeChunkLoading,
|
|
1425
|
+
wasmLoading: 'fetch',
|
|
1426
|
+
module: 'module' === resolvedServerOutput
|
|
1427
|
+
}
|
|
622
1428
|
}
|
|
623
1429
|
}
|
|
624
1430
|
}
|
|
625
1431
|
}
|
|
626
1432
|
}
|
|
627
1433
|
});
|
|
628
|
-
}), api.modifyEnvironmentConfig(async (config, { name, mergeEnvironmentConfig })=>'web'
|
|
1434
|
+
}), api.modifyEnvironmentConfig(async (config, { name, mergeEnvironmentConfig })=>'web' !== name && 'node' !== name ? config : mergeEnvironmentConfig(config, {
|
|
629
1435
|
tools: {
|
|
630
1436
|
rspack: (rspackConfig)=>{
|
|
631
|
-
if (
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
1437
|
+
if (pluginOptions.federation && ((rspackConfig)=>{
|
|
1438
|
+
if (rspackConfig?.plugins?.length) for (let plugin of rspackConfig.plugins){
|
|
1439
|
+
if (!plugin || 'object' != typeof plugin || 'ModuleFederationPlugin' !== plugin.name) continue;
|
|
1440
|
+
let pluginOptions = plugin._options ?? plugin.options;
|
|
1441
|
+
pluginOptions && (pluginOptions.experiments = {
|
|
1442
|
+
...pluginOptions.experiments,
|
|
1443
|
+
asyncStartup: !0
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
})(rspackConfig), 'node' === name && 'module' === resolvedServerOutput) {
|
|
1447
|
+
let output = rspackConfig.output, library = output?.library, libraryType = library && 'object' == typeof library && !Array.isArray(library) && 'type' in library ? library.type : void 0;
|
|
1448
|
+
output && 'commonjs2' === libraryType && (rspackConfig.output = {
|
|
1449
|
+
...output,
|
|
1450
|
+
library: {
|
|
1451
|
+
type: 'module'
|
|
1452
|
+
}
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
return 'web' === name && rspackConfig.plugins && rspackConfig.plugins.push(function(routes, pluginOptions, appDirectory, assetPrefix = '/', routeChunkOptions, options) {
|
|
1456
|
+
return {
|
|
1457
|
+
apply (compiler) {
|
|
1458
|
+
compiler.hooks.emit.tapAsync('ModifyBrowserManifest', async (compilation, callback)=>{
|
|
1459
|
+
let sri, stats = compilation.getStats().toJson(), manifest = await getReactRouterManifestForDev(routes, pluginOptions, stats, appDirectory, assetPrefix, routeChunkOptions), virtualManifestPath = 'static/js/virtual/react-router/browser-manifest.js';
|
|
1460
|
+
if (compilation.assets[virtualManifestPath]) {
|
|
1461
|
+
let newSource = compilation.assets[virtualManifestPath].source().toString().replace(/["'`]PLACEHOLDER["'`]/, jsesc(manifest, {
|
|
1462
|
+
es6: !0
|
|
1463
|
+
}));
|
|
1464
|
+
compilation.assets[virtualManifestPath] = {
|
|
1465
|
+
source: ()=>newSource,
|
|
1466
|
+
size: ()=>newSource.length,
|
|
1467
|
+
map: ()=>({
|
|
657
1468
|
version: 3,
|
|
658
1469
|
sources: [
|
|
659
|
-
|
|
1470
|
+
virtualManifestPath
|
|
660
1471
|
],
|
|
661
1472
|
names: [],
|
|
662
1473
|
mappings: '',
|
|
663
|
-
file:
|
|
1474
|
+
file: virtualManifestPath,
|
|
664
1475
|
sourcesContent: [
|
|
665
1476
|
newSource
|
|
666
1477
|
]
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
1478
|
+
}),
|
|
1479
|
+
sourceAndMap: ()=>({
|
|
1480
|
+
source: newSource,
|
|
1481
|
+
map: {
|
|
1482
|
+
version: 3,
|
|
1483
|
+
sources: [
|
|
1484
|
+
virtualManifestPath
|
|
1485
|
+
],
|
|
1486
|
+
names: [],
|
|
1487
|
+
mappings: '',
|
|
1488
|
+
file: virtualManifestPath,
|
|
1489
|
+
sourcesContent: [
|
|
1490
|
+
newSource
|
|
1491
|
+
]
|
|
1492
|
+
}
|
|
1493
|
+
}),
|
|
1494
|
+
updateHash: (hash)=>hash.update(newSource),
|
|
1495
|
+
buffer: ()=>Buffer.from(newSource)
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
if (routeChunkOptions?.isBuild) {
|
|
1499
|
+
let entryAssets = stats?.assetsByChunkName?.['entry.client'], entryJsAssets = entryAssets?.filter((asset)=>asset.endsWith('.js')) || [], manifestPath = getReactRouterManifestPath({
|
|
1500
|
+
version: manifest.version,
|
|
1501
|
+
isBuild: !0,
|
|
1502
|
+
entryModulePath: entryJsAssets[0]
|
|
1503
|
+
}), manifestSource = `window.__reactRouterManifest=${jsesc(manifest, {
|
|
1504
|
+
es6: !0
|
|
1505
|
+
})};`;
|
|
1506
|
+
compilation.assets[manifestPath] = new rspack.sources.RawSource(manifestSource);
|
|
1507
|
+
}
|
|
1508
|
+
if (routeChunkOptions?.isBuild && options?.future?.unstable_subResourceIntegrity) for (let asset of (sri = {}, 'function' == typeof compilation.getAssets ? compilation.getAssets() : Object.entries(compilation.assets).map(([name, asset])=>({
|
|
1509
|
+
name,
|
|
1510
|
+
source: asset
|
|
1511
|
+
})))){
|
|
1512
|
+
if (!asset.name.endsWith('.js')) continue;
|
|
1513
|
+
let source = asset.source.source().toString(), hash = createHash('sha384').update(source).digest('base64');
|
|
1514
|
+
sri[combineURLs(assetPrefix, asset.name)] = `sha384-${hash}`;
|
|
1515
|
+
}
|
|
1516
|
+
options?.onManifest?.(manifest, sri), callback();
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
};
|
|
1520
|
+
}(routes, pluginOptions, appDirectory, assetPrefix, routeChunkOptions, {
|
|
1521
|
+
future,
|
|
1522
|
+
onManifest: (manifest, sri)=>{
|
|
1523
|
+
let baseServerManifest = {
|
|
1524
|
+
...manifest,
|
|
1525
|
+
sri
|
|
1526
|
+
};
|
|
1527
|
+
for (let [bundleId, bundleRoutes] of (latestServerManifest = baseServerManifest, Object.entries(routesByServerBundleId))){
|
|
1528
|
+
if (!bundleRoutes) continue;
|
|
1529
|
+
let routeIds = new Set(Object.keys(bundleRoutes)), filteredRoutes = Object.fromEntries(Object.entries(manifest.routes).filter(([routeId])=>routeIds.has(routeId)));
|
|
1530
|
+
latestServerManifestsByBundleId[bundleId] = {
|
|
1531
|
+
...baseServerManifest,
|
|
1532
|
+
routes: filteredRoutes
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
675
1535
|
}
|
|
676
|
-
});
|
|
677
|
-
return rspackConfig;
|
|
1536
|
+
})), rspackConfig;
|
|
678
1537
|
}
|
|
679
1538
|
}
|
|
680
|
-
})
|
|
1539
|
+
})), api.processAssets({
|
|
681
1540
|
stage: 'additional',
|
|
682
1541
|
targets: [
|
|
683
1542
|
'node'
|
|
684
1543
|
]
|
|
685
1544
|
}, ({ sources, compilation })=>{
|
|
686
|
-
let packageJsonPath = 'package.json', source = new sources.RawSource(`{"type": "${
|
|
1545
|
+
let packageJsonPath = 'package.json', source = new sources.RawSource(`{"type": "${resolvedServerOutput}"}`);
|
|
687
1546
|
compilation.getAsset(packageJsonPath) ? compilation.updateAsset(packageJsonPath, source) : compilation.emitAsset(packageJsonPath, source);
|
|
688
1547
|
}), api.transform({
|
|
689
1548
|
test: /virtual\/react-router\/(browser|server)-manifest/
|
|
@@ -691,36 +1550,288 @@ let pluginReactRouter = (options = {})=>({
|
|
|
691
1550
|
if ('web' === args.environment.name) return {
|
|
692
1551
|
code: 'window.__reactRouterManifest = "PLACEHOLDER";'
|
|
693
1552
|
};
|
|
694
|
-
let manifest = await getReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory);
|
|
1553
|
+
let bundleMatch = args.resource.match(/virtual\/react-router\/server-manifest(?:-([^?]+))?/), bundleId = bundleMatch?.[1]?.replace(/\\.js$/, ''), manifest = (isBuild && latestServerManifest ? bundleId && latestServerManifestsByBundleId[bundleId] ? latestServerManifestsByBundleId[bundleId] : latestServerManifest : null) ?? await getReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory, assetPrefix, routeChunkOptions);
|
|
695
1554
|
return {
|
|
696
|
-
code: `export default ${(
|
|
1555
|
+
code: `export default ${jsesc(manifest, {
|
|
697
1556
|
es6: !0
|
|
698
1557
|
})};`
|
|
699
1558
|
};
|
|
700
1559
|
}), api.transform({
|
|
701
|
-
resourceQuery:
|
|
702
|
-
}, async (args)=>
|
|
1560
|
+
resourceQuery: /__react-router-build-client-route/
|
|
1561
|
+
}, async (args)=>{
|
|
1562
|
+
let code = await transformToEsm(args.code, args.resourcePath), exportNames = await getExportNames(code), isServer = args.environment?.name === 'node', chunkedExportSet = new Set(!isServer && isBuild && splitRouteModules ? (await detectRouteChunksIfEnabled(routeChunkCache, routeChunkConfig, args.resourcePath, code)).chunkedExports : []), reexports = exportNames.filter((exp)=>!chunkedExportSet.has(exp) && (CLIENT_ROUTE_EXPORTS.includes(exp) || isServer && SERVER_ONLY_ROUTE_EXPORTS.includes(exp))), target = `${args.resourcePath}?react-router-route`;
|
|
1563
|
+
return {
|
|
1564
|
+
code: `export { ${reexports.join(', ')} } from ${JSON.stringify(target)};`
|
|
1565
|
+
};
|
|
1566
|
+
}), api.transform({
|
|
1567
|
+
resourceQuery: /route-chunk=/
|
|
1568
|
+
}, async (args)=>{
|
|
1569
|
+
if (args.environment?.name !== 'web') return {
|
|
1570
|
+
code: args.code,
|
|
1571
|
+
map: null
|
|
1572
|
+
};
|
|
1573
|
+
let preventEmptyChunkSnippet = (reason)=>`Math.random()<0&&console.log(${JSON.stringify(reason)});`;
|
|
1574
|
+
if (!isBuild || !splitRouteModules) return {
|
|
1575
|
+
code: preventEmptyChunkSnippet('Split route modules disabled'),
|
|
1576
|
+
map: null
|
|
1577
|
+
};
|
|
1578
|
+
let chunkName = ((id)=>{
|
|
1579
|
+
if (!id.includes(routeChunkQueryStringPrefix)) return null;
|
|
1580
|
+
let chunkName = id.split(routeChunkQueryStringPrefix)[1].split('&')[0];
|
|
1581
|
+
return 'main' === chunkName || routeChunkExportNames.includes(chunkName) ? chunkName : null;
|
|
1582
|
+
})(args.resource);
|
|
1583
|
+
if (!chunkName) throw Error(`Invalid route chunk name in "${args.resource}"`);
|
|
1584
|
+
let transformed = await transformToEsm(args.code, args.resourcePath), chunk = await getRouteChunkIfEnabled(routeChunkCache, routeChunkConfig, args.resourcePath, chunkName, transformed);
|
|
1585
|
+
if (enforceSplitRouteModules && 'main' === chunkName && chunk) {
|
|
1586
|
+
let exportNames = await getExportNames(chunk);
|
|
1587
|
+
validateRouteChunks({
|
|
1588
|
+
config: routeChunkConfig,
|
|
1589
|
+
id: args.resourcePath,
|
|
1590
|
+
valid: {
|
|
1591
|
+
clientAction: !exportNames.includes('clientAction'),
|
|
1592
|
+
clientLoader: !exportNames.includes('clientLoader'),
|
|
1593
|
+
clientMiddleware: !exportNames.includes('clientMiddleware'),
|
|
1594
|
+
HydrateFallback: !exportNames.includes('HydrateFallback')
|
|
1595
|
+
}
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
return {
|
|
1599
|
+
code: chunk ?? preventEmptyChunkSnippet(`No ${chunkName} chunk`),
|
|
1600
|
+
map: null
|
|
1601
|
+
};
|
|
1602
|
+
}), api.transform({
|
|
1603
|
+
test: /\.[cm]?[jt]sx?$/
|
|
1604
|
+
}, async (args)=>{
|
|
1605
|
+
if (args.environment?.name !== 'web' || !isBuild || !splitRouteModules || args.resource.includes(BUILD_CLIENT_ROUTE_QUERY_STRING) || args.resource.includes('?react-router-route') || args.resource.includes('route-chunk=') || !routeByFilePath.get(args.resourcePath)) return {
|
|
1606
|
+
code: args.code,
|
|
1607
|
+
map: null
|
|
1608
|
+
};
|
|
1609
|
+
let transformed = await transformToEsm(args.code, args.resourcePath), { hasRouteChunks, chunkedExports } = await detectRouteChunksIfEnabled(routeChunkCache, routeChunkConfig, args.resourcePath, transformed);
|
|
1610
|
+
if (!hasRouteChunks) return {
|
|
1611
|
+
code: args.code,
|
|
1612
|
+
map: null
|
|
1613
|
+
};
|
|
1614
|
+
let sourceExports = await getCachedRouteExports(args.resourcePath), chunkedExportSet = new Set(chunkedExports), mainChunkReexports = sourceExports.filter((name)=>!chunkedExportSet.has(name)).join(', '), chunkBasePath = `./${external_pathe_basename(args.resourcePath)}`;
|
|
1615
|
+
return {
|
|
1616
|
+
code: [
|
|
1617
|
+
mainChunkReexports ? `export { ${mainChunkReexports} } from "${getRouteChunkModuleId(chunkBasePath, 'main')}";` : null,
|
|
1618
|
+
...chunkedExports.map((exportName)=>`export { ${exportName} } from "${getRouteChunkModuleId(chunkBasePath, exportName)}";`)
|
|
1619
|
+
].filter(Boolean).join('\n'),
|
|
1620
|
+
map: null
|
|
1621
|
+
};
|
|
1622
|
+
}), api.transform({
|
|
1623
|
+
test: /[\\/]\.server[\\/]|\.server(\.[cm]?[jt]sx?)?$/
|
|
1624
|
+
}, async (args)=>{
|
|
1625
|
+
if (args.environment?.name !== 'web') return {
|
|
1626
|
+
code: args.code,
|
|
1627
|
+
map: null
|
|
1628
|
+
};
|
|
1629
|
+
let relativePath = relative(process.cwd(), args.resourcePath);
|
|
1630
|
+
throw Error(`[${PLUGIN_NAME}] Server-only module referenced by client: ${relativePath}`);
|
|
1631
|
+
}), api.transform({
|
|
1632
|
+
test: /[\\/]\.client[\\/]|\.client(\.[cm]?[jt]sx?)?$/
|
|
1633
|
+
}, async (args)=>{
|
|
1634
|
+
if (args.environment?.name !== 'node') return {
|
|
1635
|
+
code: args.code,
|
|
1636
|
+
map: null
|
|
1637
|
+
};
|
|
1638
|
+
let code = await transformToEsm(args.code, args.resourcePath), { exportNames: directExportNames, exportAllModules } = await getExportNamesAndExportAll(code), exportNames = new Set(directExportNames), unresolvedExportAll = new Set(), visitedModules = new Set(), resolveIndexFile = (dirPath)=>{
|
|
1639
|
+
for (let ext of JS_EXTENSIONS){
|
|
1640
|
+
let candidate = resolve(dirPath, `index${ext}`);
|
|
1641
|
+
if (existsSync(candidate)) try {
|
|
1642
|
+
if (statSync(candidate).isFile()) return candidate;
|
|
1643
|
+
} catch {
|
|
1644
|
+
continue;
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
return null;
|
|
1648
|
+
}, resolveExportAllModule = (specifier, importerPath)=>{
|
|
1649
|
+
if (specifier.startsWith('.') || specifier.startsWith('/')) {
|
|
1650
|
+
let resolvedPath = ((basePath)=>{
|
|
1651
|
+
if (existsSync(basePath)) try {
|
|
1652
|
+
let stats = statSync(basePath);
|
|
1653
|
+
if (stats.isFile()) return basePath;
|
|
1654
|
+
if (stats.isDirectory()) return resolveIndexFile(basePath);
|
|
1655
|
+
} catch {}
|
|
1656
|
+
for (let ext of JS_EXTENSIONS){
|
|
1657
|
+
let candidate = `${basePath}${ext}`;
|
|
1658
|
+
if (existsSync(candidate)) try {
|
|
1659
|
+
if (statSync(candidate).isFile()) return candidate;
|
|
1660
|
+
} catch {
|
|
1661
|
+
continue;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
return resolveIndexFile(basePath);
|
|
1665
|
+
})(specifier.startsWith('/') ? specifier : resolve(dirname(importerPath), specifier));
|
|
1666
|
+
if (resolvedPath) return resolvedPath;
|
|
1667
|
+
}
|
|
1668
|
+
try {
|
|
1669
|
+
return createRequire(pathToFileURL(importerPath).href).resolve(specifier);
|
|
1670
|
+
} catch {
|
|
1671
|
+
return null;
|
|
1672
|
+
}
|
|
1673
|
+
}, collectExportNamesFromModule = async (modulePath)=>{
|
|
1674
|
+
if (visitedModules.has(modulePath)) return;
|
|
1675
|
+
visitedModules.add(modulePath);
|
|
1676
|
+
let source = await readFile(modulePath, 'utf8'), moduleCode = await transformToEsm(source, modulePath), { exportNames: moduleExportNames, exportAllModules: moduleExportAll } = await getExportNamesAndExportAll(moduleCode);
|
|
1677
|
+
for (let name of moduleExportNames)'default' !== name && exportNames.add(name);
|
|
1678
|
+
for (let nestedSpecifier of moduleExportAll){
|
|
1679
|
+
let nestedPath = resolveExportAllModule(nestedSpecifier, modulePath);
|
|
1680
|
+
if (!nestedPath) {
|
|
1681
|
+
unresolvedExportAll.add(nestedSpecifier);
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
await collectExportNamesFromModule(nestedPath);
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
for (let specifier of exportAllModules){
|
|
1688
|
+
let resolvedPath = resolveExportAllModule(specifier, args.resourcePath);
|
|
1689
|
+
if (!resolvedPath) {
|
|
1690
|
+
unresolvedExportAll.add(specifier);
|
|
1691
|
+
continue;
|
|
1692
|
+
}
|
|
1693
|
+
await collectExportNamesFromModule(resolvedPath);
|
|
1694
|
+
}
|
|
1695
|
+
if (unresolvedExportAll.size > 0) throw Error(`[${PLUGIN_NAME}] Client-only module uses \`export * from\` with unresolvable specifier(s): ${Array.from(unresolvedExportAll).map((spec)=>`\`${spec}\``).join(', ')}. Please explicitly re-export named bindings in \`${relative(process.cwd(), args.resourcePath)}\`.`);
|
|
1696
|
+
return {
|
|
1697
|
+
code: Array.from(exportNames).map((name)=>'default' === name ? 'export default undefined;' : `export const ${name} = undefined;`).join('\n'),
|
|
1698
|
+
map: null
|
|
1699
|
+
};
|
|
1700
|
+
}), api.transform({
|
|
703
1701
|
resourceQuery: /\?react-router-route/
|
|
704
1702
|
}, async (args)=>{
|
|
705
|
-
let code;
|
|
1703
|
+
let code, scopeCrawled;
|
|
706
1704
|
try {
|
|
707
|
-
code =
|
|
708
|
-
jsx: 'automatic',
|
|
709
|
-
format: 'esm',
|
|
710
|
-
platform: 'neutral',
|
|
711
|
-
loader: args.resourcePath.endsWith('x') ? 'tsx' : 'ts'
|
|
712
|
-
})).code;
|
|
1705
|
+
code = await transformToEsm(args.code, args.resourcePath);
|
|
713
1706
|
} catch (error) {
|
|
714
1707
|
throw console.error(args.resourcePath), error;
|
|
715
1708
|
}
|
|
1709
|
+
if ('web' === args.environment.name && !ssr && isSpaMode) {
|
|
1710
|
+
let exportNames = await getExportNames(code), isRootRoute = args.resourcePath === rootRoutePath, invalidServerOnly = exportNames.filter((exp)=>(!isRootRoute || 'loader' !== exp) && SERVER_ONLY_ROUTE_EXPORTS.includes(exp));
|
|
1711
|
+
if (invalidServerOnly.length > 0) {
|
|
1712
|
+
let list = invalidServerOnly.map((e)=>`\`${e}\``).join(', ');
|
|
1713
|
+
throw Error(`SPA Mode: ${invalidServerOnly.length} invalid route export(s) in \`${relative(process.cwd(), args.resourcePath)}\`: ${list}. See https://reactrouter.com/how-to/spa for more information.`);
|
|
1714
|
+
}
|
|
1715
|
+
if (!isRootRoute && exportNames.includes('HydrateFallback')) throw Error(`SPA Mode: Invalid \`HydrateFallback\` export found in \`${relative(process.cwd(), args.resourcePath)}\`. \`HydrateFallback\` is only permitted on the root route in SPA Mode. See https://reactrouter.com/how-to/spa for more information.`);
|
|
1716
|
+
}
|
|
716
1717
|
let defaultExportMatch = code.match(/\n\s{0,}([\w\d_]+)\sas default,?/);
|
|
717
1718
|
defaultExportMatch && 'number' == typeof defaultExportMatch.index && (code = code.slice(0, defaultExportMatch.index) + code.slice(defaultExportMatch.index + defaultExportMatch[0].length) + `\nexport default ${defaultExportMatch[1]};`);
|
|
718
|
-
let ast =
|
|
1719
|
+
let ast = parse(code, {
|
|
719
1720
|
sourceType: 'module'
|
|
720
1721
|
});
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
1722
|
+
if ('web' === args.environment.name) {
|
|
1723
|
+
var exportsToRemove = [
|
|
1724
|
+
...SERVER_ONLY_ROUTE_EXPORTS
|
|
1725
|
+
];
|
|
1726
|
+
let previouslyReferencedIdentifiers = findReferencedIdentifiers(ast), exportsFiltered = !1, markedForRemoval = new Set(), removedExportLocalNames = new Set();
|
|
1727
|
+
if (traverse(ast, {
|
|
1728
|
+
ExportDeclaration (path) {
|
|
1729
|
+
if ('ExportNamedDeclaration' === path.node.type) {
|
|
1730
|
+
if (path.node.specifiers.length && (path.node.specifiers = path.node.specifiers.filter((specifier)=>!('ExportSpecifier' === specifier.type && 'Identifier' === specifier.exported.type && exportsToRemove.includes(specifier.exported.name)) || (exportsFiltered = !0, specifier.local && 'Identifier' === specifier.local.type && specifier.local.name !== specifier.exported.name && removedExportLocalNames.add(specifier.local.name), !1)), 0 === path.node.specifiers.length && markedForRemoval.add(path)), path.node.declaration?.type === 'VariableDeclaration') {
|
|
1731
|
+
let declaration = path.node.declaration;
|
|
1732
|
+
declaration.declarations = declaration.declarations.filter((declaration)=>'Identifier' === declaration.id.type && exportsToRemove.includes(declaration.id.name) ? (exportsFiltered = !0, !1) : (('ArrayPattern' === declaration.id.type || 'ObjectPattern' === declaration.id.type) && function validateDestructuredExports(id, exportsToRemove) {
|
|
1733
|
+
if ('ArrayPattern' === id.type) {
|
|
1734
|
+
for (let element of id.elements)if (element) {
|
|
1735
|
+
if ('Identifier' === element.type && exportsToRemove.includes(element.name)) throw invalidDestructureError(element.name);
|
|
1736
|
+
if ('RestElement' === element.type && 'Identifier' === element.argument.type && exportsToRemove.includes(element.argument.name)) throw invalidDestructureError(element.argument.name);
|
|
1737
|
+
('ArrayPattern' === element.type || 'ObjectPattern' === element.type) && validateDestructuredExports(element, exportsToRemove);
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
if ('ObjectPattern' === id.type) {
|
|
1741
|
+
for (let property of id.properties)if (property) {
|
|
1742
|
+
if ('ObjectProperty' === property.type && 'Identifier' === property.key.type) {
|
|
1743
|
+
if ('Identifier' === property.value.type && exportsToRemove.includes(property.value.name)) throw invalidDestructureError(property.value.name);
|
|
1744
|
+
('ArrayPattern' === property.value.type || 'ObjectPattern' === property.value.type) && validateDestructuredExports(property.value, exportsToRemove);
|
|
1745
|
+
}
|
|
1746
|
+
if ('RestElement' === property.type && 'Identifier' === property.argument.type && exportsToRemove.includes(property.argument.name)) throw invalidDestructureError(property.argument.name);
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
}(declaration.id, exportsToRemove), !0)), 0 === declaration.declarations.length && markedForRemoval.add(path);
|
|
1750
|
+
}
|
|
1751
|
+
if (path.node.declaration?.type === 'FunctionDeclaration') {
|
|
1752
|
+
let id = path.node.declaration.id;
|
|
1753
|
+
id && exportsToRemove.includes(id.name) && markedForRemoval.add(path);
|
|
1754
|
+
}
|
|
1755
|
+
if (path.node.declaration?.type === 'ClassDeclaration') {
|
|
1756
|
+
let id = path.node.declaration.id;
|
|
1757
|
+
id && exportsToRemove.includes(id.name) && markedForRemoval.add(path);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
'ExportDefaultDeclaration' === path.node.type && exportsToRemove.includes('default') && (markedForRemoval.add(path), path.node.declaration && ('Identifier' === path.node.declaration.type ? removedExportLocalNames.add(path.node.declaration.name) : ('FunctionDeclaration' === path.node.declaration.type || 'ClassDeclaration' === path.node.declaration.type) && path.node.declaration.id && removedExportLocalNames.add(path.node.declaration.id.name)));
|
|
1761
|
+
}
|
|
1762
|
+
}), traverse(ast, {
|
|
1763
|
+
ExpressionStatement (path) {
|
|
1764
|
+
if (!path.parentPath.isProgram()) return;
|
|
1765
|
+
let expr = path.node.expression;
|
|
1766
|
+
if ('AssignmentExpression' !== expr.type) return;
|
|
1767
|
+
let left = expr.left;
|
|
1768
|
+
'MemberExpression' === left.type && 'Identifier' === left.object.type && (exportsToRemove.includes(left.object.name) || removedExportLocalNames.has(left.object.name)) && markedForRemoval.add(path);
|
|
1769
|
+
}
|
|
1770
|
+
}), markedForRemoval.size > 0 || exportsFiltered) {
|
|
1771
|
+
for (let path of markedForRemoval)path.remove();
|
|
1772
|
+
deadCodeElimination(ast, previouslyReferencedIdentifiers);
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
let hocs = [];
|
|
1776
|
+
function getHocUid(path, hocName) {
|
|
1777
|
+
let uid = path.scope.generateUidIdentifier(hocName);
|
|
1778
|
+
return hocs.push([
|
|
1779
|
+
hocName,
|
|
1780
|
+
uid
|
|
1781
|
+
]), uid;
|
|
1782
|
+
}
|
|
1783
|
+
return traverse(ast, {
|
|
1784
|
+
ExportDeclaration (path) {
|
|
1785
|
+
if (path.isExportDefaultDeclaration()) {
|
|
1786
|
+
let declaration = path.get('declaration'), expr = declaration.isExpression() ? declaration.node : declaration.isFunctionDeclaration() ? toFunctionExpression(declaration.node) : void 0;
|
|
1787
|
+
if (expr) {
|
|
1788
|
+
let uid = getHocUid(path, 'withComponentProps');
|
|
1789
|
+
declaration.replaceWith(__rspack_external__babel_types_69e65b52.callExpression(uid, [
|
|
1790
|
+
expr
|
|
1791
|
+
]));
|
|
1792
|
+
}
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
if (path.isExportNamedDeclaration()) {
|
|
1796
|
+
let decl = path.get('declaration');
|
|
1797
|
+
if (decl.isVariableDeclaration()) return void decl.get('declarations').forEach((varDeclarator)=>{
|
|
1798
|
+
let id = varDeclarator.get('id'), init = varDeclarator.get('init'), expr = init.node;
|
|
1799
|
+
if (!expr || !id.isIdentifier()) return;
|
|
1800
|
+
let { name } = id.node;
|
|
1801
|
+
if (!isNamedComponentExport(name)) return;
|
|
1802
|
+
let uid = getHocUid(path, `with${name}Props`);
|
|
1803
|
+
init.replaceWith(__rspack_external__babel_types_69e65b52.callExpression(uid, [
|
|
1804
|
+
expr
|
|
1805
|
+
]));
|
|
1806
|
+
});
|
|
1807
|
+
if (decl.isFunctionDeclaration()) {
|
|
1808
|
+
let { id } = decl.node;
|
|
1809
|
+
if (!id) return;
|
|
1810
|
+
let { name } = id;
|
|
1811
|
+
if (!isNamedComponentExport(name)) return;
|
|
1812
|
+
let uid = getHocUid(path, `with${name}Props`);
|
|
1813
|
+
decl.replaceWith(__rspack_external__babel_types_69e65b52.variableDeclaration('const', [
|
|
1814
|
+
__rspack_external__babel_types_69e65b52.variableDeclarator(__rspack_external__babel_types_69e65b52.identifier(name), __rspack_external__babel_types_69e65b52.callExpression(uid, [
|
|
1815
|
+
toFunctionExpression(decl.node)
|
|
1816
|
+
]))
|
|
1817
|
+
]));
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
}), hocs.length > 0 && ast.program.body.unshift(__rspack_external__babel_types_69e65b52.importDeclaration(hocs.map(([name, identifier])=>__rspack_external__babel_types_69e65b52.importSpecifier(identifier, __rspack_external__babel_types_69e65b52.identifier(name))), __rspack_external__babel_types_69e65b52.stringLiteral('virtual/react-router/with-props'))), 'web' === args.environment.name && (scopeCrawled = !1, traverse(ast, {
|
|
1822
|
+
Program (path) {
|
|
1823
|
+
scopeCrawled || (path.scope.crawl(), scopeCrawled = !0);
|
|
1824
|
+
},
|
|
1825
|
+
ImportDeclaration (path) {
|
|
1826
|
+
if (0 !== path.node.specifiers.length) {
|
|
1827
|
+
for (let specifierPath of path.get('specifiers')){
|
|
1828
|
+
let local = specifierPath.node.local, binding = local ? path.scope.getBinding(local.name) : null;
|
|
1829
|
+
binding && binding.referenced || specifierPath.remove();
|
|
1830
|
+
}
|
|
1831
|
+
0 === path.node.specifiers.length && path.remove();
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
})), generate(ast, {
|
|
724
1835
|
sourceMaps: !0,
|
|
725
1836
|
filename: args.resource,
|
|
726
1837
|
sourceFileName: args.resourcePath
|