@tanstack/router-generator 1.8.2 → 1.11.0
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/dist/cjs/config.cjs +10 -6
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/config.d.cts +1 -1
- package/dist/cjs/generator.cjs +86 -32
- package/dist/cjs/generator.cjs.map +1 -1
- package/dist/cjs/generator.d.cts +1 -0
- package/dist/esm/config.d.ts +1 -1
- package/dist/esm/config.js +10 -6
- package/dist/esm/config.js.map +1 -1
- package/dist/esm/generator.d.ts +1 -0
- package/dist/esm/generator.js +85 -32
- package/dist/esm/generator.js.map +1 -1
- package/package.json +1 -1
- package/src/config.ts +13 -7
- package/src/generator.ts +109 -41
package/dist/cjs/config.cjs
CHANGED
|
@@ -11,16 +11,20 @@ const configSchema = zod.z.object({
|
|
|
11
11
|
quoteStyle: zod.z.enum(["single", "double"]).optional().default("single"),
|
|
12
12
|
disableTypes: zod.z.boolean().optional().default(false)
|
|
13
13
|
});
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
async function getConfig(inlineConfig = {}, configDirectory) {
|
|
15
|
+
if (configDirectory === void 0) {
|
|
16
|
+
configDirectory = process.cwd();
|
|
17
|
+
}
|
|
18
|
+
const configFilePathJson = path.resolve(configDirectory, "tsr.config.json");
|
|
16
19
|
const exists = fs.existsSync(configFilePathJson);
|
|
17
20
|
let config;
|
|
18
21
|
if (exists) {
|
|
19
|
-
config = configSchema.parse(
|
|
20
|
-
JSON.parse(fs.readFileSync(configFilePathJson, "utf-8"))
|
|
21
|
-
|
|
22
|
+
config = configSchema.parse({
|
|
23
|
+
...JSON.parse(fs.readFileSync(configFilePathJson, "utf-8")),
|
|
24
|
+
...inlineConfig
|
|
25
|
+
});
|
|
22
26
|
} else {
|
|
23
|
-
config = configSchema.parse(
|
|
27
|
+
config = configSchema.parse(inlineConfig);
|
|
24
28
|
}
|
|
25
29
|
if (config.disableTypes) {
|
|
26
30
|
config.generatedRouteTree = config.generatedRouteTree.replace(
|
package/dist/cjs/config.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs","sources":["../../src/config.ts"],"sourcesContent":["import path from 'path'\nimport { readFileSync, existsSync } from 'fs'\nimport { z } from 'zod'\n\nexport const configSchema = z.object({\n routeFilePrefix: z.string().optional(),\n routeFileIgnorePrefix: z.string().optional().default('-'),\n routesDirectory: z.string().optional().default('./src/routes'),\n generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'),\n quoteStyle: z.enum(['single', 'double']).optional().default('single'),\n disableTypes: z.boolean().optional().default(false),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\
|
|
1
|
+
{"version":3,"file":"config.cjs","sources":["../../src/config.ts"],"sourcesContent":["import path from 'path'\nimport { readFileSync, existsSync } from 'fs'\nimport { z } from 'zod'\n\nexport const configSchema = z.object({\n routeFilePrefix: z.string().optional(),\n routeFileIgnorePrefix: z.string().optional().default('-'),\n routesDirectory: z.string().optional().default('./src/routes'),\n generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'),\n quoteStyle: z.enum(['single', 'double']).optional().default('single'),\n disableTypes: z.boolean().optional().default(false),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\nexport async function getConfig(\n inlineConfig: Partial<Config> = {},\n configDirectory?: string,\n): Promise<Config> {\n if (configDirectory === undefined) {\n configDirectory = process.cwd()\n }\n const configFilePathJson = path.resolve(configDirectory, 'tsr.config.json')\n const exists = existsSync(configFilePathJson)\n\n let config: Config\n\n if (exists) {\n config = configSchema.parse({\n ...JSON.parse(readFileSync(configFilePathJson, 'utf-8')),\n ...inlineConfig,\n })\n } else {\n config = configSchema.parse(inlineConfig)\n }\n\n // If typescript is disabled, make sure the generated route tree is a .js file\n if (config.disableTypes) {\n config.generatedRouteTree = config.generatedRouteTree.replace(\n /\\.(ts|tsx)$/,\n '.js',\n )\n }\n\n return config\n}\n"],"names":["z","existsSync","readFileSync"],"mappings":";;;;;AAIa,MAAA,eAAeA,MAAE,OAAO;AAAA,EACnC,iBAAiBA,IAAA,EAAE,OAAO,EAAE,SAAS;AAAA,EACrC,uBAAuBA,IAAE,EAAA,OAAA,EAAS,SAAS,EAAE,QAAQ,GAAG;AAAA,EACxD,iBAAiBA,IAAE,EAAA,OAAA,EAAS,SAAS,EAAE,QAAQ,cAAc;AAAA,EAC7D,oBAAoBA,IAAE,EAAA,OAAA,EAAS,SAAS,EAAE,QAAQ,wBAAwB;AAAA,EAC1E,YAAYA,IAAAA,EAAE,KAAK,CAAC,UAAU,QAAQ,CAAC,EAAE,SAAA,EAAW,QAAQ,QAAQ;AAAA,EACpE,cAAcA,IAAE,EAAA,QAAA,EAAU,SAAS,EAAE,QAAQ,KAAK;AACpD,CAAC;AAID,eAAsB,UACpB,eAAgC,CAAC,GACjC,iBACiB;AACjB,MAAI,oBAAoB,QAAW;AACjC,sBAAkB,QAAQ;EAC5B;AACA,QAAM,qBAAqB,KAAK,QAAQ,iBAAiB,iBAAiB;AACpE,QAAA,SAASC,cAAW,kBAAkB;AAExC,MAAA;AAEJ,MAAI,QAAQ;AACV,aAAS,aAAa,MAAM;AAAA,MAC1B,GAAG,KAAK,MAAMC,GAAa,aAAA,oBAAoB,OAAO,CAAC;AAAA,MACvD,GAAG;AAAA,IAAA,CACJ;AAAA,EAAA,OACI;AACI,aAAA,aAAa,MAAM,YAAY;AAAA,EAC1C;AAGA,MAAI,OAAO,cAAc;AAChB,WAAA,qBAAqB,OAAO,mBAAmB;AAAA,MACpD;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEO,SAAA;AACT;;;"}
|
package/dist/cjs/config.d.cts
CHANGED
|
@@ -22,4 +22,4 @@ export declare const configSchema: z.ZodObject<{
|
|
|
22
22
|
disableTypes?: boolean | undefined;
|
|
23
23
|
}>;
|
|
24
24
|
export type Config = z.infer<typeof configSchema>;
|
|
25
|
-
export declare function getConfig(): Promise<Config>;
|
|
25
|
+
export declare function getConfig(inlineConfig?: Partial<Config>, configDirectory?: string): Promise<Config>;
|
package/dist/cjs/generator.cjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const path = require("path");
|
|
4
|
-
const fs = require("fs
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const fsp = require("fs/promises");
|
|
5
6
|
const prettier = require("prettier");
|
|
6
7
|
const utils = require("./utils.cjs");
|
|
7
8
|
function _interopNamespaceDefault(e) {
|
|
@@ -21,6 +22,7 @@ function _interopNamespaceDefault(e) {
|
|
|
21
22
|
return Object.freeze(n);
|
|
22
23
|
}
|
|
23
24
|
const fs__namespace = /* @__PURE__ */ _interopNamespaceDefault(fs);
|
|
25
|
+
const fsp__namespace = /* @__PURE__ */ _interopNamespaceDefault(fsp);
|
|
24
26
|
const prettier__namespace = /* @__PURE__ */ _interopNamespaceDefault(prettier);
|
|
25
27
|
let latestTask = 0;
|
|
26
28
|
const rootPathId = "__root";
|
|
@@ -29,7 +31,7 @@ async function getRouteNodes(config) {
|
|
|
29
31
|
let routeNodes = [];
|
|
30
32
|
async function recurse(dir) {
|
|
31
33
|
const fullDir = path.resolve(config.routesDirectory, dir);
|
|
32
|
-
let dirList = await
|
|
34
|
+
let dirList = await fsp__namespace.readdir(fullDir, { withFileTypes: true });
|
|
33
35
|
dirList = dirList.filter((d) => {
|
|
34
36
|
if (d.name.startsWith(".") || routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix)) {
|
|
35
37
|
return false;
|
|
@@ -55,8 +57,21 @@ async function getRouteNodes(config) {
|
|
|
55
57
|
let isErrorComponent = routePath == null ? void 0 : routePath.endsWith("/errorComponent");
|
|
56
58
|
let isPendingComponent = routePath == null ? void 0 : routePath.endsWith("/pendingComponent");
|
|
57
59
|
let isLoader = routePath == null ? void 0 : routePath.endsWith("/loader");
|
|
60
|
+
let isLazy = routePath == null ? void 0 : routePath.endsWith("/lazy");
|
|
61
|
+
[
|
|
62
|
+
[isComponent, "component"],
|
|
63
|
+
[isErrorComponent, "errorComponent"],
|
|
64
|
+
[isPendingComponent, "pendingComponent"],
|
|
65
|
+
[isLoader, "loader"]
|
|
66
|
+
].forEach(([isType, type]) => {
|
|
67
|
+
if (isType) {
|
|
68
|
+
console.warn(
|
|
69
|
+
`WARNING: The \`.${type}.tsx\` suffix used for the ${filePath} file is deprecated. Use the new \`.lazy.tsx\` suffix instead.`
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
58
73
|
routePath = routePath == null ? void 0 : routePath.replace(
|
|
59
|
-
/\/(component|errorComponent|pendingComponent|loader|route)$/,
|
|
74
|
+
/\/(component|errorComponent|pendingComponent|loader|route|lazy)$/,
|
|
60
75
|
""
|
|
61
76
|
);
|
|
62
77
|
if (routePath === "index") {
|
|
@@ -72,7 +87,8 @@ async function getRouteNodes(config) {
|
|
|
72
87
|
isComponent,
|
|
73
88
|
isErrorComponent,
|
|
74
89
|
isPendingComponent,
|
|
75
|
-
isLoader
|
|
90
|
+
isLoader,
|
|
91
|
+
isLazy
|
|
76
92
|
});
|
|
77
93
|
}
|
|
78
94
|
})
|
|
@@ -118,7 +134,7 @@ async function generator(config) {
|
|
|
118
134
|
(d) => {
|
|
119
135
|
var _a;
|
|
120
136
|
return ((_a = d.filePath) == null ? void 0 : _a.match(
|
|
121
|
-
/[./](component|errorComponent|pendingComponent|loader)[.]/
|
|
137
|
+
/[./](component|errorComponent|pendingComponent|loader|lazy)[.]/
|
|
122
138
|
)) ? 1 : -1;
|
|
123
139
|
},
|
|
124
140
|
(d) => {
|
|
@@ -136,8 +152,8 @@ async function generator(config) {
|
|
|
136
152
|
const routeTree = [];
|
|
137
153
|
const routePiecesByPath = {};
|
|
138
154
|
let routeNodes = [];
|
|
139
|
-
const handleNode = (node) => {
|
|
140
|
-
var _a;
|
|
155
|
+
const handleNode = async (node) => {
|
|
156
|
+
var _a, _b;
|
|
141
157
|
const parentRoute = hasParentRoute(routeNodes, node.routePath);
|
|
142
158
|
if (parentRoute)
|
|
143
159
|
node.parent = parentRoute;
|
|
@@ -148,14 +164,52 @@ async function generator(config) {
|
|
|
148
164
|
node.isNonPath = first2.startsWith("_");
|
|
149
165
|
node.isNonLayout = first2.endsWith("_");
|
|
150
166
|
node.cleanedPath = removeUnderscores(node.path) ?? "";
|
|
151
|
-
|
|
167
|
+
const routeCode = fs__namespace.readFileSync(node.fullPath, "utf-8");
|
|
168
|
+
const escapedRoutePath = removeTrailingUnderscores(
|
|
169
|
+
((_b = node.routePath) == null ? void 0 : _b.replaceAll("$", "$$")) ?? ""
|
|
170
|
+
);
|
|
171
|
+
let replaced = routeCode;
|
|
172
|
+
if (!routeCode) {
|
|
173
|
+
if (node.isLazy) {
|
|
174
|
+
replaced = [
|
|
175
|
+
`import { createLazyFileRoute } from '@tanstack/react-router'`,
|
|
176
|
+
`export const Route = createLazyFileRoute('${escapedRoutePath}')({
|
|
177
|
+
component: () => <div>Hello ${escapedRoutePath}!</div>
|
|
178
|
+
})`
|
|
179
|
+
].join("\n\n");
|
|
180
|
+
} else if (node.isRoute || !node.isComponent && !node.isErrorComponent && !node.isPendingComponent && !node.isLoader) {
|
|
181
|
+
replaced = [
|
|
182
|
+
`import { createFileRoute } from '@tanstack/react-router'`,
|
|
183
|
+
`export const Route = createFileRoute('${escapedRoutePath}')({
|
|
184
|
+
component: () => <div>Hello ${escapedRoutePath}!</div>
|
|
185
|
+
})`
|
|
186
|
+
].join("\n\n");
|
|
187
|
+
}
|
|
188
|
+
} else {
|
|
189
|
+
replaced = routeCode.replace(
|
|
190
|
+
/(FileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
191
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
192
|
+
).replace(
|
|
193
|
+
/(createFileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
194
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
195
|
+
).replace(
|
|
196
|
+
/(createLazyFileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
197
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
if (replaced !== routeCode) {
|
|
201
|
+
console.log(`🌲 Updating ${node.fullPath}`);
|
|
202
|
+
await fsp__namespace.writeFile(node.fullPath, replaced);
|
|
203
|
+
}
|
|
204
|
+
if (!node.isVirtual && (node.isLoader || node.isComponent || node.isErrorComponent || node.isPendingComponent || node.isLazy)) {
|
|
152
205
|
routePiecesByPath[node.routePath] = routePiecesByPath[node.routePath] || {};
|
|
153
|
-
routePiecesByPath[node.routePath][node.isLoader ? "loader" : node.isErrorComponent ? "errorComponent" : node.isPendingComponent ? "pendingComponent" : "component"] = node;
|
|
206
|
+
routePiecesByPath[node.routePath][node.isLazy ? "lazy" : node.isLoader ? "loader" : node.isErrorComponent ? "errorComponent" : node.isPendingComponent ? "pendingComponent" : "component"] = node;
|
|
154
207
|
const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath);
|
|
155
208
|
if (!anchorRoute) {
|
|
156
209
|
handleNode({
|
|
157
210
|
...node,
|
|
158
211
|
isVirtual: true,
|
|
212
|
+
isLazy: false,
|
|
159
213
|
isLoader: false,
|
|
160
214
|
isComponent: false,
|
|
161
215
|
isErrorComponent: false,
|
|
@@ -175,24 +229,12 @@ async function generator(config) {
|
|
|
175
229
|
preRouteNodes.forEach((node) => handleNode(node));
|
|
176
230
|
async function buildRouteConfig(nodes, depth = 1) {
|
|
177
231
|
const children = nodes.map(async (node) => {
|
|
178
|
-
var _a
|
|
179
|
-
const routeCode = await fs__namespace.readFile(node.fullPath, "utf-8");
|
|
232
|
+
var _a;
|
|
180
233
|
if (node.isRoot) {
|
|
181
234
|
return;
|
|
182
235
|
}
|
|
183
|
-
const escapedRoutePath = removeTrailingUnderscores(
|
|
184
|
-
((_a = node.routePath) == null ? void 0 : _a.replaceAll("$", "$$")) ?? ""
|
|
185
|
-
);
|
|
186
|
-
config.quoteStyle === "single" ? `'` : `"`;
|
|
187
|
-
const replaced = routeCode.replace(
|
|
188
|
-
/(FileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
189
|
-
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
190
|
-
);
|
|
191
|
-
if (replaced !== routeCode) {
|
|
192
|
-
await fs__namespace.writeFile(node.fullPath, replaced);
|
|
193
|
-
}
|
|
194
236
|
const route = `${node.variableName}Route`;
|
|
195
|
-
if ((
|
|
237
|
+
if ((_a = node.children) == null ? void 0 : _a.length) {
|
|
196
238
|
const childConfigs = await buildRouteConfig(node.children, depth + 1);
|
|
197
239
|
return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`;
|
|
198
240
|
}
|
|
@@ -217,7 +259,7 @@ async function generator(config) {
|
|
|
217
259
|
(d) => d
|
|
218
260
|
]);
|
|
219
261
|
const imports = Object.entries({
|
|
220
|
-
|
|
262
|
+
createFileRoute: sortedRouteNodes.some((d) => d.isVirtual),
|
|
221
263
|
lazyFn: sortedRouteNodes.some(
|
|
222
264
|
(node) => {
|
|
223
265
|
var _a;
|
|
@@ -257,22 +299,23 @@ async function generator(config) {
|
|
|
257
299
|
].join("\n"),
|
|
258
300
|
virtualRouteNodes.length ? "// Create Virtual Routes" : "",
|
|
259
301
|
virtualRouteNodes.map((node) => {
|
|
260
|
-
return `const ${node.variableName}Import =
|
|
302
|
+
return `const ${node.variableName}Import = createFileRoute('${removeTrailingUnderscores(
|
|
261
303
|
node.routePath
|
|
262
|
-
)}')
|
|
304
|
+
)}')()`;
|
|
263
305
|
}).join("\n"),
|
|
264
306
|
"// Create/Update Routes",
|
|
265
307
|
sortedRouteNodes.map((node) => {
|
|
266
|
-
var _a, _b, _c, _d, _e;
|
|
308
|
+
var _a, _b, _c, _d, _e, _f;
|
|
267
309
|
const loaderNode = (_a = routePiecesByPath[node.routePath]) == null ? void 0 : _a.loader;
|
|
268
310
|
const componentNode = (_b = routePiecesByPath[node.routePath]) == null ? void 0 : _b.component;
|
|
269
311
|
const errorComponentNode = (_c = routePiecesByPath[node.routePath]) == null ? void 0 : _c.errorComponent;
|
|
270
312
|
const pendingComponentNode = (_d = routePiecesByPath[node.routePath]) == null ? void 0 : _d.pendingComponent;
|
|
313
|
+
const lazyComponentNode = (_e = routePiecesByPath[node.routePath]) == null ? void 0 : _e.lazy;
|
|
271
314
|
return [
|
|
272
315
|
`const ${node.variableName}Route = ${node.variableName}Import.update({
|
|
273
316
|
${[
|
|
274
317
|
node.isNonPath ? `id: '${node.path}'` : `path: '${node.cleanedPath}'`,
|
|
275
|
-
`getParentRoute: () => ${((
|
|
318
|
+
`getParentRoute: () => ${((_f = node.parent) == null ? void 0 : _f.variableName) ?? "root"}Route`
|
|
276
319
|
].filter(Boolean).join(",")}
|
|
277
320
|
}${config.disableTypes ? "" : "as any"})`,
|
|
278
321
|
loaderNode ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(
|
|
@@ -298,7 +341,18 @@ async function generator(config) {
|
|
|
298
341
|
)
|
|
299
342
|
)}'), '${d[0]}')`;
|
|
300
343
|
}).join("\n,")}
|
|
301
|
-
})` : ""
|
|
344
|
+
})` : "",
|
|
345
|
+
lazyComponentNode ? `.lazy(() => import('./${replaceBackslash(
|
|
346
|
+
removeExt(
|
|
347
|
+
path.relative(
|
|
348
|
+
path.dirname(config.generatedRouteTree),
|
|
349
|
+
path.resolve(
|
|
350
|
+
config.routesDirectory,
|
|
351
|
+
lazyComponentNode.filePath
|
|
352
|
+
)
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
)}').then((d) => d.Route))` : ""
|
|
302
356
|
].join("");
|
|
303
357
|
}).join("\n\n"),
|
|
304
358
|
...config.disableTypes ? [] : [
|
|
@@ -323,7 +377,7 @@ async function generator(config) {
|
|
|
323
377
|
singleQuote: config.quoteStyle === "single",
|
|
324
378
|
parser: "typescript"
|
|
325
379
|
});
|
|
326
|
-
const routeTreeContent = await
|
|
380
|
+
const routeTreeContent = await fsp__namespace.readFile(path.resolve(config.generatedRouteTree), "utf-8").catch((err) => {
|
|
327
381
|
if (err.code === "ENOENT") {
|
|
328
382
|
return void 0;
|
|
329
383
|
}
|
|
@@ -332,12 +386,12 @@ async function generator(config) {
|
|
|
332
386
|
if (!checkLatest())
|
|
333
387
|
return;
|
|
334
388
|
if (routeTreeContent !== routeConfigFileContent) {
|
|
335
|
-
await
|
|
389
|
+
await fsp__namespace.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {
|
|
336
390
|
recursive: true
|
|
337
391
|
});
|
|
338
392
|
if (!checkLatest())
|
|
339
393
|
return;
|
|
340
|
-
await
|
|
394
|
+
await fsp__namespace.writeFile(
|
|
341
395
|
path.resolve(config.generatedRouteTree),
|
|
342
396
|
routeConfigFileContent
|
|
343
397
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.cjs","sources":["../../src/generator.ts"],"sourcesContent":["import path from 'path'\nimport * as fs from 'fs/promises'\nimport * as prettier from 'prettier'\nimport { Config } from './config'\nimport { cleanPath, trimPathLeft } from './utils'\n\nlet latestTask = 0\nexport const rootPathId = '__root'\n\nexport type RouteNode = {\n filePath: string\n fullPath: string\n variableName: string\n routePath?: string\n cleanedPath?: string\n path?: string\n isNonPath?: boolean\n isNonLayout?: boolean\n isRoute?: boolean\n isLoader?: boolean\n isComponent?: boolean\n isErrorComponent?: boolean\n isPendingComponent?: boolean\n isVirtual?: boolean\n isRoot?: boolean\n children?: RouteNode[]\n parent?: RouteNode\n}\n\nasync function getRouteNodes(config: Config) {\n const { routeFilePrefix, routeFileIgnorePrefix } = config\n\n let routeNodes: RouteNode[] = []\n\n async function recurse(dir: string) {\n const fullDir = path.resolve(config.routesDirectory, dir)\n let dirList = await fs.readdir(fullDir, { withFileTypes: true })\n\n dirList = dirList.filter((d) => {\n if (\n d.name.startsWith('.') ||\n (routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix))\n ) {\n return false\n }\n\n if (routeFilePrefix) {\n return d.name.startsWith(routeFilePrefix)\n }\n\n return true\n })\n\n await Promise.all(\n dirList.map(async (dirent) => {\n const fullPath = path.join(fullDir, dirent.name)\n const relativePath = path.join(dir, dirent.name)\n\n if (dirent.isDirectory()) {\n await recurse(relativePath)\n } else if (fullPath.match(/\\.(tsx|ts|jsx|js)$/)) {\n const filePath = replaceBackslash(path.join(dir, dirent.name))\n const filePathNoExt = removeExt(filePath)\n let routePath =\n cleanPath(`/${filePathNoExt.split('.').join('/')}`) || ''\n const variableName = routePathToVariable(routePath)\n\n // Remove the index from the route path and\n // if the route path is empty, use `/'\n\n let isRoute = routePath?.endsWith('/route')\n let isComponent = routePath?.endsWith('/component')\n let isErrorComponent = routePath?.endsWith('/errorComponent')\n let isPendingComponent = routePath?.endsWith('/pendingComponent')\n let isLoader = routePath?.endsWith('/loader')\n\n routePath = routePath?.replace(\n /\\/(component|errorComponent|pendingComponent|loader|route)$/,\n '',\n )\n\n if (routePath === 'index') {\n routePath = '/'\n }\n\n routePath = routePath.replace(/\\/index$/, '/') || '/'\n\n routeNodes.push({\n filePath,\n fullPath,\n routePath,\n variableName,\n isRoute,\n isComponent,\n isErrorComponent,\n isPendingComponent,\n isLoader,\n })\n }\n }),\n )\n\n return routeNodes\n }\n\n await recurse('./')\n\n return routeNodes\n}\n\nlet first = false\nlet skipMessage = false\n\ntype RouteSubNode = {\n component?: RouteNode\n errorComponent?: RouteNode\n pendingComponent?: RouteNode\n loader?: RouteNode\n}\n\nexport async function generator(config: Config) {\n console.log()\n\n if (!first) {\n console.log('🔄 Generating routes...')\n first = true\n } else if (skipMessage) {\n skipMessage = false\n } else {\n console.log('♻️ Regenerating routes...')\n }\n\n const taskId = latestTask + 1\n latestTask = taskId\n\n const checkLatest = () => {\n if (latestTask !== taskId) {\n skipMessage = true\n return false\n }\n\n return true\n }\n\n const start = Date.now()\n const routePathIdPrefix = config.routeFilePrefix ?? ''\n\n const preRouteNodes = multiSortBy(await getRouteNodes(config), [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.filePath?.match(/[./]index[.]/) ? 1 : -1),\n (d) =>\n d.filePath?.match(\n /[./](component|errorComponent|pendingComponent|loader)[.]/,\n )\n ? 1\n : -1,\n (d) => (d.filePath?.match(/[./]route[.]/) ? -1 : 1),\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter(\n (d) => ![`/${routePathIdPrefix + rootPathId}`].includes(d.routePath || ''),\n )\n\n const routeTree: RouteNode[] = []\n const routePiecesByPath: Record<string, RouteSubNode> = {}\n\n // Loop over the flat list of routeNodes and\n // build up a tree based on the routeNodes' routePath\n let routeNodes: RouteNode[] = []\n\n const handleNode = (node: RouteNode) => {\n const parentRoute = hasParentRoute(routeNodes, node.routePath)\n if (parentRoute) node.parent = parentRoute\n\n node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath!, '') || '/'\n : node.routePath\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath?.split('/') ?? []\n let first = split[0] ?? trimmedPath ?? ''\n\n node.isNonPath = first.startsWith('_')\n node.isNonLayout = first.endsWith('_')\n\n node.cleanedPath = removeUnderscores(node.path) ?? ''\n\n if (\n !node.isVirtual &&\n (node.isLoader ||\n node.isComponent ||\n node.isErrorComponent ||\n node.isPendingComponent)\n ) {\n routePiecesByPath[node.routePath!] =\n routePiecesByPath[node.routePath!] || {}\n\n routePiecesByPath[node.routePath!]![\n node.isLoader\n ? 'loader'\n : node.isErrorComponent\n ? 'errorComponent'\n : node.isPendingComponent\n ? 'pendingComponent'\n : 'component'\n ] = node\n\n const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath)\n\n if (!anchorRoute) {\n handleNode({\n ...node,\n isVirtual: true,\n isLoader: false,\n isComponent: false,\n isErrorComponent: false,\n isPendingComponent: false,\n })\n }\n return\n }\n\n if (node.parent) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n } else {\n routeTree.push(node)\n }\n\n routeNodes.push(node)\n }\n\n preRouteNodes.forEach((node) => handleNode(node))\n\n async function buildRouteConfig(\n nodes: RouteNode[],\n depth = 1,\n ): Promise<string> {\n const children = nodes.map(async (node) => {\n const routeCode = await fs.readFile(node.fullPath, 'utf-8')\n\n // Ensure the boilerplate for the route exists\n if (node.isRoot) {\n return\n }\n\n // Ensure that new FileRoute(anything?) is replaced with FileRoute(${node.routePath})\n // routePath can contain $ characters, which have special meaning when used in replace\n // so we have to escape it by turning all $ into $$. But since we do it through a replace call\n // we have to double escape it into $$$$. For more information, see\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement\n const escapedRoutePath = removeTrailingUnderscores(\n node.routePath?.replaceAll('$', '$$') ?? '',\n )\n const quote = config.quoteStyle === 'single' ? `'` : `\"`\n const replaced = routeCode.replace(\n /(FileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n\n if (replaced !== routeCode) {\n await fs.writeFile(node.fullPath, replaced)\n }\n\n const route = `${node.variableName}Route`\n\n if (node.children?.length) {\n const childConfigs = await buildRouteConfig(node.children, depth + 1)\n return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`\n }\n\n return route\n })\n\n return (await Promise.all(children)).filter(Boolean).join(`,`)\n }\n\n const routeConfigChildrenText = await buildRouteConfig(routeTree)\n\n const sortedRouteNodes = multiSortBy(routeNodes, [\n (d) =>\n d.routePath?.includes(`/${routePathIdPrefix + rootPathId}`) ? -1 : 1,\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(\"index'\") ? -1 : 1),\n (d) => d,\n ])\n\n const imports = Object.entries({\n FileRoute: sortedRouteNodes.some((d) => d.isVirtual),\n lazyFn: sortedRouteNodes.some(\n (node) => routePiecesByPath[node.routePath!]?.loader,\n ),\n lazyRouteComponent: sortedRouteNodes.some(\n (node) =>\n routePiecesByPath[node.routePath!]?.component ||\n routePiecesByPath[node.routePath!]?.errorComponent ||\n routePiecesByPath[node.routePath!]?.pendingComponent,\n ),\n })\n .filter((d) => d[1])\n .map((d) => d[0])\n\n const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual)\n\n const routeImports = [\n '// This file is auto-generated by TanStack Router',\n imports.length\n ? `import { ${imports.join(', ')} } from '@tanstack/react-router'\\n`\n : '',\n '// Import Routes',\n [\n `import { Route as rootRoute } from './${replaceBackslash(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, routePathIdPrefix + rootPathId),\n ),\n )}'`,\n ...sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .map((node) => {\n return `import { Route as ${\n node.variableName\n }Import } from './${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n ),\n )}'`\n }),\n ].join('\\n'),\n virtualRouteNodes.length ? '// Create Virtual Routes' : '',\n virtualRouteNodes\n .map((node) => {\n return `const ${\n node.variableName\n }Import = new FileRoute('${removeTrailingUnderscores(\n node.routePath,\n )}').createRoute()`\n })\n .join('\\n'),\n '// Create/Update Routes',\n sortedRouteNodes\n .map((node) => {\n const loaderNode = routePiecesByPath[node.routePath!]?.loader\n const componentNode = routePiecesByPath[node.routePath!]?.component\n const errorComponentNode =\n routePiecesByPath[node.routePath!]?.errorComponent\n const pendingComponentNode =\n routePiecesByPath[node.routePath!]?.pendingComponent\n\n return [\n `const ${node.variableName}Route = ${node.variableName}Import.update({\n ${[\n node.isNonPath\n ? `id: '${node.path}'`\n : `path: '${node.cleanedPath}'`,\n `getParentRoute: () => ${node.parent?.variableName ?? 'root'}Route`,\n ]\n .filter(Boolean)\n .join(',')}\n }${config.disableTypes ? '' : 'as any'})`,\n loaderNode\n ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, loaderNode.filePath),\n ),\n ),\n )}'), 'loader') })`\n : '',\n componentNode || errorComponentNode || pendingComponentNode\n ? `.update({\n ${(\n [\n ['component', componentNode],\n ['errorComponent', errorComponentNode],\n ['pendingComponent', pendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n return `${\n d[0]\n }: lazyRouteComponent(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, d[1]!.filePath),\n ),\n ),\n )}'), '${d[0]}')`\n })\n .join('\\n,')}\n })`\n : '',\n ].join('')\n })\n .join('\\n\\n'),\n ...(config.disableTypes\n ? []\n : [\n '// Populate the FileRoutesByPath interface',\n `declare module '@tanstack/react-router' {\n interface FileRoutesByPath {\n ${routeNodes\n .map((routeNode) => {\n return `'${removeTrailingUnderscores(routeNode.routePath)}': {\n preLoaderRoute: typeof ${routeNode.variableName}Import\n parentRoute: typeof ${\n routeNode.parent?.variableName\n ? `${routeNode.parent?.variableName}Import`\n : 'rootRoute'\n }\n }`\n })\n .join('\\n')}\n }\n}`,\n ]),\n '// Create and export the route tree',\n `export const routeTree = rootRoute.addChildren([${routeConfigChildrenText}])`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const routeConfigFileContent = await prettier.format(routeImports, {\n semi: false,\n singleQuote: config.quoteStyle === 'single',\n parser: 'typescript',\n })\n\n const routeTreeContent = await fs\n .readFile(path.resolve(config.generatedRouteTree), 'utf-8')\n .catch((err: any) => {\n if (err.code === 'ENOENT') {\n return undefined\n }\n throw err\n })\n\n if (!checkLatest()) return\n\n if (routeTreeContent !== routeConfigFileContent) {\n await fs.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {\n recursive: true,\n })\n if (!checkLatest()) return\n await fs.writeFile(\n path.resolve(config.generatedRouteTree),\n routeConfigFileContent,\n )\n }\n\n console.log(\n `🌲 Processed ${routeNodes.length} routes in ${Date.now() - start}ms`,\n )\n}\n\nfunction routePathToVariable(d: string): string {\n return (\n removeUnderscores(d)\n ?.replace(/\\/\\$\\//g, '/splat/')\n ?.replace(/\\$$/g, 'splat')\n ?.replace(/\\$/g, '')\n ?.split(/[/-]/g)\n .map((d, i) => (i > 0 ? capitalize(d) : d))\n .join('')\n .replace(/([^a-zA-Z0-9]|[\\.])/gm, '') ?? ''\n )\n}\n\nexport function removeExt(d: string) {\n return d.substring(0, d.lastIndexOf('.')) || d\n}\n\nfunction spaces(d: number): string {\n return Array.from({ length: d })\n .map(() => ' ')\n .join('')\n}\n\nexport function multiSortBy<T>(\n arr: T[],\n accessors: ((item: T) => any)[] = [(d) => d],\n): T[] {\n return arr\n .map((d, i) => [d, i] as const)\n .sort(([a, ai], [b, bi]) => {\n for (const accessor of accessors) {\n const ao = accessor(a)\n const bo = accessor(b)\n\n if (typeof ao === 'undefined') {\n if (typeof bo === 'undefined') {\n continue\n }\n return 1\n }\n\n if (ao === bo) {\n continue\n }\n\n return ao > bo ? 1 : -1\n }\n\n return ai - bi\n })\n .map(([d]) => d)\n}\n\nfunction capitalize(s: string) {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nfunction removeUnderscores(s?: string) {\n return s?.replace(/(^_|_$)/, '').replace(/(\\/_|_\\/)/, '/')\n}\n\nfunction removeTrailingUnderscores(s?: string) {\n return s?.replace(/(_$)/, '').replace(/(_\\/)/, '/')\n}\n\nfunction replaceBackslash(s: string) {\n return s.replace(/\\\\/gi, '/')\n}\n\nexport function hasParentRoute(\n routes: RouteNode[],\n routePathToCheck: string | undefined,\n): RouteNode | null {\n if (!routePathToCheck || routePathToCheck === '/') {\n return null\n }\n\n const sortedNodes = multiSortBy(routes, [\n (d) => d.routePath!.length * -1,\n (d) => d.variableName,\n ]).filter((d) => d.routePath !== `/${rootPathId}`)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, parentRoutePath)\n}\n"],"names":["fs","cleanPath","trimPathLeft","first","prettier","d"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAI,aAAa;AACV,MAAM,aAAa;AAsB1B,eAAe,cAAc,QAAgB;AACrC,QAAA,EAAE,iBAAiB,sBAA0B,IAAA;AAEnD,MAAI,aAA0B,CAAA;AAE9B,iBAAe,QAAQ,KAAa;AAClC,UAAM,UAAU,KAAK,QAAQ,OAAO,iBAAiB,GAAG;AACpD,QAAA,UAAU,MAAMA,cAAG,QAAQ,SAAS,EAAE,eAAe,MAAM;AAErD,cAAA,QAAQ,OAAO,CAAC,MAAM;AAE5B,UAAA,EAAE,KAAK,WAAW,GAAG,KACpB,yBAAyB,EAAE,KAAK,WAAW,qBAAqB,GACjE;AACO,eAAA;AAAA,MACT;AAEA,UAAI,iBAAiB;AACZ,eAAA,EAAE,KAAK,WAAW,eAAe;AAAA,MAC1C;AAEO,aAAA;AAAA,IAAA,CACR;AAED,UAAM,QAAQ;AAAA,MACZ,QAAQ,IAAI,OAAO,WAAW;AAC5B,cAAM,WAAW,KAAK,KAAK,SAAS,OAAO,IAAI;AAC/C,cAAM,eAAe,KAAK,KAAK,KAAK,OAAO,IAAI;AAE3C,YAAA,OAAO,eAAe;AACxB,gBAAM,QAAQ,YAAY;AAAA,QACjB,WAAA,SAAS,MAAM,oBAAoB,GAAG;AAC/C,gBAAM,WAAW,iBAAiB,KAAK,KAAK,KAAK,OAAO,IAAI,CAAC;AACvD,gBAAA,gBAAgB,UAAU,QAAQ;AACpC,cAAA,YACFC,MAAU,UAAA,IAAI,cAAc,MAAM,GAAG,EAAE,KAAK,GAAG,CAAC,EA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AA,eAAe,QAAQ,eAAe;AAC/C;;;;;;"}
|
|
1
|
+
{"version":3,"file":"generator.cjs","sources":["../../src/generator.ts"],"sourcesContent":["import path from 'path'\nimport * as fs from 'fs'\nimport * as fsp from 'fs/promises'\nimport * as prettier from 'prettier'\nimport { Config } from './config'\nimport { cleanPath, trimPathLeft } from './utils'\n\nlet latestTask = 0\nexport const rootPathId = '__root'\n\nexport type RouteNode = {\n filePath: string\n fullPath: string\n variableName: string\n routePath?: string\n cleanedPath?: string\n path?: string\n isNonPath?: boolean\n isNonLayout?: boolean\n isRoute?: boolean\n isLoader?: boolean\n isComponent?: boolean\n isErrorComponent?: boolean\n isPendingComponent?: boolean\n isVirtual?: boolean\n isLazy?: boolean\n isRoot?: boolean\n children?: RouteNode[]\n parent?: RouteNode\n}\n\nasync function getRouteNodes(config: Config) {\n const { routeFilePrefix, routeFileIgnorePrefix } = config\n\n let routeNodes: RouteNode[] = []\n\n async function recurse(dir: string) {\n const fullDir = path.resolve(config.routesDirectory, dir)\n let dirList = await fsp.readdir(fullDir, { withFileTypes: true })\n\n dirList = dirList.filter((d) => {\n if (\n d.name.startsWith('.') ||\n (routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix))\n ) {\n return false\n }\n\n if (routeFilePrefix) {\n return d.name.startsWith(routeFilePrefix)\n }\n\n return true\n })\n\n await Promise.all(\n dirList.map(async (dirent) => {\n const fullPath = path.join(fullDir, dirent.name)\n const relativePath = path.join(dir, dirent.name)\n\n if (dirent.isDirectory()) {\n await recurse(relativePath)\n } else if (fullPath.match(/\\.(tsx|ts|jsx|js)$/)) {\n const filePath = replaceBackslash(path.join(dir, dirent.name))\n const filePathNoExt = removeExt(filePath)\n let routePath =\n cleanPath(`/${filePathNoExt.split('.').join('/')}`) || ''\n const variableName = routePathToVariable(routePath)\n\n // Remove the index from the route path and\n // if the route path is empty, use `/'\n\n let isRoute = routePath?.endsWith('/route')\n let isComponent = routePath?.endsWith('/component')\n let isErrorComponent = routePath?.endsWith('/errorComponent')\n let isPendingComponent = routePath?.endsWith('/pendingComponent')\n let isLoader = routePath?.endsWith('/loader')\n let isLazy = routePath?.endsWith('/lazy')\n\n ;(\n [\n [isComponent, 'component'],\n [isErrorComponent, 'errorComponent'],\n [isPendingComponent, 'pendingComponent'],\n [isLoader, 'loader'],\n ] as const\n ).forEach(([isType, type]) => {\n if (isType) {\n console.warn(\n `WARNING: The \\`.${type}.tsx\\` suffix used for the ${filePath} file is deprecated. Use the new \\`.lazy.tsx\\` suffix instead.`,\n )\n }\n })\n\n routePath = routePath?.replace(\n /\\/(component|errorComponent|pendingComponent|loader|route|lazy)$/,\n '',\n )\n\n if (routePath === 'index') {\n routePath = '/'\n }\n\n routePath = routePath.replace(/\\/index$/, '/') || '/'\n\n routeNodes.push({\n filePath,\n fullPath,\n routePath,\n variableName,\n isRoute,\n isComponent,\n isErrorComponent,\n isPendingComponent,\n isLoader,\n isLazy,\n })\n }\n }),\n )\n\n return routeNodes\n }\n\n await recurse('./')\n\n return routeNodes\n}\n\nlet first = false\nlet skipMessage = false\n\ntype RouteSubNode = {\n component?: RouteNode\n errorComponent?: RouteNode\n pendingComponent?: RouteNode\n loader?: RouteNode\n lazy?: RouteNode\n}\n\nexport async function generator(config: Config) {\n console.log()\n\n if (!first) {\n console.log('🔄 Generating routes...')\n first = true\n } else if (skipMessage) {\n skipMessage = false\n } else {\n console.log('♻️ Regenerating routes...')\n }\n\n const taskId = latestTask + 1\n latestTask = taskId\n\n const checkLatest = () => {\n if (latestTask !== taskId) {\n skipMessage = true\n return false\n }\n\n return true\n }\n\n const start = Date.now()\n const routePathIdPrefix = config.routeFilePrefix ?? ''\n\n const preRouteNodes = multiSortBy(await getRouteNodes(config), [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.filePath?.match(/[./]index[.]/) ? 1 : -1),\n (d) =>\n d.filePath?.match(\n /[./](component|errorComponent|pendingComponent|loader|lazy)[.]/,\n )\n ? 1\n : -1,\n (d) => (d.filePath?.match(/[./]route[.]/) ? -1 : 1),\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter(\n (d) => ![`/${routePathIdPrefix + rootPathId}`].includes(d.routePath || ''),\n )\n\n const routeTree: RouteNode[] = []\n const routePiecesByPath: Record<string, RouteSubNode> = {}\n\n // Loop over the flat list of routeNodes and\n // build up a tree based on the routeNodes' routePath\n let routeNodes: RouteNode[] = []\n\n const handleNode = async (node: RouteNode) => {\n const parentRoute = hasParentRoute(routeNodes, node.routePath)\n if (parentRoute) node.parent = parentRoute\n\n node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath!, '') || '/'\n : node.routePath\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath?.split('/') ?? []\n let first = split[0] ?? trimmedPath ?? ''\n\n node.isNonPath = first.startsWith('_')\n node.isNonLayout = first.endsWith('_')\n node.cleanedPath = removeUnderscores(node.path) ?? ''\n\n // Ensure the boilerplate for the route exists\n const routeCode = fs.readFileSync(node.fullPath, 'utf-8')\n\n const escapedRoutePath = removeTrailingUnderscores(\n node.routePath?.replaceAll('$', '$$') ?? '',\n )\n\n let replaced = routeCode\n\n if (!routeCode) {\n if (node.isLazy) {\n replaced = [\n `import { createLazyFileRoute } from '@tanstack/react-router'`,\n `export const Route = createLazyFileRoute('${escapedRoutePath}')({\n component: () => <div>Hello ${escapedRoutePath}!</div>\n})`,\n ].join('\\n\\n')\n } else if (\n node.isRoute ||\n (!node.isComponent &&\n !node.isErrorComponent &&\n !node.isPendingComponent &&\n !node.isLoader)\n ) {\n replaced = [\n `import { createFileRoute } from '@tanstack/react-router'`,\n `export const Route = createFileRoute('${escapedRoutePath}')({\n component: () => <div>Hello ${escapedRoutePath}!</div>\n})`,\n ].join('\\n\\n')\n }\n } else {\n replaced = routeCode\n .replace(\n /(FileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n .replace(\n /(createFileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n .replace(\n /(createLazyFileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n }\n\n if (replaced !== routeCode) {\n console.log(`🌲 Updating ${node.fullPath}`)\n await fsp.writeFile(node.fullPath, replaced)\n }\n\n if (\n !node.isVirtual &&\n (node.isLoader ||\n node.isComponent ||\n node.isErrorComponent ||\n node.isPendingComponent ||\n node.isLazy)\n ) {\n routePiecesByPath[node.routePath!] =\n routePiecesByPath[node.routePath!] || {}\n\n routePiecesByPath[node.routePath!]![\n node.isLazy\n ? 'lazy'\n : node.isLoader\n ? 'loader'\n : node.isErrorComponent\n ? 'errorComponent'\n : node.isPendingComponent\n ? 'pendingComponent'\n : 'component'\n ] = node\n\n const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath)\n\n if (!anchorRoute) {\n handleNode({\n ...node,\n isVirtual: true,\n isLazy: false,\n isLoader: false,\n isComponent: false,\n isErrorComponent: false,\n isPendingComponent: false,\n })\n }\n return\n }\n\n if (node.parent) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n } else {\n routeTree.push(node)\n }\n\n routeNodes.push(node)\n }\n\n preRouteNodes.forEach((node) => handleNode(node))\n\n async function buildRouteConfig(\n nodes: RouteNode[],\n depth = 1,\n ): Promise<string> {\n const children = nodes.map(async (node) => {\n if (node.isRoot) {\n return\n }\n\n const route = `${node.variableName}Route`\n\n if (node.children?.length) {\n const childConfigs = await buildRouteConfig(node.children, depth + 1)\n return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`\n }\n\n return route\n })\n\n return (await Promise.all(children)).filter(Boolean).join(`,`)\n }\n\n const routeConfigChildrenText = await buildRouteConfig(routeTree)\n\n const sortedRouteNodes = multiSortBy(routeNodes, [\n (d) =>\n d.routePath?.includes(`/${routePathIdPrefix + rootPathId}`) ? -1 : 1,\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(\"index'\") ? -1 : 1),\n (d) => d,\n ])\n\n const imports = Object.entries({\n createFileRoute: sortedRouteNodes.some((d) => d.isVirtual),\n lazyFn: sortedRouteNodes.some(\n (node) => routePiecesByPath[node.routePath!]?.loader,\n ),\n lazyRouteComponent: sortedRouteNodes.some(\n (node) =>\n routePiecesByPath[node.routePath!]?.component ||\n routePiecesByPath[node.routePath!]?.errorComponent ||\n routePiecesByPath[node.routePath!]?.pendingComponent,\n ),\n })\n .filter((d) => d[1])\n .map((d) => d[0])\n\n const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual)\n\n const routeImports = [\n '// This file is auto-generated by TanStack Router',\n imports.length\n ? `import { ${imports.join(', ')} } from '@tanstack/react-router'\\n`\n : '',\n '// Import Routes',\n [\n `import { Route as rootRoute } from './${replaceBackslash(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, routePathIdPrefix + rootPathId),\n ),\n )}'`,\n ...sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .map((node) => {\n return `import { Route as ${\n node.variableName\n }Import } from './${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n ),\n )}'`\n }),\n ].join('\\n'),\n virtualRouteNodes.length ? '// Create Virtual Routes' : '',\n virtualRouteNodes\n .map((node) => {\n return `const ${\n node.variableName\n }Import = createFileRoute('${removeTrailingUnderscores(\n node.routePath,\n )}')()`\n })\n .join('\\n'),\n '// Create/Update Routes',\n sortedRouteNodes\n .map((node) => {\n const loaderNode = routePiecesByPath[node.routePath!]?.loader\n const componentNode = routePiecesByPath[node.routePath!]?.component\n const errorComponentNode =\n routePiecesByPath[node.routePath!]?.errorComponent\n const pendingComponentNode =\n routePiecesByPath[node.routePath!]?.pendingComponent\n const lazyComponentNode = routePiecesByPath[node.routePath!]?.lazy\n\n return [\n `const ${node.variableName}Route = ${node.variableName}Import.update({\n ${[\n node.isNonPath\n ? `id: '${node.path}'`\n : `path: '${node.cleanedPath}'`,\n `getParentRoute: () => ${node.parent?.variableName ?? 'root'}Route`,\n ]\n .filter(Boolean)\n .join(',')}\n }${config.disableTypes ? '' : 'as any'})`,\n loaderNode\n ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, loaderNode.filePath),\n ),\n ),\n )}'), 'loader') })`\n : '',\n componentNode || errorComponentNode || pendingComponentNode\n ? `.update({\n ${(\n [\n ['component', componentNode],\n ['errorComponent', errorComponentNode],\n ['pendingComponent', pendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n return `${\n d[0]\n }: lazyRouteComponent(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, d[1]!.filePath),\n ),\n ),\n )}'), '${d[0]}')`\n })\n .join('\\n,')}\n })`\n : '',\n lazyComponentNode\n ? `.lazy(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n lazyComponentNode!.filePath,\n ),\n ),\n ),\n )}').then((d) => d.Route))`\n : '',\n ].join('')\n })\n .join('\\n\\n'),\n ...(config.disableTypes\n ? []\n : [\n '// Populate the FileRoutesByPath interface',\n `declare module '@tanstack/react-router' {\n interface FileRoutesByPath {\n ${routeNodes\n .map((routeNode) => {\n return `'${removeTrailingUnderscores(routeNode.routePath)}': {\n preLoaderRoute: typeof ${routeNode.variableName}Import\n parentRoute: typeof ${\n routeNode.parent?.variableName\n ? `${routeNode.parent?.variableName}Import`\n : 'rootRoute'\n }\n }`\n })\n .join('\\n')}\n }\n}`,\n ]),\n '// Create and export the route tree',\n `export const routeTree = rootRoute.addChildren([${routeConfigChildrenText}])`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const routeConfigFileContent = await prettier.format(routeImports, {\n semi: false,\n singleQuote: config.quoteStyle === 'single',\n parser: 'typescript',\n })\n\n const routeTreeContent = await fsp\n .readFile(path.resolve(config.generatedRouteTree), 'utf-8')\n .catch((err: any) => {\n if (err.code === 'ENOENT') {\n return undefined\n }\n throw err\n })\n\n if (!checkLatest()) return\n\n if (routeTreeContent !== routeConfigFileContent) {\n await fsp.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {\n recursive: true,\n })\n if (!checkLatest()) return\n await fsp.writeFile(\n path.resolve(config.generatedRouteTree),\n routeConfigFileContent,\n )\n }\n\n console.log(\n `🌲 Processed ${routeNodes.length} routes in ${Date.now() - start}ms`,\n )\n}\n\nfunction routePathToVariable(d: string): string {\n return (\n removeUnderscores(d)\n ?.replace(/\\/\\$\\//g, '/splat/')\n ?.replace(/\\$$/g, 'splat')\n ?.replace(/\\$/g, '')\n ?.split(/[/-]/g)\n .map((d, i) => (i > 0 ? capitalize(d) : d))\n .join('')\n .replace(/([^a-zA-Z0-9]|[\\.])/gm, '') ?? ''\n )\n}\n\nexport function removeExt(d: string) {\n return d.substring(0, d.lastIndexOf('.')) || d\n}\n\nfunction spaces(d: number): string {\n return Array.from({ length: d })\n .map(() => ' ')\n .join('')\n}\n\nexport function multiSortBy<T>(\n arr: T[],\n accessors: ((item: T) => any)[] = [(d) => d],\n): T[] {\n return arr\n .map((d, i) => [d, i] as const)\n .sort(([a, ai], [b, bi]) => {\n for (const accessor of accessors) {\n const ao = accessor(a)\n const bo = accessor(b)\n\n if (typeof ao === 'undefined') {\n if (typeof bo === 'undefined') {\n continue\n }\n return 1\n }\n\n if (ao === bo) {\n continue\n }\n\n return ao > bo ? 1 : -1\n }\n\n return ai - bi\n })\n .map(([d]) => d)\n}\n\nfunction capitalize(s: string) {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nfunction removeUnderscores(s?: string) {\n return s?.replace(/(^_|_$)/, '').replace(/(\\/_|_\\/)/, '/')\n}\n\nfunction removeTrailingUnderscores(s?: string) {\n return s?.replace(/(_$)/, '').replace(/(_\\/)/, '/')\n}\n\nfunction replaceBackslash(s: string) {\n return s.replace(/\\\\/gi, '/')\n}\n\nexport function hasParentRoute(\n routes: RouteNode[],\n routePathToCheck: string | undefined,\n): RouteNode | null {\n if (!routePathToCheck || routePathToCheck === '/') {\n return null\n }\n\n const sortedNodes = multiSortBy(routes, [\n (d) => d.routePath!.length * -1,\n (d) => d.variableName,\n ]).filter((d) => d.routePath !== `/${rootPathId}`)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, parentRoutePath)\n}\n"],"names":["fsp","cleanPath","trimPathLeft","first","fs","prettier","d"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,IAAI,aAAa;AACV,MAAM,aAAa;AAuB1B,eAAe,cAAc,QAAgB;AACrC,QAAA,EAAE,iBAAiB,sBAA0B,IAAA;AAEnD,MAAI,aAA0B,CAAA;AAE9B,iBAAe,QAAQ,KAAa;AAClC,UAAM,UAAU,KAAK,QAAQ,OAAO,iBAAiB,GAAG;AACpD,QAAA,UAAU,MAAMA,eAAI,QAAQ,SAAS,EAAE,eAAe,MAAM;AAEtD,cAAA,QAAQ,OAAO,CAAC,MAAM;AAE5B,UAAA,EAAE,KAAK,WAAW,GAAG,KACpB,yBAAyB,EAAE,KAAK,WAAW,qBAAqB,GACjE;AACO,eAAA;AAAA,MACT;AAEA,UAAI,iBAAiB;AACZ,eAAA,EAAE,KAAK,WAAW,eAAe;AAAA,MAC1C;AAEO,aAAA;AAAA,IAAA,CACR;AAED,U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AC,oBAAoB,qBAAqB,KAAK;AAC1C,WAAA;AAAA,EACT;AAEM,QAAA,cAAc,YAAY,QAAQ;AAAA,IACtC,CAAC,MAAM,EAAE,UAAW,SAAS;AAAA,IAC7B,CAAC,MAAM,EAAE;AAAA,EAAA,CACV,EAAE,OAAO,CAAC,MAAM,EAAE,cAAc,IAAI,UAAU,EAAE;AAEjD,aAAW,SAAS,aAAa;AAC/B,QAAI,MAAM,cAAc;AAAK;AAG3B,QAAA,iBAAiB,WAAW,GAAG,MAAM,SAAS,GAAG,KACjD,MAAM,cAAc,kBACpB;AACO,aAAA;AAAA,IACT;AAAA,EACF;AACM,QAAA,WAAW,iBAAiB,MAAM,GAAG;AAC3C,WAAS,IAAI;AACP,QAAA,kBAAkB,SAAS,KAAK,GAAG;AAElC,SAAA,eAAe,QAAQ,eAAe;AAC/C;;;;;;"}
|
package/dist/cjs/generator.d.cts
CHANGED
package/dist/esm/config.d.ts
CHANGED
|
@@ -22,4 +22,4 @@ export declare const configSchema: z.ZodObject<{
|
|
|
22
22
|
disableTypes?: boolean | undefined;
|
|
23
23
|
}>;
|
|
24
24
|
export type Config = z.infer<typeof configSchema>;
|
|
25
|
-
export declare function getConfig(): Promise<Config>;
|
|
25
|
+
export declare function getConfig(inlineConfig?: Partial<Config>, configDirectory?: string): Promise<Config>;
|
package/dist/esm/config.js
CHANGED
|
@@ -9,16 +9,20 @@ const configSchema = z.object({
|
|
|
9
9
|
quoteStyle: z.enum(["single", "double"]).optional().default("single"),
|
|
10
10
|
disableTypes: z.boolean().optional().default(false)
|
|
11
11
|
});
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
async function getConfig(inlineConfig = {}, configDirectory) {
|
|
13
|
+
if (configDirectory === void 0) {
|
|
14
|
+
configDirectory = process.cwd();
|
|
15
|
+
}
|
|
16
|
+
const configFilePathJson = path.resolve(configDirectory, "tsr.config.json");
|
|
14
17
|
const exists = existsSync(configFilePathJson);
|
|
15
18
|
let config;
|
|
16
19
|
if (exists) {
|
|
17
|
-
config = configSchema.parse(
|
|
18
|
-
JSON.parse(readFileSync(configFilePathJson, "utf-8"))
|
|
19
|
-
|
|
20
|
+
config = configSchema.parse({
|
|
21
|
+
...JSON.parse(readFileSync(configFilePathJson, "utf-8")),
|
|
22
|
+
...inlineConfig
|
|
23
|
+
});
|
|
20
24
|
} else {
|
|
21
|
-
config = configSchema.parse(
|
|
25
|
+
config = configSchema.parse(inlineConfig);
|
|
22
26
|
}
|
|
23
27
|
if (config.disableTypes) {
|
|
24
28
|
config.generatedRouteTree = config.generatedRouteTree.replace(
|
package/dist/esm/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sources":["../../src/config.ts"],"sourcesContent":["import path from 'path'\nimport { readFileSync, existsSync } from 'fs'\nimport { z } from 'zod'\n\nexport const configSchema = z.object({\n routeFilePrefix: z.string().optional(),\n routeFileIgnorePrefix: z.string().optional().default('-'),\n routesDirectory: z.string().optional().default('./src/routes'),\n generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'),\n quoteStyle: z.enum(['single', 'double']).optional().default('single'),\n disableTypes: z.boolean().optional().default(false),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\
|
|
1
|
+
{"version":3,"file":"config.js","sources":["../../src/config.ts"],"sourcesContent":["import path from 'path'\nimport { readFileSync, existsSync } from 'fs'\nimport { z } from 'zod'\n\nexport const configSchema = z.object({\n routeFilePrefix: z.string().optional(),\n routeFileIgnorePrefix: z.string().optional().default('-'),\n routesDirectory: z.string().optional().default('./src/routes'),\n generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'),\n quoteStyle: z.enum(['single', 'double']).optional().default('single'),\n disableTypes: z.boolean().optional().default(false),\n})\n\nexport type Config = z.infer<typeof configSchema>\n\nexport async function getConfig(\n inlineConfig: Partial<Config> = {},\n configDirectory?: string,\n): Promise<Config> {\n if (configDirectory === undefined) {\n configDirectory = process.cwd()\n }\n const configFilePathJson = path.resolve(configDirectory, 'tsr.config.json')\n const exists = existsSync(configFilePathJson)\n\n let config: Config\n\n if (exists) {\n config = configSchema.parse({\n ...JSON.parse(readFileSync(configFilePathJson, 'utf-8')),\n ...inlineConfig,\n })\n } else {\n config = configSchema.parse(inlineConfig)\n }\n\n // If typescript is disabled, make sure the generated route tree is a .js file\n if (config.disableTypes) {\n config.generatedRouteTree = config.generatedRouteTree.replace(\n /\\.(ts|tsx)$/,\n '.js',\n )\n }\n\n return config\n}\n"],"names":[],"mappings":";;;AAIa,MAAA,eAAe,EAAE,OAAO;AAAA,EACnC,iBAAiB,EAAE,OAAO,EAAE,SAAS;AAAA,EACrC,uBAAuB,EAAE,OAAA,EAAS,SAAS,EAAE,QAAQ,GAAG;AAAA,EACxD,iBAAiB,EAAE,OAAA,EAAS,SAAS,EAAE,QAAQ,cAAc;AAAA,EAC7D,oBAAoB,EAAE,OAAA,EAAS,SAAS,EAAE,QAAQ,wBAAwB;AAAA,EAC1E,YAAY,EAAE,KAAK,CAAC,UAAU,QAAQ,CAAC,EAAE,SAAA,EAAW,QAAQ,QAAQ;AAAA,EACpE,cAAc,EAAE,QAAA,EAAU,SAAS,EAAE,QAAQ,KAAK;AACpD,CAAC;AAID,eAAsB,UACpB,eAAgC,CAAC,GACjC,iBACiB;AACjB,MAAI,oBAAoB,QAAW;AACjC,sBAAkB,QAAQ;EAC5B;AACA,QAAM,qBAAqB,KAAK,QAAQ,iBAAiB,iBAAiB;AACpE,QAAA,SAAS,WAAW,kBAAkB;AAExC,MAAA;AAEJ,MAAI,QAAQ;AACV,aAAS,aAAa,MAAM;AAAA,MAC1B,GAAG,KAAK,MAAM,aAAa,oBAAoB,OAAO,CAAC;AAAA,MACvD,GAAG;AAAA,IAAA,CACJ;AAAA,EAAA,OACI;AACI,aAAA,aAAa,MAAM,YAAY;AAAA,EAC1C;AAGA,MAAI,OAAO,cAAc;AAChB,WAAA,qBAAqB,OAAO,mBAAmB;AAAA,MACpD;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEO,SAAA;AACT;"}
|
package/dist/esm/generator.d.ts
CHANGED
package/dist/esm/generator.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from "path";
|
|
2
|
-
import * as fs from "fs
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as fsp from "fs/promises";
|
|
3
4
|
import * as prettier from "prettier";
|
|
4
5
|
import { trimPathLeft, cleanPath } from "./utils.js";
|
|
5
6
|
let latestTask = 0;
|
|
@@ -9,7 +10,7 @@ async function getRouteNodes(config) {
|
|
|
9
10
|
let routeNodes = [];
|
|
10
11
|
async function recurse(dir) {
|
|
11
12
|
const fullDir = path.resolve(config.routesDirectory, dir);
|
|
12
|
-
let dirList = await
|
|
13
|
+
let dirList = await fsp.readdir(fullDir, { withFileTypes: true });
|
|
13
14
|
dirList = dirList.filter((d) => {
|
|
14
15
|
if (d.name.startsWith(".") || routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix)) {
|
|
15
16
|
return false;
|
|
@@ -35,8 +36,21 @@ async function getRouteNodes(config) {
|
|
|
35
36
|
let isErrorComponent = routePath == null ? void 0 : routePath.endsWith("/errorComponent");
|
|
36
37
|
let isPendingComponent = routePath == null ? void 0 : routePath.endsWith("/pendingComponent");
|
|
37
38
|
let isLoader = routePath == null ? void 0 : routePath.endsWith("/loader");
|
|
39
|
+
let isLazy = routePath == null ? void 0 : routePath.endsWith("/lazy");
|
|
40
|
+
[
|
|
41
|
+
[isComponent, "component"],
|
|
42
|
+
[isErrorComponent, "errorComponent"],
|
|
43
|
+
[isPendingComponent, "pendingComponent"],
|
|
44
|
+
[isLoader, "loader"]
|
|
45
|
+
].forEach(([isType, type]) => {
|
|
46
|
+
if (isType) {
|
|
47
|
+
console.warn(
|
|
48
|
+
`WARNING: The \`.${type}.tsx\` suffix used for the ${filePath} file is deprecated. Use the new \`.lazy.tsx\` suffix instead.`
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
38
52
|
routePath = routePath == null ? void 0 : routePath.replace(
|
|
39
|
-
/\/(component|errorComponent|pendingComponent|loader|route)$/,
|
|
53
|
+
/\/(component|errorComponent|pendingComponent|loader|route|lazy)$/,
|
|
40
54
|
""
|
|
41
55
|
);
|
|
42
56
|
if (routePath === "index") {
|
|
@@ -52,7 +66,8 @@ async function getRouteNodes(config) {
|
|
|
52
66
|
isComponent,
|
|
53
67
|
isErrorComponent,
|
|
54
68
|
isPendingComponent,
|
|
55
|
-
isLoader
|
|
69
|
+
isLoader,
|
|
70
|
+
isLazy
|
|
56
71
|
});
|
|
57
72
|
}
|
|
58
73
|
})
|
|
@@ -98,7 +113,7 @@ async function generator(config) {
|
|
|
98
113
|
(d) => {
|
|
99
114
|
var _a;
|
|
100
115
|
return ((_a = d.filePath) == null ? void 0 : _a.match(
|
|
101
|
-
/[./](component|errorComponent|pendingComponent|loader)[.]/
|
|
116
|
+
/[./](component|errorComponent|pendingComponent|loader|lazy)[.]/
|
|
102
117
|
)) ? 1 : -1;
|
|
103
118
|
},
|
|
104
119
|
(d) => {
|
|
@@ -116,8 +131,8 @@ async function generator(config) {
|
|
|
116
131
|
const routeTree = [];
|
|
117
132
|
const routePiecesByPath = {};
|
|
118
133
|
let routeNodes = [];
|
|
119
|
-
const handleNode = (node) => {
|
|
120
|
-
var _a;
|
|
134
|
+
const handleNode = async (node) => {
|
|
135
|
+
var _a, _b;
|
|
121
136
|
const parentRoute = hasParentRoute(routeNodes, node.routePath);
|
|
122
137
|
if (parentRoute)
|
|
123
138
|
node.parent = parentRoute;
|
|
@@ -128,14 +143,52 @@ async function generator(config) {
|
|
|
128
143
|
node.isNonPath = first2.startsWith("_");
|
|
129
144
|
node.isNonLayout = first2.endsWith("_");
|
|
130
145
|
node.cleanedPath = removeUnderscores(node.path) ?? "";
|
|
131
|
-
|
|
146
|
+
const routeCode = fs.readFileSync(node.fullPath, "utf-8");
|
|
147
|
+
const escapedRoutePath = removeTrailingUnderscores(
|
|
148
|
+
((_b = node.routePath) == null ? void 0 : _b.replaceAll("$", "$$")) ?? ""
|
|
149
|
+
);
|
|
150
|
+
let replaced = routeCode;
|
|
151
|
+
if (!routeCode) {
|
|
152
|
+
if (node.isLazy) {
|
|
153
|
+
replaced = [
|
|
154
|
+
`import { createLazyFileRoute } from '@tanstack/react-router'`,
|
|
155
|
+
`export const Route = createLazyFileRoute('${escapedRoutePath}')({
|
|
156
|
+
component: () => <div>Hello ${escapedRoutePath}!</div>
|
|
157
|
+
})`
|
|
158
|
+
].join("\n\n");
|
|
159
|
+
} else if (node.isRoute || !node.isComponent && !node.isErrorComponent && !node.isPendingComponent && !node.isLoader) {
|
|
160
|
+
replaced = [
|
|
161
|
+
`import { createFileRoute } from '@tanstack/react-router'`,
|
|
162
|
+
`export const Route = createFileRoute('${escapedRoutePath}')({
|
|
163
|
+
component: () => <div>Hello ${escapedRoutePath}!</div>
|
|
164
|
+
})`
|
|
165
|
+
].join("\n\n");
|
|
166
|
+
}
|
|
167
|
+
} else {
|
|
168
|
+
replaced = routeCode.replace(
|
|
169
|
+
/(FileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
170
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
171
|
+
).replace(
|
|
172
|
+
/(createFileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
173
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
174
|
+
).replace(
|
|
175
|
+
/(createLazyFileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
176
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
if (replaced !== routeCode) {
|
|
180
|
+
console.log(`🌲 Updating ${node.fullPath}`);
|
|
181
|
+
await fsp.writeFile(node.fullPath, replaced);
|
|
182
|
+
}
|
|
183
|
+
if (!node.isVirtual && (node.isLoader || node.isComponent || node.isErrorComponent || node.isPendingComponent || node.isLazy)) {
|
|
132
184
|
routePiecesByPath[node.routePath] = routePiecesByPath[node.routePath] || {};
|
|
133
|
-
routePiecesByPath[node.routePath][node.isLoader ? "loader" : node.isErrorComponent ? "errorComponent" : node.isPendingComponent ? "pendingComponent" : "component"] = node;
|
|
185
|
+
routePiecesByPath[node.routePath][node.isLazy ? "lazy" : node.isLoader ? "loader" : node.isErrorComponent ? "errorComponent" : node.isPendingComponent ? "pendingComponent" : "component"] = node;
|
|
134
186
|
const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath);
|
|
135
187
|
if (!anchorRoute) {
|
|
136
188
|
handleNode({
|
|
137
189
|
...node,
|
|
138
190
|
isVirtual: true,
|
|
191
|
+
isLazy: false,
|
|
139
192
|
isLoader: false,
|
|
140
193
|
isComponent: false,
|
|
141
194
|
isErrorComponent: false,
|
|
@@ -155,24 +208,12 @@ async function generator(config) {
|
|
|
155
208
|
preRouteNodes.forEach((node) => handleNode(node));
|
|
156
209
|
async function buildRouteConfig(nodes, depth = 1) {
|
|
157
210
|
const children = nodes.map(async (node) => {
|
|
158
|
-
var _a
|
|
159
|
-
const routeCode = await fs.readFile(node.fullPath, "utf-8");
|
|
211
|
+
var _a;
|
|
160
212
|
if (node.isRoot) {
|
|
161
213
|
return;
|
|
162
214
|
}
|
|
163
|
-
const escapedRoutePath = removeTrailingUnderscores(
|
|
164
|
-
((_a = node.routePath) == null ? void 0 : _a.replaceAll("$", "$$")) ?? ""
|
|
165
|
-
);
|
|
166
|
-
config.quoteStyle === "single" ? `'` : `"`;
|
|
167
|
-
const replaced = routeCode.replace(
|
|
168
|
-
/(FileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
169
|
-
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`
|
|
170
|
-
);
|
|
171
|
-
if (replaced !== routeCode) {
|
|
172
|
-
await fs.writeFile(node.fullPath, replaced);
|
|
173
|
-
}
|
|
174
215
|
const route = `${node.variableName}Route`;
|
|
175
|
-
if ((
|
|
216
|
+
if ((_a = node.children) == null ? void 0 : _a.length) {
|
|
176
217
|
const childConfigs = await buildRouteConfig(node.children, depth + 1);
|
|
177
218
|
return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`;
|
|
178
219
|
}
|
|
@@ -197,7 +238,7 @@ async function generator(config) {
|
|
|
197
238
|
(d) => d
|
|
198
239
|
]);
|
|
199
240
|
const imports = Object.entries({
|
|
200
|
-
|
|
241
|
+
createFileRoute: sortedRouteNodes.some((d) => d.isVirtual),
|
|
201
242
|
lazyFn: sortedRouteNodes.some(
|
|
202
243
|
(node) => {
|
|
203
244
|
var _a;
|
|
@@ -237,22 +278,23 @@ async function generator(config) {
|
|
|
237
278
|
].join("\n"),
|
|
238
279
|
virtualRouteNodes.length ? "// Create Virtual Routes" : "",
|
|
239
280
|
virtualRouteNodes.map((node) => {
|
|
240
|
-
return `const ${node.variableName}Import =
|
|
281
|
+
return `const ${node.variableName}Import = createFileRoute('${removeTrailingUnderscores(
|
|
241
282
|
node.routePath
|
|
242
|
-
)}')
|
|
283
|
+
)}')()`;
|
|
243
284
|
}).join("\n"),
|
|
244
285
|
"// Create/Update Routes",
|
|
245
286
|
sortedRouteNodes.map((node) => {
|
|
246
|
-
var _a, _b, _c, _d, _e;
|
|
287
|
+
var _a, _b, _c, _d, _e, _f;
|
|
247
288
|
const loaderNode = (_a = routePiecesByPath[node.routePath]) == null ? void 0 : _a.loader;
|
|
248
289
|
const componentNode = (_b = routePiecesByPath[node.routePath]) == null ? void 0 : _b.component;
|
|
249
290
|
const errorComponentNode = (_c = routePiecesByPath[node.routePath]) == null ? void 0 : _c.errorComponent;
|
|
250
291
|
const pendingComponentNode = (_d = routePiecesByPath[node.routePath]) == null ? void 0 : _d.pendingComponent;
|
|
292
|
+
const lazyComponentNode = (_e = routePiecesByPath[node.routePath]) == null ? void 0 : _e.lazy;
|
|
251
293
|
return [
|
|
252
294
|
`const ${node.variableName}Route = ${node.variableName}Import.update({
|
|
253
295
|
${[
|
|
254
296
|
node.isNonPath ? `id: '${node.path}'` : `path: '${node.cleanedPath}'`,
|
|
255
|
-
`getParentRoute: () => ${((
|
|
297
|
+
`getParentRoute: () => ${((_f = node.parent) == null ? void 0 : _f.variableName) ?? "root"}Route`
|
|
256
298
|
].filter(Boolean).join(",")}
|
|
257
299
|
}${config.disableTypes ? "" : "as any"})`,
|
|
258
300
|
loaderNode ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(
|
|
@@ -278,7 +320,18 @@ async function generator(config) {
|
|
|
278
320
|
)
|
|
279
321
|
)}'), '${d[0]}')`;
|
|
280
322
|
}).join("\n,")}
|
|
281
|
-
})` : ""
|
|
323
|
+
})` : "",
|
|
324
|
+
lazyComponentNode ? `.lazy(() => import('./${replaceBackslash(
|
|
325
|
+
removeExt(
|
|
326
|
+
path.relative(
|
|
327
|
+
path.dirname(config.generatedRouteTree),
|
|
328
|
+
path.resolve(
|
|
329
|
+
config.routesDirectory,
|
|
330
|
+
lazyComponentNode.filePath
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
)
|
|
334
|
+
)}').then((d) => d.Route))` : ""
|
|
282
335
|
].join("");
|
|
283
336
|
}).join("\n\n"),
|
|
284
337
|
...config.disableTypes ? [] : [
|
|
@@ -303,7 +356,7 @@ async function generator(config) {
|
|
|
303
356
|
singleQuote: config.quoteStyle === "single",
|
|
304
357
|
parser: "typescript"
|
|
305
358
|
});
|
|
306
|
-
const routeTreeContent = await
|
|
359
|
+
const routeTreeContent = await fsp.readFile(path.resolve(config.generatedRouteTree), "utf-8").catch((err) => {
|
|
307
360
|
if (err.code === "ENOENT") {
|
|
308
361
|
return void 0;
|
|
309
362
|
}
|
|
@@ -312,12 +365,12 @@ async function generator(config) {
|
|
|
312
365
|
if (!checkLatest())
|
|
313
366
|
return;
|
|
314
367
|
if (routeTreeContent !== routeConfigFileContent) {
|
|
315
|
-
await
|
|
368
|
+
await fsp.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {
|
|
316
369
|
recursive: true
|
|
317
370
|
});
|
|
318
371
|
if (!checkLatest())
|
|
319
372
|
return;
|
|
320
|
-
await
|
|
373
|
+
await fsp.writeFile(
|
|
321
374
|
path.resolve(config.generatedRouteTree),
|
|
322
375
|
routeConfigFileContent
|
|
323
376
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.js","sources":["../../src/generator.ts"],"sourcesContent":["import path from 'path'\nimport * as fs from 'fs/promises'\nimport * as prettier from 'prettier'\nimport { Config } from './config'\nimport { cleanPath, trimPathLeft } from './utils'\n\nlet latestTask = 0\nexport const rootPathId = '__root'\n\nexport type RouteNode = {\n filePath: string\n fullPath: string\n variableName: string\n routePath?: string\n cleanedPath?: string\n path?: string\n isNonPath?: boolean\n isNonLayout?: boolean\n isRoute?: boolean\n isLoader?: boolean\n isComponent?: boolean\n isErrorComponent?: boolean\n isPendingComponent?: boolean\n isVirtual?: boolean\n isRoot?: boolean\n children?: RouteNode[]\n parent?: RouteNode\n}\n\nasync function getRouteNodes(config: Config) {\n const { routeFilePrefix, routeFileIgnorePrefix } = config\n\n let routeNodes: RouteNode[] = []\n\n async function recurse(dir: string) {\n const fullDir = path.resolve(config.routesDirectory, dir)\n let dirList = await fs.readdir(fullDir, { withFileTypes: true })\n\n dirList = dirList.filter((d) => {\n if (\n d.name.startsWith('.') ||\n (routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix))\n ) {\n return false\n }\n\n if (routeFilePrefix) {\n return d.name.startsWith(routeFilePrefix)\n }\n\n return true\n })\n\n await Promise.all(\n dirList.map(async (dirent) => {\n const fullPath = path.join(fullDir, dirent.name)\n const relativePath = path.join(dir, dirent.name)\n\n if (dirent.isDirectory()) {\n await recurse(relativePath)\n } else if (fullPath.match(/\\.(tsx|ts|jsx|js)$/)) {\n const filePath = replaceBackslash(path.join(dir, dirent.name))\n const filePathNoExt = removeExt(filePath)\n let routePath =\n cleanPath(`/${filePathNoExt.split('.').join('/')}`) || ''\n const variableName = routePathToVariable(routePath)\n\n // Remove the index from the route path and\n // if the route path is empty, use `/'\n\n let isRoute = routePath?.endsWith('/route')\n let isComponent = routePath?.endsWith('/component')\n let isErrorComponent = routePath?.endsWith('/errorComponent')\n let isPendingComponent = routePath?.endsWith('/pendingComponent')\n let isLoader = routePath?.endsWith('/loader')\n\n routePath = routePath?.replace(\n /\\/(component|errorComponent|pendingComponent|loader|route)$/,\n '',\n )\n\n if (routePath === 'index') {\n routePath = '/'\n }\n\n routePath = routePath.replace(/\\/index$/, '/') || '/'\n\n routeNodes.push({\n filePath,\n fullPath,\n routePath,\n variableName,\n isRoute,\n isComponent,\n isErrorComponent,\n isPendingComponent,\n isLoader,\n })\n }\n }),\n )\n\n return routeNodes\n }\n\n await recurse('./')\n\n return routeNodes\n}\n\nlet first = false\nlet skipMessage = false\n\ntype RouteSubNode = {\n component?: RouteNode\n errorComponent?: RouteNode\n pendingComponent?: RouteNode\n loader?: RouteNode\n}\n\nexport async function generator(config: Config) {\n console.log()\n\n if (!first) {\n console.log('🔄 Generating routes...')\n first = true\n } else if (skipMessage) {\n skipMessage = false\n } else {\n console.log('♻️ Regenerating routes...')\n }\n\n const taskId = latestTask + 1\n latestTask = taskId\n\n const checkLatest = () => {\n if (latestTask !== taskId) {\n skipMessage = true\n return false\n }\n\n return true\n }\n\n const start = Date.now()\n const routePathIdPrefix = config.routeFilePrefix ?? ''\n\n const preRouteNodes = multiSortBy(await getRouteNodes(config), [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.filePath?.match(/[./]index[.]/) ? 1 : -1),\n (d) =>\n d.filePath?.match(\n /[./](component|errorComponent|pendingComponent|loader)[.]/,\n )\n ? 1\n : -1,\n (d) => (d.filePath?.match(/[./]route[.]/) ? -1 : 1),\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter(\n (d) => ![`/${routePathIdPrefix + rootPathId}`].includes(d.routePath || ''),\n )\n\n const routeTree: RouteNode[] = []\n const routePiecesByPath: Record<string, RouteSubNode> = {}\n\n // Loop over the flat list of routeNodes and\n // build up a tree based on the routeNodes' routePath\n let routeNodes: RouteNode[] = []\n\n const handleNode = (node: RouteNode) => {\n const parentRoute = hasParentRoute(routeNodes, node.routePath)\n if (parentRoute) node.parent = parentRoute\n\n node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath!, '') || '/'\n : node.routePath\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath?.split('/') ?? []\n let first = split[0] ?? trimmedPath ?? ''\n\n node.isNonPath = first.startsWith('_')\n node.isNonLayout = first.endsWith('_')\n\n node.cleanedPath = removeUnderscores(node.path) ?? ''\n\n if (\n !node.isVirtual &&\n (node.isLoader ||\n node.isComponent ||\n node.isErrorComponent ||\n node.isPendingComponent)\n ) {\n routePiecesByPath[node.routePath!] =\n routePiecesByPath[node.routePath!] || {}\n\n routePiecesByPath[node.routePath!]![\n node.isLoader\n ? 'loader'\n : node.isErrorComponent\n ? 'errorComponent'\n : node.isPendingComponent\n ? 'pendingComponent'\n : 'component'\n ] = node\n\n const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath)\n\n if (!anchorRoute) {\n handleNode({\n ...node,\n isVirtual: true,\n isLoader: false,\n isComponent: false,\n isErrorComponent: false,\n isPendingComponent: false,\n })\n }\n return\n }\n\n if (node.parent) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n } else {\n routeTree.push(node)\n }\n\n routeNodes.push(node)\n }\n\n preRouteNodes.forEach((node) => handleNode(node))\n\n async function buildRouteConfig(\n nodes: RouteNode[],\n depth = 1,\n ): Promise<string> {\n const children = nodes.map(async (node) => {\n const routeCode = await fs.readFile(node.fullPath, 'utf-8')\n\n // Ensure the boilerplate for the route exists\n if (node.isRoot) {\n return\n }\n\n // Ensure that new FileRoute(anything?) is replaced with FileRoute(${node.routePath})\n // routePath can contain $ characters, which have special meaning when used in replace\n // so we have to escape it by turning all $ into $$. But since we do it through a replace call\n // we have to double escape it into $$$$. For more information, see\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement\n const escapedRoutePath = removeTrailingUnderscores(\n node.routePath?.replaceAll('$', '$$') ?? '',\n )\n const quote = config.quoteStyle === 'single' ? `'` : `\"`\n const replaced = routeCode.replace(\n /(FileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n\n if (replaced !== routeCode) {\n await fs.writeFile(node.fullPath, replaced)\n }\n\n const route = `${node.variableName}Route`\n\n if (node.children?.length) {\n const childConfigs = await buildRouteConfig(node.children, depth + 1)\n return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`\n }\n\n return route\n })\n\n return (await Promise.all(children)).filter(Boolean).join(`,`)\n }\n\n const routeConfigChildrenText = await buildRouteConfig(routeTree)\n\n const sortedRouteNodes = multiSortBy(routeNodes, [\n (d) =>\n d.routePath?.includes(`/${routePathIdPrefix + rootPathId}`) ? -1 : 1,\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(\"index'\") ? -1 : 1),\n (d) => d,\n ])\n\n const imports = Object.entries({\n FileRoute: sortedRouteNodes.some((d) => d.isVirtual),\n lazyFn: sortedRouteNodes.some(\n (node) => routePiecesByPath[node.routePath!]?.loader,\n ),\n lazyRouteComponent: sortedRouteNodes.some(\n (node) =>\n routePiecesByPath[node.routePath!]?.component ||\n routePiecesByPath[node.routePath!]?.errorComponent ||\n routePiecesByPath[node.routePath!]?.pendingComponent,\n ),\n })\n .filter((d) => d[1])\n .map((d) => d[0])\n\n const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual)\n\n const routeImports = [\n '// This file is auto-generated by TanStack Router',\n imports.length\n ? `import { ${imports.join(', ')} } from '@tanstack/react-router'\\n`\n : '',\n '// Import Routes',\n [\n `import { Route as rootRoute } from './${replaceBackslash(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, routePathIdPrefix + rootPathId),\n ),\n )}'`,\n ...sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .map((node) => {\n return `import { Route as ${\n node.variableName\n }Import } from './${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n ),\n )}'`\n }),\n ].join('\\n'),\n virtualRouteNodes.length ? '// Create Virtual Routes' : '',\n virtualRouteNodes\n .map((node) => {\n return `const ${\n node.variableName\n }Import = new FileRoute('${removeTrailingUnderscores(\n node.routePath,\n )}').createRoute()`\n })\n .join('\\n'),\n '// Create/Update Routes',\n sortedRouteNodes\n .map((node) => {\n const loaderNode = routePiecesByPath[node.routePath!]?.loader\n const componentNode = routePiecesByPath[node.routePath!]?.component\n const errorComponentNode =\n routePiecesByPath[node.routePath!]?.errorComponent\n const pendingComponentNode =\n routePiecesByPath[node.routePath!]?.pendingComponent\n\n return [\n `const ${node.variableName}Route = ${node.variableName}Import.update({\n ${[\n node.isNonPath\n ? `id: '${node.path}'`\n : `path: '${node.cleanedPath}'`,\n `getParentRoute: () => ${node.parent?.variableName ?? 'root'}Route`,\n ]\n .filter(Boolean)\n .join(',')}\n }${config.disableTypes ? '' : 'as any'})`,\n loaderNode\n ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, loaderNode.filePath),\n ),\n ),\n )}'), 'loader') })`\n : '',\n componentNode || errorComponentNode || pendingComponentNode\n ? `.update({\n ${(\n [\n ['component', componentNode],\n ['errorComponent', errorComponentNode],\n ['pendingComponent', pendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n return `${\n d[0]\n }: lazyRouteComponent(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, d[1]!.filePath),\n ),\n ),\n )}'), '${d[0]}')`\n })\n .join('\\n,')}\n })`\n : '',\n ].join('')\n })\n .join('\\n\\n'),\n ...(config.disableTypes\n ? []\n : [\n '// Populate the FileRoutesByPath interface',\n `declare module '@tanstack/react-router' {\n interface FileRoutesByPath {\n ${routeNodes\n .map((routeNode) => {\n return `'${removeTrailingUnderscores(routeNode.routePath)}': {\n preLoaderRoute: typeof ${routeNode.variableName}Import\n parentRoute: typeof ${\n routeNode.parent?.variableName\n ? `${routeNode.parent?.variableName}Import`\n : 'rootRoute'\n }\n }`\n })\n .join('\\n')}\n }\n}`,\n ]),\n '// Create and export the route tree',\n `export const routeTree = rootRoute.addChildren([${routeConfigChildrenText}])`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const routeConfigFileContent = await prettier.format(routeImports, {\n semi: false,\n singleQuote: config.quoteStyle === 'single',\n parser: 'typescript',\n })\n\n const routeTreeContent = await fs\n .readFile(path.resolve(config.generatedRouteTree), 'utf-8')\n .catch((err: any) => {\n if (err.code === 'ENOENT') {\n return undefined\n }\n throw err\n })\n\n if (!checkLatest()) return\n\n if (routeTreeContent !== routeConfigFileContent) {\n await fs.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {\n recursive: true,\n })\n if (!checkLatest()) return\n await fs.writeFile(\n path.resolve(config.generatedRouteTree),\n routeConfigFileContent,\n )\n }\n\n console.log(\n `🌲 Processed ${routeNodes.length} routes in ${Date.now() - start}ms`,\n )\n}\n\nfunction routePathToVariable(d: string): string {\n return (\n removeUnderscores(d)\n ?.replace(/\\/\\$\\//g, '/splat/')\n ?.replace(/\\$$/g, 'splat')\n ?.replace(/\\$/g, '')\n ?.split(/[/-]/g)\n .map((d, i) => (i > 0 ? capitalize(d) : d))\n .join('')\n .replace(/([^a-zA-Z0-9]|[\\.])/gm, '') ?? ''\n )\n}\n\nexport function removeExt(d: string) {\n return d.substring(0, d.lastIndexOf('.')) || d\n}\n\nfunction spaces(d: number): string {\n return Array.from({ length: d })\n .map(() => ' ')\n .join('')\n}\n\nexport function multiSortBy<T>(\n arr: T[],\n accessors: ((item: T) => any)[] = [(d) => d],\n): T[] {\n return arr\n .map((d, i) => [d, i] as const)\n .sort(([a, ai], [b, bi]) => {\n for (const accessor of accessors) {\n const ao = accessor(a)\n const bo = accessor(b)\n\n if (typeof ao === 'undefined') {\n if (typeof bo === 'undefined') {\n continue\n }\n return 1\n }\n\n if (ao === bo) {\n continue\n }\n\n return ao > bo ? 1 : -1\n }\n\n return ai - bi\n })\n .map(([d]) => d)\n}\n\nfunction capitalize(s: string) {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nfunction removeUnderscores(s?: string) {\n return s?.replace(/(^_|_$)/, '').replace(/(\\/_|_\\/)/, '/')\n}\n\nfunction removeTrailingUnderscores(s?: string) {\n return s?.replace(/(_$)/, '').replace(/(_\\/)/, '/')\n}\n\nfunction replaceBackslash(s: string) {\n return s.replace(/\\\\/gi, '/')\n}\n\nexport function hasParentRoute(\n routes: RouteNode[],\n routePathToCheck: string | undefined,\n): RouteNode | null {\n if (!routePathToCheck || routePathToCheck === '/') {\n return null\n }\n\n const sortedNodes = multiSortBy(routes, [\n (d) => d.routePath!.length * -1,\n (d) => d.variableName,\n ]).filter((d) => d.routePath !== `/${rootPathId}`)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, parentRoutePath)\n}\n"],"names":["first","d"],"mappings":";;;;AAMA,IAAI,aAAa;AACV,MAAM,aAAa;AAsB1B,eAAe,cAAc,QAAgB;AACrC,QAAA,EAAE,iBAAiB,sBAA0B,IAAA;AAEnD,MAAI,aAA0B,CAAA;AAE9B,iBAAe,QAAQ,KAAa;AAClC,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AACrC,SAAO,uBAAG,QAAQ,WAAW,IAAI,QAAQ,aAAa;AACxD;AAEA,SAAS,0BAA0B,GAAY;AAC7C,SAAO,uBAAG,QAAQ,QAAQ,IAAI,QAAQ,SAAS;AACjD;AAEA,SAAS,iBAAiB,GAAW;AAC5B,SAAA,EAAE,QAAQ,QAAQ,GAAG;AAC9B;AAEgB,SAAA,eACd,QACA,kBACkB;AACd,MAAA,CAAC,oBAAoB,qBAAqB,KAAK;AAC1C,WAAA;AAAA,EACT;AAEM,QAAA,cAAc,YAAY,QAAQ;AAAA,IACtC,CAAC,MAAM,EAAE,UAAW,SAAS;AAAA,IAC7B,CAAC,MAAM,EAAE;AAAA,EAAA,CACV,EAAE,OAAO,CAAC,MAAM,EAAE,cAAc,IAAI,UAAU,EAAE;AAEjD,aAAW,SAAS,aAAa;AAC/B,QAAI,MAAM,cAAc;AAAK;AAG3B,QAAA,iBAAiB,WAAW,GAAG,MAAM,SAAS,GAAG,KACjD,MAAM,cAAc,kBACpB;AACO,aAAA;AAAA,IACT;AAAA,EACF;AACM,QAAA,WAAW,iBAAiB,MAAM,GAAG;AAC3C,WAAS,IAAI;AACP,QAAA,kBAAkB,SAAS,KAAK,GAAG;AAElC,SAAA,eAAe,QAAQ,eAAe;AAC/C;"}
|
|
1
|
+
{"version":3,"file":"generator.js","sources":["../../src/generator.ts"],"sourcesContent":["import path from 'path'\nimport * as fs from 'fs'\nimport * as fsp from 'fs/promises'\nimport * as prettier from 'prettier'\nimport { Config } from './config'\nimport { cleanPath, trimPathLeft } from './utils'\n\nlet latestTask = 0\nexport const rootPathId = '__root'\n\nexport type RouteNode = {\n filePath: string\n fullPath: string\n variableName: string\n routePath?: string\n cleanedPath?: string\n path?: string\n isNonPath?: boolean\n isNonLayout?: boolean\n isRoute?: boolean\n isLoader?: boolean\n isComponent?: boolean\n isErrorComponent?: boolean\n isPendingComponent?: boolean\n isVirtual?: boolean\n isLazy?: boolean\n isRoot?: boolean\n children?: RouteNode[]\n parent?: RouteNode\n}\n\nasync function getRouteNodes(config: Config) {\n const { routeFilePrefix, routeFileIgnorePrefix } = config\n\n let routeNodes: RouteNode[] = []\n\n async function recurse(dir: string) {\n const fullDir = path.resolve(config.routesDirectory, dir)\n let dirList = await fsp.readdir(fullDir, { withFileTypes: true })\n\n dirList = dirList.filter((d) => {\n if (\n d.name.startsWith('.') ||\n (routeFileIgnorePrefix && d.name.startsWith(routeFileIgnorePrefix))\n ) {\n return false\n }\n\n if (routeFilePrefix) {\n return d.name.startsWith(routeFilePrefix)\n }\n\n return true\n })\n\n await Promise.all(\n dirList.map(async (dirent) => {\n const fullPath = path.join(fullDir, dirent.name)\n const relativePath = path.join(dir, dirent.name)\n\n if (dirent.isDirectory()) {\n await recurse(relativePath)\n } else if (fullPath.match(/\\.(tsx|ts|jsx|js)$/)) {\n const filePath = replaceBackslash(path.join(dir, dirent.name))\n const filePathNoExt = removeExt(filePath)\n let routePath =\n cleanPath(`/${filePathNoExt.split('.').join('/')}`) || ''\n const variableName = routePathToVariable(routePath)\n\n // Remove the index from the route path and\n // if the route path is empty, use `/'\n\n let isRoute = routePath?.endsWith('/route')\n let isComponent = routePath?.endsWith('/component')\n let isErrorComponent = routePath?.endsWith('/errorComponent')\n let isPendingComponent = routePath?.endsWith('/pendingComponent')\n let isLoader = routePath?.endsWith('/loader')\n let isLazy = routePath?.endsWith('/lazy')\n\n ;(\n [\n [isComponent, 'component'],\n [isErrorComponent, 'errorComponent'],\n [isPendingComponent, 'pendingComponent'],\n [isLoader, 'loader'],\n ] as const\n ).forEach(([isType, type]) => {\n if (isType) {\n console.warn(\n `WARNING: The \\`.${type}.tsx\\` suffix used for the ${filePath} file is deprecated. Use the new \\`.lazy.tsx\\` suffix instead.`,\n )\n }\n })\n\n routePath = routePath?.replace(\n /\\/(component|errorComponent|pendingComponent|loader|route|lazy)$/,\n '',\n )\n\n if (routePath === 'index') {\n routePath = '/'\n }\n\n routePath = routePath.replace(/\\/index$/, '/') || '/'\n\n routeNodes.push({\n filePath,\n fullPath,\n routePath,\n variableName,\n isRoute,\n isComponent,\n isErrorComponent,\n isPendingComponent,\n isLoader,\n isLazy,\n })\n }\n }),\n )\n\n return routeNodes\n }\n\n await recurse('./')\n\n return routeNodes\n}\n\nlet first = false\nlet skipMessage = false\n\ntype RouteSubNode = {\n component?: RouteNode\n errorComponent?: RouteNode\n pendingComponent?: RouteNode\n loader?: RouteNode\n lazy?: RouteNode\n}\n\nexport async function generator(config: Config) {\n console.log()\n\n if (!first) {\n console.log('🔄 Generating routes...')\n first = true\n } else if (skipMessage) {\n skipMessage = false\n } else {\n console.log('♻️ Regenerating routes...')\n }\n\n const taskId = latestTask + 1\n latestTask = taskId\n\n const checkLatest = () => {\n if (latestTask !== taskId) {\n skipMessage = true\n return false\n }\n\n return true\n }\n\n const start = Date.now()\n const routePathIdPrefix = config.routeFilePrefix ?? ''\n\n const preRouteNodes = multiSortBy(await getRouteNodes(config), [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.filePath?.match(/[./]index[.]/) ? 1 : -1),\n (d) =>\n d.filePath?.match(\n /[./](component|errorComponent|pendingComponent|loader|lazy)[.]/,\n )\n ? 1\n : -1,\n (d) => (d.filePath?.match(/[./]route[.]/) ? -1 : 1),\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter(\n (d) => ![`/${routePathIdPrefix + rootPathId}`].includes(d.routePath || ''),\n )\n\n const routeTree: RouteNode[] = []\n const routePiecesByPath: Record<string, RouteSubNode> = {}\n\n // Loop over the flat list of routeNodes and\n // build up a tree based on the routeNodes' routePath\n let routeNodes: RouteNode[] = []\n\n const handleNode = async (node: RouteNode) => {\n const parentRoute = hasParentRoute(routeNodes, node.routePath)\n if (parentRoute) node.parent = parentRoute\n\n node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath!, '') || '/'\n : node.routePath\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath?.split('/') ?? []\n let first = split[0] ?? trimmedPath ?? ''\n\n node.isNonPath = first.startsWith('_')\n node.isNonLayout = first.endsWith('_')\n node.cleanedPath = removeUnderscores(node.path) ?? ''\n\n // Ensure the boilerplate for the route exists\n const routeCode = fs.readFileSync(node.fullPath, 'utf-8')\n\n const escapedRoutePath = removeTrailingUnderscores(\n node.routePath?.replaceAll('$', '$$') ?? '',\n )\n\n let replaced = routeCode\n\n if (!routeCode) {\n if (node.isLazy) {\n replaced = [\n `import { createLazyFileRoute } from '@tanstack/react-router'`,\n `export const Route = createLazyFileRoute('${escapedRoutePath}')({\n component: () => <div>Hello ${escapedRoutePath}!</div>\n})`,\n ].join('\\n\\n')\n } else if (\n node.isRoute ||\n (!node.isComponent &&\n !node.isErrorComponent &&\n !node.isPendingComponent &&\n !node.isLoader)\n ) {\n replaced = [\n `import { createFileRoute } from '@tanstack/react-router'`,\n `export const Route = createFileRoute('${escapedRoutePath}')({\n component: () => <div>Hello ${escapedRoutePath}!</div>\n})`,\n ].join('\\n\\n')\n }\n } else {\n replaced = routeCode\n .replace(\n /(FileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n .replace(\n /(createFileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n .replace(\n /(createLazyFileRoute\\(\\s*['\"])([^\\s]+)(['\"](?:,?)\\s*\\))/g,\n (match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,\n )\n }\n\n if (replaced !== routeCode) {\n console.log(`🌲 Updating ${node.fullPath}`)\n await fsp.writeFile(node.fullPath, replaced)\n }\n\n if (\n !node.isVirtual &&\n (node.isLoader ||\n node.isComponent ||\n node.isErrorComponent ||\n node.isPendingComponent ||\n node.isLazy)\n ) {\n routePiecesByPath[node.routePath!] =\n routePiecesByPath[node.routePath!] || {}\n\n routePiecesByPath[node.routePath!]![\n node.isLazy\n ? 'lazy'\n : node.isLoader\n ? 'loader'\n : node.isErrorComponent\n ? 'errorComponent'\n : node.isPendingComponent\n ? 'pendingComponent'\n : 'component'\n ] = node\n\n const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath)\n\n if (!anchorRoute) {\n handleNode({\n ...node,\n isVirtual: true,\n isLazy: false,\n isLoader: false,\n isComponent: false,\n isErrorComponent: false,\n isPendingComponent: false,\n })\n }\n return\n }\n\n if (node.parent) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n } else {\n routeTree.push(node)\n }\n\n routeNodes.push(node)\n }\n\n preRouteNodes.forEach((node) => handleNode(node))\n\n async function buildRouteConfig(\n nodes: RouteNode[],\n depth = 1,\n ): Promise<string> {\n const children = nodes.map(async (node) => {\n if (node.isRoot) {\n return\n }\n\n const route = `${node.variableName}Route`\n\n if (node.children?.length) {\n const childConfigs = await buildRouteConfig(node.children, depth + 1)\n return `${route}.addChildren([${spaces(depth * 4)}${childConfigs}])`\n }\n\n return route\n })\n\n return (await Promise.all(children)).filter(Boolean).join(`,`)\n }\n\n const routeConfigChildrenText = await buildRouteConfig(routeTree)\n\n const sortedRouteNodes = multiSortBy(routeNodes, [\n (d) =>\n d.routePath?.includes(`/${routePathIdPrefix + rootPathId}`) ? -1 : 1,\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(\"index'\") ? -1 : 1),\n (d) => d,\n ])\n\n const imports = Object.entries({\n createFileRoute: sortedRouteNodes.some((d) => d.isVirtual),\n lazyFn: sortedRouteNodes.some(\n (node) => routePiecesByPath[node.routePath!]?.loader,\n ),\n lazyRouteComponent: sortedRouteNodes.some(\n (node) =>\n routePiecesByPath[node.routePath!]?.component ||\n routePiecesByPath[node.routePath!]?.errorComponent ||\n routePiecesByPath[node.routePath!]?.pendingComponent,\n ),\n })\n .filter((d) => d[1])\n .map((d) => d[0])\n\n const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual)\n\n const routeImports = [\n '// This file is auto-generated by TanStack Router',\n imports.length\n ? `import { ${imports.join(', ')} } from '@tanstack/react-router'\\n`\n : '',\n '// Import Routes',\n [\n `import { Route as rootRoute } from './${replaceBackslash(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, routePathIdPrefix + rootPathId),\n ),\n )}'`,\n ...sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .map((node) => {\n return `import { Route as ${\n node.variableName\n }Import } from './${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n ),\n )}'`\n }),\n ].join('\\n'),\n virtualRouteNodes.length ? '// Create Virtual Routes' : '',\n virtualRouteNodes\n .map((node) => {\n return `const ${\n node.variableName\n }Import = createFileRoute('${removeTrailingUnderscores(\n node.routePath,\n )}')()`\n })\n .join('\\n'),\n '// Create/Update Routes',\n sortedRouteNodes\n .map((node) => {\n const loaderNode = routePiecesByPath[node.routePath!]?.loader\n const componentNode = routePiecesByPath[node.routePath!]?.component\n const errorComponentNode =\n routePiecesByPath[node.routePath!]?.errorComponent\n const pendingComponentNode =\n routePiecesByPath[node.routePath!]?.pendingComponent\n const lazyComponentNode = routePiecesByPath[node.routePath!]?.lazy\n\n return [\n `const ${node.variableName}Route = ${node.variableName}Import.update({\n ${[\n node.isNonPath\n ? `id: '${node.path}'`\n : `path: '${node.cleanedPath}'`,\n `getParentRoute: () => ${node.parent?.variableName ?? 'root'}Route`,\n ]\n .filter(Boolean)\n .join(',')}\n }${config.disableTypes ? '' : 'as any'})`,\n loaderNode\n ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, loaderNode.filePath),\n ),\n ),\n )}'), 'loader') })`\n : '',\n componentNode || errorComponentNode || pendingComponentNode\n ? `.update({\n ${(\n [\n ['component', componentNode],\n ['errorComponent', errorComponentNode],\n ['pendingComponent', pendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n return `${\n d[0]\n }: lazyRouteComponent(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, d[1]!.filePath),\n ),\n ),\n )}'), '${d[0]}')`\n })\n .join('\\n,')}\n })`\n : '',\n lazyComponentNode\n ? `.lazy(() => import('./${replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n lazyComponentNode!.filePath,\n ),\n ),\n ),\n )}').then((d) => d.Route))`\n : '',\n ].join('')\n })\n .join('\\n\\n'),\n ...(config.disableTypes\n ? []\n : [\n '// Populate the FileRoutesByPath interface',\n `declare module '@tanstack/react-router' {\n interface FileRoutesByPath {\n ${routeNodes\n .map((routeNode) => {\n return `'${removeTrailingUnderscores(routeNode.routePath)}': {\n preLoaderRoute: typeof ${routeNode.variableName}Import\n parentRoute: typeof ${\n routeNode.parent?.variableName\n ? `${routeNode.parent?.variableName}Import`\n : 'rootRoute'\n }\n }`\n })\n .join('\\n')}\n }\n}`,\n ]),\n '// Create and export the route tree',\n `export const routeTree = rootRoute.addChildren([${routeConfigChildrenText}])`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n const routeConfigFileContent = await prettier.format(routeImports, {\n semi: false,\n singleQuote: config.quoteStyle === 'single',\n parser: 'typescript',\n })\n\n const routeTreeContent = await fsp\n .readFile(path.resolve(config.generatedRouteTree), 'utf-8')\n .catch((err: any) => {\n if (err.code === 'ENOENT') {\n return undefined\n }\n throw err\n })\n\n if (!checkLatest()) return\n\n if (routeTreeContent !== routeConfigFileContent) {\n await fsp.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {\n recursive: true,\n })\n if (!checkLatest()) return\n await fsp.writeFile(\n path.resolve(config.generatedRouteTree),\n routeConfigFileContent,\n )\n }\n\n console.log(\n `🌲 Processed ${routeNodes.length} routes in ${Date.now() - start}ms`,\n )\n}\n\nfunction routePathToVariable(d: string): string {\n return (\n removeUnderscores(d)\n ?.replace(/\\/\\$\\//g, '/splat/')\n ?.replace(/\\$$/g, 'splat')\n ?.replace(/\\$/g, '')\n ?.split(/[/-]/g)\n .map((d, i) => (i > 0 ? capitalize(d) : d))\n .join('')\n .replace(/([^a-zA-Z0-9]|[\\.])/gm, '') ?? ''\n )\n}\n\nexport function removeExt(d: string) {\n return d.substring(0, d.lastIndexOf('.')) || d\n}\n\nfunction spaces(d: number): string {\n return Array.from({ length: d })\n .map(() => ' ')\n .join('')\n}\n\nexport function multiSortBy<T>(\n arr: T[],\n accessors: ((item: T) => any)[] = [(d) => d],\n): T[] {\n return arr\n .map((d, i) => [d, i] as const)\n .sort(([a, ai], [b, bi]) => {\n for (const accessor of accessors) {\n const ao = accessor(a)\n const bo = accessor(b)\n\n if (typeof ao === 'undefined') {\n if (typeof bo === 'undefined') {\n continue\n }\n return 1\n }\n\n if (ao === bo) {\n continue\n }\n\n return ao > bo ? 1 : -1\n }\n\n return ai - bi\n })\n .map(([d]) => d)\n}\n\nfunction capitalize(s: string) {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nfunction removeUnderscores(s?: string) {\n return s?.replace(/(^_|_$)/, '').replace(/(\\/_|_\\/)/, '/')\n}\n\nfunction removeTrailingUnderscores(s?: string) {\n return s?.replace(/(_$)/, '').replace(/(_\\/)/, '/')\n}\n\nfunction replaceBackslash(s: string) {\n return s.replace(/\\\\/gi, '/')\n}\n\nexport function hasParentRoute(\n routes: RouteNode[],\n routePathToCheck: string | undefined,\n): RouteNode | null {\n if (!routePathToCheck || routePathToCheck === '/') {\n return null\n }\n\n const sortedNodes = multiSortBy(routes, [\n (d) => d.routePath!.length * -1,\n (d) => d.variableName,\n ]).filter((d) => d.routePath !== `/${rootPathId}`)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, parentRoutePath)\n}\n"],"names":["first","d"],"mappings":";;;;;AAOA,IAAI,aAAa;AACV,MAAM,aAAa;AAuB1B,eAAe,cAAc,QAAgB;AACrC,QAAA,EAAE,iBAAiB,sBAA0B,IAAA;AAEnD,MAAI,aAA0B,CAAA;AAE9B,iBAAe,QAAQ,KAAa;AAClC,UAAM,UAAU,KAAK,QAAQ,OAAO,iBAAiB,GAAG;AACpD,QAAA,UAAU,MAAM,IAAI,QAAQ,SAAS,EAAE,eAAe,MAAM;AAEtD,cAAA,QAAQ,OAAO,CAAC,MAAM;AAE5B,UAAA,EAAE,KAAK,WAAW,GAAG,KACpB,yBAAyB,EAAE,KAAK,WAAW,qBAAqB,GACjE;AACO,eAAA;AAAA,MACT;AAEA,UAAI,iBAAiB;AACZ,eAAA,EAAE,KAAK,WAAW,eAAe;AAAA,MAC1C;AAEO,aAAA;AAAA,IAAA,CACR;AAED,UAAM,QAAQ;AAAA,MACZ,QAAQ,IAAI,OAAO,WAAW;AAC5B,cAAM,WAAW,KAAK,KAAK,SAAS,OAAO,IAAI;AAC/C,cAAM,eAAe,KAAK,KAAK,KAAK,OAAO,IAAI;AAE3C,YAAA,OAAO,eAAe;AACxB,gBAAM,QAAQ,YAAY;AAAA,QACjB,WAAA,SAAS,MAAM,oBAAoB,GAAG;AAC/C,gBAAM,WAAW,iBAAiB,KAAK,KAAK,KAAK,OAAO,IAAI,CAAC;AACvD,gBAAA,gBAAgB,UAAU,QAAQ;AACpC,cAAA,YACF,UAAU,IAAI,cAAc,MAAM,GAAG,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK;AACnD,gBAAA,eAAe,oBAAoB,SAAS;AAK9C,cAAA,UAAU,uCAAW,SAAS;AAC9B,cAAA,cAAc,uCAAW,SAAS;AAClC,cAAA,mBA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
@@ -13,19 +13,25 @@ export const configSchema = z.object({
|
|
|
13
13
|
|
|
14
14
|
export type Config = z.infer<typeof configSchema>
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
export async function getConfig(
|
|
17
|
+
inlineConfig: Partial<Config> = {},
|
|
18
|
+
configDirectory?: string,
|
|
19
|
+
): Promise<Config> {
|
|
20
|
+
if (configDirectory === undefined) {
|
|
21
|
+
configDirectory = process.cwd()
|
|
22
|
+
}
|
|
23
|
+
const configFilePathJson = path.resolve(configDirectory, 'tsr.config.json')
|
|
19
24
|
const exists = existsSync(configFilePathJson)
|
|
20
25
|
|
|
21
26
|
let config: Config
|
|
22
27
|
|
|
23
28
|
if (exists) {
|
|
24
|
-
config = configSchema.parse(
|
|
25
|
-
JSON.parse(readFileSync(configFilePathJson, 'utf-8')),
|
|
26
|
-
|
|
29
|
+
config = configSchema.parse({
|
|
30
|
+
...JSON.parse(readFileSync(configFilePathJson, 'utf-8')),
|
|
31
|
+
...inlineConfig,
|
|
32
|
+
})
|
|
27
33
|
} else {
|
|
28
|
-
config = configSchema.parse(
|
|
34
|
+
config = configSchema.parse(inlineConfig)
|
|
29
35
|
}
|
|
30
36
|
|
|
31
37
|
// If typescript is disabled, make sure the generated route tree is a .js file
|
package/src/generator.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from 'path'
|
|
2
|
-
import * as fs from 'fs
|
|
2
|
+
import * as fs from 'fs'
|
|
3
|
+
import * as fsp from 'fs/promises'
|
|
3
4
|
import * as prettier from 'prettier'
|
|
4
5
|
import { Config } from './config'
|
|
5
6
|
import { cleanPath, trimPathLeft } from './utils'
|
|
@@ -22,6 +23,7 @@ export type RouteNode = {
|
|
|
22
23
|
isErrorComponent?: boolean
|
|
23
24
|
isPendingComponent?: boolean
|
|
24
25
|
isVirtual?: boolean
|
|
26
|
+
isLazy?: boolean
|
|
25
27
|
isRoot?: boolean
|
|
26
28
|
children?: RouteNode[]
|
|
27
29
|
parent?: RouteNode
|
|
@@ -34,7 +36,7 @@ async function getRouteNodes(config: Config) {
|
|
|
34
36
|
|
|
35
37
|
async function recurse(dir: string) {
|
|
36
38
|
const fullDir = path.resolve(config.routesDirectory, dir)
|
|
37
|
-
let dirList = await
|
|
39
|
+
let dirList = await fsp.readdir(fullDir, { withFileTypes: true })
|
|
38
40
|
|
|
39
41
|
dirList = dirList.filter((d) => {
|
|
40
42
|
if (
|
|
@@ -73,9 +75,25 @@ async function getRouteNodes(config: Config) {
|
|
|
73
75
|
let isErrorComponent = routePath?.endsWith('/errorComponent')
|
|
74
76
|
let isPendingComponent = routePath?.endsWith('/pendingComponent')
|
|
75
77
|
let isLoader = routePath?.endsWith('/loader')
|
|
78
|
+
let isLazy = routePath?.endsWith('/lazy')
|
|
79
|
+
|
|
80
|
+
;(
|
|
81
|
+
[
|
|
82
|
+
[isComponent, 'component'],
|
|
83
|
+
[isErrorComponent, 'errorComponent'],
|
|
84
|
+
[isPendingComponent, 'pendingComponent'],
|
|
85
|
+
[isLoader, 'loader'],
|
|
86
|
+
] as const
|
|
87
|
+
).forEach(([isType, type]) => {
|
|
88
|
+
if (isType) {
|
|
89
|
+
console.warn(
|
|
90
|
+
`WARNING: The \`.${type}.tsx\` suffix used for the ${filePath} file is deprecated. Use the new \`.lazy.tsx\` suffix instead.`,
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
})
|
|
76
94
|
|
|
77
95
|
routePath = routePath?.replace(
|
|
78
|
-
/\/(component|errorComponent|pendingComponent|loader|route)$/,
|
|
96
|
+
/\/(component|errorComponent|pendingComponent|loader|route|lazy)$/,
|
|
79
97
|
'',
|
|
80
98
|
)
|
|
81
99
|
|
|
@@ -95,6 +113,7 @@ async function getRouteNodes(config: Config) {
|
|
|
95
113
|
isErrorComponent,
|
|
96
114
|
isPendingComponent,
|
|
97
115
|
isLoader,
|
|
116
|
+
isLazy,
|
|
98
117
|
})
|
|
99
118
|
}
|
|
100
119
|
}),
|
|
@@ -116,6 +135,7 @@ type RouteSubNode = {
|
|
|
116
135
|
errorComponent?: RouteNode
|
|
117
136
|
pendingComponent?: RouteNode
|
|
118
137
|
loader?: RouteNode
|
|
138
|
+
lazy?: RouteNode
|
|
119
139
|
}
|
|
120
140
|
|
|
121
141
|
export async function generator(config: Config) {
|
|
@@ -151,7 +171,7 @@ export async function generator(config: Config) {
|
|
|
151
171
|
(d) => (d.filePath?.match(/[./]index[.]/) ? 1 : -1),
|
|
152
172
|
(d) =>
|
|
153
173
|
d.filePath?.match(
|
|
154
|
-
/[./](component|errorComponent|pendingComponent|loader)[.]/,
|
|
174
|
+
/[./](component|errorComponent|pendingComponent|loader|lazy)[.]/,
|
|
155
175
|
)
|
|
156
176
|
? 1
|
|
157
177
|
: -1,
|
|
@@ -169,7 +189,7 @@ export async function generator(config: Config) {
|
|
|
169
189
|
// build up a tree based on the routeNodes' routePath
|
|
170
190
|
let routeNodes: RouteNode[] = []
|
|
171
191
|
|
|
172
|
-
const handleNode = (node: RouteNode) => {
|
|
192
|
+
const handleNode = async (node: RouteNode) => {
|
|
173
193
|
const parentRoute = hasParentRoute(routeNodes, node.routePath)
|
|
174
194
|
if (parentRoute) node.parent = parentRoute
|
|
175
195
|
|
|
@@ -184,27 +204,81 @@ export async function generator(config: Config) {
|
|
|
184
204
|
|
|
185
205
|
node.isNonPath = first.startsWith('_')
|
|
186
206
|
node.isNonLayout = first.endsWith('_')
|
|
187
|
-
|
|
188
207
|
node.cleanedPath = removeUnderscores(node.path) ?? ''
|
|
189
208
|
|
|
209
|
+
// Ensure the boilerplate for the route exists
|
|
210
|
+
const routeCode = fs.readFileSync(node.fullPath, 'utf-8')
|
|
211
|
+
|
|
212
|
+
const escapedRoutePath = removeTrailingUnderscores(
|
|
213
|
+
node.routePath?.replaceAll('$', '$$') ?? '',
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
let replaced = routeCode
|
|
217
|
+
|
|
218
|
+
if (!routeCode) {
|
|
219
|
+
if (node.isLazy) {
|
|
220
|
+
replaced = [
|
|
221
|
+
`import { createLazyFileRoute } from '@tanstack/react-router'`,
|
|
222
|
+
`export const Route = createLazyFileRoute('${escapedRoutePath}')({
|
|
223
|
+
component: () => <div>Hello ${escapedRoutePath}!</div>
|
|
224
|
+
})`,
|
|
225
|
+
].join('\n\n')
|
|
226
|
+
} else if (
|
|
227
|
+
node.isRoute ||
|
|
228
|
+
(!node.isComponent &&
|
|
229
|
+
!node.isErrorComponent &&
|
|
230
|
+
!node.isPendingComponent &&
|
|
231
|
+
!node.isLoader)
|
|
232
|
+
) {
|
|
233
|
+
replaced = [
|
|
234
|
+
`import { createFileRoute } from '@tanstack/react-router'`,
|
|
235
|
+
`export const Route = createFileRoute('${escapedRoutePath}')({
|
|
236
|
+
component: () => <div>Hello ${escapedRoutePath}!</div>
|
|
237
|
+
})`,
|
|
238
|
+
].join('\n\n')
|
|
239
|
+
}
|
|
240
|
+
} else {
|
|
241
|
+
replaced = routeCode
|
|
242
|
+
.replace(
|
|
243
|
+
/(FileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
244
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,
|
|
245
|
+
)
|
|
246
|
+
.replace(
|
|
247
|
+
/(createFileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
248
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,
|
|
249
|
+
)
|
|
250
|
+
.replace(
|
|
251
|
+
/(createLazyFileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
252
|
+
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,
|
|
253
|
+
)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (replaced !== routeCode) {
|
|
257
|
+
console.log(`🌲 Updating ${node.fullPath}`)
|
|
258
|
+
await fsp.writeFile(node.fullPath, replaced)
|
|
259
|
+
}
|
|
260
|
+
|
|
190
261
|
if (
|
|
191
262
|
!node.isVirtual &&
|
|
192
263
|
(node.isLoader ||
|
|
193
264
|
node.isComponent ||
|
|
194
265
|
node.isErrorComponent ||
|
|
195
|
-
node.isPendingComponent
|
|
266
|
+
node.isPendingComponent ||
|
|
267
|
+
node.isLazy)
|
|
196
268
|
) {
|
|
197
269
|
routePiecesByPath[node.routePath!] =
|
|
198
270
|
routePiecesByPath[node.routePath!] || {}
|
|
199
271
|
|
|
200
272
|
routePiecesByPath[node.routePath!]![
|
|
201
|
-
node.
|
|
202
|
-
? '
|
|
203
|
-
: node.
|
|
204
|
-
? '
|
|
205
|
-
: node.
|
|
206
|
-
? '
|
|
207
|
-
:
|
|
273
|
+
node.isLazy
|
|
274
|
+
? 'lazy'
|
|
275
|
+
: node.isLoader
|
|
276
|
+
? 'loader'
|
|
277
|
+
: node.isErrorComponent
|
|
278
|
+
? 'errorComponent'
|
|
279
|
+
: node.isPendingComponent
|
|
280
|
+
? 'pendingComponent'
|
|
281
|
+
: 'component'
|
|
208
282
|
] = node
|
|
209
283
|
|
|
210
284
|
const anchorRoute = routeNodes.find((d) => d.routePath === node.routePath)
|
|
@@ -213,6 +287,7 @@ export async function generator(config: Config) {
|
|
|
213
287
|
handleNode({
|
|
214
288
|
...node,
|
|
215
289
|
isVirtual: true,
|
|
290
|
+
isLazy: false,
|
|
216
291
|
isLoader: false,
|
|
217
292
|
isComponent: false,
|
|
218
293
|
isErrorComponent: false,
|
|
@@ -239,31 +314,10 @@ export async function generator(config: Config) {
|
|
|
239
314
|
depth = 1,
|
|
240
315
|
): Promise<string> {
|
|
241
316
|
const children = nodes.map(async (node) => {
|
|
242
|
-
const routeCode = await fs.readFile(node.fullPath, 'utf-8')
|
|
243
|
-
|
|
244
|
-
// Ensure the boilerplate for the route exists
|
|
245
317
|
if (node.isRoot) {
|
|
246
318
|
return
|
|
247
319
|
}
|
|
248
320
|
|
|
249
|
-
// Ensure that new FileRoute(anything?) is replaced with FileRoute(${node.routePath})
|
|
250
|
-
// routePath can contain $ characters, which have special meaning when used in replace
|
|
251
|
-
// so we have to escape it by turning all $ into $$. But since we do it through a replace call
|
|
252
|
-
// we have to double escape it into $$$$. For more information, see
|
|
253
|
-
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement
|
|
254
|
-
const escapedRoutePath = removeTrailingUnderscores(
|
|
255
|
-
node.routePath?.replaceAll('$', '$$') ?? '',
|
|
256
|
-
)
|
|
257
|
-
const quote = config.quoteStyle === 'single' ? `'` : `"`
|
|
258
|
-
const replaced = routeCode.replace(
|
|
259
|
-
/(FileRoute\(\s*['"])([^\s]+)(['"](?:,?)\s*\))/g,
|
|
260
|
-
(match, p1, p2, p3) => `${p1}${escapedRoutePath}${p3}`,
|
|
261
|
-
)
|
|
262
|
-
|
|
263
|
-
if (replaced !== routeCode) {
|
|
264
|
-
await fs.writeFile(node.fullPath, replaced)
|
|
265
|
-
}
|
|
266
|
-
|
|
267
321
|
const route = `${node.variableName}Route`
|
|
268
322
|
|
|
269
323
|
if (node.children?.length) {
|
|
@@ -288,7 +342,7 @@ export async function generator(config: Config) {
|
|
|
288
342
|
])
|
|
289
343
|
|
|
290
344
|
const imports = Object.entries({
|
|
291
|
-
|
|
345
|
+
createFileRoute: sortedRouteNodes.some((d) => d.isVirtual),
|
|
292
346
|
lazyFn: sortedRouteNodes.some(
|
|
293
347
|
(node) => routePiecesByPath[node.routePath!]?.loader,
|
|
294
348
|
),
|
|
@@ -337,9 +391,9 @@ export async function generator(config: Config) {
|
|
|
337
391
|
.map((node) => {
|
|
338
392
|
return `const ${
|
|
339
393
|
node.variableName
|
|
340
|
-
}Import =
|
|
394
|
+
}Import = createFileRoute('${removeTrailingUnderscores(
|
|
341
395
|
node.routePath,
|
|
342
|
-
)}')
|
|
396
|
+
)}')()`
|
|
343
397
|
})
|
|
344
398
|
.join('\n'),
|
|
345
399
|
'// Create/Update Routes',
|
|
@@ -351,6 +405,7 @@ export async function generator(config: Config) {
|
|
|
351
405
|
routePiecesByPath[node.routePath!]?.errorComponent
|
|
352
406
|
const pendingComponentNode =
|
|
353
407
|
routePiecesByPath[node.routePath!]?.pendingComponent
|
|
408
|
+
const lazyComponentNode = routePiecesByPath[node.routePath!]?.lazy
|
|
354
409
|
|
|
355
410
|
return [
|
|
356
411
|
`const ${node.variableName}Route = ${node.variableName}Import.update({
|
|
@@ -398,6 +453,19 @@ export async function generator(config: Config) {
|
|
|
398
453
|
.join('\n,')}
|
|
399
454
|
})`
|
|
400
455
|
: '',
|
|
456
|
+
lazyComponentNode
|
|
457
|
+
? `.lazy(() => import('./${replaceBackslash(
|
|
458
|
+
removeExt(
|
|
459
|
+
path.relative(
|
|
460
|
+
path.dirname(config.generatedRouteTree),
|
|
461
|
+
path.resolve(
|
|
462
|
+
config.routesDirectory,
|
|
463
|
+
lazyComponentNode!.filePath,
|
|
464
|
+
),
|
|
465
|
+
),
|
|
466
|
+
),
|
|
467
|
+
)}').then((d) => d.Route))`
|
|
468
|
+
: '',
|
|
401
469
|
].join('')
|
|
402
470
|
})
|
|
403
471
|
.join('\n\n'),
|
|
@@ -434,7 +502,7 @@ export async function generator(config: Config) {
|
|
|
434
502
|
parser: 'typescript',
|
|
435
503
|
})
|
|
436
504
|
|
|
437
|
-
const routeTreeContent = await
|
|
505
|
+
const routeTreeContent = await fsp
|
|
438
506
|
.readFile(path.resolve(config.generatedRouteTree), 'utf-8')
|
|
439
507
|
.catch((err: any) => {
|
|
440
508
|
if (err.code === 'ENOENT') {
|
|
@@ -446,11 +514,11 @@ export async function generator(config: Config) {
|
|
|
446
514
|
if (!checkLatest()) return
|
|
447
515
|
|
|
448
516
|
if (routeTreeContent !== routeConfigFileContent) {
|
|
449
|
-
await
|
|
517
|
+
await fsp.mkdir(path.dirname(path.resolve(config.generatedRouteTree)), {
|
|
450
518
|
recursive: true,
|
|
451
519
|
})
|
|
452
520
|
if (!checkLatest()) return
|
|
453
|
-
await
|
|
521
|
+
await fsp.writeFile(
|
|
454
522
|
path.resolve(config.generatedRouteTree),
|
|
455
523
|
routeConfigFileContent,
|
|
456
524
|
)
|