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.

Add route-collision pre-flight; fix TanStack dep classification

Damian Legawiec6484f695e57a
diff --git a/packages/dashboard/package.json b/packages/dashboard/package.json
index e8488926c9..33e70b5415 100644
--- a/packages/dashboard/package.json
+++ b/packages/dashboard/package.json
@@ -8,6 +8,7 @@
".": "./src/index.ts",
"./styles.css": "./src/styles.css",
"./vite": "./src/vite/index.ts",
+ "./vite/route-collisions": "./src/vite/route-collisions.ts",
"./components/spree/payment-method-editors/types": "./src/components/spree/payment-method-editors/types.ts"
},
"files": [
@@ -40,8 +41,8 @@
"@spree/dashboard-ui": "workspace:^",
"@tanstack/react-hotkeys": "^0.10.0",
"@tanstack/react-query": "^5.100.9",
- "@tanstack/react-router": "^1.169.2",
"@tanstack/react-table": "^8.21.3",
+ "@tanstack/router-plugin": "^1.167.35",
"@tanstack/virtual-file-routes": "^1.162.0",
"@tiptap/extension-link": "^3.22.5",
"@tiptap/extension-placeholder": "^3.22.5",
@@ -74,7 +75,6 @@
"devDependencies": {
"@playwright/test": "^1.59.1",
"@spree/dashboard-plugin-example": "workspace:^",
- "@tanstack/router-plugin": "^1.167.35",
"@types/node": "^25.6.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
@@ -89,5 +89,8 @@
"overrides": {
"vite": "^8.0.16"
}
+ },
+ "peerDependencies": {
+ "@tanstack/react-router": "^1.169.2"
}
}
diff --git a/packages/dashboard/src/vite/index.ts b/packages/dashboard/src/vite/index.ts
index 5114242511..694f2c0415 100644
--- a/packages/dashboard/src/vite/index.ts
+++ b/packages/dashboard/src/vite/index.ts
@@ -15,6 +15,10 @@
*/
import { createRequire } from 'node:module'
import path from 'node:path'
+// Self-referencing package import (not a relative path): Node loads this
+// module raw when a host's vite.config.ts imports `@spree/dashboard/vite`,
+// and TS type-stripping can't resolve extensionless relative specifiers.
+import { assertNoRouteCollisions, type RouteSource } from '@spree/dashboard/vite/route-collisions'
import {
type SpreeDashboardPluginOptions as CoreOptions,
spreeDashboardPlugin as spreeDashboardCorePlugin,
@@ -71,9 +75,22 @@ function dashboardRouterPlugin(hostRoot: string, options: SpreeDashboardPluginOp
{ root: hostRoot, onWarn: (msg) => console.warn(`[@spree/dashboard/vite] ${msg}`) },
options.plugins,
)
- const pluginMounts = manifests
- .filter((m) => m.routesDir)
- .map((m) => physical('', path.relative(shellRoutesDir, m.routesDir as string)))
+ const routedPlugins = manifests.filter((m): m is typeof m & { routesDir: string } =>
+ Boolean(m.routesDir),
+ )
+
+ // 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 })),
+ ]
+ assertNoRouteCollisions(sources)
+
+ const pluginMounts = routedPlugins.map((m) =>
+ physical('', path.relative(shellRoutesDir, m.routesDir)),
+ )
const virtualRouteConfig = rootRoute('__root.tsx', [
route('/login', 'login.tsx'),
diff --git a/packages/dashboard/src/vite/route-collisions.test.ts b/packages/dashboard/src/vite/route-collisions.test.ts
new file mode 100644
index 0000000000..fb150521b9
--- /dev/null
+++ b/packages/dashboard/src/vite/route-collisions.test.ts
@@ -0,0 +1,91 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { assertNoRouteCollisions, type RouteSource } from './route-collisions'
+
+describe('assertNoRouteCollisions', () => {
+ let root: string
+
+ beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'route-collision-'))
+ })
+ afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true })
+ })
+
+ function makeSource(label: string, routes: Record<string, string>): RouteSource {
+ const dir = path.join(root, label.replace(/[^a-z0-9]/gi, '_'))
+ fs.mkdirSync(dir, { recursive: true })
+ for (const [file, routePath] of Object.entries(routes)) {
+ fs.writeFileSync(
+ path.join(dir, file),
+ `import { createFileRoute } from '@tanstack/react-router'\n` +
+ `export const Route = createFileRoute('${routePath}')({ component: () => null })\n`,
+ )
+ }
+ return { label, routesDir: dir }
+ }
+
+ it('passes when every route path is unique across sources', () => {
+ const sources = [
+ makeSource('@spree/dashboard', { 'products.tsx': '/_authenticated/$storeId/products/' }),
+ makeSource('@acme/brands', { 'brands.index.tsx': '/_authenticated/$storeId/brands/' }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).not.toThrow()
+ })
+
+ it('throws naming both packages and the path on a cross-plugin collision', () => {
+ const sources = [
+ makeSource('@acme/brands', { 'brands.index.tsx': '/_authenticated/$storeId/brands/' }),
+ makeSource('@other/brands', { 'b.tsx': '/_authenticated/$storeId/brands/' }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/@acme\/brands/)
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/@other\/brands/)
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/\/_authenticated\/\$storeId\/brands\//)
+ })
+
+ it('catches a plugin colliding with a built-in shell route', () => {
+ const sources = [
+ makeSource('@spree/dashboard', { 'products.tsx': '/_authenticated/$storeId/products/' }),
+ makeSource('@acme/rogue', { 'p.tsx': '/_authenticated/$storeId/products/' }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/@spree\/dashboard/)
+ expect(() => assertNoRouteCollisions(sources)).toThrow(/@acme\/rogue/)
+ })
+
+ it('ignores duplicate paths within a single source (generator reports those)', () => {
+ const sources = [
+ makeSource('@acme/brands', {
+ 'brands.index.tsx': '/_authenticated/$storeId/brands/',
+ 'brands.copy.tsx': '/_authenticated/$storeId/brands/',
+ }),
+ ]
+ expect(() => assertNoRouteCollisions(sources)).not.toThrow()
+ })
+
+ it('ignores non-route files and missing directories', () => {
+ const dir = path.join(root, 'plugin')
+ fs.mkdirSync(dir)
+ fs.writeFileSync(path.join(dir, 'helper.ts'), 'export const x = 1\n')
+ const sources: RouteSource[] = [
+ { label: '@acme/brands', routesDir: dir },
+ { label: '@acme/gone', routesDir: path.join(root, 'does-not-exist') },
+ ]
+ expect(() => assertNoRouteCollisions(sources)).not.toThrow()
+ })
+
+ it('scans nested route directories', () => {
+ const dir = path.join(root, 'nested')
+ fs.mkdirSync(path.join(dir, 'sub'), { recursive: true })
+ fs.writeFileSync(
+ path.join(dir, 'sub', 'deep.tsx'),
+ `import { createFileRoute } from '@tanstack/react-router'\n` +
+ `export const Route = createFileRoute('/_authenticated/$storeId/deep/')({})\n`,
+ )
+ const other = makeSource('@other/deep', { 'd.tsx': '/_authenticated/$storeId/deep/' })
+ expect(() =>
+ assertNoRouteCollisions([{ label: '@acme/nested', routesDir: dir }, other]),
+ ).toThrow(/@acme\/nested/)
+ })
+})
diff --git a/packages/dashboard/src/vite/route-collisions.ts b/packages/dashboard/src/vite/route-collisions.ts
new file mode 100644
index 0000000000..9b05cf14bf
--- /dev/null
+++ b/packages/dashboard/src/vite/route-collisions.ts
@@ -0,0 +1,110 @@
+import fs from 'node:fs'
+import path from 'node:path'
+
+/**
+ * A source of route files being composed into the tree — either the shell or
+ * a plugin. `label` is what a collision message names (a package name), so
+ * authors see "@acme/reviews" rather than a deep node_modules path.
+ */
+export interface RouteSource {
+ label: string
+ routesDir: string
+}
+
+interface DeclaredRoute {
+ /** The composed path from the file's `createFileRoute('…')` literal. */
+ routePath: string
+ file: string
+ source: string
+}
+
+// Matches the first `createFileRoute('…')` / `createFileRoute("…")` literal.
+// The generator treats this literal as authoritative for the route path, so
+// pre-flighting on it detects exactly the conflicts the generator would.
+const CREATE_FILE_ROUTE = /createFileRoute\(\s*(['"])([^'"]+)\1/
+const ROUTE_FILE_EXT = new Set(['.tsx', '.ts', '.jsx', '.js'])
+
+/**
+ * Detect route-path collisions across the shell and every plugin *before*
+ * the TanStack generator runs, and throw an error that names the conflicting
+ * **packages** and path. Without this, a duplicate route surfaces as the
+ * generator's file-path-only error, which plugin authors must map back to
+ * packages by hand.
+ *
+ * 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
+ * already actionable there.
+ *
+ * @throws Error naming the conflicting sources and path.
+ */
+export function assertNoRouteCollisions(sources: RouteSource[]): void {
+ const byPath = new Map<string, DeclaredRoute[]>()
+
+ for (const source of sources) {
+ const seenInSource = new Set<string>()
+ for (const { routePath, file } of readDeclaredRoutes(source.routesDir)) {
+ // 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)
+ }
+ }
+
+ const conflicts = [...byPath.values()].filter((list) => list.length > 1)
+ if (conflicts.length === 0) return
+
+ 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}`
+ })
+ .join('\n\n')
+
+ throw new Error(
+ `Dashboard route collision.\n\n${details}\n\n` +
+ 'Two packages cannot own the same route path. Rename one route, or ' +
+ "remove the plugin that shouldn't own it.",
+ )
+}
+
+/** Extract the `createFileRoute` literal from every route file under `dir`. */
+function readDeclaredRoutes(dir: string): Array<{ routePath: string; file: string }> {
+ if (!dirExists(dir)) return []
+ const out: Array<{ routePath: string; file: string }> = []
+ for (const file of walkFiles(dir)) {
+ if (!ROUTE_FILE_EXT.has(path.extname(file))) continue
+ let contents: string
+ try {
+ contents = fs.readFileSync(file, 'utf8')
+ } catch {
+ continue
+ }
+ const match = CREATE_FILE_ROUTE.exec(contents)
+ if (match) out.push({ routePath: match[2], file })
+ }
+ return out
+}
+
+function dirExists(dir: string): boolean {
+ try {
+ return fs.statSync(dir).isDirectory()
+ } catch {
+ return false
+ }
+}
+
+function* walkFiles(dir: string): Generator<string> {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name)
+ if (entry.isDirectory()) {
+ yield* walkFiles(full)
+ } else if (entry.isFile()) {
+ yield full
+ }
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 82cc1cc39c..0528e03153 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -192,6 +192,9 @@ importers:
'@tanstack/react-table':
specifier: ^8.21.3
+ '@tanstack/router-plugin':
+ specifier: ^1.167.35
'@tanstack/virtual-file-routes':
specifier: ^1.162.0
version: 1.162.0
@@ -283,9 +286,6 @@ importers:
'@spree/dashboard-plugin-example':
specifier: workspace:^
version: link:../dashboard-plugin-example
- '@tanstack/router-plugin':
- specifier: ^1.167.35
'@types/node':
specifier: ^25.6.0
version: 25.6.0