rsbuild-plugin-react-router 0.2.0 → 0.3.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 +213 -201
- package/dist/451.js +1103 -0
- package/dist/bounded-cache.d.ts +1 -0
- package/dist/build-manifest.d.ts +7 -4
- package/dist/build-output-transforms.d.ts +30 -0
- package/dist/concurrency.d.ts +3 -0
- package/dist/config-imports.d.ts +10 -0
- package/dist/constants.d.ts +3 -0
- package/dist/dev-background-resources.d.ts +38 -0
- package/dist/dev-generation.d.ts +25 -0
- package/dist/dev-runtime-artifacts.d.ts +47 -0
- package/dist/dev-runtime-compilation.d.ts +47 -0
- package/dist/dev-runtime-controller.d.ts +14 -0
- package/dist/dev-runtime-session.d.ts +34 -0
- package/dist/dev-server.d.ts +16 -2
- package/dist/effect-runtime.d.ts +18 -0
- package/dist/export-utils.d.ts +15 -7
- package/dist/index.cjs +13775 -1412
- package/dist/index.d.ts +8 -1
- package/dist/index.js +9429 -1501
- package/dist/lazy-compilation-prewarm.d.ts +25 -0
- package/dist/lazy-compilation.d.ts +6 -0
- package/dist/manifest.d.ts +48 -10
- package/dist/modify-browser-manifest.d.ts +30 -13
- package/dist/parallel-route-transform-protocol.d.ts +25 -0
- package/dist/parallel-route-transform-worker.d.ts +1 -0
- package/dist/parallel-route-transform-worker.js +38 -0
- package/dist/parallel-route-transforms.d.ts +29 -0
- package/dist/performance.d.ts +26 -0
- package/dist/plugin-utils.d.ts +2 -12
- package/dist/prerender-build.d.ts +36 -0
- package/dist/prerender.d.ts +27 -2
- package/dist/react-router-config.d.ts +15 -5
- package/dist/route-artifacts.d.ts +33 -0
- package/dist/route-ast.d.ts +21 -0
- package/dist/route-chunks.d.ts +9 -1
- package/dist/route-component-transform.d.ts +5 -0
- package/dist/route-export-pruning.d.ts +6 -0
- package/dist/route-export-resolution.d.ts +5 -0
- package/dist/route-transform-tasks.d.ts +47 -0
- package/dist/route-watch.d.ts +27 -0
- package/dist/server-build-plan.d.ts +22 -0
- package/dist/server-build-resolution.d.ts +3 -0
- package/dist/server-utils.d.ts +3 -2
- package/dist/ssr-externals.d.ts +1 -0
- package/dist/templates/entry.server.cjs +3 -3
- package/dist/templates/entry.server.js +3 -3
- package/dist/typegen.d.ts +15 -0
- package/dist/types.d.ts +41 -14
- package/dist/virtual-modules.d.ts +2 -0
- package/dist/warnings/warn-on-client-source-maps.d.ts +1 -0
- package/dist/yuku.d.ts +15 -0
- package/package.json +24 -19
- package/src/bounded-cache.ts +18 -0
- package/src/build-manifest.ts +205 -0
- package/src/build-output-transforms.ts +273 -0
- package/src/concurrency.ts +15 -0
- package/src/config-imports.ts +83 -0
- package/src/constants.ts +91 -0
- package/src/dev-background-resources.ts +255 -0
- package/src/dev-generation.ts +690 -0
- package/src/dev-runtime-artifacts.ts +239 -0
- package/src/dev-runtime-compilation.ts +171 -0
- package/src/dev-runtime-controller.ts +542 -0
- package/src/dev-runtime-session.ts +191 -0
- package/src/dev-server.ts +88 -0
- package/src/effect-runtime.ts +130 -0
- package/src/export-utils.ts +278 -0
- package/src/index.ts +990 -0
- package/src/lazy-compilation-prewarm.ts +279 -0
- package/src/lazy-compilation.ts +101 -0
- package/src/manifest.ts +591 -0
- package/src/modify-browser-manifest.ts +246 -0
- package/src/parallel-route-transform-protocol.ts +35 -0
- package/src/parallel-route-transform-worker.ts +82 -0
- package/src/parallel-route-transforms.ts +458 -0
- package/src/performance.ts +254 -0
- package/src/plugin-utils.ts +82 -0
- package/src/prerender-build.ts +687 -0
- package/src/prerender.ts +349 -0
- package/src/react-router-config.ts +245 -0
- package/src/route-artifacts.ts +155 -0
- package/src/route-ast.ts +163 -0
- package/src/route-chunks.ts +857 -0
- package/src/route-component-transform.ts +314 -0
- package/src/route-config.ts +106 -0
- package/src/route-export-pruning.ts +668 -0
- package/src/route-export-resolution.ts +329 -0
- package/src/route-transform-tasks.ts +249 -0
- package/src/route-watch.ts +357 -0
- package/src/server-build-plan.ts +91 -0
- package/src/server-build-resolution.ts +131 -0
- package/src/server-utils.ts +111 -0
- package/src/ssr-externals.ts +59 -0
- package/src/templates/context.ts +12 -0
- package/src/templates/entry.client.tsx +12 -0
- package/src/templates/entry.server.tsx +76 -0
- package/src/typegen.ts +178 -0
- package/src/types.ts +92 -0
- package/src/validation/validate-plugin-order.ts +76 -0
- package/src/virtual-modules.ts +30 -0
- package/src/warnings/warn-on-client-source-maps.ts +96 -0
- package/src/yuku.ts +67 -0
- package/dist/0~rslib-runtime.js +0 -16
- package/dist/babel.d.ts +0 -8
package/dist/451.js
ADDED
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
import { basename, dirname, normalize, relative, resolve } from "pathe";
|
|
2
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { langFromPath, parse, walk as external_yuku_parser_walk } from "yuku-parser";
|
|
4
|
+
import { Analyzer } from "yuku-analyzer";
|
|
5
|
+
import { print } from "yuku-codegen";
|
|
6
|
+
import { readFile, stat } from "node:fs/promises";
|
|
7
|
+
import { rspack } from "@rsbuild/core";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
let PLUGIN_NAME = 'rsbuild:react-router', JS_EXTENSIONS = [
|
|
10
|
+
'.tsx',
|
|
11
|
+
'.ts',
|
|
12
|
+
'.jsx',
|
|
13
|
+
'.js',
|
|
14
|
+
'.mjs',
|
|
15
|
+
'.mts'
|
|
16
|
+
], BUILD_CLIENT_ROUTE_QUERY_STRING = '?__react-router-build-client-route', SERVER_ONLY_ROUTE_EXPORTS = [
|
|
17
|
+
'loader',
|
|
18
|
+
'action',
|
|
19
|
+
'middleware',
|
|
20
|
+
'headers'
|
|
21
|
+
], SERVER_ONLY_ROUTE_EXPORTS_SET = new Set(SERVER_ONLY_ROUTE_EXPORTS), CLIENT_ROUTE_EXPORTS_SET = new Set([
|
|
22
|
+
'clientAction',
|
|
23
|
+
'clientLoader',
|
|
24
|
+
'clientMiddleware',
|
|
25
|
+
'handle',
|
|
26
|
+
'meta',
|
|
27
|
+
'links',
|
|
28
|
+
'shouldRevalidate',
|
|
29
|
+
'default',
|
|
30
|
+
'ErrorBoundary',
|
|
31
|
+
'HydrateFallback',
|
|
32
|
+
'Layout'
|
|
33
|
+
]), NAMED_COMPONENT_EXPORTS_SET = new Set([
|
|
34
|
+
'HydrateFallback',
|
|
35
|
+
'ErrorBoundary'
|
|
36
|
+
]), SERVER_EXPORTS = {
|
|
37
|
+
loader: 'loader',
|
|
38
|
+
action: 'action',
|
|
39
|
+
middleware: 'middleware',
|
|
40
|
+
headers: 'headers'
|
|
41
|
+
}, CLIENT_EXPORTS = {
|
|
42
|
+
clientAction: 'clientAction',
|
|
43
|
+
clientLoader: 'clientLoader',
|
|
44
|
+
clientMiddleware: 'clientMiddleware',
|
|
45
|
+
default: 'default',
|
|
46
|
+
ErrorBoundary: 'ErrorBoundary',
|
|
47
|
+
handle: 'handle',
|
|
48
|
+
HydrateFallback: 'HydrateFallback',
|
|
49
|
+
Layout: 'Layout',
|
|
50
|
+
links: 'links',
|
|
51
|
+
meta: 'meta',
|
|
52
|
+
shouldRevalidate: 'shouldRevalidate'
|
|
53
|
+
}, getPatternIdentifierNames = (pattern, names = new Set())=>{
|
|
54
|
+
if (!pattern) return names;
|
|
55
|
+
if ('Identifier' === pattern.type) return names.add(pattern.name), names;
|
|
56
|
+
if ('RestElement' === pattern.type) return getPatternIdentifierNames(pattern.argument, names);
|
|
57
|
+
if ('AssignmentPattern' === pattern.type) return getPatternIdentifierNames(pattern.left, names);
|
|
58
|
+
if ('ArrayPattern' === pattern.type) {
|
|
59
|
+
for (let element of pattern.elements ?? [])getPatternIdentifierNames(element, names);
|
|
60
|
+
return names;
|
|
61
|
+
}
|
|
62
|
+
if ('ObjectPattern' === pattern.type) for (let property of pattern.properties ?? [])'RestElement' === property.type ? getPatternIdentifierNames(property.argument, names) : getPatternIdentifierNames(property.value, names);
|
|
63
|
+
return names;
|
|
64
|
+
}, getIdentifierNamesFromPattern = (pattern)=>Array.from(getPatternIdentifierNames(pattern)), getExportedName = (node)=>{
|
|
65
|
+
let exported = node?.exported ?? node;
|
|
66
|
+
return exported ? 'Identifier' === exported.type ? exported.name : 'Literal' === exported.type || 'StringLiteral' === exported.type ? String(exported.value) : null : null;
|
|
67
|
+
}, identifier = (name)=>({
|
|
68
|
+
type: 'Identifier',
|
|
69
|
+
start: 0,
|
|
70
|
+
end: 0,
|
|
71
|
+
name,
|
|
72
|
+
decorators: [],
|
|
73
|
+
optional: !1,
|
|
74
|
+
typeAnnotation: null
|
|
75
|
+
}), callExpression = (callee, args)=>({
|
|
76
|
+
type: 'CallExpression',
|
|
77
|
+
start: 0,
|
|
78
|
+
end: 0,
|
|
79
|
+
callee,
|
|
80
|
+
arguments: args,
|
|
81
|
+
optional: !1
|
|
82
|
+
}), importDeclaration = (specifiers, source)=>({
|
|
83
|
+
type: 'ImportDeclaration',
|
|
84
|
+
start: 0,
|
|
85
|
+
end: 0,
|
|
86
|
+
specifiers: specifiers.map((specifier)=>({
|
|
87
|
+
type: 'ImportSpecifier',
|
|
88
|
+
start: 0,
|
|
89
|
+
end: 0,
|
|
90
|
+
imported: identifier(specifier.imported),
|
|
91
|
+
local: identifier(specifier.local),
|
|
92
|
+
importKind: 'value'
|
|
93
|
+
})),
|
|
94
|
+
source: {
|
|
95
|
+
type: 'Literal',
|
|
96
|
+
start: 0,
|
|
97
|
+
end: 0,
|
|
98
|
+
value: source,
|
|
99
|
+
raw: JSON.stringify(source)
|
|
100
|
+
},
|
|
101
|
+
attributes: [],
|
|
102
|
+
phase: null,
|
|
103
|
+
importKind: 'value'
|
|
104
|
+
}), exportSpecifier = (local, exported)=>({
|
|
105
|
+
type: 'ExportSpecifier',
|
|
106
|
+
start: 0,
|
|
107
|
+
end: 0,
|
|
108
|
+
local: identifier(local),
|
|
109
|
+
exported: identifier(exported),
|
|
110
|
+
exportKind: 'value'
|
|
111
|
+
}), exportNamedDeclaration = (specifiers)=>({
|
|
112
|
+
type: 'ExportNamedDeclaration',
|
|
113
|
+
start: 0,
|
|
114
|
+
end: 0,
|
|
115
|
+
declaration: null,
|
|
116
|
+
specifiers,
|
|
117
|
+
source: null,
|
|
118
|
+
attributes: [],
|
|
119
|
+
exportKind: 'value'
|
|
120
|
+
}), variableDeclaration = (name, init)=>({
|
|
121
|
+
type: 'VariableDeclaration',
|
|
122
|
+
start: 0,
|
|
123
|
+
end: 0,
|
|
124
|
+
kind: 'const',
|
|
125
|
+
declare: !1,
|
|
126
|
+
declarations: [
|
|
127
|
+
{
|
|
128
|
+
type: 'VariableDeclarator',
|
|
129
|
+
start: 0,
|
|
130
|
+
end: 0,
|
|
131
|
+
id: identifier(name),
|
|
132
|
+
init,
|
|
133
|
+
definite: !1
|
|
134
|
+
}
|
|
135
|
+
]
|
|
136
|
+
}), removeFromArray = (array, value)=>{
|
|
137
|
+
let index = array.indexOf(value);
|
|
138
|
+
index >= 0 && array.splice(index, 1);
|
|
139
|
+
}, assertAllowedBindingName = (name, exportsToRemove)=>{
|
|
140
|
+
if (exportsToRemove.has(name)) throw Error(`Cannot remove destructured export "${name}"`);
|
|
141
|
+
}, validateRestElement = (element, exportsToRemove)=>{
|
|
142
|
+
element.argument?.type === 'Identifier' && element.argument.name && assertAllowedBindingName(element.argument.name, exportsToRemove);
|
|
143
|
+
}, validateObjectProperty = (property, exportsToRemove)=>{
|
|
144
|
+
'RestElement' === property.type ? validateRestElement(property, exportsToRemove) : 'Property' === property.type && validateBindingTarget(property.value, exportsToRemove);
|
|
145
|
+
}, validateBindingTarget = (node, exportsToRemove)=>{
|
|
146
|
+
if (node) switch(node.type){
|
|
147
|
+
case 'Identifier':
|
|
148
|
+
node.name && assertAllowedBindingName(node.name, exportsToRemove);
|
|
149
|
+
return;
|
|
150
|
+
case 'AssignmentPattern':
|
|
151
|
+
validateBindingTarget(node.left, exportsToRemove);
|
|
152
|
+
return;
|
|
153
|
+
case 'ArrayPattern':
|
|
154
|
+
for (let element of node.elements ?? [])element?.type === 'RestElement' ? validateRestElement(element, exportsToRemove) : validateBindingTarget(element, exportsToRemove);
|
|
155
|
+
return;
|
|
156
|
+
case 'ObjectPattern':
|
|
157
|
+
for (let property of node.properties ?? [])validateObjectProperty(property, exportsToRemove);
|
|
158
|
+
}
|
|
159
|
+
}, getDeclaredNames = (node)=>{
|
|
160
|
+
let names = new Set();
|
|
161
|
+
if ('VariableDeclaration' === node.type) for (let declarator of node.declarations ?? [])getPatternIdentifierNames(declarator.id, names);
|
|
162
|
+
else if (('FunctionDeclaration' === node.type || 'ClassDeclaration' === node.type) && node.id?.name) names.add(node.id.name);
|
|
163
|
+
else if ('ImportDeclaration' === node.type) for (let specifier of node.specifiers ?? [])specifier.local?.name && names.add(specifier.local.name);
|
|
164
|
+
return names;
|
|
165
|
+
}, collectReferencedNames = (node)=>{
|
|
166
|
+
let referenced = new Set();
|
|
167
|
+
return external_yuku_parser_walk(node, {
|
|
168
|
+
Identifier (node, ctx) {
|
|
169
|
+
let parent = ctx.parent;
|
|
170
|
+
!(parent && 'Identifier' === node.type && (((node, parent)=>{
|
|
171
|
+
if (!parent || 'Identifier' !== node.type) return !1;
|
|
172
|
+
if (('FunctionDeclaration' === parent.type || 'FunctionExpression' === parent.type || 'ClassDeclaration' === parent.type || 'ClassExpression' === parent.type) && parent.id === node) return !0;
|
|
173
|
+
if ('VariableDeclarator' === parent.type) return !!(node.name && getPatternIdentifierNames(parent.id).has(node.name));
|
|
174
|
+
if (('ImportSpecifier' === parent.type || 'ImportDefaultSpecifier' === parent.type || 'ImportNamespaceSpecifier' === parent.type) && parent.local === node) return !0;
|
|
175
|
+
if (('FunctionDeclaration' === parent.type || 'FunctionExpression' === parent.type || 'ArrowFunctionExpression' === parent.type) && node.name) {
|
|
176
|
+
let name = node.name;
|
|
177
|
+
return (parent.params ?? []).some((param)=>getPatternIdentifierNames(param).has(name));
|
|
178
|
+
}
|
|
179
|
+
return !1;
|
|
180
|
+
})(node, parent) || 'MemberExpression' === parent.type && parent.property === node && !parent.computed || 'Property' === parent.type && parent.key === node && !parent.computed && !parent.shorthand || 'MethodDefinition' === parent.type && parent.key === node && !parent.computed || 'ExportSpecifier' === parent.type || 'ExportDefaultSpecifier' === parent.type || 'ExportNamespaceSpecifier' === parent.type || 'ImportSpecifier' === parent.type && parent.imported === node || 'LabeledStatement' === parent.type || 'BreakStatement' === parent.type || 'ContinueStatement' === parent.type)) && node.name && referenced.add(node.name);
|
|
181
|
+
},
|
|
182
|
+
JSXIdentifier (node, ctx) {
|
|
183
|
+
let name, parent = ctx.parent;
|
|
184
|
+
if (parent) {
|
|
185
|
+
if ('JSXMemberExpression' === parent.type && parent.object === node) {
|
|
186
|
+
node.name && referenced.add(node.name);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (node.name && (name = node.name, /^[A-Z]/.test(name)) && ('JSXOpeningElement' === parent.type || 'JSXClosingElement' === parent.type) && parent.name === node) return void referenced.add(node.name);
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
ExportSpecifier (node, ctx) {
|
|
193
|
+
let declaration = ctx.parent;
|
|
194
|
+
!declaration?.source && declaration?.exportKind !== 'type' && node.local?.name && 'type' !== node.exportKind && referenced.add(node.local.name);
|
|
195
|
+
}
|
|
196
|
+
}), referenced;
|
|
197
|
+
}, collectLiveTopLevelDeclarations = (program, graph)=>{
|
|
198
|
+
let pendingNames = [];
|
|
199
|
+
for (let statement of program.body ?? [])if ('VariableDeclaration' !== statement.type && !graph.declarationsByNode.has(statement)) for (let name of collectReferencedNames(statement))pendingNames.push(name);
|
|
200
|
+
let visitedNames = new Set(), liveDeclarations = new Set();
|
|
201
|
+
for(; pendingNames.length > 0;){
|
|
202
|
+
let name = pendingNames.pop();
|
|
203
|
+
if (!(!name || visitedNames.has(name))) {
|
|
204
|
+
for (let declaration of (visitedNames.add(name), graph.declarationsByName.get(name) ?? []))if (!liveDeclarations.has(declaration)) for (let referencedName of (liveDeclarations.add(declaration), declaration.referencedNames))pendingNames.push(referencedName);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return liveDeclarations;
|
|
208
|
+
}, declarationReferencesName = (declaration, names, graph, cache, visitedNames = new Set())=>{
|
|
209
|
+
let cached = cache.get(declaration);
|
|
210
|
+
if (void 0 !== cached) return cached;
|
|
211
|
+
for (let referencedName of declaration.referencedNames){
|
|
212
|
+
if (names.has(referencedName)) return cache.set(declaration, !0), !0;
|
|
213
|
+
if (!visitedNames.has(referencedName)) {
|
|
214
|
+
for (let referencedDeclaration of (visitedNames.add(referencedName), graph.declarationsByName.get(referencedName) ?? []))if (declarationReferencesName(referencedDeclaration, names, graph, cache, visitedNames)) return cache.set(declaration, !0), !0;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return cache.set(declaration, !1), !1;
|
|
218
|
+
};
|
|
219
|
+
function toFunctionExpression(decl) {
|
|
220
|
+
return {
|
|
221
|
+
...decl,
|
|
222
|
+
type: 'FunctionExpression',
|
|
223
|
+
declare: void 0
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
function toClassExpression(decl) {
|
|
227
|
+
return {
|
|
228
|
+
...decl,
|
|
229
|
+
type: 'ClassExpression',
|
|
230
|
+
declare: void 0
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
let getComponentExportName = (exportedName)=>{
|
|
234
|
+
var name;
|
|
235
|
+
return 'default' === exportedName ? 'Component' : (name = exportedName, NAMED_COMPONENT_EXPORTS_SET.has(name)) ? exportedName : null;
|
|
236
|
+
}, declarationIncludesName = (declaration, name)=>'VariableDeclaration' === declaration.type ? (declaration.declarations ?? []).some((declarator)=>{
|
|
237
|
+
let pattern;
|
|
238
|
+
return pattern = declarator.id, getPatternIdentifierNames(pattern).has(name);
|
|
239
|
+
}) : ('FunctionDeclaration' === declaration.type || 'ClassDeclaration' === declaration.type || 'TSEnumDeclaration' === declaration.type) && declaration.id?.name ? declaration.id.name === name : 'ImportDeclaration' === declaration.type && (declaration.specifiers ?? []).some((specifier)=>specifier.local?.name === name), hasTopLevelBindingName = (program, name)=>{
|
|
240
|
+
for (let statement of program.body ?? []){
|
|
241
|
+
if ('ImportDeclaration' === statement.type) {
|
|
242
|
+
if (declarationIncludesName(statement, name)) return !0;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if ('ExportDefaultDeclaration' === statement.type) {
|
|
246
|
+
if (statement.declaration?.id?.name === name) return !0;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
let declaration = 'ExportNamedDeclaration' === statement.type ? statement.declaration : statement;
|
|
250
|
+
if (declaration && declarationIncludesName(declaration, name)) return !0;
|
|
251
|
+
}
|
|
252
|
+
return !1;
|
|
253
|
+
};
|
|
254
|
+
function combineURLs(baseURL, relativeURL) {
|
|
255
|
+
return relativeURL ? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}` : baseURL;
|
|
256
|
+
}
|
|
257
|
+
function normalizeAssetPrefix(assetPrefix) {
|
|
258
|
+
return assetPrefix && 'auto' !== assetPrefix ? assetPrefix.endsWith('/') ? assetPrefix : `${assetPrefix}/` : '/';
|
|
259
|
+
}
|
|
260
|
+
function createRouteId(file) {
|
|
261
|
+
return normalize(file.replace(/\.[^/.]+$/, ''));
|
|
262
|
+
}
|
|
263
|
+
function findEntryFile(basePath) {
|
|
264
|
+
for (let ext of JS_EXTENSIONS){
|
|
265
|
+
let filePath = `${basePath}${ext}`;
|
|
266
|
+
if (existsSync(filePath)) return filePath;
|
|
267
|
+
}
|
|
268
|
+
return `${basePath}.tsx`;
|
|
269
|
+
}
|
|
270
|
+
function generateWithProps() {
|
|
271
|
+
return `
|
|
272
|
+
import { createElement as h } from "react";
|
|
273
|
+
import { useActionData, useLoaderData, useMatches, useParams, useRouteError } from "react-router";
|
|
274
|
+
|
|
275
|
+
export function withComponentProps(Component) {
|
|
276
|
+
return function Wrapped() {
|
|
277
|
+
const props = {
|
|
278
|
+
params: useParams(),
|
|
279
|
+
loaderData: useLoaderData(),
|
|
280
|
+
actionData: useActionData(),
|
|
281
|
+
matches: useMatches(),
|
|
282
|
+
};
|
|
283
|
+
return h(Component, props);
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export function withHydrateFallbackProps(HydrateFallback) {
|
|
288
|
+
return function Wrapped() {
|
|
289
|
+
const props = {
|
|
290
|
+
params: useParams(),
|
|
291
|
+
};
|
|
292
|
+
return h(HydrateFallback, props);
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export function withErrorBoundaryProps(ErrorBoundary) {
|
|
297
|
+
return function Wrapped() {
|
|
298
|
+
const props = {
|
|
299
|
+
params: useParams(),
|
|
300
|
+
loaderData: useLoaderData(),
|
|
301
|
+
actionData: useActionData(),
|
|
302
|
+
error: useRouteError(),
|
|
303
|
+
};
|
|
304
|
+
return h(ErrorBoundary, props);
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
`;
|
|
308
|
+
}
|
|
309
|
+
let routeChunkExportNames = [
|
|
310
|
+
'clientAction',
|
|
311
|
+
'clientLoader',
|
|
312
|
+
'clientMiddleware',
|
|
313
|
+
'HydrateFallback'
|
|
314
|
+
];
|
|
315
|
+
[
|
|
316
|
+
...routeChunkExportNames
|
|
317
|
+
];
|
|
318
|
+
let mightContainRouteChunkExportName = (source)=>routeChunkExportNames.some((exportName)=>source.includes(exportName)), createRouteChunkExportMap = (getValue)=>Object.fromEntries(routeChunkExportNames.map((exportName)=>[
|
|
319
|
+
exportName,
|
|
320
|
+
getValue(exportName)
|
|
321
|
+
])), routeChunkQueryStringPrefix = '?route-chunk=', routeChunkQueryStrings = {
|
|
322
|
+
main: `${routeChunkQueryStringPrefix}main`,
|
|
323
|
+
clientAction: `${routeChunkQueryStringPrefix}clientAction`,
|
|
324
|
+
clientLoader: `${routeChunkQueryStringPrefix}clientLoader`,
|
|
325
|
+
clientMiddleware: `${routeChunkQueryStringPrefix}clientMiddleware`,
|
|
326
|
+
HydrateFallback: `${routeChunkQueryStringPrefix}HydrateFallback`
|
|
327
|
+
}, routeChunkEntrySuffix = {
|
|
328
|
+
clientAction: 'client-action',
|
|
329
|
+
clientLoader: 'client-loader',
|
|
330
|
+
clientMiddleware: 'client-middleware',
|
|
331
|
+
HydrateFallback: 'hydrate-fallback'
|
|
332
|
+
}, invariant = (value, message)=>{
|
|
333
|
+
if (!value) throw Error(message);
|
|
334
|
+
}, getOrSetFromCache = (cache, key, version, getValue)=>{
|
|
335
|
+
let entry = cache.get(key);
|
|
336
|
+
if (entry?.version === version) return entry.value;
|
|
337
|
+
let value = getValue();
|
|
338
|
+
return cache.set(key, {
|
|
339
|
+
value,
|
|
340
|
+
version
|
|
341
|
+
}), value;
|
|
342
|
+
}, analyzeCode = (code, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::analyzeCode`, code, ()=>{
|
|
343
|
+
let module = new Analyzer().addFile(cacheKey, code, {
|
|
344
|
+
lang: 'tsx',
|
|
345
|
+
sourceType: 'module',
|
|
346
|
+
attachComments: !0
|
|
347
|
+
}), errors = module.diagnostics.filter((diagnostic)=>'error' === diagnostic.severity);
|
|
348
|
+
if (errors.length > 0) throw Error(errors.map((error)=>error.message).join('\n'));
|
|
349
|
+
return {
|
|
350
|
+
module,
|
|
351
|
+
program: module.ast
|
|
352
|
+
};
|
|
353
|
+
}), route_chunks_getExportedName = (exported)=>'Identifier' === exported.type ? exported.name : String(exported.value), setsIntersect = (set1, set2)=>{
|
|
354
|
+
let smallerSet = set1, largerSet = set2;
|
|
355
|
+
for (let element of (set1.size > set2.size && (smallerSet = set2, largerSet = set1), smallerSet))if (largerSet.has(element)) return !0;
|
|
356
|
+
return !1;
|
|
357
|
+
}, getExportDependencies = (code, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::getExportDependencies`, code, ()=>{
|
|
358
|
+
let { module } = analyzeCode(code, cache, cacheKey), exportDependencies = new Map(), topLevelStatementCache = new Map(), variableDeclaratorCache = new Map(), getCachedTopLevelStatementForNode = (node)=>{
|
|
359
|
+
let cached = topLevelStatementCache.get(node);
|
|
360
|
+
if (cached) return cached;
|
|
361
|
+
let statement = ((module, node)=>{
|
|
362
|
+
let current = node, parent = module.parentOf(current);
|
|
363
|
+
for(; parent && 'Program' !== parent.type;)current = parent, parent = module.parentOf(current);
|
|
364
|
+
return invariant(parent?.type === 'Program', 'Expected node to be within Program'), current;
|
|
365
|
+
})(module, node);
|
|
366
|
+
return topLevelStatementCache.set(node, statement), statement;
|
|
367
|
+
}, getCachedVariableDeclaratorForNode = (node)=>{
|
|
368
|
+
if (variableDeclaratorCache.has(node)) return variableDeclaratorCache.get(node) ?? null;
|
|
369
|
+
let declarator = ((module, node)=>{
|
|
370
|
+
let current = node;
|
|
371
|
+
for(; current;){
|
|
372
|
+
if ('VariableDeclarator' === current.type) return current;
|
|
373
|
+
current = module.parentOf(current);
|
|
374
|
+
}
|
|
375
|
+
return null;
|
|
376
|
+
})(module, node);
|
|
377
|
+
return variableDeclaratorCache.set(node, declarator), declarator;
|
|
378
|
+
}, addCachedTopLevelStatement = (dependencies, node)=>{
|
|
379
|
+
let statement = getCachedTopLevelStatementForNode(node);
|
|
380
|
+
return dependencies.topLevelStatements.add(statement), 'ImportDeclaration' === statement.type || statement.type.startsWith('Export') || dependencies.topLevelNonModuleStatements.add(statement), statement;
|
|
381
|
+
}, handleExport = (exportName, exportNode, localSymbol)=>{
|
|
382
|
+
let dependencies = {
|
|
383
|
+
topLevelStatements: new Set(),
|
|
384
|
+
topLevelNonModuleStatements: new Set(),
|
|
385
|
+
importedIdentifierNames: new Set(),
|
|
386
|
+
exportedVariableDeclarators: new Set()
|
|
387
|
+
}, visitedSymbols = new Set(), scannedNodes = new Set(), scanNode = (node)=>{
|
|
388
|
+
scannedNodes.has(node) || (scannedNodes.add(node), external_yuku_parser_walk(node, {
|
|
389
|
+
Identifier (node) {
|
|
390
|
+
let reference = module.referenceOf(node);
|
|
391
|
+
reference?.symbol && visitSymbol(reference.symbol);
|
|
392
|
+
}
|
|
393
|
+
}));
|
|
394
|
+
}, visitSymbol = (symbol)=>{
|
|
395
|
+
if (!visitedSymbols.has(symbol)) {
|
|
396
|
+
for (let declaration of (visitedSymbols.add(symbol), symbol.declarations)){
|
|
397
|
+
let statement = addCachedTopLevelStatement(dependencies, declaration);
|
|
398
|
+
'ImportDeclaration' === statement.type && dependencies.importedIdentifierNames.add(symbol.name);
|
|
399
|
+
let declarator = getCachedVariableDeclaratorForNode(declaration);
|
|
400
|
+
declarator && 'ExportNamedDeclaration' === getCachedTopLevelStatementForNode(declarator).type && dependencies.exportedVariableDeclarators.add(declarator), scanNode(declarator ?? statement);
|
|
401
|
+
}
|
|
402
|
+
for (let reference of symbol.references){
|
|
403
|
+
let statement = addCachedTopLevelStatement(dependencies, reference.node);
|
|
404
|
+
scanNode(getCachedVariableDeclaratorForNode(reference.node) ?? statement);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
addCachedTopLevelStatement(dependencies, exportNode), localSymbol ? visitSymbol(localSymbol) : scanNode(getCachedTopLevelStatementForNode(exportNode)), exportDependencies.set(exportName, dependencies);
|
|
409
|
+
};
|
|
410
|
+
for (let exp of module.exports)exp.typeOnly || exp.isStar || exp.isExportEquals || handleExport(exp.name, exp.node, exp.local ?? null);
|
|
411
|
+
return exportDependencies;
|
|
412
|
+
}), getChunkableExportMap = (code, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::getChunkableExportMap`, code, ()=>{
|
|
413
|
+
let exportDependencies = getExportDependencies(code, cache, cacheKey);
|
|
414
|
+
return createRouteChunkExportMap((exportName)=>((exportName, exportDependencies)=>{
|
|
415
|
+
let dependencies = exportDependencies.get(exportName);
|
|
416
|
+
if (!dependencies) return !1;
|
|
417
|
+
for (let [currentExportName, currentDependencies] of exportDependencies)if (currentExportName !== exportName && setsIntersect(currentDependencies.topLevelNonModuleStatements, dependencies.topLevelNonModuleStatements)) return !1;
|
|
418
|
+
if (dependencies.exportedVariableDeclarators.size > 1) return !1;
|
|
419
|
+
if (dependencies.exportedVariableDeclarators.size > 0) {
|
|
420
|
+
for (let [currentExportName, currentDependencies] of exportDependencies)if (currentExportName !== exportName && setsIntersect(currentDependencies.exportedVariableDeclarators, dependencies.exportedVariableDeclarators)) return !1;
|
|
421
|
+
}
|
|
422
|
+
return !0;
|
|
423
|
+
})(exportName, exportDependencies));
|
|
424
|
+
}), generateCode = (program)=>{
|
|
425
|
+
if (0 === program.body.length) return;
|
|
426
|
+
let result = print(program, {
|
|
427
|
+
comments: !0
|
|
428
|
+
});
|
|
429
|
+
if (result.errors.length > 0) throw Error(result.errors.map((error)=>error.message).join('\n'));
|
|
430
|
+
return result.code;
|
|
431
|
+
}, filterImportSpecifiers = (node, shouldKeep)=>{
|
|
432
|
+
if (0 === node.specifiers.length) return node;
|
|
433
|
+
let specifiers = node.specifiers.filter((specifier)=>shouldKeep(specifier.local.name));
|
|
434
|
+
return specifiers.length > 0 ? {
|
|
435
|
+
...node,
|
|
436
|
+
specifiers
|
|
437
|
+
} : null;
|
|
438
|
+
}, getChunkedExport = (code, exportName, cache, cacheKey)=>getOrSetFromCache(cache, `${cacheKey}::getChunkedExport::${exportName}`, code, ()=>{
|
|
439
|
+
if (!routeChunkExportNames.includes(exportName) || !getChunkableExportMap(code, cache, cacheKey)[exportName]) return;
|
|
440
|
+
let dependencies = getExportDependencies(code, cache, cacheKey).get(exportName);
|
|
441
|
+
invariant(dependencies, 'Expected export to have dependencies');
|
|
442
|
+
let program = analyzeCode(code, cache, cacheKey).program, body = program.body.filter((node)=>dependencies.topLevelStatements.has(node)).map((node)=>'ImportDeclaration' !== node.type ? node : 0 === dependencies.importedIdentifierNames.size ? null : filterImportSpecifiers(node, (importedName)=>dependencies.importedIdentifierNames.has(importedName))).map((node)=>{
|
|
443
|
+
if (!node || !node.type.startsWith('Export')) return node;
|
|
444
|
+
if ('ExportAllDeclaration' === node.type) return null;
|
|
445
|
+
if ('ExportDefaultDeclaration' === node.type) return 'default' === exportName ? node : null;
|
|
446
|
+
let { declaration } = node;
|
|
447
|
+
if (declaration?.type === 'VariableDeclaration') {
|
|
448
|
+
let declarations = declaration.declarations.filter((declarationNode)=>dependencies.exportedVariableDeclarators.has(declarationNode));
|
|
449
|
+
return declarations.length > 0 ? {
|
|
450
|
+
...node,
|
|
451
|
+
declaration: {
|
|
452
|
+
...declaration,
|
|
453
|
+
declarations
|
|
454
|
+
}
|
|
455
|
+
} : null;
|
|
456
|
+
}
|
|
457
|
+
if (declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') return declaration.id?.name === exportName ? node : null;
|
|
458
|
+
if ('ExportNamedDeclaration' === node.type) {
|
|
459
|
+
let specifiers = node.specifiers.filter((specifier)=>route_chunks_getExportedName(specifier.exported) === exportName);
|
|
460
|
+
return specifiers.length > 0 ? {
|
|
461
|
+
...node,
|
|
462
|
+
specifiers
|
|
463
|
+
} : null;
|
|
464
|
+
}
|
|
465
|
+
throw Error('Unknown export node type');
|
|
466
|
+
}).filter(Boolean);
|
|
467
|
+
return generateCode({
|
|
468
|
+
...program,
|
|
469
|
+
body
|
|
470
|
+
});
|
|
471
|
+
}), hasCachedChunkedExport = (code, exportName, cache, cacheKey)=>{
|
|
472
|
+
let key;
|
|
473
|
+
return key = `${cacheKey}::getChunkedExport::${exportName}`, cache.get(key)?.version === code;
|
|
474
|
+
}, getRouteChunkModuleId = (filePath, chunkName)=>`${filePath}${routeChunkQueryStrings[chunkName]}`, normalizeRelativeFilePath = (file, appDirectory)=>{
|
|
475
|
+
let fullPath = resolve(appDirectory, file);
|
|
476
|
+
return normalize(relative(appDirectory, fullPath)).split('?')[0];
|
|
477
|
+
}, isRootRouteModuleId = (config, id)=>normalizeRelativeFilePath(id, config.appDirectory) === config.rootRouteFile, shouldAnalyzeRouteChunks = (config, id, code)=>!!config.splitRouteModules && mightContainRouteChunkExportName(code) && !isRootRouteModuleId(config, id), createEmptyRouteChunkByExportName = ()=>createRouteChunkExportMap(()=>!1), buildManifestChunkValidity = (exportNames, hasRouteChunkByExportName)=>createRouteChunkExportMap((exportName)=>!exportNames.has(exportName) || hasRouteChunkByExportName[exportName]), detectRouteChunksIfEnabled = async (cache, config, id, code)=>{
|
|
478
|
+
let analysisCache, exportDependencies, hasRouteChunkByExportName, chunkedExports, hasRouteChunks;
|
|
479
|
+
if (!shouldAnalyzeRouteChunks(config, id, code)) return {
|
|
480
|
+
exportNames: [],
|
|
481
|
+
chunkedExports: [],
|
|
482
|
+
hasRouteChunks: !1,
|
|
483
|
+
hasRouteChunkByExportName: createEmptyRouteChunkByExportName()
|
|
484
|
+
};
|
|
485
|
+
let cacheKey = normalizeRelativeFilePath(id, config.appDirectory);
|
|
486
|
+
return exportDependencies = getExportDependencies(code, analysisCache = cache ?? new Map(), cacheKey), hasRouteChunks = (chunkedExports = Object.entries(hasRouteChunkByExportName = getChunkableExportMap(code, analysisCache, cacheKey)).filter(([, isChunked])=>isChunked).map(([exportName])=>exportName)).length > 0, {
|
|
487
|
+
exportNames: Array.from(exportDependencies.keys()),
|
|
488
|
+
hasRouteChunks,
|
|
489
|
+
hasRouteChunkByExportName,
|
|
490
|
+
chunkedExports
|
|
491
|
+
};
|
|
492
|
+
}, getRouteChunkIfEnabled = async (cache, config, id, chunkName, code)=>{
|
|
493
|
+
if (!config.splitRouteModules) return null;
|
|
494
|
+
if ('main' === chunkName) {
|
|
495
|
+
if (!mightContainRouteChunkExportName(code)) return code;
|
|
496
|
+
} else if (!code.includes(chunkName)) return null;
|
|
497
|
+
return ((code, chunkName, cache, cacheKey)=>{
|
|
498
|
+
let analysisCache = cache ?? new Map();
|
|
499
|
+
if ('main' === chunkName) return getOrSetFromCache(analysisCache, `${cacheKey}::omitChunkedExports::${routeChunkExportNames.join(',')}`, code, ()=>{
|
|
500
|
+
let chunkableExportMap = getChunkableExportMap(code, analysisCache, cacheKey), exportNameSet = new Set(routeChunkExportNames), isOmitted = (exportName)=>exportNameSet.has(exportName) && !!chunkableExportMap[exportName], exportDependencies = getExportDependencies(code, analysisCache, cacheKey), allExportNames = Array.from(exportDependencies.keys()), omittedExportNames = allExportNames.filter(isOmitted), retainedExportNames = allExportNames.filter((exportName)=>!isOmitted(exportName)), omittedStatements = new Set(), omittedExportedVariableDeclarators = new Set(), retainedImportedIdentifierNames = new Set(), omittedImportedIdentifierNames = new Set();
|
|
501
|
+
for (let omittedExportName of omittedExportNames){
|
|
502
|
+
let dependencies = exportDependencies.get(omittedExportName);
|
|
503
|
+
for (let statement of (invariant(dependencies, `Expected dependencies for ${omittedExportName}`), dependencies.topLevelNonModuleStatements))omittedStatements.add(statement);
|
|
504
|
+
for (let declarator of dependencies.exportedVariableDeclarators)omittedExportedVariableDeclarators.add(declarator);
|
|
505
|
+
for (let importedName of dependencies.importedIdentifierNames)omittedImportedIdentifierNames.add(importedName);
|
|
506
|
+
}
|
|
507
|
+
for (let retainedExportName of retainedExportNames){
|
|
508
|
+
let dependencies = exportDependencies.get(retainedExportName);
|
|
509
|
+
if (dependencies) for (let importedName of dependencies.importedIdentifierNames)retainedImportedIdentifierNames.add(importedName);
|
|
510
|
+
}
|
|
511
|
+
let program = analyzeCode(code, analysisCache, cacheKey).program, body = program.body.filter((node)=>!omittedStatements.has(node)).map((node)=>'ImportDeclaration' !== node.type ? node : filterImportSpecifiers(node, (importedName)=>!!retainedImportedIdentifierNames.has(importedName) || !omittedImportedIdentifierNames.has(importedName))).map((node)=>{
|
|
512
|
+
if (!node || !node.type.startsWith('Export') || 'ExportAllDeclaration' === node.type) return node;
|
|
513
|
+
if ('ExportDefaultDeclaration' === node.type) return isOmitted('default') ? null : node;
|
|
514
|
+
if (node.declaration?.type === 'VariableDeclaration') {
|
|
515
|
+
let declarations = node.declaration.declarations.filter((declarationNode)=>!omittedExportedVariableDeclarators.has(declarationNode));
|
|
516
|
+
return declarations.length > 0 ? {
|
|
517
|
+
...node,
|
|
518
|
+
declaration: {
|
|
519
|
+
...node.declaration,
|
|
520
|
+
declarations
|
|
521
|
+
}
|
|
522
|
+
} : null;
|
|
523
|
+
}
|
|
524
|
+
if (node.declaration?.type === 'FunctionDeclaration' || node.declaration?.type === 'ClassDeclaration') return isOmitted(node.declaration.id.name) ? null : node;
|
|
525
|
+
if ('ExportNamedDeclaration' === node.type) {
|
|
526
|
+
let specifiers = node.specifiers.filter((specifier)=>!isOmitted(route_chunks_getExportedName(specifier.exported)));
|
|
527
|
+
return specifiers.length > 0 || node.declaration ? {
|
|
528
|
+
...node,
|
|
529
|
+
specifiers
|
|
530
|
+
} : null;
|
|
531
|
+
}
|
|
532
|
+
throw Error('Unknown node type');
|
|
533
|
+
}).filter(Boolean);
|
|
534
|
+
return generateCode({
|
|
535
|
+
...program,
|
|
536
|
+
body
|
|
537
|
+
});
|
|
538
|
+
});
|
|
539
|
+
return hasCachedChunkedExport(code, chunkName, analysisCache, cacheKey) || ((code, cache, cacheKey)=>{
|
|
540
|
+
let chunkableExportMap = getChunkableExportMap(code, cache, cacheKey);
|
|
541
|
+
for (let exportName of routeChunkExportNames)chunkableExportMap[exportName] && (hasCachedChunkedExport(code, exportName, cache, cacheKey) || getChunkedExport(code, exportName, cache, cacheKey));
|
|
542
|
+
})(code, analysisCache, cacheKey), getChunkedExport(code, chunkName, analysisCache, cacheKey);
|
|
543
|
+
})(code, chunkName, cache, normalizeRelativeFilePath(id, config.appDirectory)) ?? null;
|
|
544
|
+
}, validateRouteChunks = ({ config, id, valid })=>{
|
|
545
|
+
if (isRootRouteModuleId(config, id)) return;
|
|
546
|
+
let invalidChunks = Object.entries(valid).filter(([, isValid])=>!isValid).map(([chunkName])=>chunkName);
|
|
547
|
+
if (0 === invalidChunks.length) return;
|
|
548
|
+
let plural = invalidChunks.length > 1;
|
|
549
|
+
throw Error([
|
|
550
|
+
`Error splitting route module: ${normalizeRelativeFilePath(id, config.appDirectory)}`,
|
|
551
|
+
invalidChunks.map((name)=>`- ${name}`).join('\n'),
|
|
552
|
+
`${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.`
|
|
553
|
+
].join('\n\n'));
|
|
554
|
+
}, getRouteChunkEntryName = (routeId, chunkName)=>`${routeId}-${routeChunkEntrySuffix[chunkName]}`, setBoundedCacheEntry = (cache, key, value, maxEntries)=>{
|
|
555
|
+
if (maxEntries <= 0) return void cache.clear();
|
|
556
|
+
if (!cache.has(key) && cache.size >= maxEntries) {
|
|
557
|
+
let oldestEntry = cache.keys().next();
|
|
558
|
+
oldestEntry.done || cache.delete(oldestEntry.value);
|
|
559
|
+
}
|
|
560
|
+
cache.set(key, value);
|
|
561
|
+
}, exportInfoCache = new Map(), routeModuleAnalysisCache = new Map(), getParseErrors = (result)=>result.diagnostics.filter((diagnostic)=>'error' === diagnostic.severity), getParseErrorMessage = (errors)=>errors.map((error)=>error.message).join('\n'), parseProgram = (code, resourcePath)=>{
|
|
562
|
+
let sourcePath = resourcePath ? resourcePath.replace(/[?#].*$/, '') : void 0, lang = sourcePath ? langFromPath(sourcePath) : 'tsx', result = parse(code, {
|
|
563
|
+
sourceType: 'module',
|
|
564
|
+
lang
|
|
565
|
+
}), errors = getParseErrors(result);
|
|
566
|
+
if (0 === errors.length) return result.program ?? result;
|
|
567
|
+
if (!sourcePath || 'ts' !== lang && 'tsx' !== lang) throw Error(getParseErrorMessage(errors));
|
|
568
|
+
let normalizedResult = parse(rspack.experiments.swc.transformSync(code, {
|
|
569
|
+
filename: sourcePath,
|
|
570
|
+
jsc: {
|
|
571
|
+
parser: {
|
|
572
|
+
syntax: "typescript",
|
|
573
|
+
tsx: 'tsx' === lang
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}).code, {
|
|
577
|
+
sourceType: 'module',
|
|
578
|
+
lang: 'js'
|
|
579
|
+
}), normalizedErrors = getParseErrors(normalizedResult);
|
|
580
|
+
if (normalizedErrors.length > 0) throw Error(getParseErrorMessage(normalizedErrors));
|
|
581
|
+
return normalizedResult.program ?? normalizedResult;
|
|
582
|
+
}, cachePromiseOnReject = (promise, invalidate)=>promise.catch((error)=>{
|
|
583
|
+
throw invalidate(), error;
|
|
584
|
+
}), isTypeOnlyExport = (node)=>'type' === node.exportKind || 'TSExportAssignment' === node.type || node.declaration?.declare === !0 || 'ExportDefaultDeclaration' === node.type && node.declaration?.type === 'TSInterfaceDeclaration', collectProgramExportNames = (program)=>{
|
|
585
|
+
let exportNames = new Set();
|
|
586
|
+
for (let statement of program.body ?? []){
|
|
587
|
+
if (isTypeOnlyExport(statement)) continue;
|
|
588
|
+
if ('ExportAllDeclaration' === statement.type) {
|
|
589
|
+
let exported = getExportedName(statement.exported);
|
|
590
|
+
exported && exportNames.add(exported);
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
if ('ExportDefaultDeclaration' === statement.type) {
|
|
594
|
+
exportNames.add('default');
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
if ('ExportNamedDeclaration' !== statement.type) continue;
|
|
598
|
+
let declaration = statement.declaration;
|
|
599
|
+
if (declaration) {
|
|
600
|
+
if ('VariableDeclaration' === declaration.type) for (let declarator of declaration.declarations ?? [])for (let name of getIdentifierNamesFromPattern(declarator.id))exportNames.add(name);
|
|
601
|
+
else ('FunctionDeclaration' === declaration.type || 'ClassDeclaration' === declaration.type || 'TSEnumDeclaration' === declaration.type) && declaration.id?.name && exportNames.add(declaration.id.name);
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
for (let specifier of statement.specifiers ?? []){
|
|
605
|
+
if ('type' === specifier.exportKind) continue;
|
|
606
|
+
let exported = getExportedName(specifier.exported);
|
|
607
|
+
exported && exportNames.add(exported);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return Array.from(exportNames);
|
|
611
|
+
}, collectExportAllModules = (program)=>{
|
|
612
|
+
let modules = [];
|
|
613
|
+
for (let statement of program.body ?? []){
|
|
614
|
+
if ('ExportAllDeclaration' !== statement.type || isTypeOnlyExport(statement) || statement.exported) continue;
|
|
615
|
+
let source = statement.source?.value;
|
|
616
|
+
'string' == typeof source && modules.push(source);
|
|
617
|
+
}
|
|
618
|
+
return modules;
|
|
619
|
+
}, getExportNames = async (code, resourcePath)=>(await getExportNamesAndExportAll(code, resourcePath)).exportNames, getExportNamesAndExportAll = async (code, resourcePath)=>{
|
|
620
|
+
var code1, resourcePath1;
|
|
621
|
+
let lang, trackedExportInfo, cacheKey = (code1 = code, lang = (resourcePath1 = resourcePath) ? langFromPath(resourcePath1.replace(/[?#].*$/, '')) : 'inline', `${lang}\0${code1}`), cached = exportInfoCache.get(cacheKey);
|
|
622
|
+
return cached || (trackedExportInfo = cachePromiseOnReject((async ()=>{
|
|
623
|
+
let program = parseProgram(code, resourcePath);
|
|
624
|
+
return {
|
|
625
|
+
exportNames: collectProgramExportNames(program),
|
|
626
|
+
exportAllModules: collectExportAllModules(program)
|
|
627
|
+
};
|
|
628
|
+
})(), ()=>{
|
|
629
|
+
exportInfoCache.get(cacheKey) === trackedExportInfo && exportInfoCache.delete(cacheKey);
|
|
630
|
+
}), setBoundedCacheEntry(exportInfoCache, cacheKey, trackedExportInfo, 2048), trackedExportInfo);
|
|
631
|
+
}, getRouteModuleAnalysis = async (resourcePath)=>{
|
|
632
|
+
let trackedAnalysis, stats = await stat(resourcePath), cached = routeModuleAnalysisCache.get(resourcePath);
|
|
633
|
+
return cached?.mtimeMs === stats.mtimeMs && cached.size === stats.size ? cached.analysis : (trackedAnalysis = cachePromiseOnReject((async ()=>{
|
|
634
|
+
let source = await readFile(resourcePath, 'utf8'), program = parseProgram(source, resourcePath);
|
|
635
|
+
return {
|
|
636
|
+
code: source,
|
|
637
|
+
exports: collectProgramExportNames(program),
|
|
638
|
+
exportAllModules: collectExportAllModules(program)
|
|
639
|
+
};
|
|
640
|
+
})(), ()=>{
|
|
641
|
+
routeModuleAnalysisCache.get(resourcePath)?.analysis === trackedAnalysis && routeModuleAnalysisCache.delete(resourcePath);
|
|
642
|
+
}), setBoundedCacheEntry(routeModuleAnalysisCache, resourcePath, {
|
|
643
|
+
mtimeMs: stats.mtimeMs,
|
|
644
|
+
size: stats.size,
|
|
645
|
+
analysis: trackedAnalysis
|
|
646
|
+
}, 2048), trackedAnalysis);
|
|
647
|
+
}, tryStat = (path)=>statSync(path, {
|
|
648
|
+
throwIfNoEntry: !1
|
|
649
|
+
}) ?? null, PACKAGE_IMPORT_CONDITIONS = new Set([
|
|
650
|
+
'import',
|
|
651
|
+
'node'
|
|
652
|
+
]), PACKAGE_RESOLUTION_NOT_APPLICABLE = Symbol('package resolution not applicable'), resolveIndexFile = (dirPath)=>{
|
|
653
|
+
for (let ext of JS_EXTENSIONS){
|
|
654
|
+
let candidate = resolve(dirPath, `index${ext}`), stats = tryStat(candidate);
|
|
655
|
+
if (stats?.isFile()) return candidate;
|
|
656
|
+
}
|
|
657
|
+
return null;
|
|
658
|
+
}, resolvePathWithExtensions = (basePath)=>{
|
|
659
|
+
let stats = tryStat(basePath);
|
|
660
|
+
if (stats?.isFile()) return basePath;
|
|
661
|
+
if (stats?.isDirectory()) return resolveIndexFile(basePath);
|
|
662
|
+
for (let ext of JS_EXTENSIONS){
|
|
663
|
+
let candidate = `${basePath}${ext}`, candidateStats = tryStat(candidate);
|
|
664
|
+
if (candidateStats?.isFile()) return candidate;
|
|
665
|
+
}
|
|
666
|
+
return resolveIndexFile(basePath);
|
|
667
|
+
}, resolvePackageExportTarget = (target)=>{
|
|
668
|
+
if (!target) return null;
|
|
669
|
+
if ('string' == typeof target) return target;
|
|
670
|
+
if (Array.isArray(target)) {
|
|
671
|
+
for (let nestedTarget of target){
|
|
672
|
+
let resolvedTarget = resolvePackageExportTarget(nestedTarget);
|
|
673
|
+
if (resolvedTarget) return resolvedTarget;
|
|
674
|
+
}
|
|
675
|
+
return null;
|
|
676
|
+
}
|
|
677
|
+
for (let [condition, nestedTarget] of Object.entries(target))if ('default' === condition || PACKAGE_IMPORT_CONDITIONS.has(condition)) {
|
|
678
|
+
let resolvedTarget = resolvePackageExportTarget(nestedTarget);
|
|
679
|
+
if (resolvedTarget) return resolvedTarget;
|
|
680
|
+
}
|
|
681
|
+
return null;
|
|
682
|
+
}, resolveExportAllModule = (specifier, importerPath)=>{
|
|
683
|
+
if (specifier.startsWith('.') || specifier.startsWith('/')) {
|
|
684
|
+
let resolvedPath = resolvePathWithExtensions(specifier.startsWith('/') ? specifier : resolve(dirname(importerPath), specifier));
|
|
685
|
+
if (resolvedPath) return resolvedPath;
|
|
686
|
+
}
|
|
687
|
+
let importResolvedPath = ((specifier, importerPath)=>{
|
|
688
|
+
let parsedSpecifier = ((specifier)=>{
|
|
689
|
+
if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('#')) return null;
|
|
690
|
+
let parts = specifier.split('/'), packageName = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0], packagePathParts = specifier.startsWith('@') ? parts.slice(2) : parts.slice(1);
|
|
691
|
+
return {
|
|
692
|
+
packageName,
|
|
693
|
+
packageSubpath: packagePathParts.length > 0 ? `./${packagePathParts.join('/')}` : '.'
|
|
694
|
+
};
|
|
695
|
+
})(specifier);
|
|
696
|
+
if (!parsedSpecifier) return PACKAGE_RESOLUTION_NOT_APPLICABLE;
|
|
697
|
+
let packageDirectory = ((importerPath, packageName)=>{
|
|
698
|
+
let currentDirectory = dirname(importerPath);
|
|
699
|
+
for(;;){
|
|
700
|
+
let packageDirectory = resolve(currentDirectory, 'node_modules', packageName), packageJsonPath = resolve(packageDirectory, 'package.json');
|
|
701
|
+
if (tryStat(packageJsonPath)?.isFile()) return packageDirectory;
|
|
702
|
+
let parentDirectory = dirname(currentDirectory);
|
|
703
|
+
if (parentDirectory === currentDirectory) return null;
|
|
704
|
+
currentDirectory = parentDirectory;
|
|
705
|
+
}
|
|
706
|
+
})(importerPath, parsedSpecifier.packageName);
|
|
707
|
+
if (!packageDirectory) return PACKAGE_RESOLUTION_NOT_APPLICABLE;
|
|
708
|
+
let packageJson = ((packageDirectory)=>{
|
|
709
|
+
try {
|
|
710
|
+
return JSON.parse(readFileSync(resolve(packageDirectory, 'package.json'), 'utf8'));
|
|
711
|
+
} catch {
|
|
712
|
+
return null;
|
|
713
|
+
}
|
|
714
|
+
})(packageDirectory);
|
|
715
|
+
return packageJson && (void 0 !== packageJson.exports || packageJson.module || packageJson.main) ? ((packageDirectory, packageSubpath, packageJson)=>{
|
|
716
|
+
let exports = packageJson.exports;
|
|
717
|
+
if (!exports) {
|
|
718
|
+
let entry = packageJson.module ?? packageJson.main;
|
|
719
|
+
return entry ? resolvePathWithExtensions(resolve(packageDirectory, entry)) : null;
|
|
720
|
+
}
|
|
721
|
+
let resolvedTarget = resolvePackageExportTarget('object' == typeof exports && !Array.isArray(exports) && Object.keys(exports).some((key)=>key.startsWith('.')) ? exports[packageSubpath] : '.' === packageSubpath ? exports : void 0);
|
|
722
|
+
return resolvedTarget && resolvedTarget.startsWith('./') ? resolvePathWithExtensions(resolve(packageDirectory, resolvedTarget)) : null;
|
|
723
|
+
})(packageDirectory, parsedSpecifier.packageSubpath, packageJson) : PACKAGE_RESOLUTION_NOT_APPLICABLE;
|
|
724
|
+
})(specifier, importerPath);
|
|
725
|
+
if (importResolvedPath !== PACKAGE_RESOLUTION_NOT_APPLICABLE) return importResolvedPath;
|
|
726
|
+
try {
|
|
727
|
+
return createRequire(importerPath).resolve(specifier);
|
|
728
|
+
} catch {
|
|
729
|
+
return null;
|
|
730
|
+
}
|
|
731
|
+
}, createBundlerRouteExportResolver = (resolveModule)=>(specifier, importerPath)=>new Promise((resolvePromise)=>{
|
|
732
|
+
resolveModule(dirname(importerPath), specifier, (error, resolved)=>{
|
|
733
|
+
resolvePromise(error || !resolved ? null : resolved);
|
|
734
|
+
});
|
|
735
|
+
}), collectClientOnlyStubExportNames = async (code, resourcePath, resolveModule = resolveExportAllModule)=>{
|
|
736
|
+
let { exportNames: directExportNames, exportAllModules } = await getExportNamesAndExportAll(code, resourcePath), exportNames = new Set(directExportNames), unresolvedExportAll = new Set(), visitedModules = new Set(), collectExportNamesFromModule = async (modulePath)=>{
|
|
737
|
+
if (visitedModules.has(modulePath)) return;
|
|
738
|
+
visitedModules.add(modulePath);
|
|
739
|
+
let { exports: moduleExportNames, exportAllModules: moduleExportAll } = await getRouteModuleAnalysis(modulePath);
|
|
740
|
+
for (let name of moduleExportNames)'default' !== name && exportNames.add(name);
|
|
741
|
+
for (let nestedSpecifier of moduleExportAll){
|
|
742
|
+
let nestedPath = await resolveModule(nestedSpecifier, modulePath);
|
|
743
|
+
if (!nestedPath) {
|
|
744
|
+
unresolvedExportAll.add(nestedSpecifier);
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
await collectExportNamesFromModule(nestedPath);
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
for (let specifier of exportAllModules){
|
|
751
|
+
let resolvedPath = await resolveModule(specifier, resourcePath);
|
|
752
|
+
if (!resolvedPath) {
|
|
753
|
+
unresolvedExportAll.add(specifier);
|
|
754
|
+
continue;
|
|
755
|
+
}
|
|
756
|
+
await collectExportNamesFromModule(resolvedPath);
|
|
757
|
+
}
|
|
758
|
+
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(), resourcePath)}\`.`);
|
|
759
|
+
return exportNames;
|
|
760
|
+
}, createRouteClientEntryArtifact = async ({ code, resourcePath, environmentName, isBuild, routeChunkCache, routeChunkConfig })=>{
|
|
761
|
+
let isServer = 'node' === environmentName, routeChunkInfo = !isServer && isBuild && shouldAnalyzeRouteChunks(routeChunkConfig, resourcePath, code) ? await detectRouteChunksIfEnabled(routeChunkCache, routeChunkConfig, resourcePath, code) : null;
|
|
762
|
+
return {
|
|
763
|
+
code: (({ exportNames, chunkedExports, isServer, resourcePath })=>{
|
|
764
|
+
let chunkedExportSet = chunkedExports.length > 0 ? new Set(chunkedExports) : void 0, reexports = exportNames.filter((exp)=>!chunkedExportSet?.has(exp) && (CLIENT_ROUTE_EXPORTS_SET.has(exp) || isServer && SERVER_ONLY_ROUTE_EXPORTS_SET.has(exp))).sort(), target = `${resourcePath}?react-router-route`;
|
|
765
|
+
return `export { ${reexports.join(', ')} } from ${JSON.stringify(target)};`;
|
|
766
|
+
})({
|
|
767
|
+
exportNames: routeChunkInfo?.exportNames ?? await getExportNames(code, resourcePath),
|
|
768
|
+
chunkedExports: routeChunkInfo?.chunkedExports ?? [],
|
|
769
|
+
isServer,
|
|
770
|
+
resourcePath
|
|
771
|
+
})
|
|
772
|
+
};
|
|
773
|
+
}, createRouteChunkArtifact = async ({ code, resource, resourcePath, isBuild, routeChunkCache, routeChunkConfig })=>{
|
|
774
|
+
let splitRouteModules = routeChunkConfig.splitRouteModules;
|
|
775
|
+
if (!isBuild || !splitRouteModules) return {
|
|
776
|
+
code: 'export {};',
|
|
777
|
+
map: null
|
|
778
|
+
};
|
|
779
|
+
let chunkName = ((id)=>{
|
|
780
|
+
let queryIndex = id.indexOf(routeChunkQueryStringPrefix);
|
|
781
|
+
if (-1 === queryIndex) return null;
|
|
782
|
+
let chunkNameStart = queryIndex + routeChunkQueryStringPrefix.length, chunkNameEnd = id.indexOf('&', chunkNameStart), chunkName = id.slice(chunkNameStart, -1 === chunkNameEnd ? void 0 : chunkNameEnd);
|
|
783
|
+
return 'main' === chunkName || routeChunkExportNames.includes(chunkName) ? chunkName : null;
|
|
784
|
+
})(resource);
|
|
785
|
+
if (!chunkName) throw Error(`Invalid route chunk name in "${resource}"`);
|
|
786
|
+
if ('main' !== chunkName && !code.includes(chunkName)) return {
|
|
787
|
+
code: 'export {};',
|
|
788
|
+
map: null
|
|
789
|
+
};
|
|
790
|
+
let chunk = await getRouteChunkIfEnabled(routeChunkCache, routeChunkConfig, resourcePath, chunkName, code);
|
|
791
|
+
if ('enforce' === splitRouteModules && 'main' === chunkName && chunk) {
|
|
792
|
+
let exportNameSet, exportNames = await getExportNames(chunk, resourcePath);
|
|
793
|
+
validateRouteChunks({
|
|
794
|
+
config: routeChunkConfig,
|
|
795
|
+
id: resourcePath,
|
|
796
|
+
valid: (exportNameSet = new Set(exportNames), createRouteChunkExportMap((exportName)=>!exportNameSet.has(exportName)))
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
return {
|
|
800
|
+
code: chunk ?? 'export {};',
|
|
801
|
+
map: null
|
|
802
|
+
};
|
|
803
|
+
}, defaultRouteChunkCache = new Map(), getRouteChunkCache = (options)=>options?.routeChunkCache ?? defaultRouteChunkCache, splitRouteExports = async (task, options)=>{
|
|
804
|
+
let { exportNames, hasRouteChunks, chunkedExports } = await detectRouteChunksIfEnabled(getRouteChunkCache(options), task.routeChunkConfig, task.resourcePath, task.code);
|
|
805
|
+
if (!hasRouteChunks) return {
|
|
806
|
+
code: task.code,
|
|
807
|
+
map: null
|
|
808
|
+
};
|
|
809
|
+
let chunkedExportSet = new Set(chunkedExports), mainChunkReexports = exportNames.filter((name)=>!chunkedExportSet.has(name)).join(', '), chunkBasePath = `./${basename(task.resourcePath)}`;
|
|
810
|
+
return {
|
|
811
|
+
code: [
|
|
812
|
+
mainChunkReexports ? `export { ${mainChunkReexports} } from "${getRouteChunkModuleId(chunkBasePath, 'main')}";` : null,
|
|
813
|
+
...chunkedExports.map((exportName)=>`export { ${exportName} } from "${getRouteChunkModuleId(chunkBasePath, exportName)}";`)
|
|
814
|
+
].filter(Boolean).join('\n'),
|
|
815
|
+
map: null
|
|
816
|
+
};
|
|
817
|
+
}, createClientOnlyStub = async (task)=>({
|
|
818
|
+
code: Array.from(await collectClientOnlyStubExportNames(task.code, task.resourcePath, task.resolveExportAllModule)).map((name)=>'default' === name ? 'export default undefined;' : `export const ${name} = undefined;`).join('\n'),
|
|
819
|
+
map: null
|
|
820
|
+
}), transformRouteModule = async (task)=>{
|
|
821
|
+
let code = task.code, defaultExportMatch = code.match(/\n\s{0,}([\w\d_]+)\sas default,?/);
|
|
822
|
+
defaultExportMatch && 'number' == typeof defaultExportMatch.index && (code = code.slice(0, defaultExportMatch.index) + code.slice(defaultExportMatch.index + defaultExportMatch[0].length) + `\nexport default ${defaultExportMatch[1]};`);
|
|
823
|
+
let ast = ((code, options = {})=>{
|
|
824
|
+
let result = parse(code, {
|
|
825
|
+
...options,
|
|
826
|
+
sourceType: options.sourceType ?? 'module',
|
|
827
|
+
lang: options.lang ?? 'tsx',
|
|
828
|
+
attachComments: options.attachComments ?? !0
|
|
829
|
+
}), errors = result.diagnostics.filter((diagnostic)=>'error' === diagnostic.severity);
|
|
830
|
+
if (errors.length > 0) throw Error(errors.map((error)=>error.message).join('\n'));
|
|
831
|
+
return result;
|
|
832
|
+
})(code, {
|
|
833
|
+
sourceType: 'module'
|
|
834
|
+
});
|
|
835
|
+
if ('web' === task.environmentName && !task.ssr && task.isSpaMode) {
|
|
836
|
+
let resolvedExportNames = collectProgramExportNames(ast.program ?? ast), isRootRoute = task.resourcePath === task.rootRoutePath, relativePath = relative(process.cwd(), task.resourcePath), invalidServerOnly = resolvedExportNames.filter((exp)=>(!isRootRoute || 'loader' !== exp) && SERVER_ONLY_ROUTE_EXPORTS_SET.has(exp));
|
|
837
|
+
if (invalidServerOnly.length > 0) {
|
|
838
|
+
let list = invalidServerOnly.map((e)=>`\`${e}\``).join(', ');
|
|
839
|
+
throw Error(`SPA Mode: ${invalidServerOnly.length} invalid route export(s) in \`${relativePath}\`: ${list}. See https://reactrouter.com/how-to/spa for more information.`);
|
|
840
|
+
}
|
|
841
|
+
if (!isRootRoute && resolvedExportNames.includes('HydrateFallback')) throw Error(`SPA Mode: Invalid \`HydrateFallback\` export found in \`${relativePath}\`. \`HydrateFallback\` is only permitted on the root route in SPA Mode. See https://reactrouter.com/how-to/spa for more information.`);
|
|
842
|
+
}
|
|
843
|
+
let removedServerOnlyExports = 'web' === task.environmentName && ((ast, exportsToRemove, exportsToRemoveSet = new Set(exportsToRemove))=>{
|
|
844
|
+
let currentlyLive, removedReferenceCache, isRemovableDeadDeclaration, program = ast.program ?? ast;
|
|
845
|
+
if (!((program, exportsToRemove)=>{
|
|
846
|
+
let removesNamedExports = [
|
|
847
|
+
...exportsToRemove
|
|
848
|
+
].some((name)=>'default' !== name);
|
|
849
|
+
for (let statement of program.body ?? []){
|
|
850
|
+
if ('ExportAllDeclaration' === statement.type) {
|
|
851
|
+
let exportedName = statement.exported ? getExportedName({
|
|
852
|
+
exported: statement.exported
|
|
853
|
+
}) : null;
|
|
854
|
+
if (exportedName && exportsToRemove.has(exportedName) || !exportedName && removesNamedExports) return !0;
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
if ('ExportDefaultDeclaration' === statement.type) {
|
|
858
|
+
if (exportsToRemove.has('default')) return !0;
|
|
859
|
+
continue;
|
|
860
|
+
}
|
|
861
|
+
if ('ExportNamedDeclaration' !== statement.type) continue;
|
|
862
|
+
for (let specifier of statement.specifiers ?? []){
|
|
863
|
+
if ('ExportSpecifier' !== specifier.type) continue;
|
|
864
|
+
let exportedName = getExportedName(specifier);
|
|
865
|
+
if (exportedName && exportsToRemove.has(exportedName)) return !0;
|
|
866
|
+
}
|
|
867
|
+
let declaration = statement.declaration;
|
|
868
|
+
if (declaration?.type === 'VariableDeclaration') {
|
|
869
|
+
for (let declarator of declaration.declarations ?? [])for (let name of getPatternIdentifierNames(declarator.id))if (exportsToRemove.has(name)) return !0;
|
|
870
|
+
continue;
|
|
871
|
+
}
|
|
872
|
+
if ((declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') && declaration.id?.name && exportsToRemove.has(declaration.id.name)) return !0;
|
|
873
|
+
}
|
|
874
|
+
return !1;
|
|
875
|
+
})(program, exportsToRemoveSet)) return !1;
|
|
876
|
+
let declarationGraph = ((program)=>{
|
|
877
|
+
let declarationsByNode = new Map(), declarationsByName = new Map(), registerDeclaration = (node, declarationNode, declaredNames)=>{
|
|
878
|
+
let declaration = {
|
|
879
|
+
referencedNames: collectReferencedNames(declarationNode)
|
|
880
|
+
};
|
|
881
|
+
for (let name of (declarationsByNode.set(node, declaration), declaredNames)){
|
|
882
|
+
let namedDeclarations = declarationsByName.get(name) ?? new Set();
|
|
883
|
+
namedDeclarations.add(declaration), declarationsByName.set(name, namedDeclarations);
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
for (let statement of [
|
|
887
|
+
...program.body ?? []
|
|
888
|
+
]){
|
|
889
|
+
if ('VariableDeclaration' === statement.type) {
|
|
890
|
+
for (let declarator of statement.declarations ?? [])registerDeclaration(declarator, declarator, getPatternIdentifierNames(declarator.id));
|
|
891
|
+
continue;
|
|
892
|
+
}
|
|
893
|
+
('FunctionDeclaration' === statement.type || 'ClassDeclaration' === statement.type) && registerDeclaration(statement, statement, getDeclaredNames(statement));
|
|
894
|
+
}
|
|
895
|
+
return {
|
|
896
|
+
declarationsByNode,
|
|
897
|
+
declarationsByName
|
|
898
|
+
};
|
|
899
|
+
})(program), previouslyLive = collectLiveTopLevelDeclarations(program, declarationGraph), exportsChanged = !1, removedExportLocalNames = new Set(), removedExportReferencedNames = new Set(), removesNamedExports = exportsToRemove.some((name)=>'default' !== name), trackRemovedExportReferences = (node)=>{
|
|
900
|
+
if (!node) return;
|
|
901
|
+
let declaration = declarationGraph.declarationsByNode.get(node);
|
|
902
|
+
for (let name of declaration?.referencedNames ?? collectReferencedNames(node))removedExportReferencedNames.add(name);
|
|
903
|
+
};
|
|
904
|
+
for (let statement of [
|
|
905
|
+
...program.body
|
|
906
|
+
]){
|
|
907
|
+
if ('ExportAllDeclaration' === statement.type) {
|
|
908
|
+
let exportedName = statement.exported ? getExportedName({
|
|
909
|
+
exported: statement.exported
|
|
910
|
+
}) : null;
|
|
911
|
+
if (exportedName && exportsToRemoveSet.has(exportedName) && (exportsChanged = !0, removeFromArray(program.body, statement)), !exportedName && removesNamedExports) throw Error('Cannot remove named exports from `export *`; use explicit named re-exports.');
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
if ('ExportNamedDeclaration' === statement.type) {
|
|
915
|
+
statement.specifiers?.length && (statement.specifiers = statement.specifiers.filter((specifier)=>{
|
|
916
|
+
if ('ExportSpecifier' !== specifier.type) return !0;
|
|
917
|
+
let exportedName = getExportedName(specifier);
|
|
918
|
+
return !(exportedName && exportsToRemoveSet.has(exportedName)) || (exportsChanged = !0, specifier.local?.name && (removedExportLocalNames.add(specifier.local.name), removedExportReferencedNames.add(specifier.local.name)), !1);
|
|
919
|
+
}), 0 !== statement.specifiers.length || statement.declaration || removeFromArray(program.body, statement));
|
|
920
|
+
let declaration = statement.declaration;
|
|
921
|
+
declaration?.type === 'VariableDeclaration' && (declaration.declarations = (declaration.declarations ?? []).filter((declarator)=>{
|
|
922
|
+
let id = declarator.id;
|
|
923
|
+
return id?.type === 'Identifier' ? !(id.name && exportsToRemoveSet.has(id.name)) || (exportsChanged = !0, removedExportLocalNames.add(id.name), removedExportReferencedNames.add(id.name), trackRemovedExportReferences(declarator), !1) : (id && validateBindingTarget(id, new Set(exportsToRemove)), !0);
|
|
924
|
+
}), 0 === declaration.declarations.length && removeFromArray(program.body, statement)), (declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') && declaration.id?.name && exportsToRemoveSet.has(declaration.id.name) && (exportsChanged = !0, removedExportLocalNames.add(declaration.id.name), removedExportReferencedNames.add(declaration.id.name), trackRemovedExportReferences(statement), removeFromArray(program.body, statement));
|
|
925
|
+
}
|
|
926
|
+
if ('ExportDefaultDeclaration' === statement.type && exportsToRemoveSet.has('default')) {
|
|
927
|
+
exportsChanged = !0;
|
|
928
|
+
let declaration = statement.declaration;
|
|
929
|
+
declaration?.type === 'Identifier' && declaration.name ? (removedExportLocalNames.add(declaration.name), removedExportReferencedNames.add(declaration.name)) : declaration?.id?.name && (removedExportLocalNames.add(declaration.id.name), removedExportReferencedNames.add(declaration.id.name)), trackRemovedExportReferences(statement), removeFromArray(program.body, statement);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
for (let statement of [
|
|
933
|
+
...program.body
|
|
934
|
+
]){
|
|
935
|
+
let expression = 'ExpressionStatement' === statement.type ? statement.expression : null, left = expression?.type === 'AssignmentExpression' ? expression.left : null;
|
|
936
|
+
left?.type === 'MemberExpression' && left.object?.type === 'Identifier' && left.object.name && removedExportLocalNames.has(left.object.name) && removeFromArray(program.body, statement);
|
|
937
|
+
}
|
|
938
|
+
return exportsChanged && (currentlyLive = collectLiveTopLevelDeclarations(program, declarationGraph), removedReferenceCache = new Map(), isRemovableDeadDeclaration = (node)=>{
|
|
939
|
+
let declaration = declarationGraph.declarationsByNode.get(node);
|
|
940
|
+
return !(!declaration || currentlyLive.has(declaration)) && (previouslyLive.has(declaration) || declarationReferencesName(declaration, removedExportReferencedNames, declarationGraph, removedReferenceCache));
|
|
941
|
+
}, program.body = program.body.filter((statement)=>'VariableDeclaration' === statement.type ? (statement.declarations = (statement.declarations ?? []).filter((declarator)=>!isRemovableDeadDeclaration(declarator)), statement.declarations.length > 0) : !isRemovableDeadDeclaration(statement))), exportsChanged;
|
|
942
|
+
})(ast, SERVER_ONLY_ROUTE_EXPORTS, SERVER_ONLY_ROUTE_EXPORTS_SET);
|
|
943
|
+
return ((ast)=>{
|
|
944
|
+
let program = ast.program ?? ast, usedNames = new Set(), hocs = [], componentWrapperDeclarations = [];
|
|
945
|
+
function getUid(name) {
|
|
946
|
+
let uid = `_${name}`, index = 2;
|
|
947
|
+
for(; usedNames.has(uid) || hasTopLevelBindingName(program, uid);)uid = `_${name}${index++}`;
|
|
948
|
+
return usedNames.add(uid), uid;
|
|
949
|
+
}
|
|
950
|
+
function getHocUid(hocName) {
|
|
951
|
+
let uid = getUid(hocName);
|
|
952
|
+
return hocs.push([
|
|
953
|
+
hocName,
|
|
954
|
+
uid
|
|
955
|
+
]), identifier(uid);
|
|
956
|
+
}
|
|
957
|
+
for (let statement of [
|
|
958
|
+
...program.body ?? []
|
|
959
|
+
]){
|
|
960
|
+
var name, name1;
|
|
961
|
+
if ('ExportDefaultDeclaration' === statement.type) {
|
|
962
|
+
let declaration = statement.declaration;
|
|
963
|
+
if (!declaration || !0 === declaration.declare || 'TSInterfaceDeclaration' === declaration.type) continue;
|
|
964
|
+
let uid = getHocUid('withComponentProps');
|
|
965
|
+
if (('FunctionDeclaration' === declaration.type || 'ClassDeclaration' === declaration.type) && declaration.id?.name) {
|
|
966
|
+
let statementIndex = program.body.indexOf(statement);
|
|
967
|
+
program.body.splice(statementIndex, 0, declaration), statement.declaration = callExpression(uid, [
|
|
968
|
+
identifier(declaration.id.name)
|
|
969
|
+
]);
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
statement.declaration = callExpression(uid, [
|
|
973
|
+
'FunctionDeclaration' === declaration.type ? toFunctionExpression(declaration) : 'ClassDeclaration' === declaration.type ? toClassExpression(declaration) : declaration
|
|
974
|
+
]);
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
if ('ExportNamedDeclaration' !== statement.type || 'type' === statement.exportKind) continue;
|
|
978
|
+
let declaration = statement.declaration;
|
|
979
|
+
if (declaration?.type === 'VariableDeclaration') {
|
|
980
|
+
for (let declarator of declaration.declarations ?? []){
|
|
981
|
+
if (declarator.id?.type !== 'Identifier' || !declarator.init || (name = declarator.id.name, !NAMED_COMPONENT_EXPORTS_SET.has(name))) continue;
|
|
982
|
+
let uid = getHocUid(`with${declarator.id.name}Props`);
|
|
983
|
+
declarator.init = callExpression(uid, [
|
|
984
|
+
declarator.init
|
|
985
|
+
]);
|
|
986
|
+
}
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
if ((declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') && declaration.id?.name && (name1 = declaration.id.name, NAMED_COMPONENT_EXPORTS_SET.has(name1))) {
|
|
990
|
+
statement.declaration = function(name, declaration) {
|
|
991
|
+
let uid = getHocUid(`with${name}Props`);
|
|
992
|
+
return variableDeclaration(name, callExpression(uid, [
|
|
993
|
+
'FunctionDeclaration' === declaration.type ? toFunctionExpression(declaration) : 'ClassDeclaration' === declaration.type ? toClassExpression(declaration) : declaration
|
|
994
|
+
]));
|
|
995
|
+
}(declaration.id.name, declaration);
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
if (statement.source) {
|
|
999
|
+
let importSpecifiers = [], sourceWrapperDeclarations = [], wrappedExportSpecifiers = [];
|
|
1000
|
+
if (statement.specifiers = (statement.specifiers ?? []).filter((specifier)=>{
|
|
1001
|
+
if ('ExportSpecifier' !== specifier.type || 'type' === specifier.exportKind) return !0;
|
|
1002
|
+
let exportedName = getExportedName(specifier), importedName = getExportedName(specifier.local), componentExportName = exportedName ? getComponentExportName(exportedName) : null;
|
|
1003
|
+
if (!exportedName || !importedName || !componentExportName) return !0;
|
|
1004
|
+
let sourceLocalName = getUid(`${exportedName}Source`), wrappedLocalName = getUid(exportedName), uid = getHocUid(`with${componentExportName}Props`);
|
|
1005
|
+
return importSpecifiers.push({
|
|
1006
|
+
imported: importedName,
|
|
1007
|
+
local: sourceLocalName
|
|
1008
|
+
}), sourceWrapperDeclarations.push(variableDeclaration(wrappedLocalName, callExpression(uid, [
|
|
1009
|
+
identifier(sourceLocalName)
|
|
1010
|
+
]))), wrappedExportSpecifiers.push(exportSpecifier(wrappedLocalName, exportedName)), !1;
|
|
1011
|
+
}), importSpecifiers.length > 0) {
|
|
1012
|
+
let statementIndex = program.body.indexOf(statement), replacementStatements = [
|
|
1013
|
+
importDeclaration(importSpecifiers, String(statement.source.value))
|
|
1014
|
+
];
|
|
1015
|
+
statement.specifiers.length > 0 && replacementStatements.push(statement), replacementStatements.push(...sourceWrapperDeclarations), replacementStatements.push(exportNamedDeclaration(wrappedExportSpecifiers)), program.body.splice(statementIndex, 1, ...replacementStatements);
|
|
1016
|
+
}
|
|
1017
|
+
continue;
|
|
1018
|
+
}
|
|
1019
|
+
for (let specifier of statement.specifiers ?? []){
|
|
1020
|
+
if ('ExportSpecifier' !== specifier.type || 'type' === specifier.exportKind) continue;
|
|
1021
|
+
let exportedName = getExportedName(specifier), componentExportName = exportedName ? getComponentExportName(exportedName) : null;
|
|
1022
|
+
if (!exportedName || !componentExportName) continue;
|
|
1023
|
+
let localName = specifier.local?.name;
|
|
1024
|
+
if (!localName) continue;
|
|
1025
|
+
let wrappedLocalName = getUid(exportedName), uid = getHocUid(`with${componentExportName}Props`);
|
|
1026
|
+
componentWrapperDeclarations.push(variableDeclaration(wrappedLocalName, callExpression(uid, [
|
|
1027
|
+
identifier(localName)
|
|
1028
|
+
]))), specifier.local = identifier(wrappedLocalName);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
program.body.push(...componentWrapperDeclarations), hocs.length > 0 && program.body.splice(((program)=>{
|
|
1032
|
+
let index = 0;
|
|
1033
|
+
for (let statement of program.body ?? []){
|
|
1034
|
+
if ('ExpressionStatement' !== statement.type || void 0 === statement.directive && statement.expression?.type !== 'Literal') break;
|
|
1035
|
+
index += 1;
|
|
1036
|
+
}
|
|
1037
|
+
return index;
|
|
1038
|
+
})(program), 0, importDeclaration(hocs.map(([name, local])=>({
|
|
1039
|
+
imported: name,
|
|
1040
|
+
local
|
|
1041
|
+
})), 'virtual/react-router/with-props'));
|
|
1042
|
+
})(ast), removedServerOnlyExports && ((ast)=>{
|
|
1043
|
+
let program = ast.program ?? ast, referenced = collectReferencedNames(program);
|
|
1044
|
+
for (let statement of [
|
|
1045
|
+
...program.body
|
|
1046
|
+
])'ImportDeclaration' === statement.type && 0 !== (statement.specifiers ?? []).length && (statement.specifiers = (statement.specifiers ?? []).filter((specifier)=>'type' !== specifier.importKind && (!specifier.local?.name || referenced.has(specifier.local.name))), 0 === statement.specifiers.length && removeFromArray(program.body, statement));
|
|
1047
|
+
})(ast), ((ast, options = {})=>{
|
|
1048
|
+
let result = 'program' in ast ? ast : {
|
|
1049
|
+
program: ast,
|
|
1050
|
+
lineStarts: []
|
|
1051
|
+
}, generated = print(result.program, {
|
|
1052
|
+
comments: !0,
|
|
1053
|
+
sourceMaps: options.sourceMaps ? {
|
|
1054
|
+
lineStarts: result.lineStarts,
|
|
1055
|
+
file: options.filename,
|
|
1056
|
+
sourceFileName: options.sourceFileName
|
|
1057
|
+
} : void 0
|
|
1058
|
+
});
|
|
1059
|
+
if (generated.errors.length > 0) throw Error(generated.errors.map((error)=>error.message).join('\n'));
|
|
1060
|
+
let map = generated.map ? {
|
|
1061
|
+
...generated.map,
|
|
1062
|
+
file: generated.map.file ?? options.filename ?? '',
|
|
1063
|
+
sourceRoot: generated.map.sourceRoot ?? void 0,
|
|
1064
|
+
sourcesContent: generated.map.sourcesContent?.map((source)=>source ?? '') ?? void 0
|
|
1065
|
+
} : null;
|
|
1066
|
+
return {
|
|
1067
|
+
code: generated.code,
|
|
1068
|
+
map
|
|
1069
|
+
};
|
|
1070
|
+
})(ast, {
|
|
1071
|
+
sourceMaps: task.sourceMaps,
|
|
1072
|
+
filename: task.resource,
|
|
1073
|
+
sourceFileName: task.resourcePath
|
|
1074
|
+
});
|
|
1075
|
+
}, executeRouteTransformTask = async (task, options)=>{
|
|
1076
|
+
switch(task.kind){
|
|
1077
|
+
case 'routeClientEntry':
|
|
1078
|
+
return createRouteClientEntryArtifact({
|
|
1079
|
+
code: task.code,
|
|
1080
|
+
resourcePath: task.resourcePath,
|
|
1081
|
+
environmentName: task.environmentName,
|
|
1082
|
+
isBuild: task.isBuild,
|
|
1083
|
+
routeChunkCache: getRouteChunkCache(options),
|
|
1084
|
+
routeChunkConfig: task.routeChunkConfig
|
|
1085
|
+
});
|
|
1086
|
+
case 'routeChunk':
|
|
1087
|
+
return createRouteChunkArtifact({
|
|
1088
|
+
code: task.code,
|
|
1089
|
+
resource: task.resource,
|
|
1090
|
+
resourcePath: task.resourcePath,
|
|
1091
|
+
isBuild: task.isBuild,
|
|
1092
|
+
routeChunkCache: getRouteChunkCache(options),
|
|
1093
|
+
routeChunkConfig: task.routeChunkConfig
|
|
1094
|
+
});
|
|
1095
|
+
case 'splitRouteExports':
|
|
1096
|
+
return splitRouteExports(task, options);
|
|
1097
|
+
case 'clientOnlyStub':
|
|
1098
|
+
return createClientOnlyStub(task);
|
|
1099
|
+
case 'routeModule':
|
|
1100
|
+
return transformRouteModule(task);
|
|
1101
|
+
}
|
|
1102
|
+
};
|
|
1103
|
+
export { BUILD_CLIENT_ROUTE_QUERY_STRING, CLIENT_EXPORTS, JS_EXTENSIONS, PLUGIN_NAME, SERVER_EXPORTS, buildManifestChunkValidity, combineURLs, createBundlerRouteExportResolver, createEmptyRouteChunkByExportName, createRouteId, detectRouteChunksIfEnabled, executeRouteTransformTask, findEntryFile, generateWithProps, getRouteChunkEntryName, getRouteChunkModuleId, getRouteModuleAnalysis, normalizeAssetPrefix, routeChunkExportNames, setBoundedCacheEntry, validateRouteChunks };
|