@tanstack/router-generator 1.141.4 → 1.141.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"generator.js","sources":["../../src/generator.ts"],"sourcesContent":["import path from 'node:path'\nimport * as fsp from 'node:fs/promises'\nimport { existsSync, mkdirSync } from 'node:fs'\nimport crypto from 'node:crypto'\nimport { rootRouteId } from '@tanstack/router-core'\nimport { logging } from './logger'\nimport {\n isVirtualConfigFile,\n getRouteNodes as physicalGetRouteNodes,\n} from './filesystem/physical/getRouteNodes'\nimport { getRouteNodes as virtualGetRouteNodes } from './filesystem/virtual/getRouteNodes'\nimport { rootPathId } from './filesystem/physical/rootPathId'\nimport {\n buildFileRoutesByPathInterface,\n buildImportString,\n buildRouteTreeConfig,\n checkFileExists,\n checkRouteFullPathUniqueness,\n createRouteNodesByFullPath,\n createRouteNodesById,\n createRouteNodesByTo,\n determineNodePath,\n findParent,\n format,\n getImportForRouteNode,\n getImportPath,\n getResolvedRouteNodeVariableName,\n hasParentRoute,\n isRouteNodeValidForAugmentation,\n mergeImportDeclarations,\n multiSortBy,\n removeExt,\n removeGroups,\n removeLastSegmentFromPath,\n removeLayoutSegments,\n removeLeadingUnderscores,\n removeTrailingSlash,\n removeUnderscores,\n replaceBackslash,\n resetRegex,\n routePathToVariable,\n trimPathLeft,\n} from './utils'\nimport { fillTemplate, getTargetTemplate } from './template'\nimport { transform } from './transform/transform'\nimport type { GeneratorPlugin } from './plugin/types'\nimport type { TargetTemplate } from './template'\nimport type {\n FsRouteType,\n GetRouteNodesResult,\n GetRoutesByFileMapResult,\n HandleNodeAccumulator,\n ImportDeclaration,\n RouteNode,\n} from './types'\nimport type { Config } from './config'\nimport type { Logger } from './logger'\n\ninterface fs {\n stat: (\n filePath: string,\n ) => Promise<{ mtimeMs: bigint; mode: number; uid: number; gid: number }>\n rename: (oldPath: string, newPath: string) => Promise<void>\n writeFile: (filePath: string, content: string) => Promise<void>\n readFile: (\n filePath: string,\n ) => Promise<\n { stat: { mtimeMs: bigint }; fileContent: string } | 'file-not-existing'\n >\n chmod: (filePath: string, mode: number) => Promise<void>\n chown: (filePath: string, uid: number, gid: number) => Promise<void>\n}\n\nconst DefaultFileSystem: fs = {\n stat: async (filePath) => {\n const res = await fsp.stat(filePath, { bigint: true })\n return {\n mtimeMs: res.mtimeMs,\n mode: Number(res.mode),\n uid: Number(res.uid),\n gid: Number(res.gid),\n }\n },\n rename: (oldPath, newPath) => fsp.rename(oldPath, newPath),\n writeFile: (filePath, content) => fsp.writeFile(filePath, content),\n readFile: async (filePath: string) => {\n try {\n const fileHandle = await fsp.open(filePath, 'r')\n const stat = await fileHandle.stat({ bigint: true })\n const fileContent = (await fileHandle.readFile()).toString()\n await fileHandle.close()\n return { stat, fileContent }\n } catch (e: any) {\n if ('code' in e) {\n if (e.code === 'ENOENT') {\n return 'file-not-existing'\n }\n }\n throw e\n }\n },\n chmod: (filePath, mode) => fsp.chmod(filePath, mode),\n chown: (filePath, uid, gid) => fsp.chown(filePath, uid, gid),\n}\n\ninterface Rerun {\n rerun: true\n msg?: string\n event: GeneratorEvent\n}\nfunction rerun(opts: { msg?: string; event?: GeneratorEvent }): Rerun {\n const { event, ...rest } = opts\n return { rerun: true, event: event ?? { type: 'rerun' }, ...rest }\n}\n\nfunction isRerun(result: unknown): result is Rerun {\n return (\n typeof result === 'object' &&\n result !== null &&\n 'rerun' in result &&\n result.rerun === true\n )\n}\n\nexport type FileEventType = 'create' | 'update' | 'delete'\nexport type FileEvent = {\n type: FileEventType\n path: string\n}\nexport type GeneratorEvent = FileEvent | { type: 'rerun' }\n\ntype FileCacheChange<TCacheEntry extends GeneratorCacheEntry> =\n | {\n result: false\n cacheEntry: TCacheEntry\n }\n | { result: true; mtimeMs: bigint; cacheEntry: TCacheEntry }\n | {\n result: 'file-not-in-cache'\n }\n | {\n result: 'cannot-stat-file'\n }\n\ninterface GeneratorCacheEntry {\n mtimeMs: bigint\n fileContent: string\n}\n\ninterface RouteNodeCacheEntry extends GeneratorCacheEntry {\n routeId: string\n node: RouteNode\n}\n\ntype GeneratorRouteNodeCache = Map</** filePath **/ string, RouteNodeCacheEntry>\n\ninterface CrawlingResult {\n rootRouteNode: RouteNode\n routeFileResult: Array<RouteNode>\n acc: HandleNodeAccumulator\n}\n\nexport class Generator {\n /**\n * why do we have two caches for the route files?\n * During processing, we READ from the cache and WRITE to the shadow cache.\n *\n * After a route file is processed, we write to the shadow cache.\n * If during processing we bail out and re-run, we don't lose this modification\n * but still can track whether the file contributed changes and thus the route tree file needs to be regenerated.\n * After all files are processed, we swap the shadow cache with the main cache and initialize a new shadow cache.\n * That way we also ensure deleted/renamed files don't stay in the cache forever.\n */\n private routeNodeCache: GeneratorRouteNodeCache = new Map()\n private routeNodeShadowCache: GeneratorRouteNodeCache = new Map()\n\n private routeTreeFileCache: GeneratorCacheEntry | undefined\n\n private crawlingResult: CrawlingResult | undefined\n public config: Config\n public targetTemplate: TargetTemplate\n\n private root: string\n private routesDirectoryPath: string\n private sessionId?: string\n private fs: fs\n private logger: Logger\n private generatedRouteTreePath: string\n private runPromise: Promise<void> | undefined\n private fileEventQueue: Array<GeneratorEvent> = []\n private plugins: Array<GeneratorPlugin> = []\n private static routeGroupPatternRegex = /\\(.+\\)/g\n private physicalDirectories: Array<string> = []\n\n constructor(opts: { config: Config; root: string; fs?: fs }) {\n this.config = opts.config\n this.logger = logging({ disabled: this.config.disableLogging })\n this.root = opts.root\n this.fs = opts.fs || DefaultFileSystem\n this.generatedRouteTreePath = this.getGeneratedRouteTreePath()\n this.targetTemplate = getTargetTemplate(this.config)\n\n this.routesDirectoryPath = this.getRoutesDirectoryPath()\n this.plugins.push(...(opts.config.plugins || []))\n\n for (const plugin of this.plugins) {\n plugin.init?.({ generator: this })\n }\n }\n\n private getGeneratedRouteTreePath() {\n const generatedRouteTreePath = path.isAbsolute(\n this.config.generatedRouteTree,\n )\n ? this.config.generatedRouteTree\n : path.resolve(this.root, this.config.generatedRouteTree)\n\n const generatedRouteTreeDir = path.dirname(generatedRouteTreePath)\n\n if (!existsSync(generatedRouteTreeDir)) {\n mkdirSync(generatedRouteTreeDir, { recursive: true })\n }\n\n return generatedRouteTreePath\n }\n\n private getRoutesDirectoryPath() {\n return path.isAbsolute(this.config.routesDirectory)\n ? this.config.routesDirectory\n : path.resolve(this.root, this.config.routesDirectory)\n }\n\n public getRoutesByFileMap(): GetRoutesByFileMapResult {\n return new Map(\n [...this.routeNodeCache.entries()].map(([filePath, cacheEntry]) => [\n filePath,\n { routePath: cacheEntry.routeId },\n ]),\n )\n }\n\n public async run(event?: GeneratorEvent): Promise<void> {\n if (\n event &&\n event.type !== 'rerun' &&\n !this.isFileRelevantForRouteTreeGeneration(event.path)\n ) {\n return\n }\n this.fileEventQueue.push(event ?? { type: 'rerun' })\n // only allow a single run at a time\n if (this.runPromise) {\n return this.runPromise\n }\n\n this.runPromise = (async () => {\n do {\n // synchronously copy and clear the queue since we are going to iterate asynchronously over it\n // and while we do so, a new event could be put into the queue\n const tempQueue = this.fileEventQueue\n this.fileEventQueue = []\n // if we only have 'update' events in the queue\n // and we already have the affected files' latest state in our cache, we can exit early\n const remainingEvents = (\n await Promise.all(\n tempQueue.map(async (e) => {\n if (e.type === 'update') {\n let cacheEntry: GeneratorCacheEntry | undefined\n if (e.path === this.generatedRouteTreePath) {\n cacheEntry = this.routeTreeFileCache\n } else {\n // we only check the routeNodeCache here\n // if the file's state is only up-to-date in the shadow cache we need to re-run\n cacheEntry = this.routeNodeCache.get(e.path)\n }\n const change = await this.didFileChangeComparedToCache(\n { path: e.path },\n cacheEntry,\n )\n if (change.result === false) {\n return null\n }\n }\n return e\n }),\n )\n ).filter((e) => e !== null)\n\n if (remainingEvents.length === 0) {\n break\n }\n\n try {\n await this.generatorInternal()\n } catch (err) {\n const errArray = !Array.isArray(err) ? [err] : err\n\n const recoverableErrors = errArray.filter((e) => isRerun(e))\n if (recoverableErrors.length === errArray.length) {\n this.fileEventQueue.push(...recoverableErrors.map((e) => e.event))\n recoverableErrors.forEach((e) => {\n if (e.msg) {\n this.logger.info(e.msg)\n }\n })\n } else {\n const unrecoverableErrors = errArray.filter((e) => !isRerun(e))\n this.runPromise = undefined\n throw new Error(\n unrecoverableErrors.map((e) => (e as Error).message).join(),\n )\n }\n }\n } while (this.fileEventQueue.length)\n this.runPromise = undefined\n })()\n return this.runPromise\n }\n\n private async generatorInternal() {\n let writeRouteTreeFile: boolean | 'force' = false\n\n let getRouteNodesResult: GetRouteNodesResult\n\n if (this.config.virtualRouteConfig) {\n getRouteNodesResult = await virtualGetRouteNodes(this.config, this.root)\n } else {\n getRouteNodesResult = await physicalGetRouteNodes(this.config, this.root)\n }\n\n const {\n rootRouteNode,\n routeNodes: beforeRouteNodes,\n physicalDirectories,\n } = getRouteNodesResult\n if (rootRouteNode === undefined) {\n let errorMessage = `rootRouteNode must not be undefined. Make sure you've added your root route into the route-tree.`\n if (!this.config.virtualRouteConfig) {\n 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'}\"`\n }\n throw new Error(errorMessage)\n }\n this.physicalDirectories = physicalDirectories\n\n await this.handleRootNode(rootRouteNode)\n\n const preRouteNodes = multiSortBy(beforeRouteNodes, [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) =>\n d.filePath.match(new RegExp(`[./]${this.config.indexToken}[.]`))\n ? 1\n : -1,\n (d) =>\n d.filePath.match(\n /[./](component|errorComponent|notFoundComponent|pendingComponent|loader|lazy)[.]/,\n )\n ? 1\n : -1,\n (d) =>\n d.filePath.match(new RegExp(`[./]${this.config.routeToken}[.]`))\n ? -1\n : 1,\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter((d) => {\n // Exclude the root route itself, but keep component/loader pieces for the root\n if (d.routePath === `/${rootPathId}`) {\n return [\n 'component',\n 'errorComponent',\n 'notFoundComponent',\n 'pendingComponent',\n 'loader',\n 'lazy',\n ].includes(d._fsRouteType)\n }\n return true\n })\n\n const routeFileAllResult = await Promise.allSettled(\n preRouteNodes\n // only process routes that are backed by an actual file\n .filter((n) => !n.isVirtualParentRoute && !n.isVirtual)\n .map((n) => this.processRouteNodeFile(n)),\n )\n\n const rejections = routeFileAllResult.filter(\n (result) => result.status === 'rejected',\n )\n if (rejections.length > 0) {\n throw rejections.map((e) => e.reason)\n }\n\n const routeFileResult = routeFileAllResult.flatMap((result) => {\n if (result.status === 'fulfilled' && result.value !== null) {\n if (result.value.shouldWriteTree) {\n writeRouteTreeFile = true\n }\n return result.value.node\n }\n return []\n })\n\n // reset children in case we re-use a node from the cache\n routeFileResult.forEach((r) => (r.children = undefined))\n\n const acc: HandleNodeAccumulator = {\n routeTree: [],\n routeNodes: [],\n routePiecesByPath: {},\n }\n\n for (const node of routeFileResult) {\n Generator.handleNode(node, acc, this.config)\n }\n\n this.crawlingResult = { rootRouteNode, routeFileResult, acc }\n\n // this is the first time the generator runs, so read in the route tree file if it exists yet\n if (!this.routeTreeFileCache) {\n const routeTreeFile = await this.fs.readFile(this.generatedRouteTreePath)\n if (routeTreeFile !== 'file-not-existing') {\n this.routeTreeFileCache = {\n fileContent: routeTreeFile.fileContent,\n mtimeMs: routeTreeFile.stat.mtimeMs,\n }\n }\n writeRouteTreeFile = true\n } else {\n const routeTreeFileChange = await this.didFileChangeComparedToCache(\n { path: this.generatedRouteTreePath },\n this.routeTreeFileCache,\n )\n if (routeTreeFileChange.result !== false) {\n writeRouteTreeFile = 'force'\n if (routeTreeFileChange.result === true) {\n const routeTreeFile = await this.fs.readFile(\n this.generatedRouteTreePath,\n )\n if (routeTreeFile !== 'file-not-existing') {\n this.routeTreeFileCache = {\n fileContent: routeTreeFile.fileContent,\n mtimeMs: routeTreeFile.stat.mtimeMs,\n }\n }\n }\n }\n }\n\n if (!writeRouteTreeFile) {\n // only needs to be done if no other changes have been detected yet\n // compare shadowCache and cache to identify deleted routes\n if (this.routeNodeCache.size !== this.routeNodeShadowCache.size) {\n writeRouteTreeFile = true\n } else {\n for (const fullPath of this.routeNodeCache.keys()) {\n if (!this.routeNodeShadowCache.has(fullPath)) {\n writeRouteTreeFile = true\n break\n }\n }\n }\n }\n\n if (!writeRouteTreeFile) {\n this.swapCaches()\n return\n }\n\n const buildResult = this.buildRouteTree({\n rootRouteNode,\n acc,\n routeFileResult,\n })\n let routeTreeContent = buildResult.routeTreeContent\n\n routeTreeContent = this.config.enableRouteTreeFormatting\n ? await format(routeTreeContent, this.config)\n : routeTreeContent\n\n let newMtimeMs: bigint | undefined\n if (this.routeTreeFileCache) {\n if (\n writeRouteTreeFile !== 'force' &&\n this.routeTreeFileCache.fileContent === routeTreeContent\n ) {\n // existing route tree file is already up-to-date, don't write it\n // we should only get here in the initial run when the route cache is not filled yet\n } else {\n const newRouteTreeFileStat = await this.safeFileWrite({\n filePath: this.generatedRouteTreePath,\n newContent: routeTreeContent,\n strategy: {\n type: 'mtime',\n expectedMtimeMs: this.routeTreeFileCache.mtimeMs,\n },\n })\n newMtimeMs = newRouteTreeFileStat.mtimeMs\n }\n } else {\n const newRouteTreeFileStat = await this.safeFileWrite({\n filePath: this.generatedRouteTreePath,\n newContent: routeTreeContent,\n strategy: {\n type: 'new-file',\n },\n })\n newMtimeMs = newRouteTreeFileStat.mtimeMs\n }\n\n if (newMtimeMs !== undefined) {\n this.routeTreeFileCache = {\n fileContent: routeTreeContent,\n mtimeMs: newMtimeMs,\n }\n }\n\n this.plugins.map((plugin) => {\n return plugin.onRouteTreeChanged?.({\n routeTree: buildResult.routeTree,\n routeNodes: buildResult.routeNodes,\n acc,\n rootRouteNode,\n })\n })\n this.swapCaches()\n }\n\n private swapCaches() {\n this.routeNodeCache = this.routeNodeShadowCache\n this.routeNodeShadowCache = new Map()\n }\n\n public buildRouteTree(opts: {\n rootRouteNode: RouteNode\n acc: HandleNodeAccumulator\n routeFileResult: Array<RouteNode>\n config?: Partial<Config>\n }) {\n const config = { ...this.config, ...(opts.config || {}) }\n\n const { rootRouteNode, acc } = opts\n\n const sortedRouteNodes = multiSortBy(acc.routeNodes, [\n (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(config.indexToken) ? -1 : 1),\n (d) => d,\n ])\n\n const routeImports = sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .flatMap((node) =>\n getImportForRouteNode(\n node,\n config,\n this.generatedRouteTreePath,\n this.root,\n ),\n )\n\n const virtualRouteNodes = sortedRouteNodes\n .filter((d) => d.isVirtual)\n .map((node) => {\n return `const ${\n node.variableName\n }RouteImport = createFileRoute('${node.routePath}')()`\n })\n\n const imports: Array<ImportDeclaration> = []\n if (acc.routeNodes.some((n) => n.isVirtual)) {\n imports.push({\n specifiers: [{ imported: 'createFileRoute' }],\n source: this.targetTemplate.fullPkg,\n })\n }\n // Add lazyRouteComponent import if there are component pieces\n const hasComponentPieces = sortedRouteNodes.some(\n (node) =>\n acc.routePiecesByPath[node.routePath!]?.component ||\n acc.routePiecesByPath[node.routePath!]?.errorComponent ||\n acc.routePiecesByPath[node.routePath!]?.notFoundComponent ||\n acc.routePiecesByPath[node.routePath!]?.pendingComponent,\n )\n // Add lazyFn import if there are loader pieces\n const hasLoaderPieces = sortedRouteNodes.some(\n (node) => acc.routePiecesByPath[node.routePath!]?.loader,\n )\n if (hasComponentPieces || hasLoaderPieces) {\n const runtimeImport: ImportDeclaration = {\n specifiers: [],\n source: this.targetTemplate.fullPkg,\n }\n if (hasComponentPieces) {\n runtimeImport.specifiers.push({ imported: 'lazyRouteComponent' })\n }\n if (hasLoaderPieces) {\n runtimeImport.specifiers.push({ imported: 'lazyFn' })\n }\n imports.push(runtimeImport)\n }\n if (config.verboseFileRoutes === false) {\n const typeImport: ImportDeclaration = {\n specifiers: [],\n source: this.targetTemplate.fullPkg,\n importKind: 'type',\n }\n if (\n sortedRouteNodes.some(\n (d) =>\n isRouteNodeValidForAugmentation(d) && d._fsRouteType !== 'lazy',\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateFileRoute' })\n }\n if (\n sortedRouteNodes.some(\n (node) =>\n acc.routePiecesByPath[node.routePath!]?.lazy &&\n isRouteNodeValidForAugmentation(node),\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateLazyFileRoute' })\n }\n\n if (typeImport.specifiers.length > 0) {\n typeImport.specifiers.push({ imported: 'FileRoutesByPath' })\n imports.push(typeImport)\n }\n }\n\n const routeTreeConfig = buildRouteTreeConfig(\n acc.routeTree,\n config.disableTypes,\n )\n\n const createUpdateRoutes = sortedRouteNodes.map((node) => {\n const loaderNode = acc.routePiecesByPath[node.routePath!]?.loader\n const componentNode = acc.routePiecesByPath[node.routePath!]?.component\n const errorComponentNode =\n acc.routePiecesByPath[node.routePath!]?.errorComponent\n const notFoundComponentNode =\n acc.routePiecesByPath[node.routePath!]?.notFoundComponent\n const pendingComponentNode =\n acc.routePiecesByPath[node.routePath!]?.pendingComponent\n const lazyComponentNode = acc.routePiecesByPath[node.routePath!]?.lazy\n\n return [\n [\n `const ${node.variableName}Route = ${node.variableName}RouteImport.update({\n ${[\n `id: '${node.path}'`,\n !node.isNonPath ? `path: '${node.cleanedPath}'` : undefined,\n `getParentRoute: () => ${findParent(node)}`,\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 config.addExtensions,\n ),\n )}'), 'loader') })`\n : '',\n componentNode ||\n errorComponentNode ||\n notFoundComponentNode ||\n pendingComponentNode\n ? `.update({\n ${(\n [\n ['component', componentNode],\n ['errorComponent', errorComponentNode],\n ['notFoundComponent', notFoundComponentNode],\n ['pendingComponent', pendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n // For .vue files, use 'default' as the export name since Vue SFCs export default\n const isVueFile = d[1]!.filePath.endsWith('.vue')\n const exportName = isVueFile ? 'default' : d[0]\n // Keep .vue extension for Vue files since Vite requires it\n const importPath = replaceBackslash(\n isVueFile\n ? path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n d[1]!.filePath,\n ),\n )\n : removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n d[1]!.filePath,\n ),\n ),\n config.addExtensions,\n ),\n )\n return `${\n d[0]\n }: lazyRouteComponent(() => import('./${importPath}'), '${exportName}')`\n })\n .join('\\n,')}\n })`\n : '',\n lazyComponentNode\n ? (() => {\n // For .vue files, use 'default' export since Vue SFCs export default\n const isVueFile = lazyComponentNode.filePath.endsWith('.vue')\n const exportAccessor = isVueFile ? 'd.default' : 'd.Route'\n // Keep .vue extension for Vue files since Vite requires it\n const importPath = replaceBackslash(\n isVueFile\n ? path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n lazyComponentNode.filePath,\n ),\n )\n : removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n lazyComponentNode.filePath,\n ),\n ),\n config.addExtensions,\n ),\n )\n return `.lazy(() => import('./${importPath}').then((d) => ${exportAccessor}))`\n })()\n : '',\n ].join(''),\n ].join('\\n\\n')\n })\n\n // Generate update for root route if it has component pieces\n const rootRoutePath = `/${rootPathId}`\n const rootComponentNode = acc.routePiecesByPath[rootRoutePath]?.component\n const rootErrorComponentNode =\n acc.routePiecesByPath[rootRoutePath]?.errorComponent\n const rootNotFoundComponentNode =\n acc.routePiecesByPath[rootRoutePath]?.notFoundComponent\n const rootPendingComponentNode =\n acc.routePiecesByPath[rootRoutePath]?.pendingComponent\n\n let rootRouteUpdate = ''\n if (\n rootComponentNode ||\n rootErrorComponentNode ||\n rootNotFoundComponentNode ||\n rootPendingComponentNode\n ) {\n rootRouteUpdate = `const rootRouteWithChildren = rootRouteImport${\n rootComponentNode ||\n rootErrorComponentNode ||\n rootNotFoundComponentNode ||\n rootPendingComponentNode\n ? `.update({\n ${(\n [\n ['component', rootComponentNode],\n ['errorComponent', rootErrorComponentNode],\n ['notFoundComponent', rootNotFoundComponentNode],\n ['pendingComponent', rootPendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n // For .vue files, use 'default' as the export name since Vue SFCs export default\n const isVueFile = d[1]!.filePath.endsWith('.vue')\n const exportName = isVueFile ? 'default' : d[0]\n // Keep .vue extension for Vue files since Vite requires it\n const importPath = replaceBackslash(\n isVueFile\n ? path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, d[1]!.filePath),\n )\n : removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n d[1]!.filePath,\n ),\n ),\n config.addExtensions,\n ),\n )\n return `${d[0]}: lazyRouteComponent(() => import('./${importPath}'), '${exportName}')`\n })\n .join('\\n,')}\n })`\n : ''\n }._addFileChildren(rootRouteChildren)${config.disableTypes ? '' : `._addFileTypes<FileRouteTypes>()`}`\n }\n\n let fileRoutesByPathInterface = ''\n let fileRoutesByFullPath = ''\n\n if (!config.disableTypes) {\n fileRoutesByFullPath = [\n `export interface FileRoutesByFullPath {\n${[...createRouteNodesByFullPath(acc.routeNodes, config).entries()]\n .filter(([fullPath]) => fullPath)\n .map(([fullPath, routeNode]) => {\n return `'${fullPath}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRoutesByTo {\n${[...createRouteNodesByTo(acc.routeNodes, config).entries()]\n .filter(([to]) => to)\n .map(([to, routeNode]) => {\n return `'${to}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRoutesById {\n'${rootRouteId}': typeof rootRouteImport,\n${[...createRouteNodesById(acc.routeNodes).entries()].map(([id, routeNode]) => {\n return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n})}\n}`,\n `export interface FileRouteTypes {\nfileRoutesByFullPath: FileRoutesByFullPath\nfullPaths: ${\n acc.routeNodes.length > 0\n ? [...createRouteNodesByFullPath(acc.routeNodes, config).keys()]\n .filter((fullPath) => fullPath)\n .map((fullPath) => `'${fullPath}'`)\n .join('|')\n : 'never'\n }\nfileRoutesByTo: FileRoutesByTo\nto: ${\n acc.routeNodes.length > 0\n ? [...createRouteNodesByTo(acc.routeNodes, config).keys()]\n .filter((to) => to)\n .map((to) => `'${to}'`)\n .join('|')\n : 'never'\n }\nid: ${[`'${rootRouteId}'`, ...[...createRouteNodesById(acc.routeNodes).keys()].map((id) => `'${id}'`)].join('|')}\nfileRoutesById: FileRoutesById\n}`,\n `export interface RootRouteChildren {\n${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`,\n ].join('\\n')\n\n fileRoutesByPathInterface = buildFileRoutesByPathInterface({\n module: this.targetTemplate.fullPkg,\n interfaceName: 'FileRoutesByPath',\n routeNodes: sortedRouteNodes,\n config,\n })\n }\n\n const routeTree = [\n `const rootRouteChildren${config.disableTypes ? '' : `: RootRouteChildren`} = {\n ${acc.routeTree\n .map(\n (child) =>\n `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,\n )\n .join(',')}\n}`,\n rootRouteUpdate\n ? rootRouteUpdate.replace(\n 'const rootRouteWithChildren = ',\n 'export const routeTree = ',\n )\n : `export const routeTree = rootRouteImport._addFileChildren(rootRouteChildren)${config.disableTypes ? '' : `._addFileTypes<FileRouteTypes>()`}`,\n ].join('\\n')\n\n checkRouteFullPathUniqueness(\n sortedRouteNodes.filter(\n (d) => d.children === undefined && 'lazy' !== d._fsRouteType,\n ),\n config,\n )\n\n let mergedImports = mergeImportDeclarations(imports)\n if (config.disableTypes) {\n mergedImports = mergedImports.filter((d) => d.importKind !== 'type')\n }\n\n const importStatements = mergedImports.map(buildImportString)\n\n let moduleAugmentation = ''\n if (config.verboseFileRoutes === false && !config.disableTypes) {\n moduleAugmentation = opts.routeFileResult\n .map((node) => {\n const getModuleDeclaration = (routeNode?: RouteNode) => {\n if (!isRouteNodeValidForAugmentation(routeNode)) {\n return ''\n }\n let moduleAugmentation = ''\n if (routeNode._fsRouteType === 'lazy') {\n moduleAugmentation = `const createLazyFileRoute: CreateLazyFileRoute<FileRoutesByPath['${routeNode.routePath}']['preLoaderRoute']>`\n } else {\n moduleAugmentation = `const createFileRoute: CreateFileRoute<'${routeNode.routePath}',\n FileRoutesByPath['${routeNode.routePath}']['parentRoute'],\n FileRoutesByPath['${routeNode.routePath}']['id'],\n FileRoutesByPath['${routeNode.routePath}']['path'],\n FileRoutesByPath['${routeNode.routePath}']['fullPath']\n >\n `\n }\n\n return `declare module './${getImportPath(routeNode, config, this.generatedRouteTreePath)}' {\n ${moduleAugmentation}\n }`\n }\n return getModuleDeclaration(node)\n })\n .join('\\n')\n }\n\n const rootRouteImport = getImportForRouteNode(\n rootRouteNode,\n config,\n this.generatedRouteTreePath,\n this.root,\n )\n routeImports.unshift(rootRouteImport)\n\n let footer: Array<string> = []\n if (config.routeTreeFileFooter) {\n if (Array.isArray(config.routeTreeFileFooter)) {\n footer = config.routeTreeFileFooter\n } else {\n footer = config.routeTreeFileFooter()\n }\n }\n const routeTreeContent = [\n ...config.routeTreeFileHeader,\n `// This file was automatically generated by TanStack Router.\n// You should NOT make any changes in this file as it will be overwritten.\n// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`,\n [...importStatements].join('\\n'),\n mergeImportDeclarations(routeImports).map(buildImportString).join('\\n'),\n virtualRouteNodes.join('\\n'),\n createUpdateRoutes.join('\\n'),\n fileRoutesByFullPath,\n fileRoutesByPathInterface,\n moduleAugmentation,\n routeTreeConfig.join('\\n'),\n routeTree,\n ...footer,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n return {\n routeTreeContent,\n routeTree: acc.routeTree,\n routeNodes: acc.routeNodes,\n }\n }\n\n private async processRouteNodeFile(node: RouteNode): Promise<{\n shouldWriteTree: boolean\n cacheEntry: RouteNodeCacheEntry\n node: RouteNode\n } | null> {\n const result = await this.isRouteFileCacheFresh(node)\n\n if (result.status === 'fresh') {\n return {\n node: result.cacheEntry.node,\n shouldWriteTree: false,\n cacheEntry: result.cacheEntry,\n }\n }\n\n const previousCacheEntry = result.cacheEntry\n\n const existingRouteFile = await this.fs.readFile(node.fullPath)\n if (existingRouteFile === 'file-not-existing') {\n throw new Error(`⚠️ File ${node.fullPath} does not exist`)\n }\n\n const updatedCacheEntry: RouteNodeCacheEntry = {\n fileContent: existingRouteFile.fileContent,\n mtimeMs: existingRouteFile.stat.mtimeMs,\n routeId: node.routePath ?? '$$TSR_NO_ROUTE_PATH_ASSIGNED$$',\n node,\n }\n\n const escapedRoutePath = node.routePath?.replaceAll('$', '$$') ?? ''\n\n let shouldWriteRouteFile = false\n let shouldWriteTree = false\n // now we need to either scaffold the file or transform it\n if (!existingRouteFile.fileContent) {\n shouldWriteRouteFile = true\n shouldWriteTree = true\n // Creating a new lazy route file\n if (node._fsRouteType === 'lazy') {\n const tLazyRouteTemplate = this.targetTemplate.lazyRoute\n // Check by default check if the user has a specific lazy route template\n // If not, check if the user has a route template and use that instead\n updatedCacheEntry.fileContent = await fillTemplate(\n this.config,\n (this.config.customScaffolding?.lazyRouteTemplate ||\n this.config.customScaffolding?.routeTemplate) ??\n tLazyRouteTemplate.template(),\n {\n tsrImports: tLazyRouteTemplate.imports.tsrImports(),\n tsrPath: escapedRoutePath.replaceAll(/\\{(.+?)\\}/gm, '$1'),\n tsrExportStart:\n tLazyRouteTemplate.imports.tsrExportStart(escapedRoutePath),\n tsrExportEnd: tLazyRouteTemplate.imports.tsrExportEnd(),\n },\n )\n } else if (\n // Creating a new normal route file\n (['layout', 'static'] satisfies Array<FsRouteType>).some(\n (d) => d === node._fsRouteType,\n ) ||\n (\n [\n 'component',\n 'pendingComponent',\n 'errorComponent',\n 'notFoundComponent',\n 'loader',\n ] satisfies Array<FsRouteType>\n ).every((d) => d !== node._fsRouteType)\n ) {\n const tRouteTemplate = this.targetTemplate.route\n updatedCacheEntry.fileContent = await fillTemplate(\n this.config,\n this.config.customScaffolding?.routeTemplate ??\n tRouteTemplate.template(),\n {\n tsrImports: tRouteTemplate.imports.tsrImports(),\n tsrPath: escapedRoutePath.replaceAll(/\\{(.+?)\\}/gm, '$1'),\n tsrExportStart:\n tRouteTemplate.imports.tsrExportStart(escapedRoutePath),\n tsrExportEnd: tRouteTemplate.imports.tsrExportEnd(),\n },\n )\n } else {\n return null\n }\n }\n\n // Check if this is a Vue component file\n // Vue SFC files (.vue) don't need transformation as they can't have a Route export\n const isVueFile = node.filePath.endsWith('.vue')\n\n if (!isVueFile) {\n // transform the file\n const transformResult = await transform({\n source: updatedCacheEntry.fileContent,\n ctx: {\n target: this.config.target,\n routeId: escapedRoutePath,\n lazy: node._fsRouteType === 'lazy',\n verboseFileRoutes: !(this.config.verboseFileRoutes === false),\n },\n node,\n })\n\n if (transformResult.result === 'no-route-export') {\n this.logger.warn(\n `Route file \"${node.fullPath}\" does not contain any route piece. This is likely a mistake.`,\n )\n return null\n }\n if (transformResult.result === 'error') {\n throw new Error(\n `Error transforming route file ${node.fullPath}: ${transformResult.error}`,\n )\n }\n if (transformResult.result === 'modified') {\n updatedCacheEntry.fileContent = transformResult.output\n shouldWriteRouteFile = true\n }\n }\n\n for (const plugin of this.plugins) {\n plugin.afterTransform?.({ node, prevNode: previousCacheEntry?.node })\n }\n\n // file was changed\n if (shouldWriteRouteFile) {\n const stats = await this.safeFileWrite({\n filePath: node.fullPath,\n newContent: updatedCacheEntry.fileContent,\n strategy: {\n type: 'mtime',\n expectedMtimeMs: updatedCacheEntry.mtimeMs,\n },\n })\n updatedCacheEntry.mtimeMs = stats.mtimeMs\n }\n\n this.routeNodeShadowCache.set(node.fullPath, updatedCacheEntry)\n return {\n node,\n shouldWriteTree,\n cacheEntry: updatedCacheEntry,\n }\n }\n\n private async didRouteFileChangeComparedToCache(\n file: {\n path: string\n mtimeMs?: bigint\n },\n cache: 'routeNodeCache' | 'routeNodeShadowCache',\n ): Promise<FileCacheChange<RouteNodeCacheEntry>> {\n const cacheEntry = this[cache].get(file.path)\n return this.didFileChangeComparedToCache(file, cacheEntry)\n }\n\n private async didFileChangeComparedToCache<\n TCacheEntry extends GeneratorCacheEntry,\n >(\n file: {\n path: string\n mtimeMs?: bigint\n },\n cacheEntry: TCacheEntry | undefined,\n ): Promise<FileCacheChange<TCacheEntry>> {\n // for now we rely on the modification time of the file\n // to determine if the file has changed\n // we could also compare the file content but this would be slower as we would have to read the file\n\n if (!cacheEntry) {\n return { result: 'file-not-in-cache' }\n }\n let mtimeMs = file.mtimeMs\n\n if (mtimeMs === undefined) {\n try {\n const currentStat = await this.fs.stat(file.path)\n mtimeMs = currentStat.mtimeMs\n } catch {\n return { result: 'cannot-stat-file' }\n }\n }\n return { result: mtimeMs !== cacheEntry.mtimeMs, mtimeMs, cacheEntry }\n }\n\n private async safeFileWrite(opts: {\n filePath: string\n newContent: string\n strategy:\n | {\n type: 'mtime'\n expectedMtimeMs: bigint\n }\n | {\n type: 'new-file'\n }\n }) {\n const tmpPath = this.getTempFileName(opts.filePath)\n await this.fs.writeFile(tmpPath, opts.newContent)\n\n if (opts.strategy.type === 'mtime') {\n const beforeStat = await this.fs.stat(opts.filePath)\n if (beforeStat.mtimeMs !== opts.strategy.expectedMtimeMs) {\n throw rerun({\n msg: `File ${opts.filePath} was modified by another process during processing.`,\n event: { type: 'update', path: opts.filePath },\n })\n }\n const newFileState = await this.fs.stat(tmpPath)\n if (newFileState.mode !== beforeStat.mode) {\n await this.fs.chmod(tmpPath, beforeStat.mode)\n }\n if (\n newFileState.uid !== beforeStat.uid ||\n newFileState.gid !== beforeStat.gid\n ) {\n try {\n await this.fs.chown(tmpPath, beforeStat.uid, beforeStat.gid)\n } catch (err) {\n if (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as any).code === 'EPERM'\n ) {\n console.warn(\n `[safeFileWrite] chown failed: ${(err as any).message}`,\n )\n } else {\n throw err\n }\n }\n }\n } else {\n if (await checkFileExists(opts.filePath)) {\n throw rerun({\n msg: `File ${opts.filePath} already exists. Cannot overwrite.`,\n event: { type: 'update', path: opts.filePath },\n })\n }\n }\n\n const stat = await this.fs.stat(tmpPath)\n\n await this.fs.rename(tmpPath, opts.filePath)\n\n return stat\n }\n\n private getTempFileName(filePath: string) {\n const absPath = path.resolve(filePath)\n const hash = crypto.createHash('md5').update(absPath).digest('hex')\n // lazy initialize sessionId to only create tmpDir when it is first needed\n if (!this.sessionId) {\n // ensure the directory exists\n mkdirSync(this.config.tmpDir, { recursive: true })\n this.sessionId = crypto.randomBytes(4).toString('hex')\n }\n return path.join(this.config.tmpDir, `${this.sessionId}-${hash}`)\n }\n\n private async isRouteFileCacheFresh(node: RouteNode): Promise<\n | {\n status: 'fresh'\n cacheEntry: RouteNodeCacheEntry\n }\n | { status: 'stale'; cacheEntry?: RouteNodeCacheEntry }\n > {\n const fileChangedCache = await this.didRouteFileChangeComparedToCache(\n { path: node.fullPath },\n 'routeNodeCache',\n )\n if (fileChangedCache.result === false) {\n this.routeNodeShadowCache.set(node.fullPath, fileChangedCache.cacheEntry)\n return {\n status: 'fresh',\n cacheEntry: fileChangedCache.cacheEntry,\n }\n }\n if (fileChangedCache.result === 'cannot-stat-file') {\n throw new Error(`⚠️ expected route file to exist at ${node.fullPath}`)\n }\n const mtimeMs =\n fileChangedCache.result === true ? fileChangedCache.mtimeMs : undefined\n\n const shadowCacheFileChange = await this.didRouteFileChangeComparedToCache(\n { path: node.fullPath, mtimeMs },\n 'routeNodeShadowCache',\n )\n\n if (shadowCacheFileChange.result === 'cannot-stat-file') {\n throw new Error(`⚠️ expected route file to exist at ${node.fullPath}`)\n }\n\n if (shadowCacheFileChange.result === false) {\n // shadow cache has latest file state already\n if (fileChangedCache.result === true) {\n return {\n status: 'fresh',\n cacheEntry: shadowCacheFileChange.cacheEntry,\n }\n }\n }\n\n if (fileChangedCache.result === 'file-not-in-cache') {\n return {\n status: 'stale',\n }\n }\n return { status: 'stale', cacheEntry: fileChangedCache.cacheEntry }\n }\n\n private async handleRootNode(node: RouteNode) {\n const result = await this.isRouteFileCacheFresh(node)\n\n if (result.status === 'fresh') {\n this.routeNodeShadowCache.set(node.fullPath, result.cacheEntry)\n }\n const rootNodeFile = await this.fs.readFile(node.fullPath)\n if (rootNodeFile === 'file-not-existing') {\n throw new Error(`⚠️ expected root route to exist at ${node.fullPath}`)\n }\n\n const updatedCacheEntry: RouteNodeCacheEntry = {\n fileContent: rootNodeFile.fileContent,\n mtimeMs: rootNodeFile.stat.mtimeMs,\n routeId: node.routePath ?? '$$TSR_NO_ROOT_ROUTE_PATH_ASSIGNED$$',\n node,\n }\n\n // scaffold the root route\n if (!rootNodeFile.fileContent) {\n const rootTemplate = this.targetTemplate.rootRoute\n const rootRouteContent = await fillTemplate(\n this.config,\n rootTemplate.template(),\n {\n tsrImports: rootTemplate.imports.tsrImports(),\n tsrPath: rootPathId,\n tsrExportStart: rootTemplate.imports.tsrExportStart(),\n tsrExportEnd: rootTemplate.imports.tsrExportEnd(),\n },\n )\n\n this.logger.log(`🟡 Creating ${node.fullPath}`)\n const stats = await this.safeFileWrite({\n filePath: node.fullPath,\n newContent: rootRouteContent,\n strategy: {\n type: 'mtime',\n expectedMtimeMs: rootNodeFile.stat.mtimeMs,\n },\n })\n updatedCacheEntry.fileContent = rootRouteContent\n updatedCacheEntry.mtimeMs = stats.mtimeMs\n }\n\n this.routeNodeShadowCache.set(node.fullPath, updatedCacheEntry)\n }\n\n public async getCrawlingResult(): Promise<CrawlingResult | undefined> {\n await this.runPromise\n return this.crawlingResult\n }\n\n private static handleNode(\n node: RouteNode,\n acc: HandleNodeAccumulator,\n config?: Config,\n ) {\n // Do not remove this as we need to set the lastIndex to 0 as it\n // is necessary to reset the regex's index when using the global flag\n // otherwise it might not match the next time it's used\n const useExperimentalNonNestedRoutes =\n config?.experimental?.nonNestedRoutes ?? false\n\n resetRegex(this.routeGroupPatternRegex)\n\n let parentRoute = hasParentRoute(\n acc.routeNodes,\n node,\n node.routePath,\n node.originalRoutePath,\n )\n\n // if the parent route is a virtual parent route, we need to find the real parent route\n if (parentRoute?.isVirtualParentRoute && parentRoute.children?.length) {\n // only if this sub-parent route returns a valid parent route, we use it, if not leave it as it\n const possibleParentRoute = hasParentRoute(\n parentRoute.children,\n node,\n node.routePath,\n node.originalRoutePath,\n )\n if (possibleParentRoute) {\n parentRoute = possibleParentRoute\n }\n }\n\n if (parentRoute) node.parent = parentRoute\n\n node.path = determineNodePath(node)\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath.split('/')\n const lastRouteSegment = split[split.length - 1] ?? trimmedPath\n\n node.isNonPath =\n lastRouteSegment.startsWith('_') ||\n split.every((part) => this.routeGroupPatternRegex.test(part))\n\n // with new nonNestedPaths feature we can be sure any remaining trailing underscores are escaped and should remain\n // TODO with new major we can remove check and only remove leading underscores\n node.cleanedPath = removeGroups(\n (useExperimentalNonNestedRoutes\n ? removeLeadingUnderscores(\n removeLayoutSegments(node.path ?? ''),\n config?.routeToken ?? '',\n )\n : removeUnderscores(removeLayoutSegments(node.path))) ?? '',\n )\n\n if (\n node._fsRouteType === 'layout' ||\n node._fsRouteType === 'pathless_layout'\n ) {\n node.cleanedPath = removeTrailingSlash(node.cleanedPath)\n }\n\n if (\n !node.isVirtual &&\n (\n [\n 'lazy',\n 'loader',\n 'component',\n 'pendingComponent',\n 'errorComponent',\n 'notFoundComponent',\n ] satisfies Array<FsRouteType>\n ).some((d) => d === node._fsRouteType)\n ) {\n acc.routePiecesByPath[node.routePath!] =\n acc.routePiecesByPath[node.routePath!] || {}\n\n acc.routePiecesByPath[node.routePath!]![\n node._fsRouteType === 'lazy'\n ? 'lazy'\n : node._fsRouteType === 'loader'\n ? 'loader'\n : node._fsRouteType === 'errorComponent'\n ? 'errorComponent'\n : node._fsRouteType === 'notFoundComponent'\n ? 'notFoundComponent'\n : node._fsRouteType === 'pendingComponent'\n ? 'pendingComponent'\n : 'component'\n ] = node\n\n const anchorRoute = acc.routeNodes.find(\n (d) => d.routePath === node.routePath,\n )\n\n // Don't create virtual routes for root route component pieces - the root route is handled separately\n if (!anchorRoute && node.routePath !== `/${rootPathId}`) {\n this.handleNode(\n {\n ...node,\n isVirtual: true,\n _fsRouteType: 'static',\n },\n acc,\n config,\n )\n }\n return\n }\n\n const cleanedPathIsEmpty = (node.cleanedPath || '').length === 0\n const nonPathRoute =\n node._fsRouteType === 'pathless_layout' && node.isNonPath\n\n node.isVirtualParentRequired =\n node._fsRouteType === 'pathless_layout' || nonPathRoute\n ? !cleanedPathIsEmpty\n : false\n\n if (!node.isVirtual && node.isVirtualParentRequired) {\n const parentRoutePath = removeLastSegmentFromPath(node.routePath) || '/'\n const parentVariableName = routePathToVariable(parentRoutePath)\n\n const anchorRoute = acc.routeNodes.find(\n (d) => d.routePath === parentRoutePath,\n )\n\n if (!anchorRoute) {\n const parentNode: RouteNode = {\n ...node,\n path: removeLastSegmentFromPath(node.path) || '/',\n filePath: removeLastSegmentFromPath(node.filePath) || '/',\n fullPath: removeLastSegmentFromPath(node.fullPath) || '/',\n routePath: parentRoutePath,\n variableName: parentVariableName,\n isVirtual: true,\n _fsRouteType: 'layout', // layout since this route will wrap other routes\n isVirtualParentRoute: true,\n isVirtualParentRequired: false,\n }\n\n parentNode.children = parentNode.children ?? []\n parentNode.children.push(node)\n\n node.parent = parentNode\n\n if (node._fsRouteType === 'pathless_layout') {\n // since `node.path` is used as the `id` on the route definition, we need to update it\n node.path = determineNodePath(node)\n }\n\n this.handleNode(parentNode, acc, config)\n } else {\n anchorRoute.children = anchorRoute.children ?? []\n anchorRoute.children.push(node)\n\n node.parent = anchorRoute\n }\n }\n\n if (node.parent) {\n if (!node.isVirtualParentRequired) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n }\n } else {\n acc.routeTree.push(node)\n }\n\n acc.routeNodes.push(node)\n }\n\n // only process files that are relevant for the route tree generation\n private isFileRelevantForRouteTreeGeneration(filePath: string): boolean {\n // the generated route tree file\n if (filePath === this.generatedRouteTreePath) {\n return true\n }\n\n // files inside the routes folder\n if (filePath.startsWith(this.routesDirectoryPath)) {\n return true\n }\n\n // the virtual route config file passed into `virtualRouteConfig`\n if (\n typeof this.config.virtualRouteConfig === 'string' &&\n filePath === this.config.virtualRouteConfig\n ) {\n return true\n }\n\n // this covers all files that are mounted via `virtualRouteConfig` or any `__virtual.ts` files\n if (this.routeNodeCache.has(filePath)) {\n return true\n }\n\n // virtual config files such as`__virtual.ts`\n if (isVirtualConfigFile(path.basename(filePath))) {\n return true\n }\n\n // route files inside directories mounted via `physical()` inside a virtual route config\n if (this.physicalDirectories.some((dir) => filePath.startsWith(dir))) {\n return true\n }\n\n return false\n }\n}\n"],"names":["virtualGetRouteNodes","physicalGetRouteNodes","moduleAugmentation"],"mappings":";;;;;;;;;;;;AAyEA,MAAM,oBAAwB;AAAA,EAC5B,MAAM,OAAO,aAAa;AACxB,UAAM,MAAM,MAAM,IAAI,KAAK,UAAU,EAAE,QAAQ,MAAM;AACrD,WAAO;AAAA,MACL,SAAS,IAAI;AAAA,MACb,MAAM,OAAO,IAAI,IAAI;AAAA,MACrB,KAAK,OAAO,IAAI,GAAG;AAAA,MACnB,KAAK,OAAO,IAAI,GAAG;AAAA,IAAA;AAAA,EAEvB;AAAA,EACA,QAAQ,CAAC,SAAS,YAAY,IAAI,OAAO,SAAS,OAAO;AAAA,EACzD,WAAW,CAAC,UAAU,YAAY,IAAI,UAAU,UAAU,OAAO;AAAA,EACjE,UAAU,OAAO,aAAqB;AACpC,QAAI;AACF,YAAM,aAAa,MAAM,IAAI,KAAK,UAAU,GAAG;AAC/C,YAAM,OAAO,MAAM,WAAW,KAAK,EAAE,QAAQ,M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OAAO,WAAW,KAAK,OAAO,YAAY,CAAA;AAC/C,aAAK,OAAO,SAAS,KAAK,IAAI;AAAA,MAChC;AAAA,IACF,OAAO;AACL,UAAI,UAAU,KAAK,IAAI;AAAA,IACzB;AAEA,QAAI,WAAW,KAAK,IAAI;AAAA,EAC1B;AAAA;AAAA,EAGQ,qCAAqC,UAA2B;AAEtE,QAAI,aAAa,KAAK,wBAAwB;AAC5C,aAAO;AAAA,IACT;AAGA,QAAI,SAAS,WAAW,KAAK,mBAAmB,GAAG;AACjD,aAAO;AAAA,IACT;AAGA,QACE,OAAO,KAAK,OAAO,uBAAuB,YAC1C,aAAa,KAAK,OAAO,oBACzB;AACA,aAAO;AAAA,IACT;AAGA,QAAI,KAAK,eAAe,IAAI,QAAQ,GAAG;AACrC,aAAO;AAAA,IACT;AAGA,QAAI,oBAAoB,KAAK,SAAS,QAAQ,CAAC,GAAG;AAChD,aAAO;AAAA,IACT;AAGA,QAAI,KAAK,oBAAoB,KAAK,CAAC,QAAQ,SAAS,WAAW,GAAG,CAAC,GAAG;AACpE,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AACF;AAl1CE,WAAe,yBAAyB;AA7BnC,IAAM,YAAN;"}
1
+ {"version":3,"file":"generator.js","sources":["../../src/generator.ts"],"sourcesContent":["import path from 'node:path'\nimport * as fsp from 'node:fs/promises'\nimport { existsSync, mkdirSync } from 'node:fs'\nimport crypto from 'node:crypto'\nimport { rootRouteId } from '@tanstack/router-core'\nimport { logging } from './logger'\nimport {\n isVirtualConfigFile,\n getRouteNodes as physicalGetRouteNodes,\n} from './filesystem/physical/getRouteNodes'\nimport { getRouteNodes as virtualGetRouteNodes } from './filesystem/virtual/getRouteNodes'\nimport { rootPathId } from './filesystem/physical/rootPathId'\nimport {\n buildFileRoutesByPathInterface,\n buildImportString,\n buildRouteTreeConfig,\n checkFileExists,\n checkRouteFullPathUniqueness,\n createRouteNodesByFullPath,\n createRouteNodesById,\n createRouteNodesByTo,\n determineNodePath,\n findParent,\n format,\n getImportForRouteNode,\n getImportPath,\n getResolvedRouteNodeVariableName,\n hasParentRoute,\n isRouteNodeValidForAugmentation,\n mergeImportDeclarations,\n multiSortBy,\n removeExt,\n removeGroups,\n removeLastSegmentFromPath,\n removeLayoutSegments,\n removeLeadingUnderscores,\n removeTrailingSlash,\n removeUnderscores,\n replaceBackslash,\n resetRegex,\n trimPathLeft,\n} from './utils'\nimport { fillTemplate, getTargetTemplate } from './template'\nimport { transform } from './transform/transform'\nimport type { GeneratorPlugin } from './plugin/types'\nimport type { TargetTemplate } from './template'\nimport type {\n FsRouteType,\n GetRouteNodesResult,\n GetRoutesByFileMapResult,\n HandleNodeAccumulator,\n ImportDeclaration,\n RouteNode,\n} from './types'\nimport type { Config } from './config'\nimport type { Logger } from './logger'\n\ninterface fs {\n stat: (\n filePath: string,\n ) => Promise<{ mtimeMs: bigint; mode: number; uid: number; gid: number }>\n rename: (oldPath: string, newPath: string) => Promise<void>\n writeFile: (filePath: string, content: string) => Promise<void>\n readFile: (\n filePath: string,\n ) => Promise<\n { stat: { mtimeMs: bigint }; fileContent: string } | 'file-not-existing'\n >\n chmod: (filePath: string, mode: number) => Promise<void>\n chown: (filePath: string, uid: number, gid: number) => Promise<void>\n}\n\nconst DefaultFileSystem: fs = {\n stat: async (filePath) => {\n const res = await fsp.stat(filePath, { bigint: true })\n return {\n mtimeMs: res.mtimeMs,\n mode: Number(res.mode),\n uid: Number(res.uid),\n gid: Number(res.gid),\n }\n },\n rename: (oldPath, newPath) => fsp.rename(oldPath, newPath),\n writeFile: (filePath, content) => fsp.writeFile(filePath, content),\n readFile: async (filePath: string) => {\n try {\n const fileHandle = await fsp.open(filePath, 'r')\n const stat = await fileHandle.stat({ bigint: true })\n const fileContent = (await fileHandle.readFile()).toString()\n await fileHandle.close()\n return { stat, fileContent }\n } catch (e: any) {\n if ('code' in e) {\n if (e.code === 'ENOENT') {\n return 'file-not-existing'\n }\n }\n throw e\n }\n },\n chmod: (filePath, mode) => fsp.chmod(filePath, mode),\n chown: (filePath, uid, gid) => fsp.chown(filePath, uid, gid),\n}\n\ninterface Rerun {\n rerun: true\n msg?: string\n event: GeneratorEvent\n}\nfunction rerun(opts: { msg?: string; event?: GeneratorEvent }): Rerun {\n const { event, ...rest } = opts\n return { rerun: true, event: event ?? { type: 'rerun' }, ...rest }\n}\n\nfunction isRerun(result: unknown): result is Rerun {\n return (\n typeof result === 'object' &&\n result !== null &&\n 'rerun' in result &&\n result.rerun === true\n )\n}\n\nexport type FileEventType = 'create' | 'update' | 'delete'\nexport type FileEvent = {\n type: FileEventType\n path: string\n}\nexport type GeneratorEvent = FileEvent | { type: 'rerun' }\n\ntype FileCacheChange<TCacheEntry extends GeneratorCacheEntry> =\n | {\n result: false\n cacheEntry: TCacheEntry\n }\n | { result: true; mtimeMs: bigint; cacheEntry: TCacheEntry }\n | {\n result: 'file-not-in-cache'\n }\n | {\n result: 'cannot-stat-file'\n }\n\ninterface GeneratorCacheEntry {\n mtimeMs: bigint\n fileContent: string\n}\n\ninterface RouteNodeCacheEntry extends GeneratorCacheEntry {\n routeId: string\n node: RouteNode\n}\n\ntype GeneratorRouteNodeCache = Map</** filePath **/ string, RouteNodeCacheEntry>\n\ninterface CrawlingResult {\n rootRouteNode: RouteNode\n routeFileResult: Array<RouteNode>\n acc: HandleNodeAccumulator\n}\n\nexport class Generator {\n /**\n * why do we have two caches for the route files?\n * During processing, we READ from the cache and WRITE to the shadow cache.\n *\n * After a route file is processed, we write to the shadow cache.\n * If during processing we bail out and re-run, we don't lose this modification\n * but still can track whether the file contributed changes and thus the route tree file needs to be regenerated.\n * After all files are processed, we swap the shadow cache with the main cache and initialize a new shadow cache.\n * That way we also ensure deleted/renamed files don't stay in the cache forever.\n */\n private routeNodeCache: GeneratorRouteNodeCache = new Map()\n private routeNodeShadowCache: GeneratorRouteNodeCache = new Map()\n\n private routeTreeFileCache: GeneratorCacheEntry | undefined\n\n private crawlingResult: CrawlingResult | undefined\n public config: Config\n public targetTemplate: TargetTemplate\n\n private root: string\n private routesDirectoryPath: string\n private sessionId?: string\n private fs: fs\n private logger: Logger\n private generatedRouteTreePath: string\n private runPromise: Promise<void> | undefined\n private fileEventQueue: Array<GeneratorEvent> = []\n private plugins: Array<GeneratorPlugin> = []\n private static routeGroupPatternRegex = /\\(.+\\)/g\n private physicalDirectories: Array<string> = []\n\n constructor(opts: { config: Config; root: string; fs?: fs }) {\n this.config = opts.config\n this.logger = logging({ disabled: this.config.disableLogging })\n this.root = opts.root\n this.fs = opts.fs || DefaultFileSystem\n this.generatedRouteTreePath = this.getGeneratedRouteTreePath()\n this.targetTemplate = getTargetTemplate(this.config)\n\n this.routesDirectoryPath = this.getRoutesDirectoryPath()\n this.plugins.push(...(opts.config.plugins || []))\n\n for (const plugin of this.plugins) {\n plugin.init?.({ generator: this })\n }\n }\n\n private getGeneratedRouteTreePath() {\n const generatedRouteTreePath = path.isAbsolute(\n this.config.generatedRouteTree,\n )\n ? this.config.generatedRouteTree\n : path.resolve(this.root, this.config.generatedRouteTree)\n\n const generatedRouteTreeDir = path.dirname(generatedRouteTreePath)\n\n if (!existsSync(generatedRouteTreeDir)) {\n mkdirSync(generatedRouteTreeDir, { recursive: true })\n }\n\n return generatedRouteTreePath\n }\n\n private getRoutesDirectoryPath() {\n return path.isAbsolute(this.config.routesDirectory)\n ? this.config.routesDirectory\n : path.resolve(this.root, this.config.routesDirectory)\n }\n\n public getRoutesByFileMap(): GetRoutesByFileMapResult {\n return new Map(\n [...this.routeNodeCache.entries()].map(([filePath, cacheEntry]) => [\n filePath,\n { routePath: cacheEntry.routeId },\n ]),\n )\n }\n\n public async run(event?: GeneratorEvent): Promise<void> {\n if (\n event &&\n event.type !== 'rerun' &&\n !this.isFileRelevantForRouteTreeGeneration(event.path)\n ) {\n return\n }\n this.fileEventQueue.push(event ?? { type: 'rerun' })\n // only allow a single run at a time\n if (this.runPromise) {\n return this.runPromise\n }\n\n this.runPromise = (async () => {\n do {\n // synchronously copy and clear the queue since we are going to iterate asynchronously over it\n // and while we do so, a new event could be put into the queue\n const tempQueue = this.fileEventQueue\n this.fileEventQueue = []\n // if we only have 'update' events in the queue\n // and we already have the affected files' latest state in our cache, we can exit early\n const remainingEvents = (\n await Promise.all(\n tempQueue.map(async (e) => {\n if (e.type === 'update') {\n let cacheEntry: GeneratorCacheEntry | undefined\n if (e.path === this.generatedRouteTreePath) {\n cacheEntry = this.routeTreeFileCache\n } else {\n // we only check the routeNodeCache here\n // if the file's state is only up-to-date in the shadow cache we need to re-run\n cacheEntry = this.routeNodeCache.get(e.path)\n }\n const change = await this.didFileChangeComparedToCache(\n { path: e.path },\n cacheEntry,\n )\n if (change.result === false) {\n return null\n }\n }\n return e\n }),\n )\n ).filter((e) => e !== null)\n\n if (remainingEvents.length === 0) {\n break\n }\n\n try {\n await this.generatorInternal()\n } catch (err) {\n const errArray = !Array.isArray(err) ? [err] : err\n\n const recoverableErrors = errArray.filter((e) => isRerun(e))\n if (recoverableErrors.length === errArray.length) {\n this.fileEventQueue.push(...recoverableErrors.map((e) => e.event))\n recoverableErrors.forEach((e) => {\n if (e.msg) {\n this.logger.info(e.msg)\n }\n })\n } else {\n const unrecoverableErrors = errArray.filter((e) => !isRerun(e))\n this.runPromise = undefined\n throw new Error(\n unrecoverableErrors.map((e) => (e as Error).message).join(),\n )\n }\n }\n } while (this.fileEventQueue.length)\n this.runPromise = undefined\n })()\n return this.runPromise\n }\n\n private async generatorInternal() {\n let writeRouteTreeFile: boolean | 'force' = false\n\n let getRouteNodesResult: GetRouteNodesResult\n\n if (this.config.virtualRouteConfig) {\n getRouteNodesResult = await virtualGetRouteNodes(this.config, this.root)\n } else {\n getRouteNodesResult = await physicalGetRouteNodes(this.config, this.root)\n }\n\n const {\n rootRouteNode,\n routeNodes: beforeRouteNodes,\n physicalDirectories,\n } = getRouteNodesResult\n if (rootRouteNode === undefined) {\n let errorMessage = `rootRouteNode must not be undefined. Make sure you've added your root route into the route-tree.`\n if (!this.config.virtualRouteConfig) {\n 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'}\"`\n }\n throw new Error(errorMessage)\n }\n this.physicalDirectories = physicalDirectories\n\n await this.handleRootNode(rootRouteNode)\n\n const preRouteNodes = multiSortBy(beforeRouteNodes, [\n (d) => (d.routePath === '/' ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) =>\n d.filePath.match(new RegExp(`[./]${this.config.indexToken}[.]`))\n ? 1\n : -1,\n (d) =>\n d.filePath.match(\n /[./](component|errorComponent|notFoundComponent|pendingComponent|loader|lazy)[.]/,\n )\n ? 1\n : -1,\n (d) =>\n d.filePath.match(new RegExp(`[./]${this.config.routeToken}[.]`))\n ? -1\n : 1,\n (d) => (d.routePath?.endsWith('/') ? -1 : 1),\n (d) => d.routePath,\n ]).filter((d) => {\n // Exclude the root route itself, but keep component/loader pieces for the root\n if (d.routePath === `/${rootPathId}`) {\n return [\n 'component',\n 'errorComponent',\n 'notFoundComponent',\n 'pendingComponent',\n 'loader',\n 'lazy',\n ].includes(d._fsRouteType)\n }\n return true\n })\n\n const routeFileAllResult = await Promise.allSettled(\n preRouteNodes\n // only process routes that are backed by an actual file\n .filter((n) => !n.isVirtualParentRoute && !n.isVirtual)\n .map((n) => this.processRouteNodeFile(n)),\n )\n\n const rejections = routeFileAllResult.filter(\n (result) => result.status === 'rejected',\n )\n if (rejections.length > 0) {\n throw rejections.map((e) => e.reason)\n }\n\n const routeFileResult = routeFileAllResult.flatMap((result) => {\n if (result.status === 'fulfilled' && result.value !== null) {\n if (result.value.shouldWriteTree) {\n writeRouteTreeFile = true\n }\n return result.value.node\n }\n return []\n })\n\n // reset children in case we re-use a node from the cache\n routeFileResult.forEach((r) => (r.children = undefined))\n\n const acc: HandleNodeAccumulator = {\n routeTree: [],\n routeNodes: [],\n routePiecesByPath: {},\n routeNodesByPath: new Map(),\n }\n\n for (const node of routeFileResult) {\n Generator.handleNode(node, acc, this.config)\n }\n\n this.crawlingResult = { rootRouteNode, routeFileResult, acc }\n\n // this is the first time the generator runs, so read in the route tree file if it exists yet\n if (!this.routeTreeFileCache) {\n const routeTreeFile = await this.fs.readFile(this.generatedRouteTreePath)\n if (routeTreeFile !== 'file-not-existing') {\n this.routeTreeFileCache = {\n fileContent: routeTreeFile.fileContent,\n mtimeMs: routeTreeFile.stat.mtimeMs,\n }\n }\n writeRouteTreeFile = true\n } else {\n const routeTreeFileChange = await this.didFileChangeComparedToCache(\n { path: this.generatedRouteTreePath },\n this.routeTreeFileCache,\n )\n if (routeTreeFileChange.result !== false) {\n writeRouteTreeFile = 'force'\n if (routeTreeFileChange.result === true) {\n const routeTreeFile = await this.fs.readFile(\n this.generatedRouteTreePath,\n )\n if (routeTreeFile !== 'file-not-existing') {\n this.routeTreeFileCache = {\n fileContent: routeTreeFile.fileContent,\n mtimeMs: routeTreeFile.stat.mtimeMs,\n }\n }\n }\n }\n }\n\n if (!writeRouteTreeFile) {\n // only needs to be done if no other changes have been detected yet\n // compare shadowCache and cache to identify deleted routes\n if (this.routeNodeCache.size !== this.routeNodeShadowCache.size) {\n writeRouteTreeFile = true\n } else {\n for (const fullPath of this.routeNodeCache.keys()) {\n if (!this.routeNodeShadowCache.has(fullPath)) {\n writeRouteTreeFile = true\n break\n }\n }\n }\n }\n\n if (!writeRouteTreeFile) {\n this.swapCaches()\n return\n }\n\n const buildResult = this.buildRouteTree({\n rootRouteNode,\n acc,\n routeFileResult,\n })\n let routeTreeContent = buildResult.routeTreeContent\n\n routeTreeContent = this.config.enableRouteTreeFormatting\n ? await format(routeTreeContent, this.config)\n : routeTreeContent\n\n let newMtimeMs: bigint | undefined\n if (this.routeTreeFileCache) {\n if (\n writeRouteTreeFile !== 'force' &&\n this.routeTreeFileCache.fileContent === routeTreeContent\n ) {\n // existing route tree file is already up-to-date, don't write it\n // we should only get here in the initial run when the route cache is not filled yet\n } else {\n const newRouteTreeFileStat = await this.safeFileWrite({\n filePath: this.generatedRouteTreePath,\n newContent: routeTreeContent,\n strategy: {\n type: 'mtime',\n expectedMtimeMs: this.routeTreeFileCache.mtimeMs,\n },\n })\n newMtimeMs = newRouteTreeFileStat.mtimeMs\n }\n } else {\n const newRouteTreeFileStat = await this.safeFileWrite({\n filePath: this.generatedRouteTreePath,\n newContent: routeTreeContent,\n strategy: {\n type: 'new-file',\n },\n })\n newMtimeMs = newRouteTreeFileStat.mtimeMs\n }\n\n if (newMtimeMs !== undefined) {\n this.routeTreeFileCache = {\n fileContent: routeTreeContent,\n mtimeMs: newMtimeMs,\n }\n }\n\n this.plugins.map((plugin) => {\n return plugin.onRouteTreeChanged?.({\n routeTree: buildResult.routeTree,\n routeNodes: buildResult.routeNodes,\n acc,\n rootRouteNode,\n })\n })\n this.swapCaches()\n }\n\n private swapCaches() {\n this.routeNodeCache = this.routeNodeShadowCache\n this.routeNodeShadowCache = new Map()\n }\n\n public buildRouteTree(opts: {\n rootRouteNode: RouteNode\n acc: HandleNodeAccumulator\n routeFileResult: Array<RouteNode>\n config?: Partial<Config>\n }) {\n const config = { ...this.config, ...(opts.config || {}) }\n\n const { rootRouteNode, acc } = opts\n\n const sortedRouteNodes = multiSortBy(acc.routeNodes, [\n (d) => (d.routePath?.includes(`/${rootPathId}`) ? -1 : 1),\n (d) => d.routePath?.split('/').length,\n (d) => (d.routePath?.endsWith(config.indexToken) ? -1 : 1),\n (d) => d,\n ])\n\n const routeImports = sortedRouteNodes\n .filter((d) => !d.isVirtual)\n .flatMap((node) =>\n getImportForRouteNode(\n node,\n config,\n this.generatedRouteTreePath,\n this.root,\n ),\n )\n\n const virtualRouteNodes = sortedRouteNodes\n .filter((d) => d.isVirtual)\n .map((node) => {\n return `const ${\n node.variableName\n }RouteImport = createFileRoute('${node.routePath}')()`\n })\n\n const imports: Array<ImportDeclaration> = []\n if (acc.routeNodes.some((n) => n.isVirtual)) {\n imports.push({\n specifiers: [{ imported: 'createFileRoute' }],\n source: this.targetTemplate.fullPkg,\n })\n }\n // Add lazyRouteComponent import if there are component pieces\n const hasComponentPieces = sortedRouteNodes.some(\n (node) =>\n acc.routePiecesByPath[node.routePath!]?.component ||\n acc.routePiecesByPath[node.routePath!]?.errorComponent ||\n acc.routePiecesByPath[node.routePath!]?.notFoundComponent ||\n acc.routePiecesByPath[node.routePath!]?.pendingComponent,\n )\n // Add lazyFn import if there are loader pieces\n const hasLoaderPieces = sortedRouteNodes.some(\n (node) => acc.routePiecesByPath[node.routePath!]?.loader,\n )\n if (hasComponentPieces || hasLoaderPieces) {\n const runtimeImport: ImportDeclaration = {\n specifiers: [],\n source: this.targetTemplate.fullPkg,\n }\n if (hasComponentPieces) {\n runtimeImport.specifiers.push({ imported: 'lazyRouteComponent' })\n }\n if (hasLoaderPieces) {\n runtimeImport.specifiers.push({ imported: 'lazyFn' })\n }\n imports.push(runtimeImport)\n }\n if (config.verboseFileRoutes === false) {\n const typeImport: ImportDeclaration = {\n specifiers: [],\n source: this.targetTemplate.fullPkg,\n importKind: 'type',\n }\n if (\n sortedRouteNodes.some(\n (d) =>\n isRouteNodeValidForAugmentation(d) && d._fsRouteType !== 'lazy',\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateFileRoute' })\n }\n if (\n sortedRouteNodes.some(\n (node) =>\n acc.routePiecesByPath[node.routePath!]?.lazy &&\n isRouteNodeValidForAugmentation(node),\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateLazyFileRoute' })\n }\n\n if (typeImport.specifiers.length > 0) {\n typeImport.specifiers.push({ imported: 'FileRoutesByPath' })\n imports.push(typeImport)\n }\n }\n\n const routeTreeConfig = buildRouteTreeConfig(\n acc.routeTree,\n config.disableTypes,\n )\n\n const createUpdateRoutes = sortedRouteNodes.map((node) => {\n const loaderNode = acc.routePiecesByPath[node.routePath!]?.loader\n const componentNode = acc.routePiecesByPath[node.routePath!]?.component\n const errorComponentNode =\n acc.routePiecesByPath[node.routePath!]?.errorComponent\n const notFoundComponentNode =\n acc.routePiecesByPath[node.routePath!]?.notFoundComponent\n const pendingComponentNode =\n acc.routePiecesByPath[node.routePath!]?.pendingComponent\n const lazyComponentNode = acc.routePiecesByPath[node.routePath!]?.lazy\n\n return [\n [\n `const ${node.variableName}Route = ${node.variableName}RouteImport.update({\n ${[\n `id: '${node.path}'`,\n !node.isNonPath ||\n (node._fsRouteType === 'pathless_layout' && node.cleanedPath)\n ? `path: '${node.cleanedPath}'`\n : undefined,\n `getParentRoute: () => ${findParent(node)}`,\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 config.addExtensions,\n ),\n )}'), 'loader') })`\n : '',\n componentNode ||\n errorComponentNode ||\n notFoundComponentNode ||\n pendingComponentNode\n ? `.update({\n ${(\n [\n ['component', componentNode],\n ['errorComponent', errorComponentNode],\n ['notFoundComponent', notFoundComponentNode],\n ['pendingComponent', pendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n // For .vue files, use 'default' as the export name since Vue SFCs export default\n const isVueFile = d[1]!.filePath.endsWith('.vue')\n const exportName = isVueFile ? 'default' : d[0]\n // Keep .vue extension for Vue files since Vite requires it\n const importPath = replaceBackslash(\n isVueFile\n ? path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n d[1]!.filePath,\n ),\n )\n : removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n d[1]!.filePath,\n ),\n ),\n config.addExtensions,\n ),\n )\n return `${\n d[0]\n }: lazyRouteComponent(() => import('./${importPath}'), '${exportName}')`\n })\n .join('\\n,')}\n })`\n : '',\n lazyComponentNode\n ? (() => {\n // For .vue files, use 'default' export since Vue SFCs export default\n const isVueFile = lazyComponentNode.filePath.endsWith('.vue')\n const exportAccessor = isVueFile ? 'd.default' : 'd.Route'\n // Keep .vue extension for Vue files since Vite requires it\n const importPath = replaceBackslash(\n isVueFile\n ? path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n lazyComponentNode.filePath,\n ),\n )\n : removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n lazyComponentNode.filePath,\n ),\n ),\n config.addExtensions,\n ),\n )\n return `.lazy(() => import('./${importPath}').then((d) => ${exportAccessor}))`\n })()\n : '',\n ].join(''),\n ].join('\\n\\n')\n })\n\n // Generate update for root route if it has component pieces\n const rootRoutePath = `/${rootPathId}`\n const rootComponentNode = acc.routePiecesByPath[rootRoutePath]?.component\n const rootErrorComponentNode =\n acc.routePiecesByPath[rootRoutePath]?.errorComponent\n const rootNotFoundComponentNode =\n acc.routePiecesByPath[rootRoutePath]?.notFoundComponent\n const rootPendingComponentNode =\n acc.routePiecesByPath[rootRoutePath]?.pendingComponent\n\n let rootRouteUpdate = ''\n if (\n rootComponentNode ||\n rootErrorComponentNode ||\n rootNotFoundComponentNode ||\n rootPendingComponentNode\n ) {\n rootRouteUpdate = `const rootRouteWithChildren = rootRouteImport${\n rootComponentNode ||\n rootErrorComponentNode ||\n rootNotFoundComponentNode ||\n rootPendingComponentNode\n ? `.update({\n ${(\n [\n ['component', rootComponentNode],\n ['errorComponent', rootErrorComponentNode],\n ['notFoundComponent', rootNotFoundComponentNode],\n ['pendingComponent', rootPendingComponentNode],\n ] as const\n )\n .filter((d) => d[1])\n .map((d) => {\n // For .vue files, use 'default' as the export name since Vue SFCs export default\n const isVueFile = d[1]!.filePath.endsWith('.vue')\n const exportName = isVueFile ? 'default' : d[0]\n // Keep .vue extension for Vue files since Vite requires it\n const importPath = replaceBackslash(\n isVueFile\n ? path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(config.routesDirectory, d[1]!.filePath),\n )\n : removeExt(\n path.relative(\n path.dirname(config.generatedRouteTree),\n path.resolve(\n config.routesDirectory,\n d[1]!.filePath,\n ),\n ),\n config.addExtensions,\n ),\n )\n return `${d[0]}: lazyRouteComponent(() => import('./${importPath}'), '${exportName}')`\n })\n .join('\\n,')}\n })`\n : ''\n }._addFileChildren(rootRouteChildren)${config.disableTypes ? '' : `._addFileTypes<FileRouteTypes>()`}`\n }\n\n let fileRoutesByPathInterface = ''\n let fileRoutesByFullPath = ''\n\n if (!config.disableTypes) {\n fileRoutesByFullPath = [\n `export interface FileRoutesByFullPath {\n${[...createRouteNodesByFullPath(acc.routeNodes, config).entries()]\n .filter(([fullPath]) => fullPath)\n .map(([fullPath, routeNode]) => {\n return `'${fullPath}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRoutesByTo {\n${[...createRouteNodesByTo(acc.routeNodes, config).entries()]\n .filter(([to]) => to)\n .map(([to, routeNode]) => {\n return `'${to}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n })}\n}`,\n `export interface FileRoutesById {\n'${rootRouteId}': typeof rootRouteImport,\n${[...createRouteNodesById(acc.routeNodes).entries()].map(([id, routeNode]) => {\n return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}`\n})}\n}`,\n `export interface FileRouteTypes {\nfileRoutesByFullPath: FileRoutesByFullPath\nfullPaths: ${\n acc.routeNodes.length > 0\n ? [...createRouteNodesByFullPath(acc.routeNodes, config).keys()]\n .filter((fullPath) => fullPath)\n .map((fullPath) => `'${fullPath}'`)\n .join('|')\n : 'never'\n }\nfileRoutesByTo: FileRoutesByTo\nto: ${\n acc.routeNodes.length > 0\n ? [...createRouteNodesByTo(acc.routeNodes, config).keys()]\n .filter((to) => to)\n .map((to) => `'${to}'`)\n .join('|')\n : 'never'\n }\nid: ${[`'${rootRouteId}'`, ...[...createRouteNodesById(acc.routeNodes).keys()].map((id) => `'${id}'`)].join('|')}\nfileRoutesById: FileRoutesById\n}`,\n `export interface RootRouteChildren {\n${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')}\n}`,\n ].join('\\n')\n\n fileRoutesByPathInterface = buildFileRoutesByPathInterface({\n module: this.targetTemplate.fullPkg,\n interfaceName: 'FileRoutesByPath',\n routeNodes: sortedRouteNodes,\n config,\n })\n }\n\n const routeTree = [\n `const rootRouteChildren${config.disableTypes ? '' : `: RootRouteChildren`} = {\n ${acc.routeTree\n .map(\n (child) =>\n `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,\n )\n .join(',')}\n}`,\n rootRouteUpdate\n ? rootRouteUpdate.replace(\n 'const rootRouteWithChildren = ',\n 'export const routeTree = ',\n )\n : `export const routeTree = rootRouteImport._addFileChildren(rootRouteChildren)${config.disableTypes ? '' : `._addFileTypes<FileRouteTypes>()`}`,\n ].join('\\n')\n\n checkRouteFullPathUniqueness(\n sortedRouteNodes.filter(\n (d) => d.children === undefined && 'lazy' !== d._fsRouteType,\n ),\n config,\n )\n\n let mergedImports = mergeImportDeclarations(imports)\n if (config.disableTypes) {\n mergedImports = mergedImports.filter((d) => d.importKind !== 'type')\n }\n\n const importStatements = mergedImports.map(buildImportString)\n\n let moduleAugmentation = ''\n if (config.verboseFileRoutes === false && !config.disableTypes) {\n moduleAugmentation = opts.routeFileResult\n .map((node) => {\n const getModuleDeclaration = (routeNode?: RouteNode) => {\n if (!isRouteNodeValidForAugmentation(routeNode)) {\n return ''\n }\n let moduleAugmentation = ''\n if (routeNode._fsRouteType === 'lazy') {\n moduleAugmentation = `const createLazyFileRoute: CreateLazyFileRoute<FileRoutesByPath['${routeNode.routePath}']['preLoaderRoute']>`\n } else {\n moduleAugmentation = `const createFileRoute: CreateFileRoute<'${routeNode.routePath}',\n FileRoutesByPath['${routeNode.routePath}']['parentRoute'],\n FileRoutesByPath['${routeNode.routePath}']['id'],\n FileRoutesByPath['${routeNode.routePath}']['path'],\n FileRoutesByPath['${routeNode.routePath}']['fullPath']\n >\n `\n }\n\n return `declare module './${getImportPath(routeNode, config, this.generatedRouteTreePath)}' {\n ${moduleAugmentation}\n }`\n }\n return getModuleDeclaration(node)\n })\n .join('\\n')\n }\n\n const rootRouteImport = getImportForRouteNode(\n rootRouteNode,\n config,\n this.generatedRouteTreePath,\n this.root,\n )\n routeImports.unshift(rootRouteImport)\n\n let footer: Array<string> = []\n if (config.routeTreeFileFooter) {\n if (Array.isArray(config.routeTreeFileFooter)) {\n footer = config.routeTreeFileFooter\n } else {\n footer = config.routeTreeFileFooter()\n }\n }\n const routeTreeContent = [\n ...config.routeTreeFileHeader,\n `// This file was automatically generated by TanStack Router.\n// You should NOT make any changes in this file as it will be overwritten.\n// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`,\n [...importStatements].join('\\n'),\n mergeImportDeclarations(routeImports).map(buildImportString).join('\\n'),\n virtualRouteNodes.join('\\n'),\n createUpdateRoutes.join('\\n'),\n fileRoutesByFullPath,\n fileRoutesByPathInterface,\n moduleAugmentation,\n routeTreeConfig.join('\\n'),\n routeTree,\n ...footer,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n return {\n routeTreeContent,\n routeTree: acc.routeTree,\n routeNodes: acc.routeNodes,\n }\n }\n\n private async processRouteNodeFile(node: RouteNode): Promise<{\n shouldWriteTree: boolean\n cacheEntry: RouteNodeCacheEntry\n node: RouteNode\n } | null> {\n const result = await this.isRouteFileCacheFresh(node)\n\n if (result.status === 'fresh') {\n return {\n node: result.cacheEntry.node,\n shouldWriteTree: false,\n cacheEntry: result.cacheEntry,\n }\n }\n\n const previousCacheEntry = result.cacheEntry\n\n const existingRouteFile = await this.fs.readFile(node.fullPath)\n if (existingRouteFile === 'file-not-existing') {\n throw new Error(`⚠️ File ${node.fullPath} does not exist`)\n }\n\n const updatedCacheEntry: RouteNodeCacheEntry = {\n fileContent: existingRouteFile.fileContent,\n mtimeMs: existingRouteFile.stat.mtimeMs,\n routeId: node.routePath ?? '$$TSR_NO_ROUTE_PATH_ASSIGNED$$',\n node,\n }\n\n const escapedRoutePath = node.routePath?.replaceAll('$', '$$') ?? ''\n\n let shouldWriteRouteFile = false\n let shouldWriteTree = false\n // now we need to either scaffold the file or transform it\n if (!existingRouteFile.fileContent) {\n shouldWriteRouteFile = true\n shouldWriteTree = true\n // Creating a new lazy route file\n if (node._fsRouteType === 'lazy') {\n const tLazyRouteTemplate = this.targetTemplate.lazyRoute\n // Check by default check if the user has a specific lazy route template\n // If not, check if the user has a route template and use that instead\n updatedCacheEntry.fileContent = await fillTemplate(\n this.config,\n (this.config.customScaffolding?.lazyRouteTemplate ||\n this.config.customScaffolding?.routeTemplate) ??\n tLazyRouteTemplate.template(),\n {\n tsrImports: tLazyRouteTemplate.imports.tsrImports(),\n tsrPath: escapedRoutePath.replaceAll(/\\{(.+?)\\}/gm, '$1'),\n tsrExportStart:\n tLazyRouteTemplate.imports.tsrExportStart(escapedRoutePath),\n tsrExportEnd: tLazyRouteTemplate.imports.tsrExportEnd(),\n },\n )\n } else if (\n // Creating a new normal route file\n (['layout', 'static'] satisfies Array<FsRouteType>).some(\n (d) => d === node._fsRouteType,\n ) ||\n (\n [\n 'component',\n 'pendingComponent',\n 'errorComponent',\n 'notFoundComponent',\n 'loader',\n ] satisfies Array<FsRouteType>\n ).every((d) => d !== node._fsRouteType)\n ) {\n const tRouteTemplate = this.targetTemplate.route\n updatedCacheEntry.fileContent = await fillTemplate(\n this.config,\n this.config.customScaffolding?.routeTemplate ??\n tRouteTemplate.template(),\n {\n tsrImports: tRouteTemplate.imports.tsrImports(),\n tsrPath: escapedRoutePath.replaceAll(/\\{(.+?)\\}/gm, '$1'),\n tsrExportStart:\n tRouteTemplate.imports.tsrExportStart(escapedRoutePath),\n tsrExportEnd: tRouteTemplate.imports.tsrExportEnd(),\n },\n )\n } else {\n return null\n }\n }\n\n // Check if this is a Vue component file\n // Vue SFC files (.vue) don't need transformation as they can't have a Route export\n const isVueFile = node.filePath.endsWith('.vue')\n\n if (!isVueFile) {\n // transform the file\n const transformResult = await transform({\n source: updatedCacheEntry.fileContent,\n ctx: {\n target: this.config.target,\n routeId: escapedRoutePath,\n lazy: node._fsRouteType === 'lazy',\n verboseFileRoutes: !(this.config.verboseFileRoutes === false),\n },\n node,\n })\n\n if (transformResult.result === 'no-route-export') {\n this.logger.warn(\n `Route file \"${node.fullPath}\" does not contain any route piece. This is likely a mistake.`,\n )\n return null\n }\n if (transformResult.result === 'error') {\n throw new Error(\n `Error transforming route file ${node.fullPath}: ${transformResult.error}`,\n )\n }\n if (transformResult.result === 'modified') {\n updatedCacheEntry.fileContent = transformResult.output\n shouldWriteRouteFile = true\n }\n }\n\n for (const plugin of this.plugins) {\n plugin.afterTransform?.({ node, prevNode: previousCacheEntry?.node })\n }\n\n // file was changed\n if (shouldWriteRouteFile) {\n const stats = await this.safeFileWrite({\n filePath: node.fullPath,\n newContent: updatedCacheEntry.fileContent,\n strategy: {\n type: 'mtime',\n expectedMtimeMs: updatedCacheEntry.mtimeMs,\n },\n })\n updatedCacheEntry.mtimeMs = stats.mtimeMs\n }\n\n this.routeNodeShadowCache.set(node.fullPath, updatedCacheEntry)\n return {\n node,\n shouldWriteTree,\n cacheEntry: updatedCacheEntry,\n }\n }\n\n private async didRouteFileChangeComparedToCache(\n file: {\n path: string\n mtimeMs?: bigint\n },\n cache: 'routeNodeCache' | 'routeNodeShadowCache',\n ): Promise<FileCacheChange<RouteNodeCacheEntry>> {\n const cacheEntry = this[cache].get(file.path)\n return this.didFileChangeComparedToCache(file, cacheEntry)\n }\n\n private async didFileChangeComparedToCache<\n TCacheEntry extends GeneratorCacheEntry,\n >(\n file: {\n path: string\n mtimeMs?: bigint\n },\n cacheEntry: TCacheEntry | undefined,\n ): Promise<FileCacheChange<TCacheEntry>> {\n // for now we rely on the modification time of the file\n // to determine if the file has changed\n // we could also compare the file content but this would be slower as we would have to read the file\n\n if (!cacheEntry) {\n return { result: 'file-not-in-cache' }\n }\n let mtimeMs = file.mtimeMs\n\n if (mtimeMs === undefined) {\n try {\n const currentStat = await this.fs.stat(file.path)\n mtimeMs = currentStat.mtimeMs\n } catch {\n return { result: 'cannot-stat-file' }\n }\n }\n return { result: mtimeMs !== cacheEntry.mtimeMs, mtimeMs, cacheEntry }\n }\n\n private async safeFileWrite(opts: {\n filePath: string\n newContent: string\n strategy:\n | {\n type: 'mtime'\n expectedMtimeMs: bigint\n }\n | {\n type: 'new-file'\n }\n }) {\n const tmpPath = this.getTempFileName(opts.filePath)\n await this.fs.writeFile(tmpPath, opts.newContent)\n\n if (opts.strategy.type === 'mtime') {\n const beforeStat = await this.fs.stat(opts.filePath)\n if (beforeStat.mtimeMs !== opts.strategy.expectedMtimeMs) {\n throw rerun({\n msg: `File ${opts.filePath} was modified by another process during processing.`,\n event: { type: 'update', path: opts.filePath },\n })\n }\n const newFileState = await this.fs.stat(tmpPath)\n if (newFileState.mode !== beforeStat.mode) {\n await this.fs.chmod(tmpPath, beforeStat.mode)\n }\n if (\n newFileState.uid !== beforeStat.uid ||\n newFileState.gid !== beforeStat.gid\n ) {\n try {\n await this.fs.chown(tmpPath, beforeStat.uid, beforeStat.gid)\n } catch (err) {\n if (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as any).code === 'EPERM'\n ) {\n console.warn(\n `[safeFileWrite] chown failed: ${(err as any).message}`,\n )\n } else {\n throw err\n }\n }\n }\n } else {\n if (await checkFileExists(opts.filePath)) {\n throw rerun({\n msg: `File ${opts.filePath} already exists. Cannot overwrite.`,\n event: { type: 'update', path: opts.filePath },\n })\n }\n }\n\n const stat = await this.fs.stat(tmpPath)\n\n await this.fs.rename(tmpPath, opts.filePath)\n\n return stat\n }\n\n private getTempFileName(filePath: string) {\n const absPath = path.resolve(filePath)\n const hash = crypto.createHash('md5').update(absPath).digest('hex')\n // lazy initialize sessionId to only create tmpDir when it is first needed\n if (!this.sessionId) {\n // ensure the directory exists\n mkdirSync(this.config.tmpDir, { recursive: true })\n this.sessionId = crypto.randomBytes(4).toString('hex')\n }\n return path.join(this.config.tmpDir, `${this.sessionId}-${hash}`)\n }\n\n private async isRouteFileCacheFresh(node: RouteNode): Promise<\n | {\n status: 'fresh'\n cacheEntry: RouteNodeCacheEntry\n }\n | { status: 'stale'; cacheEntry?: RouteNodeCacheEntry }\n > {\n const fileChangedCache = await this.didRouteFileChangeComparedToCache(\n { path: node.fullPath },\n 'routeNodeCache',\n )\n if (fileChangedCache.result === false) {\n this.routeNodeShadowCache.set(node.fullPath, fileChangedCache.cacheEntry)\n return {\n status: 'fresh',\n cacheEntry: fileChangedCache.cacheEntry,\n }\n }\n if (fileChangedCache.result === 'cannot-stat-file') {\n throw new Error(`⚠️ expected route file to exist at ${node.fullPath}`)\n }\n const mtimeMs =\n fileChangedCache.result === true ? fileChangedCache.mtimeMs : undefined\n\n const shadowCacheFileChange = await this.didRouteFileChangeComparedToCache(\n { path: node.fullPath, mtimeMs },\n 'routeNodeShadowCache',\n )\n\n if (shadowCacheFileChange.result === 'cannot-stat-file') {\n throw new Error(`⚠️ expected route file to exist at ${node.fullPath}`)\n }\n\n if (shadowCacheFileChange.result === false) {\n // shadow cache has latest file state already\n if (fileChangedCache.result === true) {\n return {\n status: 'fresh',\n cacheEntry: shadowCacheFileChange.cacheEntry,\n }\n }\n }\n\n if (fileChangedCache.result === 'file-not-in-cache') {\n return {\n status: 'stale',\n }\n }\n return { status: 'stale', cacheEntry: fileChangedCache.cacheEntry }\n }\n\n private async handleRootNode(node: RouteNode) {\n const result = await this.isRouteFileCacheFresh(node)\n\n if (result.status === 'fresh') {\n this.routeNodeShadowCache.set(node.fullPath, result.cacheEntry)\n }\n const rootNodeFile = await this.fs.readFile(node.fullPath)\n if (rootNodeFile === 'file-not-existing') {\n throw new Error(`⚠️ expected root route to exist at ${node.fullPath}`)\n }\n\n const updatedCacheEntry: RouteNodeCacheEntry = {\n fileContent: rootNodeFile.fileContent,\n mtimeMs: rootNodeFile.stat.mtimeMs,\n routeId: node.routePath ?? '$$TSR_NO_ROOT_ROUTE_PATH_ASSIGNED$$',\n node,\n }\n\n // scaffold the root route\n if (!rootNodeFile.fileContent) {\n const rootTemplate = this.targetTemplate.rootRoute\n const rootRouteContent = await fillTemplate(\n this.config,\n rootTemplate.template(),\n {\n tsrImports: rootTemplate.imports.tsrImports(),\n tsrPath: rootPathId,\n tsrExportStart: rootTemplate.imports.tsrExportStart(),\n tsrExportEnd: rootTemplate.imports.tsrExportEnd(),\n },\n )\n\n this.logger.log(`🟡 Creating ${node.fullPath}`)\n const stats = await this.safeFileWrite({\n filePath: node.fullPath,\n newContent: rootRouteContent,\n strategy: {\n type: 'mtime',\n expectedMtimeMs: rootNodeFile.stat.mtimeMs,\n },\n })\n updatedCacheEntry.fileContent = rootRouteContent\n updatedCacheEntry.mtimeMs = stats.mtimeMs\n }\n\n this.routeNodeShadowCache.set(node.fullPath, updatedCacheEntry)\n }\n\n public async getCrawlingResult(): Promise<CrawlingResult | undefined> {\n await this.runPromise\n return this.crawlingResult\n }\n\n private static handleNode(\n node: RouteNode,\n acc: HandleNodeAccumulator,\n config?: Config,\n ) {\n // Do not remove this as we need to set the lastIndex to 0 as it\n // is necessary to reset the regex's index when using the global flag\n // otherwise it might not match the next time it's used\n const useExperimentalNonNestedRoutes =\n config?.experimental?.nonNestedRoutes ?? false\n\n resetRegex(this.routeGroupPatternRegex)\n\n const parentRoute = hasParentRoute(\n acc.routeNodes,\n node,\n node.routePath,\n node.originalRoutePath,\n )\n\n if (parentRoute) node.parent = parentRoute\n\n node.path = determineNodePath(node)\n\n const trimmedPath = trimPathLeft(node.path ?? '')\n\n const split = trimmedPath.split('/')\n const lastRouteSegment = split[split.length - 1] ?? trimmedPath\n\n node.isNonPath =\n lastRouteSegment.startsWith('_') ||\n split.every((part) => this.routeGroupPatternRegex.test(part))\n\n // with new nonNestedPaths feature we can be sure any remaining trailing underscores are escaped and should remain\n // TODO with new major we can remove check and only remove leading underscores\n node.cleanedPath = removeGroups(\n (useExperimentalNonNestedRoutes\n ? removeLeadingUnderscores(\n removeLayoutSegments(node.path ?? ''),\n config?.routeToken ?? '',\n )\n : removeUnderscores(removeLayoutSegments(node.path))) ?? '',\n )\n\n if (\n node._fsRouteType === 'layout' ||\n node._fsRouteType === 'pathless_layout'\n ) {\n node.cleanedPath = removeTrailingSlash(node.cleanedPath)\n }\n\n if (\n !node.isVirtual &&\n (\n [\n 'lazy',\n 'loader',\n 'component',\n 'pendingComponent',\n 'errorComponent',\n 'notFoundComponent',\n ] satisfies Array<FsRouteType>\n ).some((d) => d === node._fsRouteType)\n ) {\n acc.routePiecesByPath[node.routePath!] =\n acc.routePiecesByPath[node.routePath!] || {}\n\n const pieceKey =\n node._fsRouteType === 'lazy'\n ? 'lazy'\n : (node._fsRouteType as keyof (typeof acc.routePiecesByPath)[string])\n acc.routePiecesByPath[node.routePath!]![pieceKey] = node\n\n const anchorRoute = acc.routeNodesByPath.get(node.routePath!)\n\n // Don't create virtual routes for root route component pieces - the root route is handled separately\n if (!anchorRoute && node.routePath !== `/${rootPathId}`) {\n this.handleNode(\n {\n ...node,\n isVirtual: true,\n _fsRouteType: 'static',\n },\n acc,\n config,\n )\n }\n return\n }\n\n const isPathlessLayoutWithPath =\n node._fsRouteType === 'pathless_layout' &&\n node.cleanedPath &&\n node.cleanedPath.length > 0\n\n // Special handling: pathless layouts with path need to find real ancestor\n if (!node.isVirtual && isPathlessLayoutWithPath) {\n const immediateParentPath =\n removeLastSegmentFromPath(node.routePath) || '/'\n let searchPath = immediateParentPath\n\n // Find nearest real (non-virtual, non-index) parent\n while (searchPath) {\n const candidate = acc.routeNodesByPath.get(searchPath)\n if (candidate && !candidate.isVirtual && candidate.path !== '/') {\n node.parent = candidate\n node.path = node.routePath\n node.cleanedPath = removeGroups(\n removeUnderscores(removeLayoutSegments(immediateParentPath)) ?? '',\n )\n break\n }\n if (searchPath === '/') break\n searchPath = removeLastSegmentFromPath(searchPath) || '/'\n }\n }\n\n // Add to parent's children or to root\n if (node.parent) {\n node.parent.children = node.parent.children ?? []\n node.parent.children.push(node)\n } else {\n acc.routeTree.push(node)\n }\n\n acc.routeNodes.push(node)\n if (node.routePath && !node.isVirtual) {\n acc.routeNodesByPath.set(node.routePath, node)\n }\n }\n\n // only process files that are relevant for the route tree generation\n private isFileRelevantForRouteTreeGeneration(filePath: string): boolean {\n // the generated route tree file\n if (filePath === this.generatedRouteTreePath) {\n return true\n }\n\n // files inside the routes folder\n if (filePath.startsWith(this.routesDirectoryPath)) {\n return true\n }\n\n // the virtual route config file passed into `virtualRouteConfig`\n if (\n typeof this.config.virtualRouteConfig === 'string' &&\n filePath === this.config.virtualRouteConfig\n ) {\n return true\n }\n\n // this covers all files that are mounted via `virtualRouteConfig` or any `__virtual.ts` files\n if (this.routeNodeCache.has(filePath)) {\n return true\n }\n\n // virtual config files such as`__virtual.ts`\n if (isVirtualConfigFile(path.basename(filePath))) {\n return true\n }\n\n // route files inside directories mounted via `physical()` inside a virtual route config\n if (this.physicalDirectories.some((dir) => filePath.startsWith(dir))) {\n return true\n }\n\n return false\n }\n}\n"],"names":["virtualGetRouteNodes","physicalGetRouteNodes","moduleAugmentation"],"mappings":";;;;;;;;;;;;AAwEA,MAAM,oBAAwB;AAAA,EAC5B,MAAM,OAAO,aAAa;AACxB,UAAM,MAAM,MAAM,IAAI,KAAK,UAAU,EAAE,QAAQ,MAAM;AACrD,WAAO;AAAA,MACL,SAAS,IAAI;AAAA,MACb,MAAM,OAAO,IAAI,IAAI;AAAA,MACrB,KAAK,OAAO,IAAI,GAAG;AAAA,MACnB,KAAK,OAAO,IAAI,GAAG;AAAA,IAAA;AAAA,EAEvB;AAAA,EACA,QAAQ,CAAC,SAAS,YAAY,IAAI,OAAO,SAAS,OAAO;AAAA,EACzD,WAAW,CAAC,UAAU,YAAY,IAAI,UAAU,UAAU,OAAO;AAAA,EACjE,UAAU,OAAO,aAAqB;AACpC,QAAI;AACF,YAAM,aAAa,MAAM,IAAI,KAAK,UAAU,GAAG;AAC/C,YAAM,OAAO,MAAM,WAAW,KAAK,E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A,EACT;AACF;AAzyCE,WAAe,yBAAyB;AA7BnC,IAAM,YAAN;"}
@@ -8,7 +8,6 @@ export type RouteNode = {
8
8
  cleanedPath?: string;
9
9
  path?: string;
10
10
  isNonPath?: boolean;
11
- isVirtualParentRequired?: boolean;
12
11
  isVirtualParentRoute?: boolean;
13
12
  isVirtual?: boolean;
14
13
  children?: Array<RouteNode>;
@@ -43,6 +42,8 @@ export type HandleNodeAccumulator = {
43
42
  routeTree: Array<RouteNode>;
44
43
  routePiecesByPath: Record<string, RouteSubNode>;
45
44
  routeNodes: Array<RouteNode>;
45
+ /** O(1) lookup by routePath - avoids O(n) .find() on every node */
46
+ routeNodesByPath: Map<string, RouteNode>;
46
47
  };
47
48
  export type GetRoutesByFileMapResultValue = {
48
49
  routePath: string;
package/dist/esm/utils.js CHANGED
@@ -384,11 +384,7 @@ const findParent = (node) => {
384
384
  return `rootRouteImport`;
385
385
  }
386
386
  if (node.parent) {
387
- if (node.isVirtualParentRequired) {
388
- return `${node.parent.variableName}Route`;
389
- } else {
390
- return `${node.parent.variableName}Route`;
391
- }
387
+ return `${node.parent.variableName}Route`;
392
388
  }
393
389
  return findParent(node.parent);
394
390
  };
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["import * as fsp from 'node:fs/promises'\nimport path from 'node:path'\nimport * as prettier from 'prettier'\nimport { rootPathId } from './filesystem/physical/rootPathId'\nimport type { Config } from './config'\nimport type { ImportDeclaration, RouteNode } from './types'\n\nexport function multiSortBy<T>(\n arr: Array<T>,\n accessors: Array<(item: T) => any> = [(d) => d],\n): Array<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\nexport function cleanPath(path: string) {\n // remove double slashes\n return path.replace(/\\/{2,}/g, '/')\n}\n\nexport function trimPathLeft(path: string) {\n return path === '/' ? path : path.replace(/^\\/{1,}/, '')\n}\n\nexport function removeLeadingSlash(path: string): string {\n return path.replace(/^\\//, '')\n}\n\nexport function removeTrailingSlash(s: string) {\n return s.replace(/\\/$/, '')\n}\n\nconst BRACKET_CONTENT_RE = /\\[(.*?)\\]/g\nconst SPLIT_REGEX = /(?<!\\[)\\.(?!\\])/g\n\nexport function determineInitialRoutePath(\n routePath: string,\n config?: Pick<Config, 'experimental' | 'routeToken' | 'indexToken'>,\n) {\n const DISALLOWED_ESCAPE_CHARS = new Set([\n '/',\n '\\\\',\n '?',\n '#',\n ':',\n '*',\n '<',\n '>',\n '|',\n '!',\n '$',\n '%',\n ])\n\n const originalRoutePath =\n cleanPath(\n `/${(cleanPath(routePath) || '').split(SPLIT_REGEX).join('/')}`,\n ) || ''\n\n // check if the route path is a valid non-nested path,\n // TODO with new major rename to reflect not experimental anymore\n const isExperimentalNonNestedRoute = isValidNonNestedRoute(\n originalRoutePath,\n config,\n )\n\n let cleanedRoutePath = routePath\n\n // we already identified the path as non-nested and can now remove the trailing underscores\n // we need to do this now before we encounter any escaped trailing underscores\n // this way we can be sure any remaining trailing underscores should remain\n // TODO with new major we can remove check and always remove leading underscores\n if (config?.experimental?.nonNestedRoutes) {\n // we should leave trailing underscores if the route path is the root path\n if (originalRoutePath !== `/${rootPathId}`) {\n // remove trailing underscores on various path segments\n cleanedRoutePath = removeTrailingUnderscores(\n originalRoutePath,\n config.routeToken,\n )\n }\n }\n\n const parts = cleanedRoutePath.split(SPLIT_REGEX)\n\n // Escape any characters that in square brackets\n // we keep the original path untouched\n const escapedParts = parts.map((part) => {\n // Check if any disallowed characters are used in brackets\n\n let match\n while ((match = BRACKET_CONTENT_RE.exec(part)) !== null) {\n const character = match[1]\n if (character === undefined) continue\n if (DISALLOWED_ESCAPE_CHARS.has(character)) {\n console.error(\n `Error: Disallowed character \"${character}\" found in square brackets in route path \"${routePath}\".\\nYou cannot use any of the following characters in square brackets: ${Array.from(\n DISALLOWED_ESCAPE_CHARS,\n ).join(', ')}\\nPlease remove and/or replace them.`,\n )\n process.exit(1)\n }\n }\n\n // Since this split segment is safe at this point, we can\n // remove the brackets and replace them with the content inside\n return part.replace(BRACKET_CONTENT_RE, '$1')\n })\n\n // If the syntax for prefix/suffix is different, from the path\n // matching internals of router-core, we'd perform those changes here\n // on the `escapedParts` array before it is joined back together in\n // `final`\n\n const final = cleanPath(`/${escapedParts.join('/')}`) || ''\n\n return {\n routePath: final,\n isExperimentalNonNestedRoute,\n originalRoutePath,\n }\n}\n\nexport function replaceBackslash(s: string) {\n return s.replaceAll(/\\\\/gi, '/')\n}\n\nexport function routePathToVariable(routePath: string): string {\n const toVariableSafeChar = (char: string): string => {\n if (/[a-zA-Z0-9_]/.test(char)) {\n return char // Keep alphanumeric characters and underscores as is\n }\n\n // Replace special characters with meaningful text equivalents\n switch (char) {\n case '.':\n return 'Dot'\n case '-':\n return 'Dash'\n case '@':\n return 'At'\n case '(':\n return '' // Removed since route groups use parentheses\n case ')':\n return '' // Removed since route groups use parentheses\n case ' ':\n return '' // Remove spaces\n default:\n return `Char${char.charCodeAt(0)}` // For any other characters\n }\n }\n\n return (\n removeUnderscores(routePath)\n ?.replace(/\\/\\$\\//g, '/splat/')\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 .split('')\n .map(toVariableSafeChar)\n .join('')\n // .replace(/([^a-zA-Z0-9]|[.])/gm, '')\n .replace(/^(\\d)/g, 'R$1') ?? ''\n )\n}\n\nexport function removeUnderscores(s?: string) {\n return s?.replaceAll(/(^_|_$)/gi, '').replaceAll(/(\\/_|_\\/)/gi, '/')\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport function removeLeadingUnderscores(s: string, routeToken: string) {\n if (!s) return s\n\n const hasLeadingUnderscore = routeToken[0] === '_'\n\n const routeTokenToExclude = hasLeadingUnderscore\n ? routeToken.slice(1)\n : routeToken\n\n const escapedRouteToken = escapeRegExp(routeTokenToExclude)\n\n const leadingUnderscoreRegex = hasLeadingUnderscore\n ? new RegExp(`(?<=^|\\\\/)_(?!${escapedRouteToken})`, 'g')\n : new RegExp(`(?<=^|\\\\/)_`, 'g')\n\n return s.replaceAll(leadingUnderscoreRegex, '')\n}\n\nexport function removeTrailingUnderscores(s: string, routeToken: string) {\n if (!s) return s\n\n const hasTrailingUnderscore = routeToken.slice(-1) === '_'\n\n const routeTokenToExclude = hasTrailingUnderscore\n ? routeToken.slice(0, -1)\n : routeToken\n\n const escapedRouteToken = escapeRegExp(routeTokenToExclude)\n\n const trailingUnderscoreRegex = hasTrailingUnderscore\n ? new RegExp(`(?<!${escapedRouteToken})_(?=\\\\/|$)`, 'g')\n : new RegExp(`_(?=\\\\/)|_$`, 'g')\n\n return s.replaceAll(trailingUnderscoreRegex, '')\n}\n\nexport function capitalize(s: string) {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nexport function removeExt(d: string, keepExtension: boolean = false) {\n return keepExtension ? d : d.substring(0, d.lastIndexOf('.')) || d\n}\n\n/**\n * This function writes to a file if the content is different.\n *\n * @param filepath The path to the file\n * @param content Original content\n * @param incomingContent New content\n * @param callbacks Callbacks to run before and after writing\n * @returns Whether the file was written\n */\nexport async function writeIfDifferent(\n filepath: string,\n content: string,\n incomingContent: string,\n callbacks?: { beforeWrite?: () => void; afterWrite?: () => void },\n): Promise<boolean> {\n if (content !== incomingContent) {\n callbacks?.beforeWrite?.()\n await fsp.writeFile(filepath, incomingContent)\n callbacks?.afterWrite?.()\n return true\n }\n return false\n}\n\n/**\n * This function formats the source code using the default formatter (Prettier).\n *\n * @param source The content to format\n * @param config The configuration object\n * @returns The formatted content\n */\nexport async function format(\n source: string,\n config: {\n quoteStyle: 'single' | 'double'\n semicolons: boolean\n },\n): Promise<string> {\n const prettierOptions: prettier.Config = {\n semi: config.semicolons,\n singleQuote: config.quoteStyle === 'single',\n parser: 'typescript',\n }\n return prettier.format(source, prettierOptions)\n}\n\n/**\n * This function resets the regex index to 0 so that it can be reused\n * without having to create a new regex object or worry about the last\n * state when using the global flag.\n *\n * @param regex The regex object to reset\n * @returns\n */\nexport function resetRegex(regex: RegExp) {\n regex.lastIndex = 0\n return\n}\n\n/**\n * This function checks if a file exists.\n *\n * @param file The path to the file\n * @returns Whether the file exists\n */\nexport async function checkFileExists(file: string) {\n try {\n await fsp.access(file, fsp.constants.F_OK)\n return true\n } catch {\n return false\n }\n}\n\nconst possiblyNestedRouteGroupPatternRegex = /\\([^/]+\\)\\/?/g\nexport function removeGroups(s: string) {\n return s.replace(possiblyNestedRouteGroupPatternRegex, '')\n}\n\n/**\n * Removes all segments from a given path that start with an underscore ('_').\n *\n * @param {string} routePath - The path from which to remove segments. Defaults to '/'.\n * @returns {string} The path with all underscore-prefixed segments removed.\n * @example\n * removeLayoutSegments('/workspace/_auth/foo') // '/workspace/foo'\n */\nexport function removeLayoutSegments(routePath: string = '/'): string {\n const segments = routePath.split('/')\n const newSegments = segments.filter((segment) => !segment.startsWith('_'))\n return newSegments.join('/')\n}\n\n/**\n * The `node.path` is used as the `id` in the route definition.\n * This function checks if the given node has a parent and if so, it determines the correct path for the given node.\n * @param node - The node to determine the path for.\n * @returns The correct path for the given node.\n */\nexport function determineNodePath(node: RouteNode) {\n return (node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath ?? '', '') || '/'\n : node.routePath)\n}\n\n/**\n * Removes the last segment from a given path. Segments are considered to be separated by a '/'.\n *\n * @param {string} routePath - The path from which to remove the last segment. Defaults to '/'.\n * @returns {string} The path with the last segment removed.\n * @example\n * removeLastSegmentFromPath('/workspace/_auth/foo') // '/workspace/_auth'\n */\nexport function removeLastSegmentFromPath(routePath: string = '/'): string {\n const segments = routePath.split('/')\n segments.pop() // Remove the last segment\n return segments.join('/')\n}\n\nexport function hasParentRoute(\n routes: Array<RouteNode>,\n node: RouteNode,\n routePathToCheck: string | undefined,\n originalRoutePathToCheck: string | undefined,\n): RouteNode | null {\n const getNonNestedSegments = (routePath: string) => {\n const regex = /_(?=\\/|$)/g\n\n return [...routePath.matchAll(regex)]\n .filter((match) => {\n const beforeStr = routePath.substring(0, match.index)\n const openBrackets = (beforeStr.match(/\\[/g) || []).length\n const closeBrackets = (beforeStr.match(/\\]/g) || []).length\n return openBrackets === closeBrackets\n })\n .map((match) => routePath.substring(0, match.index + 1))\n .reverse()\n }\n\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 const filteredNodes = node._isExperimentalNonNestedRoute\n ? []\n : [...sortedNodes]\n\n if (node._isExperimentalNonNestedRoute && originalRoutePathToCheck) {\n const nonNestedSegments = getNonNestedSegments(originalRoutePathToCheck)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n route._isExperimentalNonNestedRoute &&\n route.routePath !== routePathToCheck &&\n originalRoutePathToCheck.startsWith(`${route.originalRoutePath}/`)\n ) {\n return route\n }\n\n if (\n nonNestedSegments.find(\n (seg) => seg === `${route.originalRoutePath}_`,\n ) ||\n !(\n route._fsRouteType === 'pathless_layout' ||\n route._fsRouteType === 'layout' ||\n route._fsRouteType === '__root'\n )\n ) {\n continue\n }\n\n filteredNodes.push(route)\n }\n }\n\n for (const route of filteredNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, node, parentRoutePath, originalRoutePathToCheck)\n}\n\n/**\n * Gets the final variable name for a route\n */\nexport const getResolvedRouteNodeVariableName = (\n routeNode: RouteNode,\n): string => {\n return routeNode.children?.length\n ? `${routeNode.variableName}RouteWithChildren`\n : `${routeNode.variableName}Route`\n}\n\n/**\n * Checks if a given RouteNode is valid for augmenting it with typing based on conditions.\n * Also asserts that the RouteNode is defined.\n *\n * @param routeNode - The RouteNode to check.\n * @returns A boolean indicating whether the RouteNode is defined.\n */\nexport function isRouteNodeValidForAugmentation(\n routeNode?: RouteNode,\n): routeNode is RouteNode {\n if (!routeNode || routeNode.isVirtual) {\n return false\n }\n return true\n}\n\n/**\n * Infers the path for use by TS\n */\nexport const inferPath = (routeNode: RouteNode): string => {\n return routeNode.cleanedPath === '/'\n ? routeNode.cleanedPath\n : (routeNode.cleanedPath?.replace(/\\/$/, '') ?? '')\n}\n\n/**\n * Infers the full path for use by TS\n */\nexport const inferFullPath = (\n routeNode: RouteNode,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): string => {\n // with new nonNestedPaths feature we can be sure any remaining trailing underscores are escaped and should remain\n // TODO with new major we can remove check and only remove leading underscores\n const fullPath = removeGroups(\n (config?.experimental?.nonNestedRoutes\n ? removeLayoutSegments(routeNode.routePath)\n : removeUnderscores(removeLayoutSegments(routeNode.routePath))) ?? '',\n )\n\n return routeNode.cleanedPath === '/' ? fullPath : fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Creates a map from fullPath to routeNode\n */\nexport const createRouteNodesByFullPath = (\n routeNodes: Array<RouteNode>,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => [\n inferFullPath(routeNode, config),\n routeNode,\n ]),\n )\n}\n\n/**\n * Create a map from 'to' to a routeNode\n */\nexport const createRouteNodesByTo = (\n routeNodes: Array<RouteNode>,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): Map<string, RouteNode> => {\n return new Map(\n dedupeBranchesAndIndexRoutes(routeNodes).map((routeNode) => [\n inferTo(routeNode, config),\n routeNode,\n ]),\n )\n}\n\n/**\n * Create a map from 'id' to a routeNode\n */\nexport const createRouteNodesById = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => {\n const id = routeNode.routePath ?? ''\n return [id, routeNode]\n }),\n )\n}\n\n/**\n * Infers to path\n */\nexport const inferTo = (\n routeNode: RouteNode,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): string => {\n const fullPath = inferFullPath(routeNode, config)\n\n if (fullPath === '/') return fullPath\n\n return fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Dedupes branches and index routes\n */\nexport const dedupeBranchesAndIndexRoutes = (\n routes: Array<RouteNode>,\n): Array<RouteNode> => {\n return routes.filter((route) => {\n if (route.children?.find((child) => child.cleanedPath === '/')) return false\n return true\n })\n}\n\nfunction checkUnique<TElement>(routes: Array<TElement>, key: keyof TElement) {\n // Check no two routes have the same `key`\n // if they do, throw an error with the conflicting filePaths\n const keys = routes.map((d) => d[key])\n const uniqueKeys = new Set(keys)\n if (keys.length !== uniqueKeys.size) {\n const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i)\n const conflictingFiles = routes.filter((d) =>\n duplicateKeys.includes(d[key]),\n )\n return conflictingFiles\n }\n return undefined\n}\n\nexport function checkRouteFullPathUniqueness(\n _routes: Array<RouteNode>,\n config: Config,\n) {\n const routes = _routes.map((d) => {\n const inferredFullPath = inferFullPath(d, config)\n return { ...d, inferredFullPath }\n })\n\n const conflictingFiles = checkUnique(routes, 'inferredFullPath')\n\n if (conflictingFiles !== undefined) {\n const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? 's' : ''}: ${conflictingFiles\n .map((p) => `\"${p.inferredFullPath}\"`)\n .join(', ')}.\nPlease ensure each Route has a unique full path.\nConflicting files: \\n ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join('\\n ')}\\n`\n throw new Error(errorMessage)\n }\n}\n\nexport function buildRouteTreeConfig(\n nodes: Array<RouteNode>,\n disableTypes: boolean,\n depth = 1,\n): Array<string> {\n const children = nodes.map((node) => {\n if (node._fsRouteType === '__root') {\n return\n }\n\n if (node._fsRouteType === 'pathless_layout' && !node.children?.length) {\n return\n }\n\n const route = `${node.variableName}`\n\n if (node.children?.length) {\n const childConfigs = buildRouteTreeConfig(\n node.children,\n disableTypes,\n depth + 1,\n )\n\n const childrenDeclaration = disableTypes\n ? ''\n : `interface ${route}RouteChildren {\n ${node.children\n .map(\n (child) =>\n `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`,\n )\n .join(',')}\n}`\n\n const children = `const ${route}RouteChildren${disableTypes ? '' : `: ${route}RouteChildren`} = {\n ${node.children\n .map(\n (child) =>\n `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,\n )\n .join(',')}\n}`\n\n const routeWithChildren = `const ${route}RouteWithChildren = ${route}Route._addFileChildren(${route}RouteChildren)`\n\n return [\n childConfigs.join('\\n'),\n childrenDeclaration,\n children,\n routeWithChildren,\n ].join('\\n\\n')\n }\n\n return undefined\n })\n\n return children.filter((x) => x !== undefined)\n}\n\nexport function buildImportString(\n importDeclaration: ImportDeclaration,\n): string {\n const { source, specifiers, importKind } = importDeclaration\n return specifiers.length\n ? `import ${importKind === 'type' ? 'type ' : ''}{ ${specifiers.map((s) => (s.local ? `${s.imported} as ${s.local}` : s.imported)).join(', ')} } from '${source}'`\n : ''\n}\n\nexport function lowerCaseFirstChar(value: string) {\n if (!value[0]) {\n return value\n }\n\n return value[0].toLowerCase() + value.slice(1)\n}\n\nexport function mergeImportDeclarations(\n imports: Array<ImportDeclaration>,\n): Array<ImportDeclaration> {\n const merged: Record<string, ImportDeclaration> = {}\n\n for (const imp of imports) {\n const key = `${imp.source}-${imp.importKind}`\n if (!merged[key]) {\n merged[key] = { ...imp, specifiers: [] }\n }\n for (const specifier of imp.specifiers) {\n // check if the specifier already exists in the merged import\n if (\n !merged[key].specifiers.some(\n (existing) =>\n existing.imported === specifier.imported &&\n existing.local === specifier.local,\n )\n ) {\n merged[key].specifiers.push(specifier)\n }\n }\n }\n\n return Object.values(merged)\n}\n\nexport const findParent = (node: RouteNode | undefined): string => {\n if (!node) {\n return `rootRouteImport`\n }\n if (node.parent) {\n if (node.isVirtualParentRequired) {\n return `${node.parent.variableName}Route`\n } else {\n return `${node.parent.variableName}Route`\n }\n }\n return findParent(node.parent)\n}\n\nexport function buildFileRoutesByPathInterface(opts: {\n routeNodes: Array<RouteNode>\n module: string\n interfaceName: string\n config?: Pick<Config, 'experimental' | 'routeToken'>\n}): string {\n return `declare module '${opts.module}' {\n interface ${opts.interfaceName} {\n ${opts.routeNodes\n .map((routeNode) => {\n const filePathId = routeNode.routePath\n const preloaderRoute = `typeof ${routeNode.variableName}RouteImport`\n\n const parent = findParent(routeNode)\n\n return `'${filePathId}': {\n id: '${filePathId}'\n path: '${inferPath(routeNode)}'\n fullPath: '${inferFullPath(routeNode, opts.config)}'\n preLoaderRoute: ${preloaderRoute}\n parentRoute: typeof ${parent}\n }`\n })\n .join('\\n')}\n }\n}`\n}\n\nexport function getImportPath(\n node: RouteNode,\n config: Config,\n generatedRouteTreePath: string,\n): string {\n return replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(generatedRouteTreePath),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n config.addExtensions,\n ),\n )\n}\n\nexport function getImportForRouteNode(\n node: RouteNode,\n config: Config,\n generatedRouteTreePath: string,\n root: string,\n): ImportDeclaration {\n let source = ''\n if (config.importRoutesUsingAbsolutePaths) {\n source = replaceBackslash(\n removeExt(\n path.resolve(root, config.routesDirectory, node.filePath),\n config.addExtensions,\n ),\n )\n } else {\n source = `./${getImportPath(node, config, generatedRouteTreePath)}`\n }\n return {\n source,\n specifiers: [\n {\n imported: 'Route',\n local: `${node.variableName}RouteImport`,\n },\n ],\n } satisfies ImportDeclaration\n}\n\n/**\n * Used to validate if a route is a pathless layout route\n * @param normalizedRoutePath Normalized route path, i.e `/foo/_layout/route.tsx` and `/foo._layout.route.tsx` to `/foo/_layout/route`\n * @param config The `router-generator` configuration object\n * @returns Boolean indicating if the route is a pathless layout route\n */\nexport function isValidNonNestedRoute(\n normalizedRoutePath: string,\n config?: Pick<Config, 'experimental' | 'routeToken' | 'indexToken'>,\n): boolean {\n if (!config?.experimental?.nonNestedRoutes) {\n return false\n }\n\n const segments = normalizedRoutePath.split('/').filter(Boolean)\n\n if (segments.length === 0) {\n return false\n }\n\n const lastRouteSegment = segments[segments.length - 1]!\n\n // If segment === __root, then exit as false\n if (lastRouteSegment === rootPathId) {\n return false\n }\n\n if (\n lastRouteSegment !== config.indexToken &&\n lastRouteSegment !== config.routeToken &&\n lastRouteSegment.endsWith('_')\n ) {\n return true\n }\n\n for (const segment of segments.slice(0, -1).reverse()) {\n if (segment === config.routeToken) {\n return false\n }\n\n if (segment.endsWith('_')) {\n return true\n }\n }\n\n return false\n}\n"],"names":["path","children"],"mappings":";;;;AAOO,SAAS,YACd,KACA,YAAqC,CAAC,CAAC,MAAM,CAAC,GACpC;AACV,SAAO,IACJ,IAAI,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAU,EAC7B,KAAK,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,MAAM;AAC1B,eAAW,YAAY,WAAW;AAChC,YAAM,KAAK,SAAS,CAAC;AACrB,YAAM,KAAK,SAAS,CAAC;AAErB,UAAI,OAAO,OAAO,aAAa;AAC7B,YAAI,OAAO,OAAO,aAAa;AAC7B;AAAA,QACF;AACA,eAAO;AAAA,MACT;AAEA,UAAI,OAAO,IAAI;AACb;AAAA,MACF;AAEA,aAAO,KAAK,KAAK,IAAI;AAAA,IACvB;AAEA,WAAO,KAAK;AAAA,EACd,CAAC,EACA,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;AACnB;AAEO,SAAS,UAAU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pD,OAAO;AAAA,IAAA;AAAA,EACT;AAEJ;AAEO,SAAS,sBACd,MACA,QACA,wBACA,MACmB;AACnB,MAAI,SAAS;AACb,MAAI,OAAO,gCAAgC;AACzC,aAAS;AAAA,MACP;AAAA,QACE,KAAK,QAAQ,MAAM,OAAO,iBAAiB,KAAK,QAAQ;AAAA,QACxD,OAAO;AAAA,MAAA;AAAA,IACT;AAAA,EAEJ,OAAO;AACL,aAAS,KAAK,cAAc,MAAM,QAAQ,sBAAsB,CAAC;AAAA,EACnE;AACA,SAAO;AAAA,IACL;AAAA,IACA,YAAY;AAAA,MACV;AAAA,QACE,UAAU;AAAA,QACV,OAAO,GAAG,KAAK,YAAY;AAAA,MAAA;AAAA,IAC7B;AAAA,EACF;AAEJ;AAQO,SAAS,sBACd,qBACA,QACS;AACT,MAAI,CAAC,QAAQ,cAAc,iBAAiB;AAC1C,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,oBAAoB,MAAM,GAAG,EAAE,OAAO,OAAO;AAE9D,MAAI,SAAS,WAAW,GAAG;AACzB,WAAO;AAAA,EACT;AAEA,QAAM,mBAAmB,SAAS,SAAS,SAAS,CAAC;AAGrD,MAAI,qBAAqB,YAAY;AACnC,WAAO;AAAA,EACT;AAEA,MACE,qBAAqB,OAAO,cAC5B,qBAAqB,OAAO,cAC5B,iBAAiB,SAAS,GAAG,GAC7B;AACA,WAAO;AAAA,EACT;AAEA,aAAW,WAAW,SAAS,MAAM,GAAG,EAAE,EAAE,WAAW;AACrD,QAAI,YAAY,OAAO,YAAY;AACjC,aAAO;AAAA,IACT;AAEA,QAAI,QAAQ,SAAS,GAAG,GAAG;AACzB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;"}
1
+ {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["import * as fsp from 'node:fs/promises'\nimport path from 'node:path'\nimport * as prettier from 'prettier'\nimport { rootPathId } from './filesystem/physical/rootPathId'\nimport type { Config } from './config'\nimport type { ImportDeclaration, RouteNode } from './types'\n\nexport function multiSortBy<T>(\n arr: Array<T>,\n accessors: Array<(item: T) => any> = [(d) => d],\n): Array<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\nexport function cleanPath(path: string) {\n // remove double slashes\n return path.replace(/\\/{2,}/g, '/')\n}\n\nexport function trimPathLeft(path: string) {\n return path === '/' ? path : path.replace(/^\\/{1,}/, '')\n}\n\nexport function removeLeadingSlash(path: string): string {\n return path.replace(/^\\//, '')\n}\n\nexport function removeTrailingSlash(s: string) {\n return s.replace(/\\/$/, '')\n}\n\nconst BRACKET_CONTENT_RE = /\\[(.*?)\\]/g\nconst SPLIT_REGEX = /(?<!\\[)\\.(?!\\])/g\n\nexport function determineInitialRoutePath(\n routePath: string,\n config?: Pick<Config, 'experimental' | 'routeToken' | 'indexToken'>,\n) {\n const DISALLOWED_ESCAPE_CHARS = new Set([\n '/',\n '\\\\',\n '?',\n '#',\n ':',\n '*',\n '<',\n '>',\n '|',\n '!',\n '$',\n '%',\n ])\n\n const originalRoutePath =\n cleanPath(\n `/${(cleanPath(routePath) || '').split(SPLIT_REGEX).join('/')}`,\n ) || ''\n\n // check if the route path is a valid non-nested path,\n // TODO with new major rename to reflect not experimental anymore\n const isExperimentalNonNestedRoute = isValidNonNestedRoute(\n originalRoutePath,\n config,\n )\n\n let cleanedRoutePath = routePath\n\n // we already identified the path as non-nested and can now remove the trailing underscores\n // we need to do this now before we encounter any escaped trailing underscores\n // this way we can be sure any remaining trailing underscores should remain\n // TODO with new major we can remove check and always remove leading underscores\n if (config?.experimental?.nonNestedRoutes) {\n // we should leave trailing underscores if the route path is the root path\n if (originalRoutePath !== `/${rootPathId}`) {\n // remove trailing underscores on various path segments\n cleanedRoutePath = removeTrailingUnderscores(\n originalRoutePath,\n config.routeToken,\n )\n }\n }\n\n const parts = cleanedRoutePath.split(SPLIT_REGEX)\n\n // Escape any characters that in square brackets\n // we keep the original path untouched\n const escapedParts = parts.map((part) => {\n // Check if any disallowed characters are used in brackets\n\n let match\n while ((match = BRACKET_CONTENT_RE.exec(part)) !== null) {\n const character = match[1]\n if (character === undefined) continue\n if (DISALLOWED_ESCAPE_CHARS.has(character)) {\n console.error(\n `Error: Disallowed character \"${character}\" found in square brackets in route path \"${routePath}\".\\nYou cannot use any of the following characters in square brackets: ${Array.from(\n DISALLOWED_ESCAPE_CHARS,\n ).join(', ')}\\nPlease remove and/or replace them.`,\n )\n process.exit(1)\n }\n }\n\n // Since this split segment is safe at this point, we can\n // remove the brackets and replace them with the content inside\n return part.replace(BRACKET_CONTENT_RE, '$1')\n })\n\n // If the syntax for prefix/suffix is different, from the path\n // matching internals of router-core, we'd perform those changes here\n // on the `escapedParts` array before it is joined back together in\n // `final`\n\n const final = cleanPath(`/${escapedParts.join('/')}`) || ''\n\n return {\n routePath: final,\n isExperimentalNonNestedRoute,\n originalRoutePath,\n }\n}\n\nexport function replaceBackslash(s: string) {\n return s.replaceAll(/\\\\/gi, '/')\n}\n\nexport function routePathToVariable(routePath: string): string {\n const toVariableSafeChar = (char: string): string => {\n if (/[a-zA-Z0-9_]/.test(char)) {\n return char // Keep alphanumeric characters and underscores as is\n }\n\n // Replace special characters with meaningful text equivalents\n switch (char) {\n case '.':\n return 'Dot'\n case '-':\n return 'Dash'\n case '@':\n return 'At'\n case '(':\n return '' // Removed since route groups use parentheses\n case ')':\n return '' // Removed since route groups use parentheses\n case ' ':\n return '' // Remove spaces\n default:\n return `Char${char.charCodeAt(0)}` // For any other characters\n }\n }\n\n return (\n removeUnderscores(routePath)\n ?.replace(/\\/\\$\\//g, '/splat/')\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 .split('')\n .map(toVariableSafeChar)\n .join('')\n // .replace(/([^a-zA-Z0-9]|[.])/gm, '')\n .replace(/^(\\d)/g, 'R$1') ?? ''\n )\n}\n\nexport function removeUnderscores(s?: string) {\n return s?.replaceAll(/(^_|_$)/gi, '').replaceAll(/(\\/_|_\\/)/gi, '/')\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport function removeLeadingUnderscores(s: string, routeToken: string) {\n if (!s) return s\n\n const hasLeadingUnderscore = routeToken[0] === '_'\n\n const routeTokenToExclude = hasLeadingUnderscore\n ? routeToken.slice(1)\n : routeToken\n\n const escapedRouteToken = escapeRegExp(routeTokenToExclude)\n\n const leadingUnderscoreRegex = hasLeadingUnderscore\n ? new RegExp(`(?<=^|\\\\/)_(?!${escapedRouteToken})`, 'g')\n : new RegExp(`(?<=^|\\\\/)_`, 'g')\n\n return s.replaceAll(leadingUnderscoreRegex, '')\n}\n\nexport function removeTrailingUnderscores(s: string, routeToken: string) {\n if (!s) return s\n\n const hasTrailingUnderscore = routeToken.slice(-1) === '_'\n\n const routeTokenToExclude = hasTrailingUnderscore\n ? routeToken.slice(0, -1)\n : routeToken\n\n const escapedRouteToken = escapeRegExp(routeTokenToExclude)\n\n const trailingUnderscoreRegex = hasTrailingUnderscore\n ? new RegExp(`(?<!${escapedRouteToken})_(?=\\\\/|$)`, 'g')\n : new RegExp(`_(?=\\\\/)|_$`, 'g')\n\n return s.replaceAll(trailingUnderscoreRegex, '')\n}\n\nexport function capitalize(s: string) {\n if (typeof s !== 'string') return ''\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\nexport function removeExt(d: string, keepExtension: boolean = false) {\n return keepExtension ? d : d.substring(0, d.lastIndexOf('.')) || d\n}\n\n/**\n * This function writes to a file if the content is different.\n *\n * @param filepath The path to the file\n * @param content Original content\n * @param incomingContent New content\n * @param callbacks Callbacks to run before and after writing\n * @returns Whether the file was written\n */\nexport async function writeIfDifferent(\n filepath: string,\n content: string,\n incomingContent: string,\n callbacks?: { beforeWrite?: () => void; afterWrite?: () => void },\n): Promise<boolean> {\n if (content !== incomingContent) {\n callbacks?.beforeWrite?.()\n await fsp.writeFile(filepath, incomingContent)\n callbacks?.afterWrite?.()\n return true\n }\n return false\n}\n\n/**\n * This function formats the source code using the default formatter (Prettier).\n *\n * @param source The content to format\n * @param config The configuration object\n * @returns The formatted content\n */\nexport async function format(\n source: string,\n config: {\n quoteStyle: 'single' | 'double'\n semicolons: boolean\n },\n): Promise<string> {\n const prettierOptions: prettier.Config = {\n semi: config.semicolons,\n singleQuote: config.quoteStyle === 'single',\n parser: 'typescript',\n }\n return prettier.format(source, prettierOptions)\n}\n\n/**\n * This function resets the regex index to 0 so that it can be reused\n * without having to create a new regex object or worry about the last\n * state when using the global flag.\n *\n * @param regex The regex object to reset\n * @returns\n */\nexport function resetRegex(regex: RegExp) {\n regex.lastIndex = 0\n return\n}\n\n/**\n * This function checks if a file exists.\n *\n * @param file The path to the file\n * @returns Whether the file exists\n */\nexport async function checkFileExists(file: string) {\n try {\n await fsp.access(file, fsp.constants.F_OK)\n return true\n } catch {\n return false\n }\n}\n\nconst possiblyNestedRouteGroupPatternRegex = /\\([^/]+\\)\\/?/g\nexport function removeGroups(s: string) {\n return s.replace(possiblyNestedRouteGroupPatternRegex, '')\n}\n\n/**\n * Removes all segments from a given path that start with an underscore ('_').\n *\n * @param {string} routePath - The path from which to remove segments. Defaults to '/'.\n * @returns {string} The path with all underscore-prefixed segments removed.\n * @example\n * removeLayoutSegments('/workspace/_auth/foo') // '/workspace/foo'\n */\nexport function removeLayoutSegments(routePath: string = '/'): string {\n const segments = routePath.split('/')\n const newSegments = segments.filter((segment) => !segment.startsWith('_'))\n return newSegments.join('/')\n}\n\n/**\n * The `node.path` is used as the `id` in the route definition.\n * This function checks if the given node has a parent and if so, it determines the correct path for the given node.\n * @param node - The node to determine the path for.\n * @returns The correct path for the given node.\n */\nexport function determineNodePath(node: RouteNode) {\n return (node.path = node.parent\n ? node.routePath?.replace(node.parent.routePath ?? '', '') || '/'\n : node.routePath)\n}\n\n/**\n * Removes the last segment from a given path. Segments are considered to be separated by a '/'.\n *\n * @param {string} routePath - The path from which to remove the last segment. Defaults to '/'.\n * @returns {string} The path with the last segment removed.\n * @example\n * removeLastSegmentFromPath('/workspace/_auth/foo') // '/workspace/_auth'\n */\nexport function removeLastSegmentFromPath(routePath: string = '/'): string {\n const segments = routePath.split('/')\n segments.pop() // Remove the last segment\n return segments.join('/')\n}\n\nexport function hasParentRoute(\n routes: Array<RouteNode>,\n node: RouteNode,\n routePathToCheck: string | undefined,\n originalRoutePathToCheck: string | undefined,\n): RouteNode | null {\n const getNonNestedSegments = (routePath: string) => {\n const regex = /_(?=\\/|$)/g\n\n return [...routePath.matchAll(regex)]\n .filter((match) => {\n const beforeStr = routePath.substring(0, match.index)\n const openBrackets = (beforeStr.match(/\\[/g) || []).length\n const closeBrackets = (beforeStr.match(/\\]/g) || []).length\n return openBrackets === closeBrackets\n })\n .map((match) => routePath.substring(0, match.index + 1))\n .reverse()\n }\n\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 const filteredNodes = node._isExperimentalNonNestedRoute\n ? []\n : [...sortedNodes]\n\n if (node._isExperimentalNonNestedRoute && originalRoutePathToCheck) {\n const nonNestedSegments = getNonNestedSegments(originalRoutePathToCheck)\n\n for (const route of sortedNodes) {\n if (route.routePath === '/') continue\n\n if (\n route._isExperimentalNonNestedRoute &&\n route.routePath !== routePathToCheck &&\n originalRoutePathToCheck.startsWith(`${route.originalRoutePath}/`)\n ) {\n return route\n }\n\n if (\n nonNestedSegments.find(\n (seg) => seg === `${route.originalRoutePath}_`,\n ) ||\n !(\n route._fsRouteType === 'pathless_layout' ||\n route._fsRouteType === 'layout' ||\n route._fsRouteType === '__root'\n )\n ) {\n continue\n }\n\n filteredNodes.push(route)\n }\n }\n\n for (const route of filteredNodes) {\n if (route.routePath === '/') continue\n\n if (\n routePathToCheck.startsWith(`${route.routePath}/`) &&\n route.routePath !== routePathToCheck\n ) {\n return route\n }\n }\n\n const segments = routePathToCheck.split('/')\n segments.pop() // Remove the last segment\n const parentRoutePath = segments.join('/')\n\n return hasParentRoute(routes, node, parentRoutePath, originalRoutePathToCheck)\n}\n\n/**\n * Gets the final variable name for a route\n */\nexport const getResolvedRouteNodeVariableName = (\n routeNode: RouteNode,\n): string => {\n return routeNode.children?.length\n ? `${routeNode.variableName}RouteWithChildren`\n : `${routeNode.variableName}Route`\n}\n\n/**\n * Checks if a given RouteNode is valid for augmenting it with typing based on conditions.\n * Also asserts that the RouteNode is defined.\n *\n * @param routeNode - The RouteNode to check.\n * @returns A boolean indicating whether the RouteNode is defined.\n */\nexport function isRouteNodeValidForAugmentation(\n routeNode?: RouteNode,\n): routeNode is RouteNode {\n if (!routeNode || routeNode.isVirtual) {\n return false\n }\n return true\n}\n\n/**\n * Infers the path for use by TS\n */\nexport const inferPath = (routeNode: RouteNode): string => {\n return routeNode.cleanedPath === '/'\n ? routeNode.cleanedPath\n : (routeNode.cleanedPath?.replace(/\\/$/, '') ?? '')\n}\n\n/**\n * Infers the full path for use by TS\n */\nexport const inferFullPath = (\n routeNode: RouteNode,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): string => {\n // with new nonNestedPaths feature we can be sure any remaining trailing underscores are escaped and should remain\n // TODO with new major we can remove check and only remove leading underscores\n const fullPath = removeGroups(\n (config?.experimental?.nonNestedRoutes\n ? removeLayoutSegments(routeNode.routePath)\n : removeUnderscores(removeLayoutSegments(routeNode.routePath))) ?? '',\n )\n\n return routeNode.cleanedPath === '/' ? fullPath : fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Creates a map from fullPath to routeNode\n */\nexport const createRouteNodesByFullPath = (\n routeNodes: Array<RouteNode>,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => [\n inferFullPath(routeNode, config),\n routeNode,\n ]),\n )\n}\n\n/**\n * Create a map from 'to' to a routeNode\n */\nexport const createRouteNodesByTo = (\n routeNodes: Array<RouteNode>,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): Map<string, RouteNode> => {\n return new Map(\n dedupeBranchesAndIndexRoutes(routeNodes).map((routeNode) => [\n inferTo(routeNode, config),\n routeNode,\n ]),\n )\n}\n\n/**\n * Create a map from 'id' to a routeNode\n */\nexport const createRouteNodesById = (\n routeNodes: Array<RouteNode>,\n): Map<string, RouteNode> => {\n return new Map(\n routeNodes.map((routeNode) => {\n const id = routeNode.routePath ?? ''\n return [id, routeNode]\n }),\n )\n}\n\n/**\n * Infers to path\n */\nexport const inferTo = (\n routeNode: RouteNode,\n config?: Pick<Config, 'experimental' | 'routeToken'>,\n): string => {\n const fullPath = inferFullPath(routeNode, config)\n\n if (fullPath === '/') return fullPath\n\n return fullPath.replace(/\\/$/, '')\n}\n\n/**\n * Dedupes branches and index routes\n */\nexport const dedupeBranchesAndIndexRoutes = (\n routes: Array<RouteNode>,\n): Array<RouteNode> => {\n return routes.filter((route) => {\n if (route.children?.find((child) => child.cleanedPath === '/')) return false\n return true\n })\n}\n\nfunction checkUnique<TElement>(routes: Array<TElement>, key: keyof TElement) {\n // Check no two routes have the same `key`\n // if they do, throw an error with the conflicting filePaths\n const keys = routes.map((d) => d[key])\n const uniqueKeys = new Set(keys)\n if (keys.length !== uniqueKeys.size) {\n const duplicateKeys = keys.filter((d, i) => keys.indexOf(d) !== i)\n const conflictingFiles = routes.filter((d) =>\n duplicateKeys.includes(d[key]),\n )\n return conflictingFiles\n }\n return undefined\n}\n\nexport function checkRouteFullPathUniqueness(\n _routes: Array<RouteNode>,\n config: Config,\n) {\n const routes = _routes.map((d) => {\n const inferredFullPath = inferFullPath(d, config)\n return { ...d, inferredFullPath }\n })\n\n const conflictingFiles = checkUnique(routes, 'inferredFullPath')\n\n if (conflictingFiles !== undefined) {\n const errorMessage = `Conflicting configuration paths were found for the following route${conflictingFiles.length > 1 ? 's' : ''}: ${conflictingFiles\n .map((p) => `\"${p.inferredFullPath}\"`)\n .join(', ')}.\nPlease ensure each Route has a unique full path.\nConflicting files: \\n ${conflictingFiles.map((d) => path.resolve(config.routesDirectory, d.filePath)).join('\\n ')}\\n`\n throw new Error(errorMessage)\n }\n}\n\nexport function buildRouteTreeConfig(\n nodes: Array<RouteNode>,\n disableTypes: boolean,\n depth = 1,\n): Array<string> {\n const children = nodes.map((node) => {\n if (node._fsRouteType === '__root') {\n return\n }\n\n if (node._fsRouteType === 'pathless_layout' && !node.children?.length) {\n return\n }\n\n const route = `${node.variableName}`\n\n if (node.children?.length) {\n const childConfigs = buildRouteTreeConfig(\n node.children,\n disableTypes,\n depth + 1,\n )\n\n const childrenDeclaration = disableTypes\n ? ''\n : `interface ${route}RouteChildren {\n ${node.children\n .map(\n (child) =>\n `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`,\n )\n .join(',')}\n}`\n\n const children = `const ${route}RouteChildren${disableTypes ? '' : `: ${route}RouteChildren`} = {\n ${node.children\n .map(\n (child) =>\n `${child.variableName}Route: ${getResolvedRouteNodeVariableName(child)}`,\n )\n .join(',')}\n}`\n\n const routeWithChildren = `const ${route}RouteWithChildren = ${route}Route._addFileChildren(${route}RouteChildren)`\n\n return [\n childConfigs.join('\\n'),\n childrenDeclaration,\n children,\n routeWithChildren,\n ].join('\\n\\n')\n }\n\n return undefined\n })\n\n return children.filter((x) => x !== undefined)\n}\n\nexport function buildImportString(\n importDeclaration: ImportDeclaration,\n): string {\n const { source, specifiers, importKind } = importDeclaration\n return specifiers.length\n ? `import ${importKind === 'type' ? 'type ' : ''}{ ${specifiers.map((s) => (s.local ? `${s.imported} as ${s.local}` : s.imported)).join(', ')} } from '${source}'`\n : ''\n}\n\nexport function lowerCaseFirstChar(value: string) {\n if (!value[0]) {\n return value\n }\n\n return value[0].toLowerCase() + value.slice(1)\n}\n\nexport function mergeImportDeclarations(\n imports: Array<ImportDeclaration>,\n): Array<ImportDeclaration> {\n const merged: Record<string, ImportDeclaration> = {}\n\n for (const imp of imports) {\n const key = `${imp.source}-${imp.importKind}`\n if (!merged[key]) {\n merged[key] = { ...imp, specifiers: [] }\n }\n for (const specifier of imp.specifiers) {\n // check if the specifier already exists in the merged import\n if (\n !merged[key].specifiers.some(\n (existing) =>\n existing.imported === specifier.imported &&\n existing.local === specifier.local,\n )\n ) {\n merged[key].specifiers.push(specifier)\n }\n }\n }\n\n return Object.values(merged)\n}\n\nexport const findParent = (node: RouteNode | undefined): string => {\n if (!node) {\n return `rootRouteImport`\n }\n if (node.parent) {\n return `${node.parent.variableName}Route`\n }\n return findParent(node.parent)\n}\n\nexport function buildFileRoutesByPathInterface(opts: {\n routeNodes: Array<RouteNode>\n module: string\n interfaceName: string\n config?: Pick<Config, 'experimental' | 'routeToken'>\n}): string {\n return `declare module '${opts.module}' {\n interface ${opts.interfaceName} {\n ${opts.routeNodes\n .map((routeNode) => {\n const filePathId = routeNode.routePath\n const preloaderRoute = `typeof ${routeNode.variableName}RouteImport`\n\n const parent = findParent(routeNode)\n\n return `'${filePathId}': {\n id: '${filePathId}'\n path: '${inferPath(routeNode)}'\n fullPath: '${inferFullPath(routeNode, opts.config)}'\n preLoaderRoute: ${preloaderRoute}\n parentRoute: typeof ${parent}\n }`\n })\n .join('\\n')}\n }\n}`\n}\n\nexport function getImportPath(\n node: RouteNode,\n config: Config,\n generatedRouteTreePath: string,\n): string {\n return replaceBackslash(\n removeExt(\n path.relative(\n path.dirname(generatedRouteTreePath),\n path.resolve(config.routesDirectory, node.filePath),\n ),\n config.addExtensions,\n ),\n )\n}\n\nexport function getImportForRouteNode(\n node: RouteNode,\n config: Config,\n generatedRouteTreePath: string,\n root: string,\n): ImportDeclaration {\n let source = ''\n if (config.importRoutesUsingAbsolutePaths) {\n source = replaceBackslash(\n removeExt(\n path.resolve(root, config.routesDirectory, node.filePath),\n config.addExtensions,\n ),\n )\n } else {\n source = `./${getImportPath(node, config, generatedRouteTreePath)}`\n }\n return {\n source,\n specifiers: [\n {\n imported: 'Route',\n local: `${node.variableName}RouteImport`,\n },\n ],\n } satisfies ImportDeclaration\n}\n\n/**\n * Used to validate if a route is a pathless layout route\n * @param normalizedRoutePath Normalized route path, i.e `/foo/_layout/route.tsx` and `/foo._layout.route.tsx` to `/foo/_layout/route`\n * @param config The `router-generator` configuration object\n * @returns Boolean indicating if the route is a pathless layout route\n */\nexport function isValidNonNestedRoute(\n normalizedRoutePath: string,\n config?: Pick<Config, 'experimental' | 'routeToken' | 'indexToken'>,\n): boolean {\n if (!config?.experimental?.nonNestedRoutes) {\n return false\n }\n\n const segments = normalizedRoutePath.split('/').filter(Boolean)\n\n if (segments.length === 0) {\n return false\n }\n\n const lastRouteSegment = segments[segments.length - 1]!\n\n // If segment === __root, then exit as false\n if (lastRouteSegment === rootPathId) {\n return false\n }\n\n if (\n lastRouteSegment !== config.indexToken &&\n lastRouteSegment !== config.routeToken &&\n lastRouteSegment.endsWith('_')\n ) {\n return true\n }\n\n for (const segment of segments.slice(0, -1).reverse()) {\n if (segment === config.routeToken) {\n return false\n }\n\n if (segment.endsWith('_')) {\n return true\n }\n }\n\n return false\n}\n"],"names":["path","children"],"mappings":";;;;AAOO,SAAS,YACd,KACA,YAAqC,CAAC,CAAC,MAAM,CAAC,GACpC;AACV,SAAO,IACJ,IAAI,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAU,EAC7B,KAAK,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,MAAM;AAC1B,eAAW,YAAY,WAAW;AAChC,YAAM,KAAK,SAAS,CAAC;AACrB,YAAM,KAAK,SAAS,CAAC;AAErB,UAAI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