Open History to see the last commit
1import path from 'node:path'
2import * as fsp from 'node:fs/promises'
3import { existsSync, mkdirSync } from 'node:fs'
4import crypto from 'node:crypto'
5import { rootRouteId } from '@tanstack/router-core'
6import { logging } from './logger'
7import {
8 isVirtualConfigFile,
9 getRouteNodes as physicalGetRouteNodes,
10} from './filesystem/physical/getRouteNodes'
11import { getRouteNodes as virtualGetRouteNodes } from './filesystem/virtual/getRouteNodes'
12import { rootPathId } from './filesystem/physical/rootPathId'
13import {
14 buildFileRoutesByPathInterface,
15 buildImportString,
16 buildRouteTreeConfig,
17 checkFileExists,
18 checkRouteFullPathUniqueness,
19 createRouteNodesByFullPath,
20 createRouteNodesById,
21 createRouteNodesByTo,
22 determineNodePath,
23 findParent,
24 format,
25 getImportForRouteNode,
26 getImportPath,
27 getResolvedRouteNodeVariableName,
28 hasParentRoute,
29 isRouteNodeValidForAugmentation,
30 mergeImportDeclarations,
31 multiSortBy,
32 removeExt,
33 removeGroups,
34 removeLastSegmentFromPath,
35 removeLayoutSegments,
36 removeLeadingUnderscores,
37 removeTrailingSlash,
38 removeUnderscores,
39 replaceBackslash,
40 resetRegex,
41 routePathToVariable,
42 trimPathLeft,
43} from './utils'
44import { fillTemplate, getTargetTemplate } from './template'
45import { transform } from './transform/transform'
46import type { GeneratorPlugin } from './plugin/types'
47import type { TargetTemplate } from './template'
48import type {
49 FsRouteType,
50 GetRouteNodesResult,
51 GetRoutesByFileMapResult,
52 HandleNodeAccumulator,
53 ImportDeclaration,
54 RouteNode,
55} from './types'
56import type { Config } from './config'
57import type { Logger } from './logger'
58
59interface fs {
60 stat: (
61 filePath: string,
62 ) => Promise<{ mtimeMs: bigint; mode: number; uid: number; gid: number }>
63 rename: (oldPath: string, newPath: string) => Promise<void>
64 writeFile: (filePath: string, content: string) => Promise<void>
65 readFile: (
66 filePath: string,
67 ) => Promise<
68 { stat: { mtimeMs: bigint }; fileContent: string } | 'file-not-existing'
69 >
70 chmod: (filePath: string, mode: number) => Promise<void>
71 chown: (filePath: string, uid: number, gid: number) => Promise<void>
72}
73
74const DefaultFileSystem: fs = {
75 stat: async (filePath) => {
76 const res = await fsp.stat(filePath, { bigint: true })
77 return {
78 mtimeMs: res.mtimeMs,
79 mode: Number(res.mode),
80 uid: Number(res.uid),
81 gid: Number(res.gid),
82 }
83 },
84 rename: (oldPath, newPath) => fsp.rename(oldPath, newPath),
85 writeFile: (filePath, content) => fsp.writeFile(filePath, content),
86 readFile: async (filePath: string) => {
87 try {
88 const fileHandle = await fsp.open(filePath, 'r')
89 const stat = await fileHandle.stat({ bigint: true })
90 const fileContent = (await fileHandle.readFile()).toString()
91 await fileHandle.close()
92 return { stat, fileContent }
93 } catch (e: any) {
94 if ('code' in e) {
95 if (e.code === 'ENOENT') {
96 return 'file-not-existing'
97 }
98 }
99 throw e
100 }
101 },
102 chmod: (filePath, mode) => fsp.chmod(filePath, mode),
103 chown: (filePath, uid, gid) => fsp.chown(filePath, uid, gid),
104}
105
106interface Rerun {
107 rerun: true
108 msg?: string
109 event: GeneratorEvent
110}
111function rerun(opts: { msg?: string; event?: GeneratorEvent }): Rerun {
112 const { event, ...rest } = opts
113 return { rerun: true, event: event ?? { type: 'rerun' }, ...rest }
114}
115
116function isRerun(result: unknown): result is Rerun {
117 return (
118 typeof result === 'object' &&
119 result !== null &&
120 'rerun' in result &&
121 result.rerun === true
122 )
123}
124
125export type FileEventType = 'create' | 'update' | 'delete'
126export type FileEvent = {
127 type: FileEventType
128 path: string
129}
130export type GeneratorEvent = FileEvent | { type: 'rerun' }
131
132type FileCacheChange<TCacheEntry extends GeneratorCacheEntry> =
133 | {
134 result: false
135 cacheEntry: TCacheEntry
136 }
137 | { result: true; mtimeMs: bigint; cacheEntry: TCacheEntry }
138 | {
139 result: 'file-not-in-cache'
140 }
141 | {
142 result: 'cannot-stat-file'
143 }
144
145interface GeneratorCacheEntry {
146 mtimeMs: bigint
147 fileContent: string
148}
149
150interface RouteNodeCacheEntry extends GeneratorCacheEntry {
151 routeId: string
152 node: RouteNode
153}
154
155type GeneratorRouteNodeCache = Map</** filePath **/ string, RouteNodeCacheEntry>
156
157interface CrawlingResult {
158 rootRouteNode: RouteNode
159 routeFileResult: Array<RouteNode>
160 acc: HandleNodeAccumulator
161}
162
163export class Generator {
164 /**
165 * why do we have two caches for the route files?
166 * During processing, we READ from the cache and WRITE to the shadow cache.
167 *
168 * After a route file is processed, we write to the shadow cache.
169 * If during processing we bail out and re-run, we don't lose this modification
170 * but still can track whether the file contributed changes and thus the route tree file needs to be regenerated.
171 * After all files are processed, we swap the shadow cache with the main cache and initialize a new shadow cache.
172 * That way we also ensure deleted/renamed files don't stay in the cache forever.
173 */
174 private routeNodeCache: GeneratorRouteNodeCache = new Map()
175 private routeNodeShadowCache: GeneratorRouteNodeCache = new Map()
176
177 private routeTreeFileCache: GeneratorCacheEntry | undefined
178
179 private crawlingResult: CrawlingResult | undefined
180 public config: Config
181 public targetTemplate: TargetTemplate
182
183 private root: string
184 private routesDirectoryPath: string
185 private sessionId?: string
186 private fs: fs
187 private logger: Logger
188 private generatedRouteTreePath: string
189 private runPromise: Promise<void> | undefined
190 private fileEventQueue: Array<GeneratorEvent> = []
191 private plugins: Array<GeneratorPlugin> = []
192 private static routeGroupPatternRegex = /\(.+\)/g
193 private physicalDirectories: Array<string> = []
194
195 constructor(opts: { config: Config; root: string; fs?: fs }) {
196 this.config = opts.config
197 this.logger = logging({ disabled: this.config.disableLogging })
198 this.root = opts.root
199 this.fs = opts.fs || DefaultFileSystem
200 this.generatedRouteTreePath = this.getGeneratedRouteTreePath()
201 this.targetTemplate = getTargetTemplate(this.config)
202
203 this.routesDirectoryPath = this.getRoutesDirectoryPath()
204 this.plugins.push(...(opts.config.plugins || []))
205
206 for (const plugin of this.plugins) {
207 plugin.init?.({ generator: this })
208 }
209 }
210
211 private getGeneratedRouteTreePath() {
212 const generatedRouteTreePath = path.isAbsolute(
213 this.config.generatedRouteTree,
214 )
215 ? this.config.generatedRouteTree
216 : path.resolve(this.root, this.config.generatedRouteTree)
217
218 const generatedRouteTreeDir = path.dirname(generatedRouteTreePath)
219
220 if (!existsSync(generatedRouteTreeDir)) {
221 mkdirSync(generatedRouteTreeDir, { recursive: true })
222 }
223
224 return generatedRouteTreePath
225 }
226
227 private getRoutesDirectoryPath() {
228 return path.isAbsolute(this.config.routesDirectory)
229 ? this.config.routesDirectory
230 : path.resolve(this.root, this.config.routesDirectory)
231 }
232
233 public getRoutesByFileMap(): GetRoutesByFileMapResult {
234 return new Map(
235 [...this.routeNodeCache.entries()].map(([filePath, cacheEntry]) => [
236 filePath,
237 { routePath: cacheEntry.routeId },
238 ]),
239 )
240 }
241
242 public async run(event?: GeneratorEvent): Promise<void> {
243 if (
244 event &&
245 event.type !== 'rerun' &&
246 !this.isFileRelevantForRouteTreeGeneration(event.path)
247 ) {
248 return
249 }
250 this.fileEventQueue.push(event ?? { type: 'rerun' })
251 // only allow a single run at a time
252 if (this.runPromise) {
253 return this.runPromise
254 }
255
256 this.runPromise = (async () => {
257 do {
258 // synchronously copy and clear the queue since we are going to iterate asynchronously over it
259 // and while we do so, a new event could be put into the queue
260 const tempQueue = this.fileEventQueue
261 this.fileEventQueue = []
262 // if we only have 'update' events in the queue
263 // and we already have the affected files' latest state in our cache, we can exit early
264 const remainingEvents = (
265 await Promise.all(
266 tempQueue.map(async (e) => {
267 if (e.type === 'update') {
268 let cacheEntry: GeneratorCacheEntry | undefined
269 if (e.path === this.generatedRouteTreePath) {
270 cacheEntry = this.routeTreeFileCache
271 } else {
272 // we only check the routeNodeCache here
273 // if the file's state is only up-to-date in the shadow cache we need to re-run
274 cacheEntry = this.routeNodeCache.get(e.path)
275 }
276 const change = await this.didFileChangeComparedToCache(
277 { path: e.path },
278 cacheEntry,
279 )
280 if (change.result === false) {
281 return null
282 }
283 }
284 return e
285 }),
286 )
287 ).filter((e) => e !== null)
288
289 if (remainingEvents.length === 0) {
290 break
291 }
292
293 try {
294 await this.generatorInternal()
295 } catch (err) {
296 const errArray = !Array.isArray(err) ? [err] : err
297
298 const recoverableErrors = errArray.filter((e) => isRerun(e))
299 if (recoverableErrors.length === errArray.length) {
300 this.fileEventQueue.push(...recoverableErrors.map((e) => e.event))
301 recoverableErrors.forEach((e) => {
302 if (e.msg) {
303 this.logger.info(e.msg)
304 }
305 })
306 } else {
307 const unrecoverableErrors = errArray.filter((e) => !isRerun(e))
308 this.runPromise = undefined
309 throw new Error(
310 unrecoverableErrors.map((e) => (e as Error).message).join(),
311 )
312 }
313 }
314 } while (this.fileEventQueue.length)
315 this.runPromise = undefined
316 })()
317 return this.runPromise
318 }
319
320 private async generatorInternal() {
321 let writeRouteTreeFile: boolean | 'force' = false
322
323 let getRouteNodesResult: GetRouteNodesResult
324
325 if (this.config.virtualRouteConfig) {
326 getRouteNodesResult = await virtualGetRouteNodes(this.config, this.root)
327 } else {
328 getRouteNodesResult = await physicalGetRouteNodes(this.config, this.root)
329 }
330
331 const {
332 rootRouteNode,
333 routeNodes: beforeRouteNodes,
334 physicalDirectories,
335 } = getRouteNodesResult
336 if (rootRouteNode === undefined) {
337 let errorMessage = `rootRouteNode must not be undefined. Make sure you've added your root route into the route-tree.`
338 if (!this.config.virtualRouteConfig) {
339 errorMessage += `\nMake sure that you add a "${rootPathId}.${this.config.disableTypes ? 'js' : 'tsx'}" file to your routes directory.\nAdd the file in: "${this.config.routesDirectory}/${rootPathId}.${this.config.disableTypes ? 'js' : 'tsx'}"`
340 }
341 throw new Error(errorMessage)
342 }
343 this.physicalDirectories = physicalDirectories
344
345 await this.handleRootNode(rootRouteNode)
346
347 const preRouteNodes = multiSortBy(beforeRouteNodes, [
348 (d) => (d.routePath === '/' ? -1 : 1),
349 (d) => d.routePath?.split('/').length,
350 (d) =>
351 d.filePath.match(new RegExp(`[./]${this.config.indexToken}[.]`))
352 ? 1
353 : -1,
354 (d) =>
355 d.filePath.match(
356 /[./](component|errorComponent|pendingComponent|loader|lazy)[.]/,
357 )
358 ? 1
359 : -1,
360 (d) =>
361 d.filePath.match(new RegExp(`[./]${this.config.routeToken}[.]`))
362 ? -1
363 : 1,
364 (d) => (d.routePath?.endsWith('/') ? -1 : 1),
365 (d) => d.routePath,
366 ]).filter((d) => ![`/${rootPathId}`].includes(d.routePath || ''))
367
368 const routeFileAllResult = await Promise.allSettled(
369 preRouteNodes
370 // only process routes that are backed by an actual file
371 .filter((n) => !n.isVirtualParentRoute && !n.isVirtual)
372 .map((n) => this.processRouteNodeFile(n)),
373 )
374
375 const rejections = routeFileAllResult.filter(
376 (result) => result.status === 'rejected',
377 )
378 if (rejections.length > 0) {
379 throw rejections.map((e) => e.reason)
380 }
381
382 const routeFileResult = routeFileAllResult.flatMap((result) => {
383 if (result.status === 'fulfilled' && result.value !== null) {
384 if (result.value.shouldWriteTree) {
385 writeRouteTreeFile = true
386 }
387 return result.value.node
388 }
389 return []
390 })
391
392 // reset children in case we re-use a node from the cache
393 routeFileResult.forEach((r) => (r.children = undefined))
394
395 const acc: HandleNodeAccumulator = {
396 routeTree: [],
397 routeNodes: [],
398 routePiecesByPath: {},
399 }
400
401 for (const node of routeFileResult) {
402 Generator.handleNode(node, acc, this.config)
403 }
404
405 this.crawlingResult = { rootRouteNode, routeFileResult, acc }
406
407 // this is the first time the generator runs, so read in the route tree file if it exists yet
408 if (!this.routeTreeFileCache) {
409 const routeTreeFile = await this.fs.readFile(this.generatedRouteTreePath)
410 if (routeTreeFile !== 'file-not-existing') {
411 this.routeTreeFileCache = {
412 fileContent: routeTreeFile.fileContent,
413 mtimeMs: routeTreeFile.stat.mtimeMs,
414 }
415 }
416 writeRouteTreeFile = true
417 } else {
418 const routeTreeFileChange = await this.didFileChangeComparedToCache(
419 { path: this.generatedRouteTreePath },
420 this.routeTreeFileCache,
421 )
422 if (routeTreeFileChange.result !== false) {
423 writeRouteTreeFile = 'force'
424 if (routeTreeFileChange.result === true) {
425 const routeTreeFile = await this.fs.readFile(
426 this.generatedRouteTreePath,
427 )
428 if (routeTreeFile !== 'file-not-existing') {
429 this.routeTreeFileCache = {
430 fileContent: routeTreeFile.fileContent,
431 mtimeMs: routeTreeFile.stat.mtimeMs,
432 }
433 }
434 }
435 }
436 }
437
438 if (!writeRouteTreeFile) {
439 // only needs to be done if no other changes have been detected yet
440 // compare shadowCache and cache to identify deleted routes
441 if (this.routeNodeCache.size !== this.routeNodeShadowCache.size) {
442 writeRouteTreeFile = true
443 } else {
444 for (const fullPath of this.routeNodeCache.keys()) {
445 if (!this.routeNodeShadowCache.has(fullPath)) {
446 writeRouteTreeFile = true
447 break
448 }
449 }
450 }
451 }
452
453 if (!writeRouteTreeFile) {
454 this.swapCaches()
455 return
456 }
457
458 const buildResult = this.buildRouteTree({
459 rootRouteNode,
460 acc,
461 routeFileResult,
462 })
463 let routeTreeContent = buildResult.routeTreeContent
464
465 routeTreeContent = this.config.enableRouteTreeFormatting
466 ? await format(routeTreeContent, this.config)
467 : routeTreeContent
468
469 let newMtimeMs: bigint | undefined
470 if (this.routeTreeFileCache) {
471 if (
472 writeRouteTreeFile !== 'force' &&
473 this.routeTreeFileCache.fileContent === routeTreeContent
474 ) {
475 // existing route tree file is already up-to-date, don't write it
476 // we should only get here in the initial run when the route cache is not filled yet
477 } else {
478 const newRouteTreeFileStat = await this.safeFileWrite({
479 filePath: this.generatedRouteTreePath,
480 newContent: routeTreeContent,
481 strategy: {
482 type: 'mtime',
483 expectedMtimeMs: this.routeTreeFileCache.mtimeMs,
484 },
485 })
486 newMtimeMs = newRouteTreeFileStat.mtimeMs
487 }
488 } else {
489 const newRouteTreeFileStat = await this.safeFileWrite({
490 filePath: this.generatedRouteTreePath,
491 newContent: routeTreeContent,
492 strategy: {
493 type: 'new-file',
494 },
495 })
496 newMtimeMs = newRouteTreeFileStat.mtimeMs
497 }
498
499 if (newMtimeMs !== undefined) {
500 this.routeTreeFileCache = {
501 fileContent: routeTreeContent,
502 mtimeMs: newMtimeMs,
503 }
504 }
505
506 this.plugins.map((plugin) => {
507 return plugin.onRouteTreeChanged?.({
508 routeTree: buildResult.routeTree,
509 routeNodes: buildResult.routeNodes,
510 acc,
511 rootRouteNode,
512 })
513 })
514 this.swapCaches()
515 }
516
517 private swapCaches() {
518 this.routeNodeCache = this.routeNodeShadowCache
519 this.routeNodeShadowCache = new Map()
520 }
521
522 public buildRouteTree(opts: {
523 rootRouteNode: RouteNode
524 acc: HandleNodeAccumulator
525 routeFileResult: Array<RouteNode>
526 config?: Partial<Config>
527 }) {
528 const config = { ...this.config, ...(opts.config || {}) }
529
530 const { rootRouteNode, acc } = opts
531
532 const sortedRouteNodes = multiSortBy(acc.routeNodes, [
533 (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1),
534 (d) => d.routePath?.split('/').length,
535 (d) => (d.routePath?.endsWith(config.indexToken) ? -1 : 1),
536 (d) => d,
537 ])
538
539 const routeImports = sortedRouteNodes
540 .filter((d) => !d.isVirtual)
541 .flatMap((node) =>
542 getImportForRouteNode(
543 node,
544 config,
545 this.generatedRouteTreePath,
546 this.root,
547 ),
548 )
549
550 const virtualRouteNodes = sortedRouteNodes
551 .filter((d) => d.isVirtual)
552 .map((node) => {
553 return `const ${
554 node.variableName
555 }RouteImport = createFileRoute('${node.routePath}')()`
556 })
557
558 const imports: Array<ImportDeclaration> = []
559 if (acc.routeNodes.some((n) => n.isVirtual)) {
560 imports.push({
561 specifiers: [{ imported: 'createFileRoute' }],
562 source: this.targetTemplate.fullPkg,
563 })
564 }
565 if (config.verboseFileRoutes === false) {
566 const typeImport: ImportDeclaration = {
567 specifiers: [],
568 source: this.targetTemplate.fullPkg,
569 importKind: 'type',
570 }
571 if (
572 sortedRouteNodes.some(
573 (d) =>
574 isRouteNodeValidForAugmentation(d) && d._fsRouteType !== 'lazy',
575 )
576 ) {
577 typeImport.specifiers.push({ imported: 'CreateFileRoute' })
578 }
579 if (
580 sortedRouteNodes.some(
581 (node) =>
582 acc.routePiecesByPath[node.routePath!]?.lazy &&
583 isRouteNodeValidForAugmentation(node),
584 )
585 ) {
586 typeImport.specifiers.push({ imported: 'CreateLazyFileRoute' })
587 }
588
589 if (typeImport.specifiers.length > 0) {
590 typeImport.specifiers.push({ imported: 'FileRoutesByPath' })
591 imports.push(typeImport)
592 }
593 }
594
595 const routeTreeConfig = buildRouteTreeConfig(
596 acc.routeTree,
597 config.disableTypes,
598 )
599
600 const createUpdateRoutes = sortedRouteNodes.map((node) => {
601 const loaderNode = acc.routePiecesByPath[node.routePath!]?.loader
602 const componentNode = acc.routePiecesByPath[node.routePath!]?.component
603 const errorComponentNode =
604 acc.routePiecesByPath[node.routePath!]?.errorComponent
605 const pendingComponentNode =
606 acc.routePiecesByPath[node.routePath!]?.pendingComponent
607 const lazyComponentNode = acc.routePiecesByPath[node.routePath!]?.lazy
608
609 return [
610 [
611 `const ${node.variableName}Route = ${node.variableName}RouteImport.update({
612 ${[
613 `id: '${node.path}'`,
614 !node.isNonPath ? `path: '${node.cleanedPath}'` : undefined,
615 `getParentRoute: () => ${findParent(node)}`,
616 ]
617 .filter(Boolean)
618 .join(',')}
619 }${config.disableTypes ? '' : 'as any'})`,
620 loaderNode
621 ? `.updateLoader({ loader: lazyFn(() => import('./${replaceBackslash(
622 removeExt(
623 path.relative(
624 path.dirname(config.generatedRouteTree),
625 path.resolve(config.routesDirectory, loaderNode.filePath),
626 ),
627 config.addExtensions,
628 ),
629 )}'), 'loader') })`
630 : '',
631 componentNode || errorComponentNode || pendingComponentNode
632 ? `.update({
633 ${(
634 [
635 ['component', componentNode],
636 ['errorComponent', errorComponentNode],
637 ['pendingComponent', pendingComponentNode],
638 ] as const
639 )
640 .filter((d) => d[1])
641 .map((d) => {
642 return `${
643 d[0]
644 }: lazyRouteComponent(() => import('./${replaceBackslash(
645 removeExt(
646 path.relative(
647 path.dirname(config.generatedRouteTree),
648 path.resolve(config.routesDirectory, d[1]!.filePath),
649 ),
650 config.addExtensions,
651 ),
652 )}'), '${d[0]}')`
653 })
654 .join('\n,')}
655 })`
656 : '',
657 lazyComponentNode
658 ? `.lazy(() => import('./${replaceBackslash(
659 removeExt(
660 path.relative(
661 path.dirname(config.generatedRouteTree),
662 path.resolve(
663 config.routesDirectory,
664 lazyComponentNode.filePath,
665 ),
666 ),
667 config.addExtensions,
668 ),
669 )}').then((d) => d.Route))`
670 : '',
671 ].join(''),
672 ].join('\n\n')
673 })
674
675 let fileRoutesByPathInterface = ''
676 let fileRoutesByFullPath = ''
677
678 if (!config.disableTypes) {
679 fileRoutesByFullPath = [
680 `export interface FileRoutesByFullPath {
681${[...createRouteNodesByFullPath(acc.routeNodes, config).entries()]
682 .filter(([fullPath]) => fullPath)
683 .map(([fullPath, routeNode]) => {
684 return `'${fullPath}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`
685 })}
686}`,
687 `export interface FileRoutesByTo {
688${[...createRouteNodesByTo(acc.routeNodes, config).entries()]
689 .filter(([to]) => to)
690 .map(([to, routeNode]) => {
691 return `'${to}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`
692 })}
693}`,
694 `export interface FileRoutesById {
695'${rootRouteId}': typeof rootRouteImport,
696${[...createRouteNodesById(acc.routeNodes).entries()].map(([id, routeNode]) => {
697 return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`
698})}
699}`,
700 `export interface FileRouteTypes {
701fileRoutesByFullPath: FileRoutesByFullPath
702fullPaths: ${
703 acc.routeNodes.length > 0
704 ? [...createRouteNodesByFullPath(acc.routeNodes, config).keys()]
705 .filter((fullPath) => fullPath)
706 .map((fullPath) => `'${fullPath}'`)
707 .join('|')
708 : 'never'
709 }
710fileRoutesByTo: FileRoutesByTo
711to: ${
712 acc.routeNodes.length > 0
713 ? [...createRouteNodesByTo(acc.routeNodes, config).keys()]
714 .filter((to) => to)
715 .map((to) => `'${to}'`)
716 .join('|')
717 : 'never'
718 }
719id: ${[`'${rootRouteId}'`, ...[...createRouteNodesById(acc.routeNodes).keys()].map((id) => `'${id}'`)].join('|')}
720fileRoutesById: FileRoutesById
721}`,
722 `export interface RootRouteChildren {
723${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')}
724}`,
725 ].join('\n')
726
727 fileRoutesByPathInterface = buildFileRoutesByPathInterface({
728 module: this.targetTemplate.fullPkg,
729 interfaceName: 'FileRoutesByPath',
730 routeNodes: sortedRouteNodes,
731 config,
732 })
733 }
734
735 const routeTree = [
736 `const rootRouteChildren${config.disableTypes ? '' : `: RootRouteChildren`} = {
737 ${acc.routeTree
738 .map(
739 (child) =>
740 `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,
741 )
742 .join(',')}
743}`,
744 `export const routeTree = rootRouteImport._addFileChildren(rootRouteChildren)${config.disableTypes ? '' : `._addFileTypes<FileRouteTypes>()`}`,
745 ].join('\n')
746
747 checkRouteFullPathUniqueness(
748 sortedRouteNodes.filter(
749 (d) => d.children === undefined && 'lazy' !== d._fsRouteType,
750 ),
751 config,
752 )
753
754 let mergedImports = mergeImportDeclarations(imports)
755 if (config.disableTypes) {
756 mergedImports = mergedImports.filter((d) => d.importKind !== 'type')
757 }
758
759 const importStatements = mergedImports.map(buildImportString)
760
761 let moduleAugmentation = ''
762 if (config.verboseFileRoutes === false && !config.disableTypes) {
763 moduleAugmentation = opts.routeFileResult
764 .map((node) => {
765 const getModuleDeclaration = (routeNode?: RouteNode) => {
766 if (!isRouteNodeValidForAugmentation(routeNode)) {
767 return ''
768 }
769 let moduleAugmentation = ''
770 if (routeNode._fsRouteType === 'lazy') {
771 moduleAugmentation = `const createLazyFileRoute: CreateLazyFileRoute<FileRoutesByPath['${routeNode.routePath}']['preLoaderRoute']>`
772 } else {
773 moduleAugmentation = `const createFileRoute: CreateFileRoute<'${routeNode.routePath}',
774 FileRoutesByPath['${routeNode.routePath}']['parentRoute'],
775 FileRoutesByPath['${routeNode.routePath}']['id'],
776 FileRoutesByPath['${routeNode.routePath}']['path'],
777 FileRoutesByPath['${routeNode.routePath}']['fullPath']
778 >
779 `
780 }
781
782 return `declare module './${getImportPath(routeNode, config, this.generatedRouteTreePath)}' {
783 ${moduleAugmentation}
784 }`
785 }
786 return getModuleDeclaration(node)
787 })
788 .join('\n')
789 }
790
791 const rootRouteImport = getImportForRouteNode(
792 rootRouteNode,
793 config,
794 this.generatedRouteTreePath,
795 this.root,
796 )
797 routeImports.unshift(rootRouteImport)
798
799 let footer: Array<string> = []
800 if (config.routeTreeFileFooter) {
801 if (Array.isArray(config.routeTreeFileFooter)) {
802 footer = config.routeTreeFileFooter
803 } else {
804 footer = config.routeTreeFileFooter()
805 }
806 }
807 const routeTreeContent = [
808 ...config.routeTreeFileHeader,
809 `// This file was automatically generated by TanStack Router.
810// You should NOT make any changes in this file as it will be overwritten.
811// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`,
812 [...importStatements].join('\n'),
813 mergeImportDeclarations(routeImports).map(buildImportString).join('\n'),
814 virtualRouteNodes.join('\n'),
815 createUpdateRoutes.join('\n'),
816 fileRoutesByFullPath,
817 fileRoutesByPathInterface,
818 moduleAugmentation,
819 routeTreeConfig.join('\n'),
820 routeTree,
821 ...footer,
822 ]
823 .filter(Boolean)
824 .join('\n\n')
825 return {
826 routeTreeContent,
827 routeTree: acc.routeTree,
828 routeNodes: acc.routeNodes,
829 }
830 }
831
832 private async processRouteNodeFile(node: RouteNode): Promise<{
833 shouldWriteTree: boolean
834 cacheEntry: RouteNodeCacheEntry
835 node: RouteNode
836 } | null> {
837 const result = await this.isRouteFileCacheFresh(node)
838
839 if (result.status === 'fresh') {
840 return {
841 node: result.cacheEntry.node,
842 shouldWriteTree: false,
843 cacheEntry: result.cacheEntry,
844 }
845 }
846
847 const previousCacheEntry = result.cacheEntry
848
849 const existingRouteFile = await this.fs.readFile(node.fullPath)
850 if (existingRouteFile === 'file-not-existing') {
851 throw new Error(`⚠️ File ${node.fullPath} does not exist`)
852 }
853
854 const updatedCacheEntry: RouteNodeCacheEntry = {
855 fileContent: existingRouteFile.fileContent,
856 mtimeMs: existingRouteFile.stat.mtimeMs,
857 routeId: node.routePath ?? '$$TSR_NO_ROUTE_PATH_ASSIGNED$$',
858 node,
859 }
860
861 const escapedRoutePath = node.routePath?.replaceAll('$', '$$') ?? ''
862
863 let shouldWriteRouteFile = false
864 let shouldWriteTree = false
865 // now we need to either scaffold the file or transform it
866 if (!existingRouteFile.fileContent) {
867 shouldWriteRouteFile = true
868 shouldWriteTree = true
869 // Creating a new lazy route file
870 if (node._fsRouteType === 'lazy') {
871 const tLazyRouteTemplate = this.targetTemplate.lazyRoute
872 // Check by default check if the user has a specific lazy route template
873 // If not, check if the user has a route template and use that instead
874 updatedCacheEntry.fileContent = await fillTemplate(
875 this.config,
876 (this.config.customScaffolding?.lazyRouteTemplate ||
877 this.config.customScaffolding?.routeTemplate) ??
878 tLazyRouteTemplate.template(),
879 {
880 tsrImports: tLazyRouteTemplate.imports.tsrImports(),
881 tsrPath: escapedRoutePath.replaceAll(/\{(.+?)\}/gm, '$1'),
882 tsrExportStart:
883 tLazyRouteTemplate.imports.tsrExportStart(escapedRoutePath),
884 tsrExportEnd: tLazyRouteTemplate.imports.tsrExportEnd(),
885 },
886 )
887 } else if (
888 // Creating a new normal route file
889 (['layout', 'static'] satisfies Array<FsRouteType>).some(
890 (d) => d === node._fsRouteType,
891 ) ||
892 (
893 [
894 'component',
895 'pendingComponent',
896 'errorComponent',
897 'loader',
898 ] satisfies Array<FsRouteType>
899 ).every((d) => d !== node._fsRouteType)
900 ) {
901 const tRouteTemplate = this.targetTemplate.route
902 updatedCacheEntry.fileContent = await fillTemplate(
903 this.config,
904 this.config.customScaffolding?.routeTemplate ??
905 tRouteTemplate.template(),
906 {
907 tsrImports: tRouteTemplate.imports.tsrImports(),
908 tsrPath: escapedRoutePath.replaceAll(/\{(.+?)\}/gm, '$1'),
909 tsrExportStart:
910 tRouteTemplate.imports.tsrExportStart(escapedRoutePath),
911 tsrExportEnd: tRouteTemplate.imports.tsrExportEnd(),
912 },
913 )
914 } else {
915 return null
916 }
917 }
918 // transform the file
919 const transformResult = await transform({
920 source: updatedCacheEntry.fileContent,
921 ctx: {
922 target: this.config.target,
923 routeId: escapedRoutePath,
924 lazy: node._fsRouteType === 'lazy',
925 verboseFileRoutes: !(this.config.verboseFileRoutes === false),
926 },
927 node,
928 })
929
930 if (transformResult.result === 'no-route-export') {
931 this.logger.warn(
932 `Route file "${node.fullPath}" does not contain any route piece. This is likely a mistake.`,
933 )
934 return null
935 }
936 if (transformResult.result === 'error') {
937 throw new Error(
938 `Error transforming route file ${node.fullPath}: ${transformResult.error}`,
939 )
940 }
941 if (transformResult.result === 'modified') {
942 updatedCacheEntry.fileContent = transformResult.output
943 shouldWriteRouteFile = true
944 }
945
946 for (const plugin of this.plugins) {
947 plugin.afterTransform?.({ node, prevNode: previousCacheEntry?.node })
948 }
949
950 // file was changed
951 if (shouldWriteRouteFile) {
952 const stats = await this.safeFileWrite({
953 filePath: node.fullPath,
954 newContent: updatedCacheEntry.fileContent,
955 strategy: {
956 type: 'mtime',
957 expectedMtimeMs: updatedCacheEntry.mtimeMs,
958 },
959 })
960 updatedCacheEntry.mtimeMs = stats.mtimeMs
961 }
962
963 this.routeNodeShadowCache.set(node.fullPath, updatedCacheEntry)
964 return {
965 node,
966 shouldWriteTree,
967 cacheEntry: updatedCacheEntry,
968 }
969 }
970
971 private async didRouteFileChangeComparedToCache(
972 file: {
973 path: string
974 mtimeMs?: bigint
975 },
976 cache: 'routeNodeCache' | 'routeNodeShadowCache',
977 ): Promise<FileCacheChange<RouteNodeCacheEntry>> {
978 const cacheEntry = this[cache].get(file.path)
979 return this.didFileChangeComparedToCache(file, cacheEntry)
980 }
981
982 private async didFileChangeComparedToCache<
983 TCacheEntry extends GeneratorCacheEntry,
984 >(
985 file: {
986 path: string
987 mtimeMs?: bigint
988 },
989 cacheEntry: TCacheEntry | undefined,
990 ): Promise<FileCacheChange<TCacheEntry>> {
991 // for now we rely on the modification time of the file
992 // to determine if the file has changed
993 // we could also compare the file content but this would be slower as we would have to read the file
994
995 if (!cacheEntry) {
996 return { result: 'file-not-in-cache' }
997 }
998 let mtimeMs = file.mtimeMs
999
1000 if (mtimeMs === undefined) {
1001 try {
1002 const currentStat = await this.fs.stat(file.path)
1003 mtimeMs = currentStat.mtimeMs
1004 } catch {
1005 return { result: 'cannot-stat-file' }
1006 }
1007 }
1008 return { result: mtimeMs !== cacheEntry.mtimeMs, mtimeMs, cacheEntry }
1009 }
1010
1011 private async safeFileWrite(opts: {
1012 filePath: string
1013 newContent: string
1014 strategy:
1015 | {
1016 type: 'mtime'
1017 expectedMtimeMs: bigint
1018 }
1019 | {
1020 type: 'new-file'
1021 }
1022 }) {
1023 const tmpPath = this.getTempFileName(opts.filePath)
1024 await this.fs.writeFile(tmpPath, opts.newContent)
1025
1026 if (opts.strategy.type === 'mtime') {
1027 const beforeStat = await this.fs.stat(opts.filePath)
1028 if (beforeStat.mtimeMs !== opts.strategy.expectedMtimeMs) {
1029 throw rerun({
1030 msg: `File ${opts.filePath} was modified by another process during processing.`,
1031 event: { type: 'update', path: opts.filePath },
1032 })
1033 }
1034 const newFileState = await this.fs.stat(tmpPath)
1035 if (newFileState.mode !== beforeStat.mode) {
1036 await this.fs.chmod(tmpPath, beforeStat.mode)
1037 }
1038 if (
1039 newFileState.uid !== beforeStat.uid ||
1040 newFileState.gid !== beforeStat.gid
1041 ) {
1042 try {
1043 await this.fs.chown(tmpPath, beforeStat.uid, beforeStat.gid)
1044 } catch (err) {
1045 if (
1046 typeof err === 'object' &&
1047 err !== null &&
1048 'code' in err &&
1049 (err as any).code === 'EPERM'
1050 ) {
1051 console.warn(
1052 `[safeFileWrite] chown failed: ${(err as any).message}`,
1053 )
1054 } else {
1055 throw err
1056 }
1057 }
1058 }
1059 } else {
1060 if (await checkFileExists(opts.filePath)) {
1061 throw rerun({
1062 msg: `File ${opts.filePath} already exists. Cannot overwrite.`,
1063 event: { type: 'update', path: opts.filePath },
1064 })
1065 }
1066 }
1067
1068 const stat = await this.fs.stat(tmpPath)
1069
1070 await this.fs.rename(tmpPath, opts.filePath)
1071
1072 return stat
1073 }
1074
1075 private getTempFileName(filePath: string) {
1076 const absPath = path.resolve(filePath)
1077 const hash = crypto.createHash('md5').update(absPath).digest('hex')
1078 // lazy initialize sessionId to only create tmpDir when it is first needed
1079 if (!this.sessionId) {
1080 // ensure the directory exists
1081 mkdirSync(this.config.tmpDir, { recursive: true })
1082 this.sessionId = crypto.randomBytes(4).toString('hex')
1083 }
1084 return path.join(this.config.tmpDir, `${this.sessionId}-${hash}`)
1085 }
1086
1087 private async isRouteFileCacheFresh(node: RouteNode): Promise<
1088 | {
1089 status: 'fresh'
1090 cacheEntry: RouteNodeCacheEntry
1091 }
1092 | { status: 'stale'; cacheEntry?: RouteNodeCacheEntry }
1093 > {
1094 const fileChangedCache = await this.didRouteFileChangeComparedToCache(
1095 { path: node.fullPath },
1096 'routeNodeCache',
1097 )
1098 if (fileChangedCache.result === false) {
1099 this.routeNodeShadowCache.set(node.fullPath, fileChangedCache.cacheEntry)
1100 return {
1101 status: 'fresh',
1102 cacheEntry: fileChangedCache.cacheEntry,
1103 }
1104 }
1105 if (fileChangedCache.result === 'cannot-stat-file') {
1106 throw new Error(`⚠️ expected route file to exist at ${node.fullPath}`)
1107 }
1108 const mtimeMs =
1109 fileChangedCache.result === true ? fileChangedCache.mtimeMs : undefined
1110
1111 const shadowCacheFileChange = await this.didRouteFileChangeComparedToCache(
1112 { path: node.fullPath, mtimeMs },
1113 'routeNodeShadowCache',
1114 )
1115
1116 if (shadowCacheFileChange.result === 'cannot-stat-file') {
1117 throw new Error(`⚠️ expected route file to exist at ${node.fullPath}`)
1118 }
1119
1120 if (shadowCacheFileChange.result === false) {
1121 // shadow cache has latest file state already
1122 if (fileChangedCache.result === true) {
1123 return {
1124 status: 'fresh',
1125 cacheEntry: shadowCacheFileChange.cacheEntry,
1126 }
1127 }
1128 }
1129
1130 if (fileChangedCache.result === 'file-not-in-cache') {
1131 return {
1132 status: 'stale',
1133 }
1134 }
1135 return { status: 'stale', cacheEntry: fileChangedCache.cacheEntry }
1136 }
1137
1138 private async handleRootNode(node: RouteNode) {
1139 const result = await this.isRouteFileCacheFresh(node)
1140
1141 if (result.status === 'fresh') {
1142 this.routeNodeShadowCache.set(node.fullPath, result.cacheEntry)
1143 }
1144 const rootNodeFile = await this.fs.readFile(node.fullPath)
1145 if (rootNodeFile === 'file-not-existing') {
1146 throw new Error(`⚠️ expected root route to exist at ${node.fullPath}`)
1147 }
1148
1149 const updatedCacheEntry: RouteNodeCacheEntry = {
1150 fileContent: rootNodeFile.fileContent,
1151 mtimeMs: rootNodeFile.stat.mtimeMs,
1152 routeId: node.routePath ?? '$$TSR_NO_ROOT_ROUTE_PATH_ASSIGNED$$',
1153 node,
1154 }
1155
1156 // scaffold the root route
1157 if (!rootNodeFile.fileContent) {
1158 const rootTemplate = this.targetTemplate.rootRoute
1159 const rootRouteContent = await fillTemplate(
1160 this.config,
1161 rootTemplate.template(),
1162 {
1163 tsrImports: rootTemplate.imports.tsrImports(),
1164 tsrPath: rootPathId,
1165 tsrExportStart: rootTemplate.imports.tsrExportStart(),
1166 tsrExportEnd: rootTemplate.imports.tsrExportEnd(),
1167 },
1168 )
1169
1170 this.logger.log(`🟡 Creating ${node.fullPath}`)
1171 const stats = await this.safeFileWrite({
1172 filePath: node.fullPath,
1173 newContent: rootRouteContent,
1174 strategy: {
1175 type: 'mtime',
1176 expectedMtimeMs: rootNodeFile.stat.mtimeMs,
1177 },
1178 })
1179 updatedCacheEntry.fileContent = rootRouteContent
1180 updatedCacheEntry.mtimeMs = stats.mtimeMs
1181 }
1182
1183 this.routeNodeShadowCache.set(node.fullPath, updatedCacheEntry)
1184 }
1185
1186 public async getCrawlingResult(): Promise<CrawlingResult | undefined> {
1187 await this.runPromise
1188 return this.crawlingResult
1189 }
1190
1191 private static handleNode(
1192 node: RouteNode,
1193 acc: HandleNodeAccumulator,
1194 config?: Config,
1195 ) {
1196 // Do not remove this as we need to set the lastIndex to 0 as it
1197 // is necessary to reset the regex's index when using the global flag
1198 // otherwise it might not match the next time it's used
1199 const useExperimentalNonNestedRoutes =
1200 config?.experimental?.nonNestedRoutes ?? false
1201
1202 resetRegex(this.routeGroupPatternRegex)
1203
1204 let parentRoute = hasParentRoute(
1205 acc.routeNodes,
1206 node,
1207 node.routePath,
1208 node.originalRoutePath,
1209 )
1210
1211 // if the parent route is a virtual parent route, we need to find the real parent route
1212 if (parentRoute?.isVirtualParentRoute && parentRoute.children?.length) {
1213 // only if this sub-parent route returns a valid parent route, we use it, if not leave it as it
1214 const possibleParentRoute = hasParentRoute(
1215 parentRoute.children,
1216 node,
1217 node.routePath,
1218 node.originalRoutePath,
1219 )
1220 if (possibleParentRoute) {
1221 parentRoute = possibleParentRoute
1222 }
1223 }
1224
1225 if (parentRoute) node.parent = parentRoute
1226
1227 node.path = determineNodePath(node)
1228
1229 const trimmedPath = trimPathLeft(node.path ?? '')
1230
1231 const split = trimmedPath.split('/')
1232 const lastRouteSegment = split[split.length - 1] ?? trimmedPath
1233
1234 node.isNonPath =
1235 lastRouteSegment.startsWith('_') ||
1236 split.every((part) => this.routeGroupPatternRegex.test(part))
1237
1238 // with new nonNestedPaths feature we can be sure any remaining trailing underscores are escaped and should remain
1239 // TODO with new major we can remove check and only remove leading underscores
1240 node.cleanedPath = removeGroups(
1241 (useExperimentalNonNestedRoutes
1242 ? removeLeadingUnderscores(
1243 removeLayoutSegments(node.path ?? ''),
1244 config?.routeToken ?? '',
1245 )
1246 : removeUnderscores(removeLayoutSegments(node.path))) ?? '',
1247 )
1248
1249 if (
1250 node._fsRouteType === 'layout' ||
1251 node._fsRouteType === 'pathless_layout'
1252 ) {
1253 node.cleanedPath = removeTrailingSlash(node.cleanedPath)
1254 }
1255
1256 if (
1257 !node.isVirtual &&
1258 (
1259 [
1260 'lazy',
1261 'loader',
1262 'component',
1263 'pendingComponent',
1264 'errorComponent',
1265 ] satisfies Array<FsRouteType>
1266 ).some((d) => d === node._fsRouteType)
1267 ) {
1268 acc.routePiecesByPath[node.routePath!] =
1269 acc.routePiecesByPath[node.routePath!] || {}
1270
1271 acc.routePiecesByPath[node.routePath!]![
1272 node._fsRouteType === 'lazy'
1273 ? 'lazy'
1274 : node._fsRouteType === 'loader'
1275 ? 'loader'
1276 : node._fsRouteType === 'errorComponent'
1277 ? 'errorComponent'
1278 : node._fsRouteType === 'pendingComponent'
1279 ? 'pendingComponent'
1280 : 'component'
1281 ] = node
1282
1283 const anchorRoute = acc.routeNodes.find(
1284 (d) => d.routePath === node.routePath,
1285 )
1286
1287 if (!anchorRoute) {
1288 this.handleNode(
1289 {
1290 ...node,
1291 isVirtual: true,
1292 _fsRouteType: 'static',
1293 },
1294 acc,
1295 config,
1296 )
1297 }
1298 return
1299 }
1300
1301 const cleanedPathIsEmpty = (node.cleanedPath || '').length === 0
1302 const nonPathRoute =
1303 node._fsRouteType === 'pathless_layout' && node.isNonPath
1304
1305 node.isVirtualParentRequired =
1306 node._fsRouteType === 'pathless_layout' || nonPathRoute
1307 ? !cleanedPathIsEmpty
1308 : false
1309
1310 if (!node.isVirtual && node.isVirtualParentRequired) {
1311 const parentRoutePath = removeLastSegmentFromPath(node.routePath) || '/'
1312 const parentVariableName = routePathToVariable(parentRoutePath)
1313
1314 const anchorRoute = acc.routeNodes.find(
1315 (d) => d.routePath === parentRoutePath,
1316 )
1317
1318 if (!anchorRoute) {
1319 const parentNode: RouteNode = {
1320 ...node,
1321 path: removeLastSegmentFromPath(node.path) || '/',
1322 filePath: removeLastSegmentFromPath(node.filePath) || '/',
1323 fullPath: removeLastSegmentFromPath(node.fullPath) || '/',
1324 routePath: parentRoutePath,
1325 variableName: parentVariableName,
1326 isVirtual: true,
1327 _fsRouteType: 'layout', // layout since this route will wrap other routes
1328 isVirtualParentRoute: true,
1329 isVirtualParentRequired: false,
1330 }
1331
1332 parentNode.children = parentNode.children ?? []
1333 parentNode.children.push(node)
1334
1335 node.parent = parentNode
1336
1337 if (node._fsRouteType === 'pathless_layout') {
1338 // since `node.path` is used as the `id` on the route definition, we need to update it
1339 node.path = determineNodePath(node)
1340 }
1341
1342 this.handleNode(parentNode, acc, config)
1343 } else {
1344 anchorRoute.children = anchorRoute.children ?? []
1345 anchorRoute.children.push(node)
1346
1347 node.parent = anchorRoute
1348 }
1349 }
1350
1351 if (node.parent) {
1352 if (!node.isVirtualParentRequired) {
1353 node.parent.children = node.parent.children ?? []
1354 node.parent.children.push(node)
1355 }
1356 } else {
1357 acc.routeTree.push(node)
1358 }
1359
1360 acc.routeNodes.push(node)
1361 }
1362
1363 // only process files that are relevant for the route tree generation
1364 private isFileRelevantForRouteTreeGeneration(filePath: string): boolean {
1365 // the generated route tree file
1366 if (filePath === this.generatedRouteTreePath) {
1367 return true
1368 }
1369
1370 // files inside the routes folder
1371 if (filePath.startsWith(this.routesDirectoryPath)) {
1372 return true
1373 }
1374
1375 // the virtual route config file passed into `virtualRouteConfig`
1376 if (
1377 typeof this.config.virtualRouteConfig === 'string' &&
1378 filePath === this.config.virtualRouteConfig
1379 ) {
1380 return true
1381 }
1382
1383 // this covers all files that are mounted via `virtualRouteConfig` or any `__virtual.ts` files
1384 if (this.routeNodeCache.has(filePath)) {
1385 return true
1386 }
1387
1388 // virtual config files such as`__virtual.ts`
1389 if (isVirtualConfigFile(path.basename(filePath))) {
1390 return true
1391 }
1392
1393 // route files inside directories mounted via `physical()` inside a virtual route config
1394 if (this.physicalDirectories.some((dir) => filePath.startsWith(dir))) {
1395 return true
1396 }
1397
1398 return false
1399 }
1400}