@tanstack/start-plugin-core 1.121.0-alpha.25 → 1.121.0-alpha.26

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.
Files changed (102) hide show
  1. package/dist/cjs/compilers.cjs +24 -10
  2. package/dist/cjs/compilers.cjs.map +1 -1
  3. package/dist/cjs/debug.cjs +5 -0
  4. package/dist/cjs/debug.cjs.map +1 -0
  5. package/dist/cjs/debug.d.cts +1 -0
  6. package/dist/cjs/nitro-plugin/build-sitemap.cjs +3 -3
  7. package/dist/cjs/nitro-plugin/build-sitemap.cjs.map +1 -1
  8. package/dist/cjs/nitro-plugin/plugin.cjs +2 -2
  9. package/dist/cjs/nitro-plugin/plugin.cjs.map +1 -1
  10. package/dist/cjs/nitro-plugin/prerender.cjs +3 -3
  11. package/dist/cjs/nitro-plugin/prerender.cjs.map +1 -1
  12. package/dist/cjs/plugin.cjs +19 -30
  13. package/dist/cjs/plugin.cjs.map +1 -1
  14. package/dist/cjs/plugin.d.cts +2 -4
  15. package/dist/cjs/schema.cjs +5 -5
  16. package/dist/cjs/schema.cjs.map +1 -1
  17. package/dist/cjs/schema.d.cts +32 -16
  18. package/dist/cjs/start-compiler-plugin.cjs +19 -17
  19. package/dist/cjs/start-compiler-plugin.cjs.map +1 -1
  20. package/dist/cjs/start-manifest-plugin/plugin.cjs +207 -0
  21. package/dist/cjs/start-manifest-plugin/plugin.cjs.map +1 -0
  22. package/dist/cjs/start-manifest-plugin/plugin.d.cts +3 -0
  23. package/dist/cjs/start-router-plugin/generator-plugins/routes-manifest-plugin.cjs +39 -0
  24. package/dist/cjs/start-router-plugin/generator-plugins/routes-manifest-plugin.cjs.map +1 -0
  25. package/dist/cjs/start-router-plugin/generator-plugins/routes-manifest-plugin.d.cts +6 -0
  26. package/dist/cjs/start-router-plugin/generator-plugins/server-routes-plugin.cjs +121 -0
  27. package/dist/cjs/start-router-plugin/generator-plugins/server-routes-plugin.cjs.map +1 -0
  28. package/dist/cjs/start-router-plugin/generator-plugins/server-routes-plugin.d.cts +2 -0
  29. package/dist/cjs/start-router-plugin/plugin.cjs +21 -0
  30. package/dist/cjs/start-router-plugin/plugin.cjs.map +1 -0
  31. package/dist/cjs/start-router-plugin/plugin.d.cts +3 -0
  32. package/dist/cjs/start-router-plugin/route-tree-client-plugin.cjs +72 -0
  33. package/dist/cjs/start-router-plugin/route-tree-client-plugin.cjs.map +1 -0
  34. package/dist/cjs/start-router-plugin/route-tree-client-plugin.d.cts +6 -0
  35. package/dist/cjs/start-router-plugin/virtual-route-tree-plugin.cjs +30 -0
  36. package/dist/cjs/start-router-plugin/virtual-route-tree-plugin.cjs.map +1 -0
  37. package/dist/cjs/start-router-plugin/virtual-route-tree-plugin.d.cts +4 -0
  38. package/dist/esm/compilers.js +24 -10
  39. package/dist/esm/compilers.js.map +1 -1
  40. package/dist/esm/debug.d.ts +1 -0
  41. package/dist/esm/debug.js +5 -0
  42. package/dist/esm/debug.js.map +1 -0
  43. package/dist/esm/plugin.d.ts +2 -4
  44. package/dist/esm/plugin.js +10 -21
  45. package/dist/esm/plugin.js.map +1 -1
  46. package/dist/esm/schema.d.ts +32 -16
  47. package/dist/esm/start-compiler-plugin.js +19 -17
  48. package/dist/esm/start-compiler-plugin.js.map +1 -1
  49. package/dist/esm/start-manifest-plugin/plugin.d.ts +3 -0
  50. package/dist/esm/start-manifest-plugin/plugin.js +207 -0
  51. package/dist/esm/start-manifest-plugin/plugin.js.map +1 -0
  52. package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.d.ts +6 -0
  53. package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.js +39 -0
  54. package/dist/esm/start-router-plugin/generator-plugins/routes-manifest-plugin.js.map +1 -0
  55. package/dist/esm/start-router-plugin/generator-plugins/server-routes-plugin.d.ts +2 -0
  56. package/dist/esm/start-router-plugin/generator-plugins/server-routes-plugin.js +121 -0
  57. package/dist/esm/start-router-plugin/generator-plugins/server-routes-plugin.js.map +1 -0
  58. package/dist/esm/start-router-plugin/plugin.d.ts +3 -0
  59. package/dist/esm/start-router-plugin/plugin.js +21 -0
  60. package/dist/esm/start-router-plugin/plugin.js.map +1 -0
  61. package/dist/esm/start-router-plugin/route-tree-client-plugin.d.ts +6 -0
  62. package/dist/esm/start-router-plugin/route-tree-client-plugin.js +55 -0
  63. package/dist/esm/start-router-plugin/route-tree-client-plugin.js.map +1 -0
  64. package/dist/esm/start-router-plugin/virtual-route-tree-plugin.d.ts +4 -0
  65. package/dist/esm/start-router-plugin/virtual-route-tree-plugin.js +30 -0
  66. package/dist/esm/start-router-plugin/virtual-route-tree-plugin.js.map +1 -0
  67. package/package.json +6 -5
  68. package/src/compilers.ts +31 -131
  69. package/src/debug.ts +3 -0
  70. package/src/global.d.ts +8 -0
  71. package/src/plugin.ts +8 -24
  72. package/src/start-compiler-plugin.ts +24 -24
  73. package/src/start-manifest-plugin/plugin.ts +275 -0
  74. package/src/start-router-plugin/generator-plugins/routes-manifest-plugin.ts +43 -0
  75. package/src/start-router-plugin/generator-plugins/server-routes-plugin.ts +138 -0
  76. package/src/start-router-plugin/plugin.ts +35 -0
  77. package/src/start-router-plugin/route-tree-client-plugin.ts +76 -0
  78. package/src/start-router-plugin/virtual-route-tree-plugin.ts +30 -0
  79. package/dist/cjs/start-routes-manifest-plugin/plugin.cjs +0 -207
  80. package/dist/cjs/start-routes-manifest-plugin/plugin.cjs.map +0 -1
  81. package/dist/cjs/start-routes-manifest-plugin/plugin.d.cts +0 -3
  82. package/dist/cjs/start-server-routes-plugin/config.d.cts +0 -49
  83. package/dist/cjs/start-server-routes-plugin/plugin.cjs +0 -614
  84. package/dist/cjs/start-server-routes-plugin/plugin.cjs.map +0 -1
  85. package/dist/cjs/start-server-routes-plugin/plugin.d.cts +0 -3
  86. package/dist/cjs/start-server-routes-plugin/template.cjs +0 -111
  87. package/dist/cjs/start-server-routes-plugin/template.cjs.map +0 -1
  88. package/dist/cjs/start-server-routes-plugin/template.d.cts +0 -34
  89. package/dist/esm/start-routes-manifest-plugin/plugin.d.ts +0 -3
  90. package/dist/esm/start-routes-manifest-plugin/plugin.js +0 -207
  91. package/dist/esm/start-routes-manifest-plugin/plugin.js.map +0 -1
  92. package/dist/esm/start-server-routes-plugin/config.d.ts +0 -49
  93. package/dist/esm/start-server-routes-plugin/plugin.d.ts +0 -3
  94. package/dist/esm/start-server-routes-plugin/plugin.js +0 -614
  95. package/dist/esm/start-server-routes-plugin/plugin.js.map +0 -1
  96. package/dist/esm/start-server-routes-plugin/template.d.ts +0 -34
  97. package/dist/esm/start-server-routes-plugin/template.js +0 -111
  98. package/dist/esm/start-server-routes-plugin/template.js.map +0 -1
  99. package/src/start-routes-manifest-plugin/plugin.ts +0 -282
  100. package/src/start-server-routes-plugin/config.ts +0 -8
  101. package/src/start-server-routes-plugin/plugin.ts +0 -900
  102. package/src/start-server-routes-plugin/template.ts +0 -164
@@ -1,614 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const path = require("node:path");
4
- const fs = require("node:fs");
5
- const fsp = require("node:fs/promises");
6
- const routerGenerator = require("@tanstack/router-generator");
7
- const routerCore = require("@tanstack/router-core");
8
- const template = require("./template.cjs");
9
- let lock = false;
10
- const checkLock = () => lock;
11
- const setLock = (bool) => {
12
- lock = bool;
13
- };
14
- function TanStackStartServerRoutesVite(config) {
15
- let ROOT = process.cwd();
16
- const moduleId = "tanstack-start-server-routes-manifest:v";
17
- const getRoutesDirectoryPath = () => {
18
- return path.isAbsolute(config.routesDirectory) ? config.routesDirectory : path.join(ROOT, config.routesDirectory);
19
- };
20
- const generate = async () => {
21
- if (checkLock()) {
22
- return;
23
- }
24
- setLock(true);
25
- try {
26
- await generator(config, ROOT);
27
- } catch (err) {
28
- console.error(err);
29
- console.info();
30
- } finally {
31
- setLock(false);
32
- }
33
- };
34
- const handleFile = async (file) => {
35
- const filePath = path.normalize(file);
36
- const routesDirectoryPath = getRoutesDirectoryPath();
37
- if (filePath.startsWith(routesDirectoryPath)) {
38
- await generate();
39
- }
40
- };
41
- return {
42
- name: "tanstack-start-server-routes-plugin",
43
- configureServer(server) {
44
- server.watcher.on("all", (event, path2) => {
45
- handleFile(path2);
46
- });
47
- },
48
- configResolved(config2) {
49
- ROOT = config2.root;
50
- },
51
- async buildStart() {
52
- await generate();
53
- },
54
- sharedDuringBuild: true,
55
- resolveId(id) {
56
- if (id === moduleId) {
57
- const generatedRouteTreePath = getGeneratedRouteTreePath(ROOT);
58
- return generatedRouteTreePath;
59
- }
60
- return null;
61
- }
62
- };
63
- }
64
- let latestTask = 0;
65
- const routeGroupPatternRegex = /\(.+\)/g;
66
- const possiblyNestedRouteGroupPatternRegex = /\([^/]+\)\/?/g;
67
- function getGeneratedRouteTreePath(root) {
68
- return path.resolve(root, ".tanstack-start/server-routes/routeTree.gen.ts");
69
- }
70
- async function generator(config, root) {
71
- const generatedServerRouteTreePath = getGeneratedRouteTreePath(root);
72
- const ROUTE_TEMPLATE = template.getTargetTemplate(config.target);
73
- const logger = routerGenerator.logging({ disabled: config.disableLogging });
74
- const taskId = latestTask + 1;
75
- latestTask = taskId;
76
- const checkLatest = () => {
77
- if (latestTask !== taskId) {
78
- return false;
79
- }
80
- return true;
81
- };
82
- let getRouteNodesResult;
83
- if (config.virtualRouteConfig) {
84
- getRouteNodesResult = await routerGenerator.virtualGetRouteNodes(config, root);
85
- } else {
86
- getRouteNodesResult = await routerGenerator.physicalGetRouteNodes(config, root);
87
- }
88
- const { rootRouteNode, routeNodes: beforeRouteNodes } = getRouteNodesResult;
89
- if (rootRouteNode === void 0) {
90
- let errorMessage = `rootRouteNode must not be undefined. Make sure you've added your root route into the route-tree.`;
91
- if (!config.virtualRouteConfig) {
92
- errorMessage += `
93
- Make sure that you add a "${routerGenerator.rootPathId}.tsx" file to your routes directory.
94
- Add the file in: "${config.routesDirectory}/${routerGenerator.rootPathId}.tsx"`;
95
- }
96
- throw new Error(errorMessage);
97
- }
98
- const preRouteNodes = routerGenerator.multiSortBy(beforeRouteNodes, [
99
- (d) => d.routePath === "/" ? -1 : 1,
100
- (d) => {
101
- var _a;
102
- return (_a = d.routePath) == null ? void 0 : _a.split("/").length;
103
- },
104
- (d) => d.filePath.match(new RegExp(`[./]${config.indexToken}[.]`)) ? 1 : -1,
105
- (d) => d.filePath.match(
106
- /[./](component|errorComponent|pendingComponent|loader|lazy)[.]/
107
- ) ? 1 : -1,
108
- (d) => d.filePath.match(new RegExp(`[./]${config.routeToken}[.]`)) ? -1 : 1,
109
- (d) => {
110
- var _a;
111
- return ((_a = d.routePath) == null ? void 0 : _a.endsWith("/")) ? -1 : 1;
112
- },
113
- (d) => d.routePath
114
- ]).filter((d) => ![`/${routerGenerator.rootPathId}`].includes(d.routePath || ""));
115
- const routeTree = [];
116
- const routeNodes = [];
117
- const handleRootNode = async (node) => {
118
- if (!node) {
119
- return;
120
- }
121
- const routeCode = fs.readFileSync(node.fullPath, "utf-8");
122
- if (!routeCode) {
123
- const _rootTemplate = ROUTE_TEMPLATE.rootRoute;
124
- const replaced = await template.fillTemplate(config, _rootTemplate.template(), {
125
- tsrImports: _rootTemplate.imports.tsrImports(),
126
- tsrPath: routerGenerator.rootPathId,
127
- tsrExportStart: _rootTemplate.imports.tsrExportStart(),
128
- tsrExportEnd: _rootTemplate.imports.tsrExportEnd()
129
- });
130
- await routerGenerator.writeIfDifferent(
131
- node.fullPath,
132
- "",
133
- // Empty string because the file doesn't exist yet
134
- replaced,
135
- {
136
- beforeWrite: () => {
137
- }
138
- }
139
- );
140
- }
141
- };
142
- await handleRootNode(rootRouteNode);
143
- const handleNode = async (node) => {
144
- var _a;
145
- routerGenerator.resetRegex(routeGroupPatternRegex);
146
- let parentRoute = hasParentRoute(routeNodes, node, node.routePath);
147
- if ((parentRoute == null ? void 0 : parentRoute.isVirtualParentRoute) && ((_a = parentRoute.children) == null ? void 0 : _a.length)) {
148
- const possibleParentRoute = hasParentRoute(
149
- parentRoute.children,
150
- node,
151
- node.routePath
152
- );
153
- if (possibleParentRoute) {
154
- parentRoute = possibleParentRoute;
155
- }
156
- }
157
- if (parentRoute) node.parent = parentRoute;
158
- node.path = determineNodePath(node);
159
- const trimmedPath = routerGenerator.trimPathLeft(node.path ?? "");
160
- const split = trimmedPath.split("/");
161
- const lastRouteSegment = split[split.length - 1] ?? trimmedPath;
162
- node.isNonPath = lastRouteSegment.startsWith("_") || routeGroupPatternRegex.test(lastRouteSegment);
163
- node.cleanedPath = removeGroups(
164
- routerGenerator.removeUnderscores(removeLayoutSegments(node.path)) ?? ""
165
- );
166
- const stats = fs.statSync(node.fullPath);
167
- const routeCode = stats.isFile() ? fs.readFileSync(node.fullPath, "utf-8") : "";
168
- if (!node.isVirtualParentRoute && !node.isVirtual) ;
169
- const cleanedPathIsEmpty = (node.cleanedPath || "").length === 0;
170
- const nonPathRoute = node._fsRouteType === "pathless_layout" && node.isNonPath;
171
- node.isVirtualParentRequired = node._fsRouteType === "pathless_layout" || nonPathRoute ? !cleanedPathIsEmpty : false;
172
- if (!node.isVirtual && node.isVirtualParentRequired) {
173
- const parentRoutePath = removeLastSegmentFromPath(node.routePath) || "/";
174
- const parentVariableName = routerGenerator.routePathToVariable(parentRoutePath);
175
- const anchorRoute = routeNodes.find(
176
- (d) => d.routePath === parentRoutePath
177
- );
178
- if (!anchorRoute) {
179
- const parentNode = {
180
- ...node,
181
- path: removeLastSegmentFromPath(node.path) || "/",
182
- filePath: removeLastSegmentFromPath(node.filePath) || "/",
183
- fullPath: removeLastSegmentFromPath(node.fullPath) || "/",
184
- routePath: parentRoutePath,
185
- variableName: parentVariableName,
186
- isVirtual: true,
187
- _fsRouteType: "layout",
188
- // layout since this route will wrap other routes
189
- isVirtualParentRoute: true,
190
- isVirtualParentRequired: false
191
- };
192
- parentNode.children = parentNode.children ?? [];
193
- parentNode.children.push(node);
194
- node.parent = parentNode;
195
- if (node._fsRouteType === "pathless_layout") {
196
- node.path = determineNodePath(node);
197
- }
198
- await handleNode(parentNode);
199
- } else {
200
- anchorRoute.children = anchorRoute.children ?? [];
201
- anchorRoute.children.push(node);
202
- node.parent = anchorRoute;
203
- }
204
- }
205
- if (!routeCode.split("\n").some((line) => line.trim().startsWith("export const ServerRoute"))) {
206
- return;
207
- }
208
- if (node.parent) {
209
- if (!node.isVirtualParentRequired) {
210
- node.parent.children = node.parent.children ?? [];
211
- node.parent.children.push(node);
212
- }
213
- } else {
214
- routeTree.push(node);
215
- }
216
- routeNodes.push(node);
217
- };
218
- for (const node of preRouteNodes) {
219
- await handleNode(node);
220
- }
221
- checkRouteFullPathUniqueness(routeNodes, config);
222
- function buildRouteTreeConfig(nodes, depth = 1) {
223
- const children = nodes.map((node) => {
224
- var _a, _b;
225
- if (node._fsRouteType === "__root") {
226
- return;
227
- }
228
- if (node._fsRouteType === "pathless_layout" && !((_a = node.children) == null ? void 0 : _a.length)) {
229
- return;
230
- }
231
- const route = `${node.variableName}Route`;
232
- if ((_b = node.children) == null ? void 0 : _b.length) {
233
- const childConfigs = buildRouteTreeConfig(node.children, depth + 1);
234
- const childrenDeclaration = `interface ${route}Children {
235
- ${node.children.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(",")}
236
- }`;
237
- const children2 = `const ${route}Children: ${route}Children = {
238
- ${node.children.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(",")}
239
- }`;
240
- const routeWithChildren = `const ${route}WithChildren = ${route}._addFileChildren(${route}Children)`;
241
- return [
242
- childConfigs,
243
- childrenDeclaration,
244
- children2,
245
- routeWithChildren
246
- ].join("\n\n");
247
- }
248
- return void 0;
249
- });
250
- return children.filter(Boolean).join("\n\n");
251
- }
252
- const routeConfigChildrenText = buildRouteTreeConfig(routeTree);
253
- const sortedRouteNodes = routerGenerator.multiSortBy(routeNodes, [
254
- (d) => {
255
- var _a;
256
- return ((_a = d.routePath) == null ? void 0 : _a.includes(`/${routerGenerator.rootPathId}`)) ? -1 : 1;
257
- },
258
- (d) => {
259
- var _a;
260
- return (_a = d.routePath) == null ? void 0 : _a.split("/").length;
261
- },
262
- (d) => {
263
- var _a;
264
- return ((_a = d.routePath) == null ? void 0 : _a.endsWith(config.indexToken)) ? -1 : 1;
265
- },
266
- (d) => d
267
- ]);
268
- const imports = Object.entries({
269
- createFileRoute: sortedRouteNodes.some((d) => d.isVirtual)
270
- }).filter((d) => d[1]).map((d) => d[0]);
271
- const virtualRouteNodes = sortedRouteNodes.filter((d) => d.isVirtual);
272
- function getImportPath(node) {
273
- return routerGenerator.replaceBackslash(
274
- routerGenerator.removeExt(
275
- path.relative(
276
- path.dirname(generatedServerRouteTreePath),
277
- path.resolve(config.routesDirectory, node.filePath)
278
- )
279
- )
280
- );
281
- }
282
- const rootRouteExists = fs.existsSync(rootRouteNode.fullPath);
283
- const rootRouteCode = rootRouteExists ? fs.readFileSync(rootRouteNode.fullPath, "utf-8") : "";
284
- const hasServerRootRoute = rootRouteExists && rootRouteCode.includes("export const ServerRoute");
285
- const routeImports = [
286
- ...config.routeTreeFileHeader,
287
- `// This file was automatically generated by TanStack Router.
288
- // You should NOT make any changes in this file as it will be overwritten.
289
- // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`,
290
- imports.length ? `import { ${imports.join(", ")} } from '${ROUTE_TEMPLATE.fullPkg}'
291
- ` : "",
292
- "// Import Routes",
293
- [
294
- `import type { FileRoutesByPath, CreateServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,
295
- `import { createServerRoute, createServerFileRoute } from '${ROUTE_TEMPLATE.fullPkg}'`,
296
- hasServerRootRoute ? `import { ServerRoute as rootRouteImport } from './${getImportPath(rootRouteNode)}'` : "",
297
- ...sortedRouteNodes.filter((d) => !d.isVirtual).map((node) => {
298
- return `import { ServerRoute as ${node.variableName}RouteImport } from './${getImportPath(node)}'`;
299
- })
300
- ].join("\n"),
301
- virtualRouteNodes.length ? "// Create Virtual Routes" : "",
302
- virtualRouteNodes.map((node) => {
303
- return `const ${node.variableName}RouteImport = createFileRoute('${node.routePath}')()`;
304
- }).join("\n"),
305
- "// Create/Update Routes",
306
- !hasServerRootRoute ? `
307
- const rootRoute = createServerRoute()
308
- ` : "",
309
- sortedRouteNodes.map((node) => {
310
- var _a;
311
- return [
312
- [
313
- `const ${node.variableName}Route = ${node.variableName}RouteImport.update({
314
- ${[
315
- `id: '${node.path}'`,
316
- !node.isNonPath ? `path: '${node.cleanedPath}'` : void 0,
317
- `getParentRoute: () => ${((_a = node.parent) == null ? void 0 : _a.variableName) ?? "root"}Route`
318
- ].filter(Boolean).join(",")}
319
- } as any)`
320
- ].join("")
321
- ].join("\n\n");
322
- }).join("\n\n"),
323
- "",
324
- "// Populate the FileRoutesByPath interface",
325
- `declare module '${ROUTE_TEMPLATE.fullPkg}' {
326
- interface FileRoutesByPath {
327
- ${routeNodes.map((routeNode) => {
328
- var _a, _b;
329
- const filePathId = routeNode.routePath;
330
- return `'${filePathId}': {
331
- id: '${filePathId}'
332
- path: '${inferPath(routeNode)}'
333
- fullPath: '${inferFullPath(routeNode)}'
334
- preLoaderRoute: typeof ${routeNode.variableName}RouteImport
335
- parentRoute: typeof ${routeNode.isVirtualParentRequired ? `${(_a = routeNode.parent) == null ? void 0 : _a.variableName}Route` : ((_b = routeNode.parent) == null ? void 0 : _b.variableName) ? `${routeNode.parent.variableName}RouteImport` : "rootRoute"}
336
- }`;
337
- }).join("\n")}
338
- }
339
- }`,
340
- `// Add type-safety to the createFileRoute function across the route tree`,
341
- routeNodes.map((routeNode) => {
342
- var _a;
343
- return `declare module './${getImportPath(routeNode)}' {
344
- const createServerFileRoute: CreateServerFileRoute<
345
- FileRoutesByPath['${routeNode.routePath}']['parentRoute'],
346
- FileRoutesByPath['${routeNode.routePath}']['id'],
347
- FileRoutesByPath['${routeNode.routePath}']['path'],
348
- FileRoutesByPath['${routeNode.routePath}']['fullPath'],
349
- ${((_a = routeNode.children) == null ? void 0 : _a.length) ? `${routeNode.variableName}RouteChildren` : "unknown"}
350
- >
351
- }`;
352
- }).join("\n"),
353
- "// Create and export the route tree",
354
- routeConfigChildrenText,
355
- `export interface FileRoutesByFullPath {
356
- ${[...createRouteNodesByFullPath(routeNodes).entries()].map(
357
- ([fullPath, routeNode]) => {
358
- return `'${fullPath}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`;
359
- }
360
- )}
361
- }`,
362
- `export interface FileRoutesByTo {
363
- ${[...createRouteNodesByTo(routeNodes).entries()].map(([to, routeNode]) => {
364
- return `'${to}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`;
365
- })}
366
- }`,
367
- `export interface FileRoutesById {
368
- '${routerCore.rootRouteId}': typeof rootRoute,
369
- ${[...createRouteNodesById(routeNodes).entries()].map(([id, routeNode]) => {
370
- return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`;
371
- })}
372
- }`,
373
- `export interface FileRouteTypes {
374
- fileRoutesByFullPath: FileRoutesByFullPath
375
- fullPaths: ${routeNodes.length > 0 ? [...createRouteNodesByFullPath(routeNodes).keys()].map((fullPath) => `'${fullPath}'`).join("|") : "never"}
376
- fileRoutesByTo: FileRoutesByTo
377
- to: ${routeNodes.length > 0 ? [...createRouteNodesByTo(routeNodes).keys()].map((to) => `'${to}'`).join("|") : "never"}
378
- id: ${[`'${routerCore.rootRouteId}'`, ...[...createRouteNodesById(routeNodes).keys()].map((id) => `'${id}'`)].join("|")}
379
- fileRoutesById: FileRoutesById
380
- }`,
381
- `export interface RootRouteChildren {
382
- ${routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(",")}
383
- }`,
384
- `const rootRouteChildren: RootRouteChildren = {
385
- ${routeTree.map((child) => `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`).join(",")}
386
- }`,
387
- `export const routeTree = rootRoute._addFileChildren(rootRouteChildren)._addFileTypes<FileRouteTypes>()`
388
- ].filter(Boolean).join("\n\n");
389
- const createRouteManifest = () => {
390
- const routesManifest = {
391
- [routerCore.rootRouteId]: {
392
- filePath: rootRouteNode.filePath,
393
- children: routeTree.map((d) => d.routePath)
394
- },
395
- ...Object.fromEntries(
396
- routeNodes.map((d) => {
397
- var _a, _b;
398
- const filePathId = d.routePath;
399
- return [
400
- filePathId,
401
- {
402
- filePath: d.filePath,
403
- parent: ((_a = d.parent) == null ? void 0 : _a.routePath) ? d.parent.routePath : void 0,
404
- children: (_b = d.children) == null ? void 0 : _b.map((childRoute) => childRoute.routePath)
405
- }
406
- ];
407
- })
408
- )
409
- };
410
- return JSON.stringify(
411
- {
412
- routes: routesManifest
413
- },
414
- null,
415
- 2
416
- );
417
- };
418
- const includeManifest = ["react", "solid"];
419
- const routeConfigFileContent = !includeManifest.includes(config.target) ? routeImports : [
420
- routeImports,
421
- "\n",
422
- "/* ROUTE_MANIFEST_START",
423
- createRouteManifest(),
424
- "ROUTE_MANIFEST_END */"
425
- ].join("\n");
426
- if (!checkLatest()) return;
427
- const existingRouteTreeContent = await fsp.readFile(path.resolve(generatedServerRouteTreePath), "utf-8").catch((err) => {
428
- if (err.code === "ENOENT") {
429
- return "";
430
- }
431
- throw err;
432
- });
433
- if (!checkLatest()) return;
434
- await fsp.mkdir(path.dirname(path.resolve(generatedServerRouteTreePath)), {
435
- recursive: true
436
- });
437
- if (!checkLatest()) return;
438
- const routeTreeWriteResult = await routerGenerator.writeIfDifferent(
439
- path.resolve(generatedServerRouteTreePath),
440
- await routerGenerator.format(existingRouteTreeContent, config),
441
- await routerGenerator.format(routeConfigFileContent, config),
442
- {
443
- beforeWrite: () => {
444
- }
445
- }
446
- );
447
- const startDeclarationFilePath = path.join(
448
- path.resolve(root, config.srcDirectory),
449
- "tanstack-start.d.ts"
450
- );
451
- const serverRoutesRelativePath = routerGenerator.removeExt(
452
- path.relative(
453
- path.dirname(startDeclarationFilePath),
454
- generatedServerRouteTreePath
455
- )
456
- );
457
- const startDeclarationFileContent = buildStartDeclarationFile({
458
- serverRoutesRelativePath
459
- });
460
- if (!fs.existsSync(startDeclarationFilePath)) {
461
- await routerGenerator.writeIfDifferent(
462
- startDeclarationFilePath,
463
- "",
464
- startDeclarationFileContent,
465
- {
466
- beforeWrite: () => {
467
- logger.log(`🟡 Creating tanstack-start.d.ts`);
468
- }
469
- }
470
- );
471
- } else {
472
- const existingDeclarationFileContent = await fsp.readFile(startDeclarationFilePath, "utf-8").catch((err) => {
473
- if (err.code === "ENOENT") {
474
- return "";
475
- }
476
- throw err;
477
- });
478
- await routerGenerator.writeIfDifferent(
479
- startDeclarationFilePath,
480
- existingDeclarationFileContent,
481
- startDeclarationFileContent,
482
- {
483
- beforeWrite: () => {
484
- logger.log(`🟡 Updating tanstack-start.d.ts`);
485
- }
486
- }
487
- );
488
- }
489
- if (routeTreeWriteResult && !checkLatest()) {
490
- return;
491
- }
492
- }
493
- function buildStartDeclarationFile({
494
- serverRoutesRelativePath
495
- }) {
496
- const serverRoutesPath = routerGenerator.replaceBackslash(serverRoutesRelativePath);
497
- return [
498
- '/// <reference types="vite/client" />',
499
- `import '${serverRoutesPath}'`
500
- ].join("\n") + "\n";
501
- }
502
- function removeGroups(s) {
503
- return s.replace(possiblyNestedRouteGroupPatternRegex, "");
504
- }
505
- function determineNodePath(node) {
506
- var _a;
507
- return node.path = node.parent ? ((_a = node.routePath) == null ? void 0 : _a.replace(node.parent.routePath ?? "", "")) || "/" : node.routePath;
508
- }
509
- function removeLastSegmentFromPath(routePath = "/") {
510
- const segments = routePath.split("/");
511
- segments.pop();
512
- return segments.join("/");
513
- }
514
- function removeLayoutSegments(routePath = "/") {
515
- const segments = routePath.split("/");
516
- const newSegments = segments.filter((segment) => !segment.startsWith("_"));
517
- return newSegments.join("/");
518
- }
519
- function hasParentRoute(routes, node, routePathToCheck) {
520
- if (!routePathToCheck || routePathToCheck === "/") {
521
- return null;
522
- }
523
- const sortedNodes = routerGenerator.multiSortBy(routes, [
524
- (d) => d.routePath.length * -1,
525
- (d) => d.variableName
526
- ]).filter((d) => d.routePath !== `/${routerGenerator.rootPathId}`);
527
- for (const route of sortedNodes) {
528
- if (route.routePath === "/") continue;
529
- if (routePathToCheck.startsWith(`${route.routePath}/`) && route.routePath !== routePathToCheck) {
530
- return route;
531
- }
532
- }
533
- const segments = routePathToCheck.split("/");
534
- segments.pop();
535
- const parentRoutePath = segments.join("/");
536
- return hasParentRoute(routes, node, parentRoutePath);
537
- }
538
- const getResolvedRouteNodeVariableName = (routeNode) => {
539
- var _a;
540
- return ((_a = routeNode.children) == null ? void 0 : _a.length) ? `${routeNode.variableName}RouteWithChildren` : `${routeNode.variableName}Route`;
541
- };
542
- const createRouteNodesByFullPath = (routeNodes) => {
543
- return new Map(
544
- routeNodes.map((routeNode) => [inferFullPath(routeNode), routeNode])
545
- );
546
- };
547
- const createRouteNodesByTo = (routeNodes) => {
548
- return new Map(
549
- dedupeBranchesAndIndexRoutes(routeNodes).map((routeNode) => [
550
- inferTo(routeNode),
551
- routeNode
552
- ])
553
- );
554
- };
555
- const createRouteNodesById = (routeNodes) => {
556
- return new Map(
557
- routeNodes.map((routeNode) => {
558
- const id = routeNode.routePath ?? "";
559
- return [id, routeNode];
560
- })
561
- );
562
- };
563
- const inferFullPath = (routeNode) => {
564
- const fullPath = removeGroups(
565
- routerGenerator.removeUnderscores(removeLayoutSegments(routeNode.routePath)) ?? ""
566
- );
567
- return routeNode.cleanedPath === "/" ? fullPath : fullPath.replace(/\/$/, "");
568
- };
569
- const inferPath = (routeNode) => {
570
- var _a;
571
- return routeNode.cleanedPath === "/" ? routeNode.cleanedPath : ((_a = routeNode.cleanedPath) == null ? void 0 : _a.replace(/\/$/, "")) ?? "";
572
- };
573
- const inferTo = (routeNode) => {
574
- const fullPath = inferFullPath(routeNode);
575
- if (fullPath === "/") return fullPath;
576
- return fullPath.replace(/\/$/, "");
577
- };
578
- const dedupeBranchesAndIndexRoutes = (routes) => {
579
- return routes.filter((route) => {
580
- var _a;
581
- if ((_a = route.children) == null ? void 0 : _a.find((child) => child.cleanedPath === "/")) return false;
582
- return true;
583
- });
584
- };
585
- function checkUnique(routes, key) {
586
- const keys = routes.map((d) => d[key]);
587
- const uniqueKeys = new Set(keys);
588
- if (keys.length !== uniqueKeys.size) {
589
- const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i);
590
- const conflictingFiles = routes.filter(
591
- (d) => duplicateKeys.includes(d[key])
592
- );
593
- return conflictingFiles;
594
- }
595
- return void 0;
596
- }
597
- function checkRouteFullPathUniqueness(_routes, config) {
598
- const routes = _routes.map((d) => {
599
- const inferredFullPath = inferFullPath(d);
600
- return { ...d, inferredFullPath };
601
- });
602
- const conflictingFiles = checkUnique(routes, "inferredFullPath");
603
- if (conflictingFiles !== void 0) {
604
- const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? "s" : ""}: ${conflictingFiles.map((p) => `"${p.inferredFullPath}"`).join(", ")}.
605
- Please ensure each Server Route has a unique full path.
606
- Conflicting files:
607
- ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join("\n ")}
608
- `;
609
- console.error(errorMessage);
610
- process.exit(1);
611
- }
612
- }
613
- exports.TanStackStartServerRoutesVite = TanStackStartServerRoutesVite;
614
- //# sourceMappingURL=plugin.cjs.map