Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/virtual-route-external-physical.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/router-generator': minor
'@tanstack/router-plugin': minor
---

feat: external directories in `physical()` virtual route mounts
4 changes: 4 additions & 0 deletions packages/router-generator/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,10 @@ export class Generator {
)
}

public getPhysicalDirectories(): Array<string> {
return [...this.physicalDirectories]
}

public async run(event?: GeneratorEvent): Promise<void> {
if (
event &&
Expand Down
33 changes: 33 additions & 0 deletions packages/router-generator/tests/generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,39 @@ describe('generator works', async () => {
})
})

it('physical() accepts a path outside routesDirectory', async () => {
const folderName = 'virtual-physical-external-abs'
const dir = makeFolderDir(folderName)
const externalDir = path.join(dir, 'external-target')
const config = await setupConfig(folderName, {
virtualRouteConfig: rootRoute('__root.tsx', [
index('index.tsx'),
physical('/external', externalDir),
]),
})

const { routeNodes, physicalDirectories } = await virtualGetRouteNodes(
config,
dir,
{
indexTokenSegmentRegex: /^(?:index)$/,
routeTokenSegmentRegex: /^(?:route)$/,
},
)

expect(physicalDirectories).toContain(externalDir)
expect(routeNodes.map((n) => n.routePath).sort()).toEqual([
'/',
'/external/bar',
'/external/foo',
])

const externalFoo = routeNodes.find((n) => n.routePath === '/external/foo')!
expect(path.resolve(config.routesDirectory, externalFoo.filePath)).toBe(
path.join(externalDir, 'foo.tsx'),
)
})

it.each(folderNames)(
'should create directory for routeTree if it does not exist',
async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/external/bar')({
component: () => 'bar',
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/external/foo')({
component: () => 'foo',
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/* eslint-disable */

// @ts-nocheck

// noinspection JSUnusedGlobalSymbols

// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.

import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'

const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)

export interface FileRoutesByFullPath {
'/': typeof IndexRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/'
fileRoutesByTo: FileRoutesByTo
to: '/'
id: '__root__' | '/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
}

declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
}
}

const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createRootRoute, Outlet } from '@tanstack/react-router'

export const Route = createRootRoute({
component: () => <Outlet />,
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/')({ component: () => 'home' })
67 changes: 60 additions & 7 deletions packages/router-plugin/src/core/router-generator-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isAbsolute, join, normalize } from 'node:path'
import { isAbsolute, join, normalize, relative } from 'node:path'
import { Generator, resolveConfigPath } from '@tanstack/router-generator'
import { getConfig } from './config'

Expand All @@ -9,6 +9,21 @@ import type { Config } from './config'

const PLUGIN_NAME = 'unplugin:router-generator'

// Physical mounts that point outside `routesDirectory` — their files aren't
// covered by the bundler's own watcher.
function isInside(parent: string, child: string): boolean {
const rel = relative(parent, child)
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
}
function getExternalPhysicalDirs(
generator: Generator,
routesDirectoryPath: string,
): Array<string> {
return generator
.getPhysicalDirectories()
.filter((dir) => !isInside(routesDirectoryPath, dir))
}

export const unpluginRouterGeneratorFactory: UnpluginFactory<
Partial<Config | (() => Config)> | undefined
> = (options = {}) => {
Expand Down Expand Up @@ -78,11 +93,30 @@ export const unpluginRouterGeneratorFactory: UnpluginFactory<
initConfigAndGenerator({ root: config.root })
await generate()
},
configureServer(server) {
const external = getExternalPhysicalDirs(
generator,
getRoutesDirectoryPath(),
)
if (external.length === 0) return
for (const dir of external) {
server.watcher.add(dir)
}
const onEvent =
(event: 'create' | 'update' | 'delete') => (file: string) => {
if (!external.some((dir) => isInside(dir, file))) return
void generate({ file, event })
}
server.watcher.on('add', onEvent('create'))
server.watcher.on('change', onEvent('update'))
server.watcher.on('unlink', onEvent('delete'))
},
},
rspack(compiler) {
initConfigAndGenerator()

let handle: FSWatcher | null = null
let externalHandle: FSWatcher | null = null

compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, () => generate())

Expand All @@ -98,19 +132,29 @@ export const unpluginRouterGeneratorFactory: UnpluginFactory<
.watch(routesDirectoryPath, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))

// External physical() mounts are outside rspack's file graph.
const external = getExternalPhysicalDirs(generator, routesDirectoryPath)
if (external.length > 0) {
externalHandle = chokidar
.watch(external, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))
.on('change', (file) => generate({ file, event: 'update' }))
.on('unlink', (file) => generate({ file, event: 'delete' }))
}

await generate()
})

compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
Comment on lines 148 to 151
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

async callback in synchronous tap hook won't await cleanup.

The watchClose hook uses .tap() which is synchronous and won't wait for the async callback's promises. The async keyword here is misleading—handle.close() returns a Promise that won't be awaited.

This could cause watchers to not be fully closed during rapid dev server restarts.

Proposed fix: use fire-and-forget or void the promises explicitly
       compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
-        if (handle) await handle.close()
-        if (externalHandle) await externalHandle.close()
+        if (handle) void handle.close()
+        if (externalHandle) void externalHandle.close()
       })

Or alternatively, if cleanup needs to be awaited, investigate if rspack supports an async shutdown hook.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) void handle.close()
if (externalHandle) void externalHandle.close()
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/router-plugin/src/core/router-generator-plugin.ts` around lines 148
- 151, The callback passed to compiler.hooks.watchClose.tap (where PLUGIN_NAME
is used) is currently declared async so handle.close() and
externalHandle.close() return promises that won't be awaited by the synchronous
tap; change the callback to a synchronous function and either fire-and-forget
the promises or explicitly void them and handle errors: inside the
compiler.hooks.watchClose.tap(PLUGIN_NAME, ...) callback call void
handle?.close()?.catch(err => /* log or ignore */) and void
externalHandle?.close()?.catch(err => /* log or ignore */) (or otherwise call
handle.close() and externalHandle.close() and attach .catch handlers) so cleanup
is not misrepresented as awaited.

},
webpack(compiler) {
initConfigAndGenerator()

let handle: FSWatcher | null = null
let externalHandle: FSWatcher | null = null

compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, () => generate())

Expand All @@ -126,13 +170,22 @@ export const unpluginRouterGeneratorFactory: UnpluginFactory<
.watch(routesDirectoryPath, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))

// External physical() mounts are outside webpack's file graph.
const external = getExternalPhysicalDirs(generator, routesDirectoryPath)
if (external.length > 0) {
externalHandle = chokidar
.watch(external, { ignoreInitial: true })
.on('add', (file) => generate({ file, event: 'create' }))
.on('change', (file) => generate({ file, event: 'update' }))
.on('unlink', (file) => generate({ file, event: 'delete' }))
}

await generate()
})

compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
Comment on lines 186 to 189
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Same async/tap mismatch as rspack.

Identical issue: the synchronous tap hook won't await the async callback's promises.

Proposed fix
       compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
-        if (handle) await handle.close()
-        if (externalHandle) await externalHandle.close()
+        if (handle) void handle.close()
+        if (externalHandle) void externalHandle.close()
       })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) {
await handle.close()
}
if (handle) await handle.close()
if (externalHandle) await externalHandle.close()
})
compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => {
if (handle) void handle.close()
if (externalHandle) void externalHandle.close()
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/router-plugin/src/core/router-generator-plugin.ts` around lines 186
- 189, The watchClose hook is registered with compiler.hooks.watchClose.tap
using an async callback (referenced symbols: compiler.hooks.watchClose.tap,
PLUGIN_NAME, handle, externalHandle), which means the hook won't wait for the
async work; change the registration to use tapPromise so the returned Promise is
awaited: replace compiler.hooks.watchClose.tap(PLUGIN_NAME, async () => { if
(handle) await handle.close(); if (externalHandle) await externalHandle.close();
}) with compiler.hooks.watchClose.tapPromise(PLUGIN_NAME, async () => { ... })
so handle.close() and externalHandle.close() are properly awaited.


compiler.hooks.done.tap(PLUGIN_NAME, () => {
Expand Down
121 changes: 121 additions & 0 deletions packages/router-plugin/tests/router-generator-plugin-watcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
import { afterEach, beforeEach, describe, it } from 'vitest'
import { createServer } from 'vite'
import type { ViteDevServer } from 'vite'

import { physical, rootRoute } from '@tanstack/virtual-file-routes'
import { tanstackRouterGenerator } from '../src/vite'
Comment on lines +6 to +9
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix import ordering to satisfy import/order.

Line 6 currently violates the configured import order (vite type import must come after the local import), which can fail lint/CI.

Proposed diff
 import { afterEach, beforeEach, describe, it } from 'vitest'
 import { createServer } from 'vite'
-import type { ViteDevServer } from 'vite'
 
 import { physical, rootRoute } from '@tanstack/virtual-file-routes'
 import { tanstackRouterGenerator } from '../src/vite'
+import type { ViteDevServer } from 'vite'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import type { ViteDevServer } from 'vite'
import { physical, rootRoute } from '@tanstack/virtual-file-routes'
import { tanstackRouterGenerator } from '../src/vite'
import { afterEach, beforeEach, describe, it } from 'vitest'
import { createServer } from 'vite'
import { physical, rootRoute } from '@tanstack/virtual-file-routes'
import { tanstackRouterGenerator } from '../src/vite'
import type { ViteDevServer } from 'vite'
🧰 Tools
🪛 ESLint

[error] 6-6: vite type import should occur after import of ../src/vite

(import/order)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/router-plugin/tests/router-generator-plugin-watcher.test.ts` around
lines 6 - 9, Reorder the imports so they satisfy the import/order rule: move the
type import "import type { ViteDevServer } from 'vite'" to come after the
local/project imports (the imports of physical, rootRoute from
'@tanstack/virtual-file-routes' and tanstackRouterGenerator from '../src/vite').
Locate the symbols ViteDevServer, physical, rootRoute, and
tanstackRouterGenerator and adjust the import block ordering so external/local
groups follow the project's ESLint import/order configuration.


const ROOT_ROUTE = `import { createRootRoute, Outlet } from '@tanstack/react-router'
export const Route = createRootRoute({ component: () => null })
`

const makeRouteFile = (routePath: string) =>
`import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('${routePath}')({ component: () => null })
`

async function waitUntil(
condition: () => boolean | Promise<boolean>,
{ timeoutMs = 10_000, intervalMs = 50 } = {},
) {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
if (await condition()) return
await new Promise((r) => setTimeout(r, intervalMs))
}
throw new Error(`Timed out after ${timeoutMs}ms`)
}

async function routeTreeIncludes(generatedRouteTree: string, match: string) {
try {
const text = await readFile(generatedRouteTree, 'utf-8')
return text.includes(match)
} catch {
return false
}
}

describe('router-generator-plugin vite watcher', () => {
let fixtureDir = ''
let externalDir = ''
let routesDir = ''
let generatedRouteTree = ''
let server: ViteDevServer | undefined

beforeEach(async () => {
// Use a directory within the package to avoid cross-device rename errors:
// the generator writes temp files to .tanstack/tmp/ then does an atomic
// rename(), which fails with EXDEV when tmpdir() is on another device.
fixtureDir = await mkdtemp(
path.join(path.dirname(fileURLToPath(import.meta.url)), 'tmp-watcher-'),
)
routesDir = path.join(fixtureDir, 'routes')
externalDir = path.join(fixtureDir, 'external')
generatedRouteTree = path.join(fixtureDir, 'routeTree.gen.ts')

await mkdir(routesDir, { recursive: true })
await mkdir(externalDir, { recursive: true })
await writeFile(path.join(routesDir, '__root.tsx'), ROOT_ROUTE)
await writeFile(
path.join(externalDir, 'alpha.tsx'),
makeRouteFile('/ext/alpha'),
)
})

afterEach(async () => {
if (server) {
await server.close()
server = undefined
}
await rm(fixtureDir, { recursive: true, force: true })
})

it(
'regenerates routeTree on add/remove in an external physical mount',
{ timeout: 30_000 },
async () => {
Comment on lines +76 to +79
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Test timeout is lower than worst-case polling duration.

This test can run longer than 20s (waitUntil is called 3 times with default 10s each, plus settle delays), so CI may timeout before helper-level failures surface.

Proposed diff
   it(
     'regenerates routeTree on add/remove in an external physical mount',
-    { timeout: 20_000 },
+    { timeout: 35_000 },
     async () => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it(
'regenerates routeTree on add/remove in an external physical mount',
{ timeout: 20_000 },
async () => {
it(
'regenerates routeTree on add/remove in an external physical mount',
{ timeout: 35_000 },
async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/router-plugin/tests/router-generator-plugin-watcher.test.ts` around
lines 71 - 74, The test 'regenerates routeTree on add/remove in an external
physical mount' has a 20_000 ms timeout that is smaller than the worst-case
duration because waitUntil is invoked multiple times with 10s defaults plus
settle delays; increase the test timeout in the it(...) call to a safe upper
bound (for example 60_000 ms) so CI won't prematurely fail, and keep the change
localized to the test declaration in router-generator-plugin-watcher.test.ts
where the test name and timeout object are defined.

server = await createServer({
root: fixtureDir,
configFile: false,
logLevel: 'silent',
appType: 'custom',
server: { middlewareMode: true, watch: {} },
plugins: [
tanstackRouterGenerator({
routesDirectory: routesDir,
generatedRouteTree,
virtualRouteConfig: rootRoute('__root.tsx', [
physical('/ext', externalDir),
]),
disableLogging: true,
}),
],
})

await waitUntil(() =>
routeTreeIncludes(generatedRouteTree, "'/ext/alpha'"),
)

// Short settle after each fs mutation — the plugin debounces and the
// generator may run multiple passes for a single chokidar burst.
const settle = () => new Promise((r) => setTimeout(r, 500))

const betaPath = path.join(externalDir, 'beta.tsx')
await writeFile(betaPath, makeRouteFile('/ext/beta'))
await settle()
await waitUntil(() =>
routeTreeIncludes(generatedRouteTree, "'/ext/beta'"),
)

await rm(betaPath)
await settle()
await waitUntil(
async () =>
!(await routeTreeIncludes(generatedRouteTree, "'/ext/beta'")),
)
},
)
})
Loading