Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added dashboard pages outside a store (#14859)

Damian Legawiec9728851b963a
diff --git a/.changeset/dashboard-root-routes.md b/.changeset/dashboard-root-routes.md
new file mode 100644
index 0000000000..ccd05cd4c4
--- /dev/null
+++ b/.changeset/dashboard-root-routes.md
@@ -0,0 +1,8 @@
+---
+"@spree/dashboard": minor
+"@spree/dashboard-core": minor
+---
+
+Plugins and host apps can now add pages outside a store, such as onboarding, sign-up and account pages. File routes go in the new `authenticatedRoutes` (signed-in users) or `publicRoutes` (anyone) directories of a plugin's `spree.dashboard` marker; registry routes take `scope: 'authenticated'` or `scope: 'public'` with a full URL path. Both mount at the root, outside the store layout, and a page that takes the path of a built-in page fails with an error naming it.
+
+The signed-in landing page at `/` can be replaced through the new `store_selection` slot, for example with a list of stores and a way to create one, and the login page renders extra content, such as a sign-up link, from the new `login.after` slot.
diff --git a/docs/developer/dashboard/customization/routes.mdx b/docs/developer/dashboard/customization/routes.mdx
index ea802ae15c..a009ec9744 100644
--- a/docs/developer/dashboard/customization/routes.mdx
+++ b/docs/developer/dashboard/customization/routes.mdx
@@ -1,7 +1,7 @@
---
title: Routes
sidebarTitle: Routes
-description: Mount custom pages under your dashboard's `/$storeId/...` path. Supports path params, permission gating, and works alongside the dashboard's built-in routes.
+description: Mount custom pages under your dashboard's `/$storeId/...` path, or outside a store at the root — onboarding, sign-up and account pages. Supports path params, permission gating, and works alongside the dashboard's built-in routes.
---
<Note>
@@ -60,15 +60,15 @@ Two packages can't own the same route path. If a plugin declares a path that ano
```
Dashboard route collision.
-Route "/_authenticated/$storeId/brands/" is declared by more than one package:
- - @acme/brands (…/node_modules/@acme/brands/src/routes/brands.index.tsx)
- - @other/brands (…/node_modules/@other/brands/src/routes/brands.index.tsx)
+Route "/$storeId/brands" is declared by more than one package:
+ - @acme/brands: "/_authenticated/$storeId/brands/" (…/node_modules/@acme/brands/src/routes/brands.index.tsx)
+ - @other/brands: "/_authenticated/$storeId/brands/" (…/node_modules/@other/brands/src/routes/brands.index.tsx)
```
Rename one of the routes, or drop the plugin that shouldn't own it. (Duplicate paths *within* a single package are reported by the TanStack generator instead — that's an authoring bug in one package.)
<Warning>
-The collision check only sees **file routes**. If a runtime-registry route (below) uses the same URL as a compiled file route, there's no build error — the file route silently wins on every navigation, because the registry's catch-all is the lowest-priority match. If a page you registered at runtime never renders, check whether an installed plugin claims the same path.
+The collision check only sees **file routes**. If a store registry route (below) uses the same URL as a compiled file route, there's no build error — the file route silently wins on every navigation, because the registry's catch-all is the lowest-priority match. If a page you registered at runtime never renders, check whether an installed plugin claims the same path.
</Warning>
## Runtime route registry (in-app & dynamic)
@@ -90,6 +90,68 @@ defineDashboardPlugin({
`path` is **relative** to `/$storeId` — the dispatcher prepends the prefix at match time. So `/reports` matches the URL `/store_xyz/reports`. The leading `/` is required.
+## Pages outside a store
+
+Most pages live inside a store, under `/$storeId`. Some don't belong to one: an onboarding flow, a sign-up page, an account page, terms of service. Both mechanisms can mount pages at the root instead, in one of two scopes:
+
+| Scope | Who can open it | Layout |
+|---|---|---|
+| `authenticated` | Signed-in users; everyone else goes to the login page | No store sidebar or top bar |
+| `public` | Anyone, signed in or not | No store sidebar or top bar |
+
+These pages render on a blank canvas. To match the login page's look, wrap them in `AuthShell` from `@spree/dashboard/components/spree/auth-shell`.
+
+**What these pages can use.** There is no current store here, so anything that reads one is unavailable: `useStore()`, store permissions (`usePermissions()`, `<Can>`), the sidebar and top bar, and the store pages' slots. Everything else works — `useAuth()` (the signed-in user on `authenticated` pages, with the stores they can open in `user.stores`), `adminClient` for calls that don't need a store, i18n, and the `@spree/dashboard-ui` components. On `public` pages nobody may be signed in, so only call endpoints that need no session.
+
+**Reserved paths.** The dashboard owns `/`, `/login`, `/setup`, `/forgot-password`, `/reset-password`, `/accept-invitation/$invitationId` and `/$storeId`. A static path such as `/sign-up` takes priority over `/$storeId`, which means no store can be reached at that path. If a future dashboard release adds a page at a path you use, the build (or, for registry routes, the router) fails with an error naming both, instead of one page silently replacing the other. Prefer specific paths (`/sign-up`, `/account`) over generic ones.
+
+**Keep them out of the main bundle.** A sign-up page is opened by people who never see the rest of the dashboard. Load the page component on demand: `lazyRouteComponent(() => import('../pages/sign-up'), 'SignUpPage')` from `@tanstack/react-router` in a file route, or `lazy(() => import('./pages/sign-up'))` from React as a registry route's `component`.
+
+### File routes
+
+Declare a separate directory per scope in your plugin's marker, next to `routes`:
+
+```jsonc
+// package.json
+"spree": {
+ "dashboard": {
+ "plugin": true,
+ "routes": "./src/routes", // → /$storeId/...
+ "authenticatedRoutes": "./src/account-routes", // → /... (signed in)
+ "publicRoutes": "./src/public-routes" // → /... (anyone)
+ }
+}
+```
+
+The committed path literal follows the same rule as store routes — it is the composed path. Signed-in pages sit inside the dashboard's `_authenticated` layout; public pages sit at the root:
+
+```tsx
+// src/account-routes/account.tsx → /account
+export const Route = createFileRoute('/_authenticated/account')({ component: AccountPage })
+
+// src/public-routes/sign-up.tsx → /sign-up
+export const Route = createFileRoute('/sign-up')({ component: SignUpPage })
+```
+
+The [collision check](#route-collisions) compares the URL each route serves, so a plugin's `/sign-up` that clashes with another plugin's — or a signed-in `/account` that clashes with a public `/account` — fails the build with both packages named. Built-in pages such as `/login` and the signed-in landing page at `/` can't be claimed; to change the landing page, register on the [`store_selection` slot](/developer/dashboard/slots-catalog#store_selection) instead.
+
+### Registry routes
+
+Give the entry a `scope`. Its `path` is then the full URL path, not one relative to `/$storeId`:
+
+```tsx
+defineDashboardPlugin({
+ routes: [
+ { key: 'sign-up', scope: 'public', path: '/sign-up', component: SignUpPage },
+ { key: 'account', scope: 'authenticated', path: '/account', component: AccountPage },
+ ],
+})
+```
+
+The component receives `params` and `searchParams`, but no `storeId`. `subject` isn't available: permissions belong to a store.
+
+Unlike store routes, these become real routes when the router is built, so register them before `createDashboardRouter` runs. Your `plugins.ts` and every installed plugin already are — `main.tsx` imports them first. A path already used by a dashboard page or another root registry route throws when the router is built, naming the route's `key`.
+
## Path parameters
TanStack-Router-style `$name` tokens match a single non-empty segment:
@@ -149,7 +211,7 @@ Always pair this with a matching `subject` on the **nav entry** so users without
## Layout
-Custom routes inherit the dashboard's `_authenticated` + `$storeId` layout (auth guard, sidebar, top bar, etc.) — your component renders inside the `<Outlet />`. Use `<ResourceLayout>` to get the same header/main/sidebar grid as core pages:
+Store routes inherit the dashboard's `_authenticated` + `$storeId` layout (auth guard, sidebar, top bar, etc.) — your component renders inside the `<Outlet />`. Use `<ResourceLayout>` to get the same header/main/sidebar grid as core pages:
```tsx
import { PageHeader, ResourceLayout } from '@spree/dashboard'
diff --git a/docs/developer/dashboard/plugins/publishing.mdx b/docs/developer/dashboard/plugins/publishing.mdx
index 6273501fcb..da8d9d429e 100644
--- a/docs/developer/dashboard/plugins/publishing.mdx
+++ b/docs/developer/dashboard/plugins/publishing.mdx
@@ -95,7 +95,7 @@ Declare your package as a dashboard plugin in its own `package.json`:
}
```
-`routes` (optional) points at your TanStack file-routes directory; the host build compiles it into its typed route tree — see the [routes guide](/developer/dashboard/customization/routes).
+`routes` (optional) points at your TanStack file-routes directory; the host build compiles it into its typed route tree — see the [routes guide](/developer/dashboard/customization/routes). `authenticatedRoutes` and `publicRoutes` (optional) do the same for [pages outside a store](/developer/dashboard/customization/routes#pages-outside-a-store).
This marker is what powers **auto-discovery**: when a host calls `spreeDashboardPlugin()` without an explicit `plugins` array (the default), the Vite plugin walks the host's `package.json` deps + devDeps, reads each one's manifest, and picks up anything with `spree.dashboard.plugin: true`. The host doesn't have to know your plugin's name — `pnpm add @your-scope/your-plugin` is the entire installation step.
diff --git a/docs/developer/dashboard/public-api.mdx b/docs/developer/dashboard/public-api.mdx
index 961226b613..15b9a8dcb3 100644
--- a/docs/developer/dashboard/public-api.mdx
+++ b/docs/developer/dashboard/public-api.mdx
@@ -26,6 +26,7 @@ import {
settingsNav,
// route registry
pluginRoutes,
+ getPluginRoutes,
matchPluginRoute,
usePluginRoutes,
// slot registry
diff --git a/docs/developer/dashboard/slots-catalog.mdx b/docs/developer/dashboard/slots-catalog.mdx
index 7a5221895f..7796dd34cf 100644
--- a/docs/developer/dashboard/slots-catalog.mdx
+++ b/docs/developer/dashboard/slots-catalog.mdx
@@ -31,6 +31,8 @@ If you need a new injection point in a built-in page, open a PR adding `<Slot na
| Settings | Payment method | `payment_method.*.<provider>` |
| Settings | Webhook endpoint | `webhook_endpoint.form_sidebar` |
| Onboarding | Getting started | `getting-started.task.<name>` |
+| Sign-in | Login page | `login.after` |
+| Sign-in | Store selection | `store_selection` |
| Sign-in | No store access | `no_store_access` |
| Seller panel | Product, order, payout, profile, team | `seller.product.*`, `seller.order.*`, `seller.payout.*`, `seller.profile.*`, `seller.team.*` |
@@ -276,10 +278,30 @@ The product page is a host form with the form key `seller.product`: fields a wid
| `seller.team.actions` | Team page, in the header's action area — bulk invite, export, an external directory sync | `{ sellerId }` |
| `seller.team.after` | Team page, below the member list — audit log, role explainer, seat usage | `{ sellerId }` |
+## Sign-in slots
+
+### `login.after`
+
+| Where | Login page, below the sign-in options |
+|---|---|
+| Use | Extra content for people who can't sign in yet — a link to a sign-up page, a support contact, terms of service |
+| Context | none |
+
+Nobody is signed in when this renders, so only call endpoints that need no session. Links to a [public page](/developer/dashboard/customization/routes#pages-outside-a-store) fit here.
+
## Replaceable slots
These slots render built-in content when nothing is registered. Registering a component **replaces** that content rather than adding to it.
+### `store_selection`
+
+| Where | The page a signed-in user lands on at `/`, before entering a store. By default it opens their first store, or shows `no_store_access` when they have none |
+|---|---|
+| Use | Replace the whole page — for example, with a list of stores to choose from and a link to an onboarding page that creates one |
+| Context | `{ user, signOut }` — `user` is the signed-in admin, with the stores they can open in `user.stores`; `signOut()` ends the session |
+
+Import the name as `STORE_SELECTION_SLOT` from `@spree/dashboard-core` rather than typing it. Every sign-in, password reset and accepted invitation lands here, so the replacement owns both cases the default handles: a user with stores (link to `/$storeId`, or open one straight away with `<Navigate>`) and a user with none. The page renders on a blank canvas; wrap it in `AuthShell` from `@spree/dashboard/components/spree/auth-shell` to match the login page.
+
### `no_store_access`
| Where | The screen shown to a signed-in admin who has a role on no store |
diff --git a/packages/dashboard-core/src/lib/route-registry.ts b/packages/dashboard-core/src/lib/route-registry.ts
index a0a5fc54ce..5992ed8851 100644
--- a/packages/dashboard-core/src/lib/route-registry.ts
+++ b/packages/dashboard-core/src/lib/route-registry.ts
@@ -3,22 +3,34 @@ import { useSyncExternalStore } from 'react'
import type { SubjectName } from './permissions'
/**
- * Dashboard route contributed by a plugin. Mounted under the dashboard's
- * `/_authenticated/$storeId/_plugins/$` catch-all, which reads this registry
- * at render time and dispatches based on the splat path.
+ * Where a registry route mounts:
+ *
+ * - `store` (default) — inside a store, under `/$storeId`, with the store's
+ * sidebar and top bar.
+ * - `authenticated` — at the root, for signed-in users, outside any store
+ * (account or onboarding pages). Signed-out visitors go to the login page.
+ * - `public` — at the root, with no sign-in required (a sign-up or terms page).
+ */
+export type RouteScope = 'store' | 'authenticated' | 'public'
+
+/**
+ * Dashboard route contributed by a plugin. Store routes mount under the
+ * dashboard's `/_authenticated/$storeId/$` catch-all, which reads this
+ * registry at render time and dispatches based on the splat path.
*
* Path patterns use TanStack-Router-style param tokens (`$brandId`) inside the
* plugin's namespace. The dashboard strips the `/$storeId/` prefix before
* matching, so a plugin pattern of `/brands/$brandId` matches the URL
* `/store_xyz/brands/br_abc123` with `params: { brandId: 'br_abc123' }`.
*/
-export interface RouteEntry {
+export interface StoreRouteEntry {
/**
* Stable identifier — used for register/remove/update and as the React key.
* Mirrors the slug a plugin would use in its `nav.add({ key })` call so the
* sidebar entry and route stay paired.
*/
key: string
+ scope?: 'store'
/**
* Path pattern relative to `/$storeId`. Examples: `/brands`,
* `/brands/$brandId`, `/wishlists/$wishlistId/items`.
@@ -30,7 +42,7 @@ export interface RouteEntry {
* The component to render. Receives:
* - `params`: extracted path params (e.g. matching `/brands/$brandId`
* against `/brands/br_abc` yields `{ brandId: 'br_abc' }`)
- * - `storeId`: the current store — every plugin route is implicitly scoped
+ * - `storeId`: the current store — every store route is implicitly scoped
* under `/$storeId/...`
* - `searchParams`: the URL search-state object from TanStack Router. Use
* this with `<ResourceTable searchParams={searchParams} ... />` so
@@ -49,6 +61,27 @@ export interface RouteEntry {
subject?: SubjectName
}
+/**
+ * Route mounted at the dashboard's root, outside any store. Unlike store
+ * routes these become real router routes when `createDashboardRouter` runs,
+ * so they must be registered before it — `plugins.ts` and installed plugins
+ * always are.
+ */
+export interface RootRouteEntry {
+ key: string
+ scope: 'authenticated' | 'public'
+ /** Full URL path, e.g. `/sign-up` or `/account/$section`. Must start with `/`. */
+ path: string
+ component: ComponentType<{
+ params: Record<string, string>
+ searchParams: Record<string, unknown>
+ }>
+}
+
+export type RouteEntry = StoreRouteEntry | RootRouteEntry
+
+const ROUTE_SCOPES: readonly RouteScope[] = ['store', 'authenticated', 'public']
+
const entries: RouteEntry[] = []
const listeners = new Set<() => void>()
@@ -63,10 +96,6 @@ function subscribe(listener: () => void): () => void {
}
}
-function getSnapshot(): readonly RouteEntry[] {
- return entries
-}
-
interface RouteMutator {
/** Register a route. Throws if `key` is already registered. */
add(entry: RouteEntry): void
@@ -82,6 +111,11 @@ export const pluginRoutes: RouteMutator = {
if (!entry.path.startsWith('/')) {
throw new Error(`Plugin route "${entry.key}" path must start with "/", got "${entry.path}".`)
}
+ if (entry.scope !== undefined && !ROUTE_SCOPES.includes(entry.scope)) {
+ throw new Error(
+ `Plugin route "${entry.key}" scope must be one of ${ROUTE_SCOPES.join(', ')}, got "${entry.scope}".`,
+ )
+ }
entries.push(entry)
notify()
},
@@ -93,17 +127,22 @@ export const pluginRoutes: RouteMutator = {
},
}
+/** Every registered route, read outside React. */
+export function getPluginRoutes(): readonly RouteEntry[] {
+ return entries
+}
+
/**
* Subscribe to plugin route updates. Returns the full list of registered
* routes; the catch-all renderer matches against this on every navigation.
*/
export function usePluginRoutes(): readonly RouteEntry[] {
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
+ return useSyncExternalStore(subscribe, getPluginRoutes, getPluginRoutes)
}
/**
* Match a URL splat (the bit after `/$storeId/`) against the registered
- * routes. Returns the matched entry plus the extracted path params, or
+ * store routes. Returns the matched entry plus the extracted path params, or
* `null` if nothing matched.
*
* Path patterns support TanStack-style `$param` tokens. A pattern segment
@@ -117,12 +156,12 @@ export function usePluginRoutes(): readonly RouteEntry[] {
export function matchPluginRoute(
splat: string,
routes: readonly RouteEntry[],
-): { entry: RouteEntry; params: Record<string, string> } | null {
+): { entry: StoreRouteEntry; params: Record<string, string> } | null {
// Normalize: strip leading slash, drop empty trailing segments.
const urlSegments = splat.replace(/^\/+/, '').split('/').filter(Boolean)
- const bySpecificity = [...routes].sort(
- (a, b) => countDynamicSegments(a.path) - countDynamicSegments(b.path),
- )
+ const bySpecificity = routes
+ .filter(isStoreRoute)
+ .sort((a, b) => countDynamicSegments(a.path) - countDynamicSegments(b.path))
for (const entry of bySpecificity) {
const patternSegments = entry.path.replace(/^\/+/, '').split('/').filter(Boolean)
if (patternSegments.length !== urlSegments.length) continue
@@ -144,6 +183,10 @@ export function matchPluginRoute(
return null
}
+function isStoreRoute(entry: RouteEntry): entry is StoreRouteEntry {
+ return entry.scope === undefined || entry.scope === 'store'
+}
+
function countDynamicSegments(path: string): number {
return path
.replace(/^\/+/, '')
diff --git a/packages/dashboard-core/src/lib/slot-registry.ts b/packages/dashboard-core/src/lib/slot-registry.ts
index 000dcac1b5..03de325db0 100644
--- a/packages/dashboard-core/src/lib/slot-registry.ts
+++ b/packages/dashboard-core/src/lib/slot-registry.ts
@@ -44,6 +44,16 @@ export interface NoStoreAccessSlotContext {
signOut: () => Promise<void>
}
+/**
+ * The page a signed-in user lands on at `/`, before entering a store. By
+ * default it opens their first store, or shows the `no_store_access` screen
+ * when they have none. Registering an entry replaces the whole page — for
+ * example with a list of stores to choose from and a way to create one.
+ */
+export const STORE_SELECTION_SLOT = 'store_selection'
+
+export type StoreSelectionSlotContext = NoStoreAccessSlotContext
+
// ============================================================================
// Registry — module-singleton keyed by slot name
// ============================================================================
diff --git a/packages/dashboard-core/src/plugin.ts b/packages/dashboard-core/src/plugin.ts
index 21c9489898..42a2085207 100644
--- a/packages/dashboard-core/src/plugin.ts
+++ b/packages/dashboard-core/src/plugin.ts
@@ -106,11 +106,11 @@ export interface DashboardPluginConfig {
/** Table mutations keyed by table key (see `defineTable`). */
tables?: Record<string, TableMutations>
/**
- * Custom routes mounted under `/$storeId/`. Each entry's `path` is relative
- * (e.g. `/brands`, `/brands/$brandId`). The dashboard's catch-all route at
- * `/$storeId/*` dispatches based on the splat — your `component` renders
- * exactly like any first-party route, including TanStack Router's
- * `useParams()` for path params.
+ * Custom routes. By default mounted under `/$storeId/`, with a relative
+ * `path` (e.g. `/brands`, `/brands/$brandId`) — the dashboard's catch-all
+ * route at `/$storeId/*` dispatches based on the splat. Set `scope` to
+ * `'authenticated'` or `'public'` to mount a page at the root, outside any
+ * store.
*/
routes?: RouteEntry[]
/**
diff --git a/packages/dashboard-core/src/vite/discover.ts b/packages/dashboard-core/src/vite/discover.ts
index 2070b9eb4e..ccf635951d 100644
--- a/packages/dashboard-core/src/vite/discover.ts
+++ b/packages/dashboard-core/src/vite/discover.ts
@@ -39,6 +39,17 @@ export interface DashboardPluginManifest {
* Compiled into the host's route tree by `@spree/dashboard/vite`.
*/
routesDir?: string
+ /**
+ * Absolute path to the plugin's directory of signed-in pages outside any
+ * store (`"authenticatedRoutes"` in the marker), mounted at the root inside
+ * the dashboard's auth guard.
+ */
+ authenticatedRoutesDir?: string
+ /**
+ * Absolute path to the plugin's directory of public pages
+ * (`"publicRoutes"` in the marker), mounted at the root with no sign-in.
+ */
+ publicRoutesDir?: string
}
/**
@@ -68,10 +79,14 @@ export function discoverDashboardPluginManifests(
manifests.push({ name })
continue
}
- const routes = pkg.spree?.dashboard?.routes
+ const marker = pkg.spree?.dashboard
+ const resolveDir = (dir?: string) =>
+ dir ? path.resolve(path.dirname(manifestPath), dir) : undefined
manifests.push({
name,
- routesDir: routes ? path.resolve(path.dirname(manifestPath), routes) : undefined,
+ routesDir: resolveDir(marker?.routes),
+ authenticatedRoutesDir: resolveDir(marker?.authenticatedRoutes),
+ publicRoutesDir: resolveDir(marker?.publicRoutes),
})
}
return manifests
@@ -156,6 +171,8 @@ interface PluginManifest {
dashboard?: {
plugin?: boolean
routes?: string
+ authenticatedRoutes?: string
+ publicRoutes?: string
}
}
}
diff --git a/packages/dashboard-core/tests/discover.test.ts b/packages/dashboard-core/tests/discover.test.ts
index 4509bbf0f1..13952e6df8 100644
--- a/packages/dashboard-core/tests/discover.test.ts
+++ b/packages/dashboard-core/tests/discover.test.ts
@@ -202,6 +202,26 @@ describe('discoverDashboardPluginManifests', () => {
expect(manifest.routesDir).toBe(path.join(store, 'src/routes'))
})
+
+ it('reports the directories of pages outside a store', () => {
+ const store = installThroughPnpmLink(fixture.root, '@acme/plugin', {
+ main: 'src/index.ts',
+ spree: {
+ dashboard: {
+ plugin: true,
+ authenticatedRoutes: './src/account-routes',
+ publicRoutes: './src/public-routes',
+ },
+ },
+ })
+ fixture.writeHost({ '@acme/plugin': '1.0.0' })
+
+ const [manifest] = discoverDashboardPluginManifests({ root: fixture.root })
+
+ expect(manifest.routesDir).toBeUndefined()
+ expect(manifest.authenticatedRoutesDir).toBe(path.join(store, 'src/account-routes'))
+ expect(manifest.publicRoutesDir).toBe(path.join(store, 'src/public-routes'))
+ })
})
describe('resolveShellRoutesDir', () => {
diff --git a/packages/dashboard-core/tests/route-registry.test.ts b/packages/dashboard-core/tests/route-registry.test.ts
index 04299cd14c..f3e7215822 100644
--- a/packages/dashboard-core/tests/route-registry.test.ts
+++ b/packages/dashboard-core/tests/route-registry.test.ts
@@ -1,5 +1,11 @@
-import { describe, expect, it } from 'vitest'
-import { matchPluginRoute, type RouteEntry } from '../src/lib/route-registry'
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ __resetPluginRoutes,
+ getPluginRoutes,
+ matchPluginRoute,
+ pluginRoutes,
+ type RouteEntry,
+} from '../src/lib/route-registry'
function entry(key: string, path: string): RouteEntry {
return { key, path, component: () => null }
@@ -27,8 +33,32 @@ describe('matchPluginRoute', () => {
expect(matchPluginRoute('brands/br_123', routes)?.entry.key).toBe('brand-detail')
})
+ it('ignores routes mounted outside a store', () => {
+ const routes: RouteEntry[] = [
+ { key: 'sign-up', scope: 'public', path: '/sign-up', component: () => null },
+ { key: 'account', scope: 'authenticated', path: '/account', component: () => null },
+ ]
+ expect(matchPluginRoute('sign-up', routes)).toBeNull()
+ expect(matchPluginRoute('account', routes)).toBeNull()
+ })
+
it('returns null when nothing matches', () => {
expect(matchPluginRoute('unknown', [entry('brands', '/brands')])).toBeNull()
expect(matchPluginRoute('', [entry('brands', '/brands')])).toBeNull()
})
})
+
+describe('pluginRoutes.add', () => {
+ afterEach(() => __resetPluginRoutes())
+
+ it('registers routes of every scope', () => {
+ pluginRoutes.add(entry('brands', '/brands'))
+ pluginRoutes.add({ key: 'sign-up', scope: 'public', path: '/sign-up', component: () => null })
+ expect(getPluginRoutes().map((route) => route.key)).toEqual(['brands', 'sign-up'])
+ })
+
+ it('rejects an unknown scope', () => {
+ const route = { key: 'odd', scope: 'global', path: '/odd', component: () => null }
+ expect(() => pluginRoutes.add(route as unknown as RouteEntry)).toThrow(/scope must be one of/)
+ })
+})
diff --git a/packages/dashboard/src/create-router.test.ts b/packages/dashboard/src/create-router.test.ts
new file mode 100644
index 0000000000..4de63aba61
--- /dev/null
+++ b/packages/dashboard/src/create-router.test.ts
@@ -0,0 +1,122 @@
+import { __resetPluginRoutes, pluginRoutes } from '@spree/dashboard-core'
+import {
+ type AnyRoute,
+ type AnyRouter,
+ createMemoryHistory,
+ createRootRoute,
+ createRoute,
+ RouterProvider,
+} from '@tanstack/react-router'
+import { createElement } from 'react'
+import { renderToString } from 'react-dom/server'
+import { afterEach, describe, expect, it } from 'vitest'
+import { createDashboardRouter } from './create-router'
+
+// The shell's top-level skeleton, built the way the generated tree builds it:
+// a pathless `_authenticated` layout holding the store picker and the store.
+function shellTree() {
+ const root = createRootRoute()
+ const authenticated = createRoute({ getParentRoute: () => root, id: '_authenticated' })
+ ;(authenticated.options as { id: string }).id = '/_authenticated'
+ const login = createRoute({ getParentRoute: () => root, path: '/login' })
+ const storeSelection = createRoute({ getParentRoute: () => authenticated, path: '/' })
+ const store = createRoute({ getParentRoute: () => authenticated, path: '$storeId' })
+ return root.addChildren([login, authenticated.addChildren([storeSelection, store])])
+}
+
+const Page = () => null
+
+function mountedRoutes(router: { routesById: unknown }) {
+ const routes = Object.values(router.routesById as Record<string, AnyRoute>)
+ return new Map(routes.map((route) => [route.fullPath as string, route]))
+}
+
+describe('createDashboardRouter', () => {
+ afterEach(() => __resetPluginRoutes())
+
+ it('mounts public registry routes at the root and signed-in ones inside the auth guard', () => {
+ pluginRoutes.add({ key: 'sign-up', scope: 'public', path: '/sign-up', component: Page })
+ pluginRoutes.add({ key: 'account', scope: 'authenticated', path: '/account', component: Page })
+ pluginRoutes.add({ key: 'brands', path: '/brands', component: Page })
+
+ const routes = mountedRoutes(createDashboardRouter(shellTree()))
+
+ expect(routes.get('/sign-up')?.parentRoute.id).toBe('__root__')
+ expect(routes.get('/account')?.parentRoute.id).toBe('/_authenticated')
+ // Store routes keep going through the `$storeId` catch-all.
+ expect(routes.has('/brands')).toBe(false)
+ })
+
+ it('matches a root registry route ahead of the store param', () => {
+ pluginRoutes.add({ key: 'account', scope: 'authenticated', path: '/account', component: Page })
+
+ const router = createDashboardRouter(shellTree())
+
+ expect(router.getMatchedRoutes('/account')[2]?.fullPath).toBe('/account')
+ expect(router.getMatchedRoutes('/store_1')[2]?.fullPath).toBe('/$storeId')
+ })
+
+ it('leaves the generated tree untouched, so every router built from it is the same', () => {
+ pluginRoutes.add({ key: 'sign-up', scope: 'public', path: '/sign-up', component: Page })
+ pluginRoutes.add({ key: 'account', scope: 'authenticated', path: '/account', component: Page })
+ const tree = shellTree()
+ const authenticated = (tree.children as unknown as AnyRoute[]).find(
+ (r) => (r.options as { id?: string }).id === '/_authenticated',
+ ) as AnyRoute
+ const rootChildren = tree.children
+ const authenticatedChildren = authenticated.children
+
+ const first = createDashboardRouter(tree)
+ const second = createDashboardRouter(tree)
+
+ expect(tree.children).toBe(rootChildren)
+ expect(tree.children).toHaveLength(2)
+ expect(authenticated.children).toBe(authenticatedChildren)
+ expect(authenticated.children).toHaveLength(2)
+ expect(Object.keys(second.routesById)).toEqual(Object.keys(first.routesById))
+ expect(Object.keys(second.routesById)).toEqual(
+ expect.arrayContaining(['/sign-up', '/_authenticated/account']),
+ )
+ })
+
+ it('renders a root registry route through the auth layout, for every router built', async () => {
+ pluginRoutes.add({
+ key: 'welcome',
+ scope: 'authenticated',
+ path: '/welcome/$step',
+ component: ({ params }) => createElement('p', null, `step ${params.step}`),
+ })
+ const tree = shellTree()
+
+ for (let build = 0; build < 2; build++) {
+ const router = createDashboardRouter(tree)
+ router.update({ history: createMemoryHistory({ initialEntries: ['/welcome/2'] }) })
+ await router.load()
+ const html = renderToString(createElement(RouterProvider, { router: router as AnyRouter }))
+ expect(html).toContain('step 2')
+ }
+ })
+
+ it('refuses a root route that takes the path of a dashboard page', () => {
+ pluginRoutes.add({ key: 'my-login', scope: 'public', path: '/login', component: Page })
+ expect(() => createDashboardRouter(shellTree())).toThrow(
+ 'Plugin route "my-login" path "/login" is already used by another dashboard page.',
+ )
+ })
+
+ it('refuses a root route that replaces the store selection page', () => {
+ pluginRoutes.add({ key: 'home', scope: 'authenticated', path: '/', component: Page })
+ expect(() => createDashboardRouter(shellTree())).toThrow(/"home" path "\/"/)
+ })
+
+ it('refuses a root route whose params only differ in name from another page', () => {
+ pluginRoutes.add({ key: 'shop', scope: 'public', path: '/$slug', component: Page })
+ expect(() => createDashboardRouter(shellTree())).toThrow(/"shop" path "\/\$slug"/)
+ })
+
+ it('refuses two root routes on the same path', () => {
+ pluginRoutes.add({ key: 'a', scope: 'public', path: '/account', component: Page })
+ pluginRoutes.add({ key: 'b', scope: 'authenticated', path: '/account/', component: Page })
+ expect(() => createDashboardRouter(shellTree())).toThrow(/"b" path "\/account\/"/)
+ })
+})
diff --git a/packages/dashboard/src/create-router.ts b/packages/dashboard/src/create-router.ts
index 450f699a33..eaba325ce6 100644
--- a/packages/dashboard/src/create-router.ts
+++ b/packages/dashboard/src/create-router.ts
@@ -1,6 +1,8 @@
+import { getPluginRoutes, type RootRouteEntry } from '@spree/dashboard-core'
import { ErrorState } from '@spree/dashboard-ui'
import {
type AnyRoute,
+ createRoute,
createRouter,
type RouterConstructorOptions,
type RouterHistory,
@@ -45,13 +47,10 @@ export function createDashboardRouter<TRouteTree extends AnyRoute>(
// Cast because the shell's root route requires no router context, which
// TypeScript cannot prove through the generic tree parameter. The return
// type stays parameterized by TRouteTree — that's what makes links typed.
- const options = { routeTree, basepath } as RouterConstructorOptions<
- TRouteTree,
- 'never',
- false,
- RouterHistory,
- Record<string, unknown>
- >
+ const options = {
+ routeTree: withRootPluginRoutes(routeTree),
+ basepath,
+ } as RouterConstructorOptions<TRouteTree, 'never', false, RouterHistory, Record<string, unknown>>
return createRouter({
...options,
// Every route inherits this while its chunk or loader resolves. Without it
@@ -71,3 +70,90 @@ export function createDashboardRouter<TRouteTree extends AnyRoute>(
defaultPendingMinMs: 400,
})
}
+
+/** Route options are a union of path and pathless shapes; both fields are optional here. */
+type RouteOptionsLike = { id?: string; path?: string }
+
+/**
+ * Registry routes scoped `public` or `authenticated` live at the root, where
+ * the store's `$storeId` param would otherwise claim every URL — so instead of
+ * a catch-all they become real routes: public ones next to the login page,
+ * authenticated ones inside the auth guard, beside the store selection page.
+ *
+ * The generated tree is shared by every router built from it, so it is never
+ * changed. The router gets views of the root and `_authenticated` routes that
+ * differ only in their children; every other read and write reaches the
+ * generated route.
+ */
+function withRootPluginRoutes<TRouteTree extends AnyRoute>(routeTree: TRouteTree): TRouteTree {
+ const entries = getPluginRoutes().filter(
+ (entry): entry is RootRouteEntry => entry.scope === 'public' || entry.scope === 'authenticated',
+ )
+ if (entries.length === 0) return routeTree
+
+ const rootChildren = routeTree.children as AnyRoute[]
+ const authenticatedLayout = rootChildren.find(
+ (route) => (route.options as RouteOptionsLike).id === '/_authenticated',
+ )
+ if (!authenticatedLayout) {
+ throw new Error("Plugin routes outside a store need the dashboard's `_authenticated` route.")
+ }
+
+ const taken = new Set(routePaths(routeTree, '').map(comparablePath))
+ const added: Record<RootRouteEntry['scope'], AnyRoute[]> = { public: [], authenticated: [] }
+ for (const entry of entries) {
+ if (taken.has(comparablePath(entry.path))) {
+ throw new Error(
+ `Plugin route "${entry.key}" path "${entry.path}" is already used by another dashboard page.`,
+ )
+ }
+ taken.add(comparablePath(entry.path))
+
+ const parent = entry.scope === 'public' ? routeTree : authenticatedLayout
+ const route: AnyRoute = createRoute({
+ getParentRoute: () => parent,
+ path: entry.path,
+ component: function PluginRootRoute() {
+ return createElement(entry.component, {
+ params: route.useParams() as Record<string, string>,
+ searchParams: route.useSearch() as Record<string, unknown>,
+ })
+ },
+ })
+ added[entry.scope].push(route)
+ }
+
+ const authenticatedView = withChildren(authenticatedLayout, [
+ ...(authenticatedLayout.children as AnyRoute[]),
+ ...added.authenticated,
+ ])
+ return withChildren(routeTree, [
+ ...rootChildren.map((route) => (route === authenticatedLayout ? authenticatedView : route)),
+ ...added.public,
+ ])
+}
+
+function withChildren<TRoute extends AnyRoute>(route: TRoute, children: AnyRoute[]): TRoute {
+ return new Proxy(route, {
+ get: (target, property) => (property === 'children' ? children : Reflect.get(target, property)),
+ })
+}
+
+/** Full URL path of every route below `route`, read from the route options. */
+function routePaths(route: AnyRoute, parentPath: string): string[] {
+ return ((route.children as AnyRoute[] | undefined) ?? []).flatMap((child) => {
+ const ownPath = (child.options as RouteOptionsLike).path
+ const fullPath = ownPath ? `${parentPath}/${ownPath}` : parentPath
+ return ownPath ? [fullPath, ...routePaths(child, fullPath)] : routePaths(child, fullPath)
+ })
+}
+
+/** `/a//b/` and `/a/b` reach the same page, as do `/a/$id` and `/a/$slug`. */
+function comparablePath(path: string): string {
+ return (
+ path
+ .replace(/\/{2,}/g, '/')
+ .replace(/\/\$[^/]+/g, '/$')
+ .replace(/\/$/, '') || '/'
+ )
+}
diff --git a/packages/dashboard/src/routes/_authenticated/index.test.tsx b/packages/dashboard/src/routes/_authenticated/index.test.tsx
new file mode 100644
index 0000000000..dcd1d5d5bc
--- /dev/null
+++ b/packages/dashboard/src/routes/_authenticated/index.test.tsx
@@ -0,0 +1,56 @@
+import {
+ __resetSlotRegistry,
+ registerSlot,
+ STORE_SELECTION_SLOT,
+ type StoreSelectionSlotContext,
+} from '@spree/dashboard-core'
+import type { ComponentType } from 'react'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const auth = vi.hoisted(() => ({
+ user: null as { email: string; stores: Array<{ id: string; name: string }> } | null,
+ logout: async () => {},
+}))
+
+vi.mock('@spree/dashboard-core', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@spree/dashboard-core')>()),
+ useAuth: () => auth,
+}))
+vi.mock('@tanstack/react-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@tanstack/react-router')>()),
+ Navigate: ({ params }: { params: { storeId: string } }) => `navigate:${params.storeId}`,
+}))
+vi.mock('../../components/spree/auth-shell', () => ({
+ AuthShell: ({ children }: { children: React.ReactNode }) => children,
+}))
+
+const { Route } = await import('./index')
+const StoreSelection = Route.options.component as ComponentType
+
+describe('signed-in landing page', () => {
+ afterEach(() => __resetSlotRegistry())
+
+ it('opens the first store by default', () => {
+ auth.user = { email: '[email protected]', stores: [{ id: 'store_1', name: 'One' }] }
+ expect(renderToStaticMarkup(<StoreSelection />)).toBe('navigate:store_1')
+ })
+
+ it('explains a user with no store has no access by default', () => {
+ auth.user = { email: '[email protected]', stores: [] }
+ expect(renderToStaticMarkup(<StoreSelection />)).toContain('[email protected]')
+ })
+
+ it('hands the whole page to a store_selection replacement, with or without stores', () => {
+ registerSlot<StoreSelectionSlotContext>(STORE_SELECTION_SLOT, {
+ id: 'store-list',
+ component: ({ user }) => <p>{user.stores.map((store) => store.name).join(',') || 'none'}</p>,
+ })
+
+ auth.user = { email: '[email protected]', stores: [{ id: 'store_1', name: 'One' }] }
+ expect(renderToStaticMarkup(<StoreSelection />)).toBe('<p>One</p>')
+
+ auth.user = { email: '[email protected]', stores: [] }
+ expect(renderToStaticMarkup(<StoreSelection />)).toBe('<p>none</p>')
+ })
+})
diff --git a/packages/dashboard/src/routes/_authenticated/index.tsx b/packages/dashboard/src/routes/_authenticated/index.tsx
index ad69a45004..ed246c5f55 100644
--- a/packages/dashboard/src/routes/_authenticated/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/index.tsx
@@ -1,24 +1,40 @@
-import { useAuth } from '@spree/dashboard-core'
+import {
+ Slot,
+ STORE_SELECTION_SLOT,
+ type StoreSelectionSlotContext,
+ useAuth,
+} from '@spree/dashboard-core'
import { createFileRoute, Navigate } from '@tanstack/react-router'
import { AuthShell } from '../../components/spree/auth-shell'
import { NoStoreAccess } from '../../components/spree/no-store-access'
export const Route = createFileRoute('/_authenticated/')({
- component: IndexRedirect,
+ component: StoreSelection,
})
-function IndexRedirect() {
+function StoreSelection() {
const { user, logout } = useAuth()
if (!user) return null
- const firstStoreId = user.stores[0]?.id
+ const context = { user, signOut: logout }
+ return (
+ <Slot<StoreSelectionSlotContext>
+ name={STORE_SELECTION_SLOT}
+ context={context}
+ fallback={<FirstStoreRedirect {...context} />}
+ />
+ )
+}
+
+function FirstStoreRedirect(context: StoreSelectionSlotContext) {
+ const firstStoreId = context.user.stores[0]?.id
if (firstStoreId) {
return <Navigate to="/$storeId" params={{ storeId: firstStoreId }} replace />
}
return (
<AuthShell>
- <NoStoreAccess user={user} signOut={logout} />
+ <NoStoreAccess {...context} />
</AuthShell>
)
}
diff --git a/packages/dashboard/src/routes/login.tsx b/packages/dashboard/src/routes/login.tsx
index 16eec9e625..969cd1d346 100644
--- a/packages/dashboard/src/routes/login.tsx
+++ b/packages/dashboard/src/routes/login.tsx
@@ -1,7 +1,7 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { AuthProvider } from '@spree/admin-sdk'
import { SpreeError } from '@spree/admin-sdk'
-import { adminClient, useAuth } from '@spree/dashboard-core'
+import { adminClient, Slot, useAuth } from '@spree/dashboard-core'
import { Button, Input, Label, Skeleton } from '@spree/dashboard-ui'
import { useQuery } from '@tanstack/react-query'
import { createFileRoute, Link, Navigate } from '@tanstack/react-router'
@@ -50,6 +50,8 @@ function LoginPage() {
isLoading={isLoadingProviders}
failed={providersFailed}
/>
+
+ <Slot name="login.after" />
</AuthShell>
)
}
diff --git a/packages/dashboard/src/vite/index.ts b/packages/dashboard/src/vite/index.ts
index 5b1393441f..684af0530f 100644
--- a/packages/dashboard/src/vite/index.ts
+++ b/packages/dashboard/src/vite/index.ts
@@ -56,9 +56,13 @@ export function spreeDashboardPlugin(options: SpreeDashboardPluginOptions = {}):
* The TanStack Router generator, configured with a virtual route config that
* mirrors the shell's top-level layout skeleton and physically mounts:
*
- * - the shell's `_authenticated/$storeId` pages, and
- * - each plugin's declared routes directory (the `spree.dashboard.routes`
- * marker), under the same authenticated store scope.
+ * - the shell's `_authenticated/$storeId` pages,
+ * - each plugin's store pages (the `spree.dashboard.routes` marker), under
+ * the same authenticated store scope,
+ * - each plugin's signed-in pages outside a store
+ * (`spree.dashboard.authenticatedRoutes`), inside the `_authenticated`
+ * layout, and
+ * - each plugin's public pages (`spree.dashboard.publicRoutes`), at the root.
*
* The skeleton names the shell's top-level route files explicitly; when the
* shell grows a new top-level route it must be added here. The shell's own
@@ -72,24 +76,32 @@ function dashboardRouterPlugin(hostRoot: string, options: SpreeDashboardPluginOp
{ root: hostRoot, onWarn: (msg) => console.warn(`[@spree/dashboard/vite] ${msg}`) },
options.plugins,
)
- const routedPlugins = manifests.filter((m): m is typeof m & { routesDir: string } =>
- Boolean(m.routesDir),
- )
+ const routeDirs = (key: 'routesDir' | 'authenticatedRoutesDir' | 'publicRoutesDir') =>
+ manifests.flatMap((m): RouteSource[] => {
+ const routesDir = m[key]
+ return routesDir ? [{ label: m.name, routesDir }] : []
+ })
+ const storeSources = routeDirs('routesDir')
+ const authenticatedSources = routeDirs('authenticatedRoutesDir')
+ const publicSources = routeDirs('publicRoutesDir')
// Pre-flight: fail on route-path collisions with an error naming the
// offending packages (the shell counts as `@spree/dashboard`), before the
// generator's file-path-only error would fire.
const sources: RouteSource[] = [
{ label: '@spree/dashboard', routesDir: shellRoutesDir },
- ...routedPlugins.map((m) => ({ label: m.name, routesDir: m.routesDir })),
+ ...storeSources,
+ ...authenticatedSources,
+ ...publicSources,
]
assertNoRouteCollisions(sources)
// POSIX-normalize: the generator expects forward slashes; path.relative
// emits backslashes on Windows.
- const pluginMounts = routedPlugins.map((m) =>
- physical('', path.relative(shellRoutesDir, m.routesDir).split(path.sep).join('/')),
- )
+ const mount = (list: RouteSource[]) =>
+ list.map((source) =>
+ physical('', path.relative(shellRoutesDir, source.routesDir).split(path.sep).join('/')),
+ )
const virtualRouteConfig = rootRoute('__root.tsx', [
route('/login', 'login.tsx'),
@@ -97,11 +109,13 @@ function dashboardRouterPlugin(hostRoot: string, options: SpreeDashboardPluginOp
route('/forgot-password', 'forgot-password.tsx'),
route('/reset-password', 'reset-password.tsx'),
route('/accept-invitation/$invitationId', 'accept-invitation.$invitationId.tsx'),
+ ...mount(publicSources),
layout('_authenticated.tsx', [
index('_authenticated/index.tsx'),
+ ...mount(authenticatedSources),
route('/$storeId', '_authenticated/$storeId.tsx', [
physical('', '_authenticated/$storeId'),
- ...pluginMounts,
+ ...mount(storeSources),
]),
]),
])
diff --git a/packages/dashboard/src/vite/route-collisions.test.ts b/packages/dashboard/src/vite/route-collisions.test.ts
index fb150521b9..92548557cf 100644
--- a/packages/dashboard/src/vite/route-collisions.test.ts
+++ b/packages/dashboard/src/vite/route-collisions.test.ts
@@ -88,4 +88,51 @@ describe('assertNoRouteCollisions', () => {
assertNoRouteCollisions([{ label: '@acme/nested', routesDir: dir }, other]),
).toThrow(/@acme\/nested/)
})
+
+ it('catches a root page claiming a built-in shell page', () => {
+ const sources = [
+ makeSource('@spree/dashboard', { 'login.tsx': '/login' }),
+ makeSource('@acme/onboarding', { 'login.tsx': '/login' }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/Route "\/login"/)
+ })
+
+ it('compares the URL a route serves, ignoring pathless layouts', () => {
+ const sources = [
+ makeSource('@acme/account', { 'account.tsx': '/_authenticated/account' }),
+ makeSource('@other/account', { 'account.tsx': '/account' }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/Route "\/account"/)
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/"\/_authenticated\/account"/)
+ })
+
+ it('treats an index route and a leaf route on the same path as one URL', () => {
+ const sources = [
+ makeSource('@acme/account', { 'account.index.tsx': '/account/' }),
+ makeSource('@other/account', { 'account.tsx': '/_authenticated/account' }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/Route "\/account"/)
+ })
+
+ it('catches a signed-in root index claiming the store selection page', () => {
+ const sources = [
+ makeSource('@spree/dashboard', {
+ '_authenticated.tsx': '/_authenticated',
+ 'index.tsx': '/_authenticated/',
+ }),
+ makeSource('@acme/home', { 'index.tsx': '/_authenticated/' }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/@acme\/home/)
+ })
+
+ it('does not treat a pathless layout as a page', () => {
+ const sources = [
+ makeSource('@spree/dashboard', { 'index.tsx': '/_authenticated/' }),
+ makeSource('@acme/wizard', {
+ 'wizard.tsx': '/_authenticated/_wizard',
+ 'step.tsx': '/_authenticated/_wizard/step',
+ }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).not.toThrow()
+ })
})
diff --git a/packages/dashboard/src/vite/route-collisions.ts b/packages/dashboard/src/vite/route-collisions.ts
index 9b05cf14bf..c6fa79464f 100644
--- a/packages/dashboard/src/vite/route-collisions.ts
+++ b/packages/dashboard/src/vite/route-collisions.ts
@@ -14,6 +14,8 @@ export interface RouteSource {
interface DeclaredRoute {
/** The composed path from the file's `createFileRoute('…')` literal. */
routePath: string
+ /** The URL the route serves — `routePath` without pathless layout segments. */
+ urlPath: string
file: string
source: string
}
@@ -31,6 +33,10 @@ const ROUTE_FILE_EXT = new Set(['.tsx', '.ts', '.jsx', '.js'])
* generator's file-path-only error, which plugin authors must map back to
* packages by hand.
*
+ * Routes are compared by the URL they serve, so a public `/account` and a
+ * signed-in `/_authenticated/account` collide even though their literals
+ * differ.
+ *
* Only flags cross-source collisions (two different packages claiming the
* same path). Duplicates *within* one source are the generator's to report —
* they're an authoring bug in a single package, and the file-level message is
@@ -44,13 +50,15 @@ export function assertNoRouteCollisions(sources: RouteSource[]): void {
for (const source of sources) {
const seenInSource = new Set<string>()
for (const { routePath, file } of readDeclaredRoutes(source.routesDir)) {
+ const urlPath = toUrlPath(routePath)
+ if (urlPath === null) continue
// Collapse within-source duplicates to a single entry so we only report
// cross-source conflicts here.
- if (seenInSource.has(routePath)) continue
- seenInSource.add(routePath)
- const list = byPath.get(routePath) ?? []
- list.push({ routePath, file, source: source.label })
- byPath.set(routePath, list)
+ if (seenInSource.has(urlPath)) continue
+ seenInSource.add(urlPath)
+ const list = byPath.get(urlPath) ?? []
+ list.push({ routePath, urlPath, file, source: source.label })
+ byPath.set(urlPath, list)
}
}
@@ -59,9 +67,8 @@ export function assertNoRouteCollisions(sources: RouteSource[]): void {
const details = conflicts
.map((list) => {
- const path = list[0].routePath
- const sources = list.map((r) => ` - ${r.source} (${r.file})`).join('\n')
- return `Route "${path}" is declared by more than one package:\n${sources}`
+ const sources = list.map((r) => ` - ${r.source}: "${r.routePath}" (${r.file})`).join('\n')
+ return `Route "${list[0].urlPath}" is declared by more than one package:\n${sources}`
})
.join('\n\n')
@@ -72,6 +79,19 @@ export function assertNoRouteCollisions(sources: RouteSource[]): void {
)
}
+/**
+ * Drop pathless layout segments (`_authenticated`), which group routes
+ * without adding to the URL, and the trailing slash that marks an index
+ * route: `/account/` and `/account` serve the same URL. A pathless layout
+ * itself serves no URL, so it returns `null`.
+ */
+function toUrlPath(routePath: string): string | null {
+ const segments = routePath.split('/')
+ if (segments[segments.length - 1].startsWith('_')) return null
+ const urlPath = segments.filter((segment) => !segment.startsWith('_')).join('/')
+ return urlPath.replace(/\/$/, '') || '/'
+}
+
/** Extract the `createFileRoute` literal from every route file under `dir`. */
function readDeclaredRoutes(dir: string): Array<{ routePath: string; file: string }> {
if (!dirExists(dir)) return []