miaoda-react-devkit 0.1.1-beta.2 → 0.1.1-beta.20
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/cloud/vite.config.js +122 -0
- package/dist/index.cjs +340 -84
- package/dist/index.d.cts +170 -2
- package/dist/index.d.ts +170 -2
- package/dist/index.js +335 -84
- package/dist/stubs/sentry-react-noop-stub.js +144 -0
- package/dist/stubs/sentry-react-stub.js +338 -85
- package/dist/vite/index.cjs +853 -0
- package/dist/vite/index.d.cts +44 -1
- package/dist/vite/index.d.ts +44 -1
- package/dist/vite/index.js +851 -0
- package/package.json +8 -1
- package/README.md +0 -181
- package/cloud/vite.config.ts +0 -156
package/dist/vite/index.cjs
CHANGED
|
@@ -30,7 +30,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/vite/index.ts
|
|
31
31
|
var vite_exports = {};
|
|
32
32
|
__export(vite_exports, {
|
|
33
|
+
extractRouterPlugin: () => extractRouterPlugin,
|
|
33
34
|
hmrTogglePlugin: () => hmrTogglePlugin,
|
|
35
|
+
withSentryBuild: () => withSentryBuild,
|
|
34
36
|
withSentryStub: () => withSentryStub
|
|
35
37
|
});
|
|
36
38
|
module.exports = __toCommonJS(vite_exports);
|
|
@@ -60,20 +62,53 @@ function withSentryStub() {
|
|
|
60
62
|
};
|
|
61
63
|
}
|
|
62
64
|
|
|
65
|
+
// src/vite/withSentryBuild.ts
|
|
66
|
+
var import_node_path2 = __toESM(require("path"), 1);
|
|
67
|
+
var import_node_url2 = require("url");
|
|
68
|
+
var SENTRY_MODULE2 = "@sentry/react";
|
|
69
|
+
var _dirname2 = import_node_path2.default.dirname((0, import_node_url2.fileURLToPath)(importMetaUrl));
|
|
70
|
+
var STUB_PATH2 = import_node_path2.default.resolve(_dirname2, "../stubs/sentry-react-noop-stub.js");
|
|
71
|
+
function withSentryBuild() {
|
|
72
|
+
return {
|
|
73
|
+
name: "miaoda-devkit:sentry-build",
|
|
74
|
+
enforce: "pre",
|
|
75
|
+
apply: "build",
|
|
76
|
+
resolveId(id) {
|
|
77
|
+
if (id === SENTRY_MODULE2) return STUB_PATH2;
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
63
83
|
// src/vite/hmrTogglePlugin.ts
|
|
64
84
|
function hmrTogglePlugin() {
|
|
65
85
|
return {
|
|
66
86
|
name: "miaoda-devkit:hmr-toggle",
|
|
67
87
|
configureServer(server) {
|
|
68
88
|
let hmrEnabled = true;
|
|
89
|
+
let pendingFullReload = false;
|
|
69
90
|
const origSend = server.ws.send.bind(server.ws);
|
|
91
|
+
const flushPendingFullReload = () => {
|
|
92
|
+
if (!hmrEnabled || !pendingFullReload) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (server.ws.clients.size === 0) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
pendingFullReload = false;
|
|
99
|
+
origSend({ type: "full-reload", path: "*" });
|
|
100
|
+
};
|
|
70
101
|
server.ws.send = (payload) => {
|
|
71
102
|
if (hmrEnabled) {
|
|
72
103
|
origSend(payload);
|
|
73
104
|
} else {
|
|
105
|
+
if (payload.type === "full-reload") {
|
|
106
|
+
pendingFullReload = true;
|
|
107
|
+
}
|
|
74
108
|
console.log("[HMR disabled] skipped payload:", payload.type);
|
|
75
109
|
}
|
|
76
110
|
};
|
|
111
|
+
server.ws.on?.("connection", flushPendingFullReload);
|
|
77
112
|
server.middlewares.use("/innerapi/v1/sourcecode/__hmr_off", (_req, res) => {
|
|
78
113
|
hmrEnabled = false;
|
|
79
114
|
res.setHeader("Content-Type", "application/json");
|
|
@@ -81,12 +116,15 @@ function hmrTogglePlugin() {
|
|
|
81
116
|
});
|
|
82
117
|
server.middlewares.use("/innerapi/v1/sourcecode/__hmr_on", (_req, res) => {
|
|
83
118
|
hmrEnabled = true;
|
|
119
|
+
flushPendingFullReload();
|
|
84
120
|
res.setHeader("Content-Type", "application/json");
|
|
85
121
|
res.end(JSON.stringify({ status: 0, msg: "HMR enabled" }));
|
|
86
122
|
});
|
|
87
123
|
server.middlewares.use("/innerapi/v1/sourcecode/__hmr_reload", (_req, res) => {
|
|
88
124
|
if (hmrEnabled) {
|
|
89
125
|
server.ws.send({ type: "full-reload", path: "*" });
|
|
126
|
+
} else {
|
|
127
|
+
pendingFullReload = true;
|
|
90
128
|
}
|
|
91
129
|
res.setHeader("Content-Type", "application/json");
|
|
92
130
|
res.end(JSON.stringify({ status: 0, msg: "Manual full reload triggered" }));
|
|
@@ -117,8 +155,823 @@ function hmrTogglePlugin() {
|
|
|
117
155
|
}
|
|
118
156
|
};
|
|
119
157
|
}
|
|
158
|
+
|
|
159
|
+
// src/vite/extractRouterPlugin/index.ts
|
|
160
|
+
var import_path3 = __toESM(require("path"), 1);
|
|
161
|
+
|
|
162
|
+
// src/vite/extractRouterPlugin/babelHelpers.ts
|
|
163
|
+
var import_traverse = __toESM(require("@babel/traverse"), 1);
|
|
164
|
+
var import_parser = require("@babel/parser");
|
|
165
|
+
var t = __toESM(require("@babel/types"), 1);
|
|
166
|
+
|
|
167
|
+
// src/vite/extractRouterPlugin/constants.ts
|
|
168
|
+
var SOURCE_TYPE = "module";
|
|
169
|
+
var PLUGINS = ["jsx", "typescript"];
|
|
170
|
+
var EXCLUDE_MODULE = ["react", "react-dom", "react-router-dom"];
|
|
171
|
+
var JS_SUFFIXES = [".ts", ".tsx", ".jsx", ".js"];
|
|
172
|
+
|
|
173
|
+
// src/vite/extractRouterPlugin/babelHelpers.ts
|
|
174
|
+
var resolveBabelModule = (mod) => {
|
|
175
|
+
if (typeof mod === "function") return mod;
|
|
176
|
+
if (typeof mod.default === "function") return mod.default;
|
|
177
|
+
throw new Error("Cannot resolve babel module");
|
|
178
|
+
};
|
|
179
|
+
var traverse = resolveBabelModule(import_traverse.default);
|
|
180
|
+
var parseCode = (code, id) => (0, import_parser.parse)(code, { sourceType: SOURCE_TYPE, plugins: PLUGINS, sourceFilename: id });
|
|
181
|
+
var isLazyCallee = (callee) => {
|
|
182
|
+
if (t.isIdentifier(callee) && callee.name === "lazy") return true;
|
|
183
|
+
if (t.isMemberExpression(callee) && t.isIdentifier(callee.property) && callee.property.name === "lazy") return true;
|
|
184
|
+
return false;
|
|
185
|
+
};
|
|
186
|
+
var createImportVisitors = (importMap, lazyImportMap) => ({
|
|
187
|
+
/** 收集 import 声明:import Foo from './Foo' → importMap.set('Foo', './Foo') */
|
|
188
|
+
ImportDeclaration(nodePath) {
|
|
189
|
+
const source = nodePath.node.source.value;
|
|
190
|
+
if (EXCLUDE_MODULE.includes(source)) return;
|
|
191
|
+
for (const spec of nodePath.node.specifiers) {
|
|
192
|
+
if (t.isImportSpecifier(spec) || t.isImportDefaultSpecifier(spec)) {
|
|
193
|
+
importMap.set(spec.local.name, source);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
/**
|
|
198
|
+
* 收集 lazy 声明:const Foo = lazy(() => import('./Foo'))
|
|
199
|
+
* → lazyImportMap.set('Foo', './Foo')
|
|
200
|
+
*/
|
|
201
|
+
VariableDeclarator(nodePath) {
|
|
202
|
+
if (!t.isIdentifier(nodePath.node.id) || !nodePath.node.init) return;
|
|
203
|
+
if (!t.isCallExpression(nodePath.node.init) || !isLazyCallee(nodePath.node.init.callee)) return;
|
|
204
|
+
const arg0 = nodePath.node.init.arguments[0];
|
|
205
|
+
if (t.isArrowFunctionExpression(arg0) && t.isCallExpression(arg0.body) && t.isImport(arg0.body.callee) && arg0.body.arguments.length > 0 && t.isStringLiteral(arg0.body.arguments[0])) {
|
|
206
|
+
lazyImportMap.set(nodePath.node.id.name, arg0.body.arguments[0].value);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
var getOriginalArrayName = (objectPath) => {
|
|
211
|
+
if (objectPath.isIdentifier()) return objectPath.node.name;
|
|
212
|
+
if (objectPath.isCallExpression()) {
|
|
213
|
+
const callee = objectPath.get("callee");
|
|
214
|
+
if (callee.isMemberExpression()) return getOriginalArrayName(callee.get("object"));
|
|
215
|
+
}
|
|
216
|
+
if (objectPath.isMemberExpression()) {
|
|
217
|
+
const property = objectPath.get("property");
|
|
218
|
+
if (property.isIdentifier()) return property.node.name;
|
|
219
|
+
return getOriginalArrayName(objectPath.get("object"));
|
|
220
|
+
}
|
|
221
|
+
return "";
|
|
222
|
+
};
|
|
223
|
+
var collectDeps = (mod, seen = /* @__PURE__ */ new Set()) => {
|
|
224
|
+
if (!mod?.id || seen.has(mod.id) || mod.id.includes("node_modules")) return [];
|
|
225
|
+
seen.add(mod.id);
|
|
226
|
+
const deps = [mod.id];
|
|
227
|
+
for (const m of mod.importedModules ?? []) {
|
|
228
|
+
deps.push(...collectDeps(m, seen));
|
|
229
|
+
}
|
|
230
|
+
return deps;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
// src/vite/extractRouterPlugin/routeTransform.ts
|
|
234
|
+
var t2 = __toESM(require("@babel/types"), 1);
|
|
235
|
+
var findResolvableJSXComponent = (jsxEl, importMap, lazyImportMap) => {
|
|
236
|
+
const dfs = (el, map) => {
|
|
237
|
+
const nameNode = el.openingElement.name;
|
|
238
|
+
if (t2.isJSXIdentifier(nameNode) && map.has(nameNode.name)) return nameNode.name;
|
|
239
|
+
for (const child of el.children) {
|
|
240
|
+
if (t2.isJSXElement(child)) {
|
|
241
|
+
const found = dfs(child, map);
|
|
242
|
+
if (found) return found;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return "";
|
|
246
|
+
};
|
|
247
|
+
return dfs(jsxEl, lazyImportMap) || dfs(jsxEl, importMap) || (t2.isJSXIdentifier(jsxEl.openingElement.name) ? jsxEl.openingElement.name.name : "");
|
|
248
|
+
};
|
|
249
|
+
var eachTree = (tree, iterator, level = 1, parents = []) => {
|
|
250
|
+
for (let i = 0; i < tree.length; i++) {
|
|
251
|
+
const item = tree[i];
|
|
252
|
+
const result = iterator(item, i, level, parents);
|
|
253
|
+
if (result === "break") break;
|
|
254
|
+
if (result === "continue") continue;
|
|
255
|
+
if (Array.isArray(item.children)) {
|
|
256
|
+
eachTree(item.children, iterator, level + 1, parents.concat(item));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
var flattenTree = (tree, mapper) => {
|
|
261
|
+
const result = [];
|
|
262
|
+
eachTree(tree, (item, index, level, parents) => result.push(mapper(item, index, level, parents)));
|
|
263
|
+
return result;
|
|
264
|
+
};
|
|
265
|
+
var flattenRouteTree = (routes) => {
|
|
266
|
+
return flattenTree(routes, (item) => {
|
|
267
|
+
if ("pageId" in item) return item;
|
|
268
|
+
return {
|
|
269
|
+
title: item.title,
|
|
270
|
+
pageId: item.path,
|
|
271
|
+
pageName: item.path
|
|
272
|
+
};
|
|
273
|
+
});
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// src/vite/extractRouterPlugin/valueResolver.ts
|
|
277
|
+
var t3 = __toESM(require("@babel/types"), 1);
|
|
278
|
+
var import_fs2 = __toESM(require("fs"), 1);
|
|
279
|
+
var import_path2 = __toESM(require("path"), 1);
|
|
280
|
+
|
|
281
|
+
// src/vite/extractRouterPlugin/pathUtils.ts
|
|
282
|
+
var import_fs = __toESM(require("fs"), 1);
|
|
283
|
+
var import_path = __toESM(require("path"), 1);
|
|
284
|
+
var joinPaths = (...paths) => {
|
|
285
|
+
const parts = paths.filter(Boolean);
|
|
286
|
+
const leadingSlash = parts.length > 0 && parts[0].startsWith("/");
|
|
287
|
+
const joined = parts.map((p) => p.replace(/^\/+|\/+$/g, "")).join("/").replace(/\/+/g, "/");
|
|
288
|
+
return leadingSlash ? `/${joined.replace(/^\/+/, "")}` : joined;
|
|
289
|
+
};
|
|
290
|
+
var fileExists = async (filepath) => {
|
|
291
|
+
try {
|
|
292
|
+
await import_fs.default.promises.access(filepath, import_fs.default.constants.F_OK);
|
|
293
|
+
return true;
|
|
294
|
+
} catch {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
var resolveFilePath = async (filepath, extensions = [".ts", ".tsx", ".js", ".jsx"]) => {
|
|
299
|
+
if (await fileExists(filepath)) return filepath;
|
|
300
|
+
for (const ext of extensions) {
|
|
301
|
+
if (await fileExists(`${filepath}${ext}`)) return `${filepath}${ext}`;
|
|
302
|
+
}
|
|
303
|
+
for (const ext of extensions) {
|
|
304
|
+
const indexPath = import_path.default.join(filepath, `index${ext}`);
|
|
305
|
+
if (await fileExists(indexPath)) return indexPath;
|
|
306
|
+
}
|
|
307
|
+
return null;
|
|
308
|
+
};
|
|
309
|
+
var readFile = async (filePath) => {
|
|
310
|
+
try {
|
|
311
|
+
return await import_fs.default.promises.readFile(filePath, "utf-8");
|
|
312
|
+
} catch {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
var resolveAlias = (importPath, aliasMap) => {
|
|
317
|
+
for (const [find, replacement] of Object.entries(aliasMap)) {
|
|
318
|
+
if (importPath === find || importPath.startsWith(`${find}/`)) {
|
|
319
|
+
return importPath.replace(find, replacement);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return importPath;
|
|
323
|
+
};
|
|
324
|
+
var toSrcPath = (importPath, aliasMap) => {
|
|
325
|
+
if (!importPath) return "";
|
|
326
|
+
if (importPath.startsWith("src/")) return importPath;
|
|
327
|
+
if (importPath.startsWith("./")) return importPath.replace("./", "src/");
|
|
328
|
+
const resolved = resolveAlias(importPath, aliasMap);
|
|
329
|
+
if (resolved !== importPath) {
|
|
330
|
+
const srcIdx = resolved.indexOf("/src/");
|
|
331
|
+
if (srcIdx !== -1) return resolved.slice(srcIdx + 1);
|
|
332
|
+
if (resolved.endsWith("/src")) return "src";
|
|
333
|
+
if (resolved.startsWith("src/")) return resolved;
|
|
334
|
+
return resolved;
|
|
335
|
+
}
|
|
336
|
+
return importPath;
|
|
337
|
+
};
|
|
338
|
+
var normalizeFilePath = (filePath, projectRoot) => {
|
|
339
|
+
let normalized = filePath;
|
|
340
|
+
if (projectRoot && normalized.startsWith(projectRoot)) {
|
|
341
|
+
normalized = normalized.slice(projectRoot.length);
|
|
342
|
+
}
|
|
343
|
+
normalized = normalized.replace(/^\//, "");
|
|
344
|
+
return normalized.replace(/\.(tsx?|jsx?)$/, "");
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
// src/vite/extractRouterPlugin/valueResolver.ts
|
|
348
|
+
var parseFileWithImports = async (filePath) => {
|
|
349
|
+
try {
|
|
350
|
+
const code = await import_fs2.default.promises.readFile(filePath, "utf-8");
|
|
351
|
+
const ast = parseCode(code, filePath);
|
|
352
|
+
const importMap = /* @__PURE__ */ new Map();
|
|
353
|
+
const lazyImportMap = /* @__PURE__ */ new Map();
|
|
354
|
+
return { ast, importMap, lazyImportMap };
|
|
355
|
+
} catch {
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
var resolveFromFile = async (filePath, exportName, option, context, parentPath, depth = 0) => {
|
|
360
|
+
if (depth > 5) return null;
|
|
361
|
+
const parsed = await parseFileWithImports(filePath);
|
|
362
|
+
if (!parsed) return null;
|
|
363
|
+
const { ast, importMap, lazyImportMap } = parsed;
|
|
364
|
+
let exportBinding;
|
|
365
|
+
let exportNodePath;
|
|
366
|
+
let directValue = null;
|
|
367
|
+
const exportAllSources = [];
|
|
368
|
+
traverse(ast, {
|
|
369
|
+
// 在遍历同时收集 import/lazy 映射(后续 resolveImportedValue 需要)
|
|
370
|
+
...createImportVisitors(importMap, lazyImportMap),
|
|
371
|
+
/** 查找 named export:export const x = ... 或 export { x } */
|
|
372
|
+
ExportNamedDeclaration(nodePath) {
|
|
373
|
+
if (exportBinding || directValue !== null || !exportName) return;
|
|
374
|
+
const declaration = nodePath.get("declaration");
|
|
375
|
+
if (declaration.isVariableDeclaration()) {
|
|
376
|
+
for (const dec of declaration.node.declarations) {
|
|
377
|
+
if (t3.isIdentifier(dec.id) && dec.id.name === exportName) {
|
|
378
|
+
exportBinding = nodePath.scope.getBinding(dec.id.name);
|
|
379
|
+
exportNodePath = nodePath;
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
for (const specifier of nodePath.node.specifiers) {
|
|
385
|
+
if (t3.isExportSpecifier(specifier) && specifier.local.name === exportName) {
|
|
386
|
+
exportBinding = nodePath.scope.getBinding(specifier.local.name);
|
|
387
|
+
exportNodePath = nodePath;
|
|
388
|
+
break;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
},
|
|
392
|
+
/** 查找 default export:export default ... */
|
|
393
|
+
ExportDefaultDeclaration(nodePath) {
|
|
394
|
+
if (exportBinding || directValue !== null) return;
|
|
395
|
+
if (exportName !== null) return;
|
|
396
|
+
const declaration = nodePath.get("declaration");
|
|
397
|
+
if (declaration.isStringLiteral()) {
|
|
398
|
+
directValue = declaration.node.value;
|
|
399
|
+
} else if (declaration.isTemplateLiteral() && declaration.node.expressions.length === 0) {
|
|
400
|
+
directValue = declaration.node.quasis[0].value.raw;
|
|
401
|
+
} else if (declaration.isIdentifier()) {
|
|
402
|
+
exportNodePath = nodePath;
|
|
403
|
+
exportBinding = nodePath.scope.getBinding(declaration.node.name);
|
|
404
|
+
}
|
|
405
|
+
},
|
|
406
|
+
/** 收集 barrel re-export 来源:export * from './sub-module' */
|
|
407
|
+
ExportAllDeclaration(nodePath) {
|
|
408
|
+
exportAllSources.push(nodePath.node.source.value);
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
const fileOption = { importMap, lazyImportMap, aliasMap: option.aliasMap };
|
|
412
|
+
if (directValue !== null) return directValue;
|
|
413
|
+
if (exportBinding) {
|
|
414
|
+
return resolveImportedValue(
|
|
415
|
+
exportBinding,
|
|
416
|
+
filePath,
|
|
417
|
+
fileOption,
|
|
418
|
+
exportNodePath ?? context,
|
|
419
|
+
parentPath
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
if (exportName) {
|
|
423
|
+
for (const src of exportAllSources) {
|
|
424
|
+
const srcPath = resolveAlias(src, option.aliasMap);
|
|
425
|
+
const srcAbsolute = import_path2.default.resolve(import_path2.default.dirname(filePath), srcPath);
|
|
426
|
+
const srcResolved = await resolveFilePath(srcAbsolute);
|
|
427
|
+
if (!srcResolved) continue;
|
|
428
|
+
const value = await resolveFromFile(srcResolved, exportName, option, context, parentPath, depth + 1);
|
|
429
|
+
if (value !== null) return value;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return null;
|
|
433
|
+
};
|
|
434
|
+
var resolveModuleBinding = async (binding, currentFilePath, option, context, parentPath) => {
|
|
435
|
+
const importDeclaration = binding.path.parent;
|
|
436
|
+
if (!t3.isImportDeclaration(importDeclaration)) return null;
|
|
437
|
+
const importPath = resolveAlias(importDeclaration.source.value, option.aliasMap);
|
|
438
|
+
const absolutePath = import_path2.default.resolve(import_path2.default.dirname(currentFilePath), importPath);
|
|
439
|
+
const resolvedPath = await resolveFilePath(absolutePath);
|
|
440
|
+
if (!resolvedPath) return null;
|
|
441
|
+
let exportName = null;
|
|
442
|
+
if (binding.path.isImportSpecifier()) {
|
|
443
|
+
const imp = binding.path.node;
|
|
444
|
+
exportName = t3.isIdentifier(imp.imported) ? imp.imported.name : null;
|
|
445
|
+
}
|
|
446
|
+
return resolveFromFile(resolvedPath, exportName, option, context, parentPath);
|
|
447
|
+
};
|
|
448
|
+
var resolveCallInit = async (init, binding, option, currentFilePath, context, parentPath) => {
|
|
449
|
+
const callee = init.get("callee");
|
|
450
|
+
if (callee.isMemberExpression()) {
|
|
451
|
+
const object = callee.get("object");
|
|
452
|
+
const originalName = getOriginalArrayName(object);
|
|
453
|
+
if (originalName) {
|
|
454
|
+
const originalBinding = binding.scope.getBinding(originalName);
|
|
455
|
+
if (originalBinding) {
|
|
456
|
+
return resolveImportedValue(originalBinding, currentFilePath, option, context, parentPath);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
if (!callee.isIdentifier()) return null;
|
|
462
|
+
const args = init.get("arguments");
|
|
463
|
+
const firstArg = args[0];
|
|
464
|
+
if (!firstArg || !firstArg.isArrowFunctionExpression() && !firstArg.isFunctionExpression()) {
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
const body = firstArg.get("body");
|
|
468
|
+
if (body.isArrayExpression()) {
|
|
469
|
+
return resolveArrayExpression(body.node, currentFilePath, context, option, parentPath);
|
|
470
|
+
}
|
|
471
|
+
if (body.isIdentifier()) {
|
|
472
|
+
const refBinding = binding.scope.getBinding(body.node.name);
|
|
473
|
+
if (refBinding) return resolveImportedValue(refBinding, currentFilePath, option, context, parentPath);
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
if (body.isBlockStatement()) {
|
|
477
|
+
for (const stmt of body.node.body) {
|
|
478
|
+
if (!t3.isReturnStatement(stmt) || !stmt.argument) continue;
|
|
479
|
+
if (t3.isArrayExpression(stmt.argument)) {
|
|
480
|
+
return resolveArrayExpression(stmt.argument, currentFilePath, context, option, parentPath);
|
|
481
|
+
}
|
|
482
|
+
if (t3.isIdentifier(stmt.argument)) {
|
|
483
|
+
const refBinding = binding.scope.getBinding(stmt.argument.name);
|
|
484
|
+
if (refBinding) return resolveImportedValue(refBinding, currentFilePath, option, context, parentPath);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return null;
|
|
489
|
+
};
|
|
490
|
+
var resolveLocalBinding = async (binding, option, currentFilePath, context, parentPath) => {
|
|
491
|
+
const init = binding.path.get("init");
|
|
492
|
+
if (Array.isArray(init)) return null;
|
|
493
|
+
if (init.isStringLiteral()) return init.node.value;
|
|
494
|
+
if (init.isTemplateLiteral() && init.node.expressions.length === 0) {
|
|
495
|
+
return init.node.quasis[0].value.raw;
|
|
496
|
+
}
|
|
497
|
+
if (init.isIdentifier()) {
|
|
498
|
+
const refBinding = binding.scope.getBinding(init.node.name);
|
|
499
|
+
return refBinding ? resolveImportedValue(refBinding, currentFilePath, option, context) : null;
|
|
500
|
+
}
|
|
501
|
+
if (init.isArrayExpression()) {
|
|
502
|
+
return resolveArrayExpression(init.node, currentFilePath, context, option, parentPath);
|
|
503
|
+
}
|
|
504
|
+
if (init.isCallExpression()) {
|
|
505
|
+
return resolveCallInit(init, binding, option, currentFilePath, context, parentPath);
|
|
506
|
+
}
|
|
507
|
+
return null;
|
|
508
|
+
};
|
|
509
|
+
var resolveParamBinding = async (binding, currentFilePath, option, context) => {
|
|
510
|
+
const functionPath = binding.path.getFunctionParent();
|
|
511
|
+
if (!functionPath) return null;
|
|
512
|
+
const node = functionPath.node;
|
|
513
|
+
const functionName = t3.isFunctionDeclaration(node) ? node.id?.name : t3.isVariableDeclarator(functionPath.parent) && t3.isIdentifier(functionPath.parent.id) ? functionPath.parent.id.name : null;
|
|
514
|
+
if (!functionName) return null;
|
|
515
|
+
const paramIndex = functionPath.node.params.findIndex(
|
|
516
|
+
(param) => t3.isIdentifier(param) && param.name === binding.identifier.name
|
|
517
|
+
);
|
|
518
|
+
if (paramIndex < 0) return null;
|
|
519
|
+
const programPath = functionPath.findParent((p) => p.isProgram());
|
|
520
|
+
const calls = [];
|
|
521
|
+
programPath?.traverse({
|
|
522
|
+
CallExpression(callPath) {
|
|
523
|
+
if (callPath.get("callee").isIdentifier({ name: functionName })) calls.push(callPath);
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
for (const callSite of calls) {
|
|
527
|
+
const arg = callSite.get("arguments")[paramIndex];
|
|
528
|
+
if (arg?.isIdentifier()) {
|
|
529
|
+
const actualBinding = callSite.scope.getBinding(arg.node.name);
|
|
530
|
+
return resolveImportedValue(actualBinding, currentFilePath, option, context, "/");
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return null;
|
|
534
|
+
};
|
|
535
|
+
var resolveImportedValue = async (binding, currentFilePath, option, context, parentPath) => {
|
|
536
|
+
if (!binding) return null;
|
|
537
|
+
if (binding.kind === "module") return resolveModuleBinding(binding, currentFilePath, option, context, parentPath);
|
|
538
|
+
if (binding.kind === "const" || binding.kind === "let" || binding.kind === "var") {
|
|
539
|
+
return resolveLocalBinding(binding, option, currentFilePath, context, parentPath);
|
|
540
|
+
}
|
|
541
|
+
if (binding.kind === "param") return resolveParamBinding(binding, currentFilePath, option, context);
|
|
542
|
+
return null;
|
|
543
|
+
};
|
|
544
|
+
var resolveArrayExpression = async (arrayExpression, currentFilePath, context, option, parentPath) => {
|
|
545
|
+
const result = [];
|
|
546
|
+
const spreadRoutes = [];
|
|
547
|
+
for (const element of arrayExpression.elements) {
|
|
548
|
+
if (!element) continue;
|
|
549
|
+
if (t3.isSpreadElement(element)) {
|
|
550
|
+
if (t3.isIdentifier(element.argument)) {
|
|
551
|
+
const binding = context.scope.getBinding(element.argument.name);
|
|
552
|
+
if (binding) {
|
|
553
|
+
const value = await resolveImportedValue(binding, currentFilePath, option, context, parentPath);
|
|
554
|
+
if (Array.isArray(value)) spreadRoutes.push(...value);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
if (!t3.isObjectExpression(element)) continue;
|
|
560
|
+
const obj = {};
|
|
561
|
+
for (const property of element.properties) {
|
|
562
|
+
if (!t3.isObjectProperty(property)) continue;
|
|
563
|
+
const key = t3.isIdentifier(property.key) ? property.key.name : t3.isStringLiteral(property.key) ? property.key.value : null;
|
|
564
|
+
if (!key || !["path", "name", "title", "children"].includes(key)) continue;
|
|
565
|
+
if (t3.isStringLiteral(property.value)) {
|
|
566
|
+
obj[key] = property.value.value;
|
|
567
|
+
} else if (t3.isIdentifier(property.value)) {
|
|
568
|
+
const propBinding = context.scope.getBinding(property.value.name);
|
|
569
|
+
if (propBinding) {
|
|
570
|
+
obj[key] = await resolveImportedValue(propBinding, currentFilePath, option, context);
|
|
571
|
+
}
|
|
572
|
+
} else if (parentPath && t3.isArrayExpression(property.value) && key === "children") {
|
|
573
|
+
const rawPath = obj.path;
|
|
574
|
+
const currentPath = rawPath ? rawPath.startsWith("/") ? rawPath : joinPaths(parentPath, rawPath) : parentPath;
|
|
575
|
+
const trimmedPath = currentPath?.replace(/\*+$/g, "").replace(/\/+$/g, "");
|
|
576
|
+
obj[key] = await resolveArrayExpression(property.value, currentFilePath, context, option, trimmedPath);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
const routePath = obj.path;
|
|
580
|
+
if (routePath && parentPath && !routePath.startsWith("/")) {
|
|
581
|
+
obj.path = joinPaths(parentPath, routePath);
|
|
582
|
+
}
|
|
583
|
+
result.push({
|
|
584
|
+
path: obj.path,
|
|
585
|
+
title: obj.title ?? obj.name ?? obj.path,
|
|
586
|
+
children: obj.children ?? []
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
return [...spreadRoutes, ...flattenRouteTree(result)];
|
|
590
|
+
};
|
|
591
|
+
var resolveExpressionValue = async (nodePath, expression, id, option) => {
|
|
592
|
+
if (t3.isStringLiteral(expression)) return expression.value;
|
|
593
|
+
if (t3.isTemplateLiteral(expression) && expression.expressions.length === 0) {
|
|
594
|
+
return expression.quasis[0].value.raw;
|
|
595
|
+
}
|
|
596
|
+
if (t3.isIdentifier(expression)) {
|
|
597
|
+
const binding = nodePath.scope.getBinding(expression.name);
|
|
598
|
+
const value = await resolveImportedValue(binding, id, option, nodePath);
|
|
599
|
+
return typeof value === "string" ? value : null;
|
|
600
|
+
}
|
|
601
|
+
return null;
|
|
602
|
+
};
|
|
603
|
+
var resolveUseRoutesCall = async (nodePath, currentFilePath, option) => {
|
|
604
|
+
const argument = nodePath.get("arguments")[0];
|
|
605
|
+
if (!argument) return [];
|
|
606
|
+
if (argument.isArrayExpression()) {
|
|
607
|
+
return resolveArrayExpression(argument.node, currentFilePath, nodePath, option, "/");
|
|
608
|
+
}
|
|
609
|
+
if (argument.isIdentifier()) {
|
|
610
|
+
const binding = argument.scope.getBinding(argument.node.name);
|
|
611
|
+
if (binding) {
|
|
612
|
+
const value = await resolveImportedValue(binding, currentFilePath, option, argument);
|
|
613
|
+
if (Array.isArray(value)) return value;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return [];
|
|
617
|
+
};
|
|
618
|
+
|
|
619
|
+
// src/vite/extractRouterPlugin/jsxParser.ts
|
|
620
|
+
var findAncestorElementAttributeRoute = (nodePath) => {
|
|
621
|
+
let current = nodePath.parentPath;
|
|
622
|
+
while (current) {
|
|
623
|
+
if (current.isJSXExpressionContainer() && current.parentPath?.isJSXAttribute()) {
|
|
624
|
+
const name = current.parentPath.get("name");
|
|
625
|
+
if (name.isJSXIdentifier({ name: "element" })) {
|
|
626
|
+
return current.parentPath.parentPath;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
current = current.parentPath;
|
|
630
|
+
}
|
|
631
|
+
return null;
|
|
632
|
+
};
|
|
633
|
+
var processRouteAttributes = async (nodePath, id, option, parentAbsolute) => {
|
|
634
|
+
let pathValue = null;
|
|
635
|
+
let filePath = "";
|
|
636
|
+
let isIndexRoute = false;
|
|
637
|
+
for (const attr of nodePath.get("attributes")) {
|
|
638
|
+
if (!attr.isJSXAttribute()) continue;
|
|
639
|
+
const name = attr.get("name");
|
|
640
|
+
if (!name.isJSXIdentifier()) continue;
|
|
641
|
+
if (name.node.name === "index") {
|
|
642
|
+
isIndexRoute = true;
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
if (name.node.name === "path") {
|
|
646
|
+
const value = attr.get("value");
|
|
647
|
+
if (!value.node) continue;
|
|
648
|
+
if (value.isStringLiteral()) {
|
|
649
|
+
pathValue = value.node.value;
|
|
650
|
+
} else if (value.isJSXExpressionContainer()) {
|
|
651
|
+
const expression = value.get("expression");
|
|
652
|
+
if (expression.node) {
|
|
653
|
+
const resolved = await resolveExpressionValue(nodePath, expression.node, id, option);
|
|
654
|
+
if (typeof resolved === "string") pathValue = resolved;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
if (name.node.name === "element") {
|
|
659
|
+
const value = attr.get("value");
|
|
660
|
+
if (!value.node || !value.isJSXExpressionContainer()) continue;
|
|
661
|
+
const expression = value.get("expression");
|
|
662
|
+
if (expression.isJSXElement()) {
|
|
663
|
+
const elementName = findResolvableJSXComponent(expression.node, option.importMap, option.lazyImportMap);
|
|
664
|
+
if (elementName) {
|
|
665
|
+
const component = option.lazyImportMap.get(elementName) ?? option.importMap.get(elementName) ?? "";
|
|
666
|
+
filePath = toSrcPath(component, option.aliasMap);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
if (!pathValue) {
|
|
672
|
+
if (isIndexRoute) pathValue = "";
|
|
673
|
+
else return null;
|
|
674
|
+
}
|
|
675
|
+
const isRelative = !!pathValue && !pathValue.startsWith("/");
|
|
676
|
+
const absolutePath = joinPaths("/", parentAbsolute ?? "", pathValue);
|
|
677
|
+
return { absolutePath, filePath, isRelative };
|
|
678
|
+
};
|
|
679
|
+
var findMapCallCallee = (nodePath) => {
|
|
680
|
+
let current = nodePath.parentPath;
|
|
681
|
+
while (current) {
|
|
682
|
+
if (current.isCallExpression()) {
|
|
683
|
+
const callee = current.get("callee");
|
|
684
|
+
if (callee.isMemberExpression() && callee.get("property").isIdentifier({ name: "map" })) {
|
|
685
|
+
return callee.get("object");
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
current = current.parentPath;
|
|
689
|
+
}
|
|
690
|
+
return null;
|
|
691
|
+
};
|
|
692
|
+
var collectRouteNodes = (code, id) => {
|
|
693
|
+
try {
|
|
694
|
+
const ast = parseCode(code, id);
|
|
695
|
+
const importMap = /* @__PURE__ */ new Map();
|
|
696
|
+
const lazyImportMap = /* @__PURE__ */ new Map();
|
|
697
|
+
const result = [];
|
|
698
|
+
const parentStack = [];
|
|
699
|
+
const loopMap = {};
|
|
700
|
+
traverse(ast, {
|
|
701
|
+
...createImportVisitors(importMap, lazyImportMap),
|
|
702
|
+
JSXOpeningElement(nodePath) {
|
|
703
|
+
if (!nodePath.get("name").isJSXIdentifier({ name: "Route" })) return;
|
|
704
|
+
const mapCallee = findMapCallCallee(nodePath);
|
|
705
|
+
const parentIndex = parentStack[parentStack.length - 1];
|
|
706
|
+
const idx = result.length;
|
|
707
|
+
result.push({ openingElement: nodePath, parentIndex });
|
|
708
|
+
if (mapCallee) loopMap[idx] = getOriginalArrayName(mapCallee);
|
|
709
|
+
const jsxElementPath = nodePath.parentPath;
|
|
710
|
+
const isSelfClosing = jsxElementPath != null && jsxElementPath.node.selfClosing === true;
|
|
711
|
+
if (!isSelfClosing) parentStack.push(idx);
|
|
712
|
+
},
|
|
713
|
+
JSXElement: {
|
|
714
|
+
/** 退出 <Route> JSXElement 时弹出父栈 */
|
|
715
|
+
exit(nodePath) {
|
|
716
|
+
if (nodePath.get("openingElement").get("name").isJSXIdentifier({ name: "Route" })) {
|
|
717
|
+
parentStack.pop();
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
});
|
|
722
|
+
return { result, importMap, lazyImportMap, loopMap };
|
|
723
|
+
} catch (error) {
|
|
724
|
+
console.error("vite-plugin-extract-router [collectRouteNodes error]:", error);
|
|
725
|
+
return null;
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
var resolveAllRoute = async (code, id, option, outWildcardMounts) => {
|
|
729
|
+
if (!code) return [];
|
|
730
|
+
try {
|
|
731
|
+
const collected = collectRouteNodes(code, id);
|
|
732
|
+
if (!collected) return [];
|
|
733
|
+
const { result, importMap, lazyImportMap, loopMap } = collected;
|
|
734
|
+
const resolverOption = { importMap, lazyImportMap, aliasMap: option.aliasMap };
|
|
735
|
+
const routes = [];
|
|
736
|
+
const nodeResults = new Array(result.length).fill(null);
|
|
737
|
+
for (let i = 0; i < result.length; i++) {
|
|
738
|
+
const { openingElement, parentIndex } = result[i];
|
|
739
|
+
let parentAbsolute = parentIndex !== void 0 ? nodeResults[parentIndex]?.absolutePath : "";
|
|
740
|
+
const ancestorElement = findAncestorElementAttributeRoute(openingElement);
|
|
741
|
+
const parentElementIndex = ancestorElement ? result.findIndex((node) => node.openingElement === ancestorElement) : -1;
|
|
742
|
+
if (parentElementIndex !== -1) {
|
|
743
|
+
const parentElementAbsolute = nodeResults[parentElementIndex]?.absolutePath;
|
|
744
|
+
if (parentElementAbsolute && !parentElementAbsolute.includes("*")) {
|
|
745
|
+
nodeResults[i] = null;
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
if (parentElementAbsolute?.includes("*")) {
|
|
749
|
+
parentAbsolute = parentElementAbsolute;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
parentAbsolute = parentAbsolute?.replace(/\*+$/g, "").replace(/\/+$/g, "");
|
|
753
|
+
const arrayName = loopMap[i];
|
|
754
|
+
if (arrayName) {
|
|
755
|
+
const binding = openingElement.scope.getBinding(arrayName);
|
|
756
|
+
if (!binding) {
|
|
757
|
+
nodeResults[i] = null;
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
const value = await resolveImportedValue(binding, id, resolverOption, openingElement);
|
|
761
|
+
if (Array.isArray(value)) routes.push(...value);
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
const routeInfo = await processRouteAttributes(openingElement, id, resolverOption, parentAbsolute);
|
|
765
|
+
nodeResults[i] = routeInfo;
|
|
766
|
+
if (routeInfo) {
|
|
767
|
+
if (routeInfo.absolutePath.endsWith("*") && routeInfo.filePath && outWildcardMounts) {
|
|
768
|
+
const prefix = routeInfo.absolutePath.replace(/\/?\*+$/, "");
|
|
769
|
+
outWildcardMounts.push({ prefix, elementFilePath: routeInfo.filePath });
|
|
770
|
+
}
|
|
771
|
+
routes.push({
|
|
772
|
+
title: routeInfo.absolutePath,
|
|
773
|
+
pageId: routeInfo.absolutePath,
|
|
774
|
+
pageName: routeInfo.absolutePath,
|
|
775
|
+
path: routeInfo.filePath,
|
|
776
|
+
_sourceFile: id,
|
|
777
|
+
_isRelative: routeInfo.isRelative
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
return routes;
|
|
782
|
+
} catch (error) {
|
|
783
|
+
console.error("vite-plugin-extract-router [resolveAllRoute error]:", error);
|
|
784
|
+
return [];
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
// src/vite/extractRouterPlugin/hooksParser.ts
|
|
789
|
+
var t4 = __toESM(require("@babel/types"), 1);
|
|
790
|
+
var resolveHooksRoute = async (code, id, option) => {
|
|
791
|
+
try {
|
|
792
|
+
const ast = parseCode(code, id);
|
|
793
|
+
const importMap = /* @__PURE__ */ new Map();
|
|
794
|
+
const lazyImportMap = /* @__PURE__ */ new Map();
|
|
795
|
+
const useRoutesCalls = [];
|
|
796
|
+
traverse(ast, {
|
|
797
|
+
...createImportVisitors(importMap, lazyImportMap),
|
|
798
|
+
CallExpression(nodePath) {
|
|
799
|
+
const callee = nodePath.node.callee;
|
|
800
|
+
if (t4.isIdentifier(callee) && callee.name === "useRoutes") {
|
|
801
|
+
useRoutesCalls.push(nodePath);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
});
|
|
805
|
+
const resolverOption = { importMap, lazyImportMap, aliasMap: option.aliasMap };
|
|
806
|
+
const routes = [];
|
|
807
|
+
for (const call of useRoutesCalls) {
|
|
808
|
+
const result = await resolveUseRoutesCall(call, id, resolverOption);
|
|
809
|
+
routes.push(...result);
|
|
810
|
+
}
|
|
811
|
+
return routes;
|
|
812
|
+
} catch (error) {
|
|
813
|
+
console.error("vite-plugin-extract-router [resolveHooksRoute error]:", error);
|
|
814
|
+
return [];
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
// src/vite/extractRouterPlugin/index.ts
|
|
819
|
+
var extractRouterPlugin = () => {
|
|
820
|
+
const hooksRoutesMap = /* @__PURE__ */ new Map();
|
|
821
|
+
const jsxRoutesMap = /* @__PURE__ */ new Map();
|
|
822
|
+
const wildcardMountsMap = /* @__PURE__ */ new Map();
|
|
823
|
+
let routes = /* @__PURE__ */ new Map();
|
|
824
|
+
let aliasMap = {};
|
|
825
|
+
let projectRoot = "";
|
|
826
|
+
let appPath = "";
|
|
827
|
+
let server = null;
|
|
828
|
+
const rebuildRoutes = () => {
|
|
829
|
+
const filePrefixMap = /* @__PURE__ */ new Map();
|
|
830
|
+
for (const mounts of wildcardMountsMap.values()) {
|
|
831
|
+
for (const mount of mounts) {
|
|
832
|
+
filePrefixMap.set(normalizeFilePath(mount.elementFilePath), mount.prefix);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
if (server) {
|
|
836
|
+
const normalizedToFileId = /* @__PURE__ */ new Map();
|
|
837
|
+
for (const fileId of jsxRoutesMap.keys()) {
|
|
838
|
+
normalizedToFileId.set(normalizeFilePath(fileId, projectRoot), fileId);
|
|
839
|
+
}
|
|
840
|
+
for (const [normalizedElement, prefix] of [...filePrefixMap]) {
|
|
841
|
+
const fileId = normalizedToFileId.get(normalizedElement);
|
|
842
|
+
if (!fileId) continue;
|
|
843
|
+
const mod = server.moduleGraph.getModuleById(fileId);
|
|
844
|
+
if (!mod?.importedModules) continue;
|
|
845
|
+
for (const imported of mod.importedModules) {
|
|
846
|
+
if (imported.id && !imported.id.includes("node_modules")) {
|
|
847
|
+
if (jsxRoutesMap.has(imported.id) || hooksRoutesMap.has(imported.id)) {
|
|
848
|
+
filePrefixMap.set(normalizeFilePath(imported.id, projectRoot), prefix);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
const merged = /* @__PURE__ */ new Map();
|
|
855
|
+
for (const [fileId, fileRoutes] of jsxRoutesMap.entries()) {
|
|
856
|
+
const normalizedFileId = normalizeFilePath(fileId, projectRoot);
|
|
857
|
+
const prefix = filePrefixMap.get(normalizedFileId);
|
|
858
|
+
for (const route of fileRoutes) {
|
|
859
|
+
const internal = route;
|
|
860
|
+
let finalRoute;
|
|
861
|
+
if (prefix && internal._isRelative) {
|
|
862
|
+
const corrected = joinPaths("/", prefix, route.pageId.replace(/^\//, ""));
|
|
863
|
+
finalRoute = { title: corrected, pageId: corrected, pageName: corrected };
|
|
864
|
+
} else {
|
|
865
|
+
finalRoute = { title: route.title, pageId: route.pageId, pageName: route.pageName };
|
|
866
|
+
}
|
|
867
|
+
if (finalRoute.pageId === "/*" || finalRoute.pageId === "*") continue;
|
|
868
|
+
merged.set(finalRoute.pageId, finalRoute);
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
for (const fileRoutes of hooksRoutesMap.values()) {
|
|
872
|
+
for (const r of fileRoutes) {
|
|
873
|
+
if (r.pageId === "/*" || r.pageId === "*") continue;
|
|
874
|
+
merged.set(r.pageId, r);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
routes = merged;
|
|
878
|
+
};
|
|
879
|
+
const collectAppRoutes = async () => {
|
|
880
|
+
const appCode = await readFile(appPath);
|
|
881
|
+
if (!appCode) return;
|
|
882
|
+
const mounts = [];
|
|
883
|
+
const appRoutes = await resolveAllRoute(appCode, appPath, { aliasMap }, mounts);
|
|
884
|
+
if (appRoutes.length > 0) jsxRoutesMap.set(appPath, appRoutes);
|
|
885
|
+
else jsxRoutesMap.delete(appPath);
|
|
886
|
+
if (mounts.length > 0) wildcardMountsMap.set(appPath, mounts);
|
|
887
|
+
else wildcardMountsMap.delete(appPath);
|
|
888
|
+
rebuildRoutes();
|
|
889
|
+
};
|
|
890
|
+
return {
|
|
891
|
+
name: "react-route-collector",
|
|
892
|
+
/** 仅在 dev server 模式下激活 */
|
|
893
|
+
apply: "serve",
|
|
894
|
+
/** 在其他插件之前执行,确保拿到未转换的源码 */
|
|
895
|
+
enforce: "pre",
|
|
896
|
+
/**
|
|
897
|
+
* Vite 配置解析完成后的钩子。
|
|
898
|
+
* 初始化 aliasMap、projectRoot 和 appPath。
|
|
899
|
+
*/
|
|
900
|
+
async configResolved(config) {
|
|
901
|
+
aliasMap = config.resolve.alias.reduce((acc, item) => {
|
|
902
|
+
const find = typeof item.find === "string" ? item.find : item.find.source;
|
|
903
|
+
acc[find] = item.replacement;
|
|
904
|
+
return acc;
|
|
905
|
+
}, {});
|
|
906
|
+
projectRoot = config.root || process.cwd();
|
|
907
|
+
appPath = await resolveFilePath(import_path3.default.resolve(projectRoot, "src/App"), [".tsx", ".jsx"]) ?? "";
|
|
908
|
+
},
|
|
909
|
+
/** 构建开始时清空所有缓存 */
|
|
910
|
+
buildStart() {
|
|
911
|
+
hooksRoutesMap.clear();
|
|
912
|
+
jsxRoutesMap.clear();
|
|
913
|
+
wildcardMountsMap.clear();
|
|
914
|
+
routes.clear();
|
|
915
|
+
},
|
|
916
|
+
/**
|
|
917
|
+
* Vite transform 钩子:处理每个含路由声明的文件。
|
|
918
|
+
*
|
|
919
|
+
* 同时覆盖两种路由写法:
|
|
920
|
+
* - useRoutes([...]):函数式声明
|
|
921
|
+
* - <Route path="..." />:JSX 声明(包括 .map() 动态渲染)
|
|
922
|
+
*
|
|
923
|
+
* 对 JSX 路由额外收集通配符挂载关系(WildcardMount),
|
|
924
|
+
* 用于 rebuildRoutes 阶段的跨文件前缀修正。
|
|
925
|
+
*/
|
|
926
|
+
async transform(code, id) {
|
|
927
|
+
if (id.includes("node_modules") || !JS_SUFFIXES.some((s) => id.endsWith(s))) return;
|
|
928
|
+
if (!appPath) return;
|
|
929
|
+
const hasUseRoutes = code.includes("useRoutes");
|
|
930
|
+
const hasJsxRoute = code.includes("<Route");
|
|
931
|
+
if (!hasUseRoutes && !hasJsxRoute) return;
|
|
932
|
+
if (hasUseRoutes) {
|
|
933
|
+
const hookRoutes = await resolveHooksRoute(code, id, { aliasMap });
|
|
934
|
+
if (hookRoutes.length > 0) hooksRoutesMap.set(id, hookRoutes);
|
|
935
|
+
else hooksRoutesMap.delete(id);
|
|
936
|
+
}
|
|
937
|
+
if (hasJsxRoute) {
|
|
938
|
+
const mounts = [];
|
|
939
|
+
const jsxRoutes = await resolveAllRoute(code, id, { aliasMap }, mounts);
|
|
940
|
+
if (jsxRoutes.length > 0) jsxRoutesMap.set(id, jsxRoutes);
|
|
941
|
+
else jsxRoutesMap.delete(id);
|
|
942
|
+
if (mounts.length > 0) wildcardMountsMap.set(id, mounts);
|
|
943
|
+
else wildcardMountsMap.delete(id);
|
|
944
|
+
}
|
|
945
|
+
rebuildRoutes();
|
|
946
|
+
},
|
|
947
|
+
/**
|
|
948
|
+
* HMR 热更新钩子:当 App.tsx 依赖链中的文件变更时,重新收集路由。
|
|
949
|
+
*/
|
|
950
|
+
async handleHotUpdate({ file }) {
|
|
951
|
+
if (!server || !appPath) return;
|
|
952
|
+
const appMod = server.moduleGraph.getModuleById(appPath);
|
|
953
|
+
const deps = collectDeps(appMod ?? {});
|
|
954
|
+
if (!deps.includes(file)) return;
|
|
955
|
+
await collectAppRoutes();
|
|
956
|
+
},
|
|
957
|
+
/**
|
|
958
|
+
* 配置 dev server:注册 /__routes 中间件接口。
|
|
959
|
+
* 路由数据由 transform 钩子实时收集,此处仅返回当前状态。
|
|
960
|
+
* 响应格式:{ data: Route[] }
|
|
961
|
+
*/
|
|
962
|
+
configureServer(_server) {
|
|
963
|
+
server = _server;
|
|
964
|
+
server.middlewares.use("/__routes", async (_req, res) => {
|
|
965
|
+
res.setHeader("Content-Type", "application/json");
|
|
966
|
+
res.end(JSON.stringify({ data: [...routes.values()] }));
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
};
|
|
120
971
|
// Annotate the CommonJS export names for ESM import in node:
|
|
121
972
|
0 && (module.exports = {
|
|
973
|
+
extractRouterPlugin,
|
|
122
974
|
hmrTogglePlugin,
|
|
975
|
+
withSentryBuild,
|
|
123
976
|
withSentryStub
|
|
124
977
|
});
|