diff --git a/.changeset/create-routes.md b/.changeset/create-routes.md new file mode 100644 index 00000000..50f77052 --- /dev/null +++ b/.changeset/create-routes.md @@ -0,0 +1,38 @@ +--- +'@tanstack/cms-ui-react': minor +'@tanstack/cms-cli': minor +'@tanstack/cms-core': patch +--- + +**Breaking:** `createRoutes(definition, spec?)` from +`@tanstack/cms-ui-react/virtual-routes` replaces `cmsVirtualRoutes(options)`, +which is removed. It takes the `defineCmsDefinition` result from +`src/cms.definition.ts`, the only app module `vite.config.ts` imports, and +reads the admin base path and plugin routes from it, so they're no longer +repeated in the Vite config. + +The spec names routes by surface. `public`, `admin`, and `api` each take `true` +(every route), `false` (none), a list of route keys (only those), or an object +that drops (`false`) or replaces (a file path) single keys. A surface you leave +out is mounted, so `createRoutes(definition)` mounts everything. `custom` +replaces `children`, and `rootFile` is unchanged. `routesDirectory` and +`generatedDirectory` move to the `tanstackCms()` Vite plugin, which has to +come before `tanstackStart()`. `CreateRoutesSpec` replaces +`CmsVirtualRoutesOptions`, and the route keys (`CmsRouteKey`) are stable public +API. An old option throws with its replacement in the message. + +```ts +// before +cmsVirtualRoutes({ + adminBasePath: '/admin', + include: { public: false }, + routes: { agent: false }, +}) +// after: admin.basePath is set in defineCmsDefinition() +createRoutes(definition, { public: false, admin: { agent: false } }) +``` + +Migrate with `pnpm codemod create-routes `, run from a +TanStack CMS checkout. It rewrites `vite.config.ts` files and Markdown code +blocks and warns where an `adminBasePath` or `plugins` value has to move into +the definition. `tanstack-cms init` now writes `createRoutes(definition)`. diff --git a/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md b/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md index ed998507..87a67d05 100644 --- a/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md +++ b/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md @@ -70,9 +70,10 @@ shape of [`examples/blog`](../../../examples/blog) (same as the Payload skill `@tanstack/router-plugin`, `typescript`, node/react types, `vitest`. Scripts: `dev`, `build`, `test:types`, `test:lib` (`vitest run`), `migrate:data`. Pick a free dev port. -- `vite.config.ts` — `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } }), nitro(), viteReact()]` - with `tanstackCms` from `@tanstack/cms-ui-react/vite` and `cmsVirtualRoutes` - from `@tanstack/cms-ui-react/virtual-routes`. +- `vite.config.ts` — `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro(), viteReact()]` + with `tanstackCms` from `@tanstack/cms-ui-react/vite`, `createRoutes` from + `@tanstack/cms-ui-react/virtual-routes`, and `definition` from + `./src/cms.definition` (the only app module the Vite config imports). - `vitest.config.ts` — plain `defineConfig({ test: { environment: 'node', include: ['src/**/*.test.ts'] } })` from `vitest/config`. - `tsconfig.json` — `{ "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts","src/**/*.tsx"] }`. @@ -84,7 +85,7 @@ shape of [`examples/blog`](../../../examples/blog) (same as the Payload skill Write `cms.definition.ts` calling `defineCmsDefinition({ collections })`, importing only from `@tanstack/cms-core/definition` (`defineCollection`, `redirectsCollection`, …): Vite config and client code load this file, and -`pnpm test:definitions` fails if it reaches React, Start, or server code. +`pnpm test:definitions` fails if it reaches React, Start, server code, or the `@tanstack/cms-core` root. Then write `cms.config.ts` calling `defineCms(definition, { blockTypes, seed, theme, … })`. Hooks and access rules that need server code attach there by collection name diff --git a/.claude/skills/emdash-to-tanstack-cms/SKILL.md b/.claude/skills/emdash-to-tanstack-cms/SKILL.md index c10e9c8a..78d01052 100644 --- a/.claude/skills/emdash-to-tanstack-cms/SKILL.md +++ b/.claude/skills/emdash-to-tanstack-cms/SKILL.md @@ -80,9 +80,10 @@ migration skills' §2): `@tanstack/router-plugin`, `typescript`, node/react types, `vitest`. Scripts: `dev`, `build`, `test:types`, `test:lib` (`vitest run`), `migrate:data`. Pick a free dev port. -- `vite.config.ts` — `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } }), nitro(), viteReact()]` - with `tanstackCms` from `@tanstack/cms-ui-react/vite` and `cmsVirtualRoutes` - from `@tanstack/cms-ui-react/virtual-routes`. +- `vite.config.ts` — `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro(), viteReact()]` + with `tanstackCms` from `@tanstack/cms-ui-react/vite`, `createRoutes` from + `@tanstack/cms-ui-react/virtual-routes`, and `definition` from + `./src/cms.definition` (the only app module the Vite config imports). - `vitest.config.ts` — plain `defineConfig({ test: { environment: 'node', include: ['src/**/*.test.ts'] } })` from `vitest/config`. - `tsconfig.json` — `{ "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts","src/**/*.tsx"] }`. @@ -98,7 +99,7 @@ npm project with a large dependency tree) — see `examples/emdash-before` and t Write `cms.definition.ts` calling `defineCmsDefinition({ collections })`, importing only from `@tanstack/cms-core/definition` (`defineCollection`, `redirectsCollection`, …): Vite config and client code load this file, and -`pnpm test:definitions` fails if it reaches React, Start, or server code. +`pnpm test:definitions` fails if it reaches React, Start, server code, or the `@tanstack/cms-core` root. Then write `cms.config.ts` calling `defineCms(definition, { blockTypes, seed, theme, … })`. Hooks and access rules that need server code attach there by collection name diff --git a/.claude/skills/payload-to-tanstack-cms/SKILL.md b/.claude/skills/payload-to-tanstack-cms/SKILL.md index 9e31b983..c6b82c68 100644 --- a/.claude/skills/payload-to-tanstack-cms/SKILL.md +++ b/.claude/skills/payload-to-tanstack-cms/SKILL.md @@ -49,7 +49,7 @@ nested docs), and custom React admin components — these drive the gap report. Outside this repo, start from a TanStack Start app and run `npx tanstack-cms init` (from `@tanstack/cms-cli`): it creates -`src/cms.definition.ts` and `src/cms.config.ts`, adds `tanstackCms()` and `cmsVirtualRoutes()` to +`src/cms.definition.ts` and `src/cms.config.ts`, adds `tanstackCms()` and `createRoutes(definition)` to `vite.config.ts`, imports the config from `src/router.tsx`, and ignores `.data/`. In this repo, copy the shape of [`examples/blog`](../../../examples/blog): @@ -63,11 +63,12 @@ Outside this repo, start from a TanStack Start app and run `test:types` (`tsc --noEmit`), `test:lib` (`vitest run`), `cms` (`tanstack-cms`), `migrate:data`. Pick a free dev port. - `vite.config.ts` — as in `examples/blog`: - `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } }), nitro(), viteReact()]` - with `tanstackCms` from `@tanstack/cms-ui-react/vite` and `cmsVirtualRoutes` - from `@tanstack/cms-ui-react/virtual-routes`. Payload serves its admin at - `/admin`; keep that URL with `cmsVirtualRoutes({ adminBasePath: '/admin' })` - plus `defineCmsDefinition({ admin: { basePath: '/admin' } })`. + `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro(), viteReact()]` + with `tanstackCms` from `@tanstack/cms-ui-react/vite`, `createRoutes` from + `@tanstack/cms-ui-react/virtual-routes`, and `definition` from + `./src/cms.definition`. Payload serves its admin at `/admin`; keep that URL + with `defineCmsDefinition({ admin: { basePath: '/admin' } })`, which + `createRoutes` mounts the admin under (set it once, in the definition). - `vitest.config.ts` — a plain `defineConfig({ test: { environment: 'node', include: ['src/**/*.test.ts'] } })` from `vitest/config`, so tests don't load the Start/Nitro plugins. - `tsconfig.json` — `{ "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts","src/**/*.tsx"] }`. @@ -80,7 +81,7 @@ Outside this repo, start from a TanStack Start app and run Write `cms.definition.ts` calling `defineCmsDefinition({ collections, admin })`, importing only from `@tanstack/cms-core/definition` (`defineCollection`, `redirectsCollection`, …): Vite config and client code load this file, and -`pnpm test:definitions` fails if it reaches React, Start, or server code. +`pnpm test:definitions` fails if it reaches React, Start, server code, or the `@tanstack/cms-core` root. Then write `cms.config.ts` calling `defineCms(definition, { blockTypes, auth, seed, collections, … })` and register the definition's type diff --git a/.claude/skills/voting/SKILL.md b/.claude/skills/voting/SKILL.md index d25faf50..488cf0fb 100644 --- a/.claude/skills/voting/SKILL.md +++ b/.claude/skills/voting/SKILL.md @@ -26,7 +26,7 @@ All store functions from `@tanstack/cms-core/server` are **async** — ## 0. Prerequisites - A TanStack CMS app (`cms.definition.ts` + `cms.config.ts` + - `cmsVirtualRoutes()`), e.g. a copy of + `createRoutes(definition)`), e.g. a copy of [`examples/blog`](../../../examples/blog). - An `auth` config (`createMockAuth()` from `@tanstack/cms-ui-react` for demos, `auth: { getUser }` in production) so votes have a voter. @@ -251,10 +251,10 @@ A small component: up arrow, score, down arrow. Requirements: silently); `useCmsAuth()` from `@tanstack/cms-ui-react` says who's signed in. - Wiring, in order of preference: 1. Render `VoteButtons` in app-owned pages (list cards, a top-posts page) - added with `cmsVirtualRoutes({ children: [route('/top', './top.tsx')] })` + added with `createRoutes(definition, { custom: [route('/top', './top.tsx')] })` — child paths are relative to `src/routes`. This is what the worked example does. - 2. **Replace the built-in post page**: `cmsVirtualRoutes({ routes: { post: './post.$id.tsx' } })` + 2. **Replace the built-in post page**: `createRoutes(definition, { public: { post: './post.$id.tsx' } })` swaps in your own file (relative to `src/routes`); it must call `createFileRoute('/post/$id')`. Start from the package's `routes/post.$id.tsx` and add the buttons. diff --git a/.claude/skills/wordpress-to-tanstack-cms/SKILL.md b/.claude/skills/wordpress-to-tanstack-cms/SKILL.md index cad61a14..d89b1deb 100644 --- a/.claude/skills/wordpress-to-tanstack-cms/SKILL.md +++ b/.claude/skills/wordpress-to-tanstack-cms/SKILL.md @@ -75,9 +75,10 @@ migration skills' §2): `@tanstack/router-plugin`, `typescript`, node/react types, `vitest`. Scripts: `dev`, `build`, `test:types`, `test:lib` (`vitest run`), `migrate:data`. Pick a free dev port. -- `vite.config.ts` — `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } }), nitro(), viteReact()]` - with `tanstackCms` from `@tanstack/cms-ui-react/vite` and `cmsVirtualRoutes` - from `@tanstack/cms-ui-react/virtual-routes`. +- `vite.config.ts` — `plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro(), viteReact()]` + with `tanstackCms` from `@tanstack/cms-ui-react/vite`, `createRoutes` from + `@tanstack/cms-ui-react/virtual-routes`, and `definition` from + `./src/cms.definition` (the only app module the Vite config imports). - `vitest.config.ts` — plain `defineConfig({ test: { environment: 'node', include: ['src/**/*.test.ts'] } })` from `vitest/config`. - `tsconfig.json` — extends `../../tsconfig.base.json`; `src/router.tsx` — @@ -91,7 +92,7 @@ workspace app. Write `cms.definition.ts` calling `defineCmsDefinition({ collections })`, importing only from `@tanstack/cms-core/definition` (`defineCollection`, `redirectsCollection`, …): Vite config and client code load this file, and -`pnpm test:definitions` fails if it reaches React, Start, or server code. +`pnpm test:definitions` fails if it reaches React, Start, server code, or the `@tanstack/cms-core` root. Then write `cms.config.ts` calling `defineCms(definition, { blockTypes, seed, theme, … })`. Hooks and access rules that need server code attach there by collection name diff --git a/README.md b/README.md index 2fc3dab3..4701dc32 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ TanStack Start app, and your UI reads its content through TanStack DB. - **TanStack Start is the runtime.** The admin, the public pages, and every API endpoint are Start routes shipped in a package and mounted with - `cmsVirtualRoutes()`. Each CMS operation is a Start server function + `createRoutes(definition)`. Each CMS operation is a Start server function (`@tanstack/cms-api/start`), so the admin and your own loaders call the engine in-process, with no HTTP hop. The same operations are served over HTTP, MCP, and WebMCP for everything outside the app. @@ -106,8 +106,8 @@ for your app's own routes and components. See - **SEO built in.** Sitemap, robots.txt, redirects, OpenGraph and JSON-LD helpers, and signed webhooks on publish, unpublish, and delete. - **Routes from a package.** The admin, public pages, and API endpoints mount - into your Start app with `cmsVirtualRoutes()`. Move the admin under a base - path, override any route with your own file, or drop it. + into your Start app with `createRoutes(definition)`. Mount only some, move + the admin under a base path, or replace or drop any route by its key. - **A CLI.** `tanstack-cms init`, `migrate`, `seed`, `export`, `import`, and `backup`. @@ -163,7 +163,9 @@ declare module '@tanstack/cms-core' { } ``` -A small app can keep both halves in one `defineCms({ collections, … })` call. +A small app can keep both halves in one `defineCms({ collections, … })` call, +but `vite.config.ts` mounts the routes from the definition, so keep at least +`defineCmsDefinition({})` in `src/cms.definition.ts`. ```ts // vite.config.ts @@ -172,14 +174,15 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' export default defineConfig({ plugins: [ tanstackCms(), tailwindcss(), - tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } }), + tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro(), viteReact(), ], diff --git a/app/base/vite.config.ts b/app/base/vite.config.ts index 201b409f..d778d827 100644 --- a/app/base/vite.config.ts +++ b/app/base/vite.config.ts @@ -4,8 +4,9 @@ import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { index, route } from '@tanstack/virtual-file-routes' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' const quickjsPackages = [ 'quickjs-emscripten', @@ -22,11 +23,11 @@ export default defineConfig({ tailwindcss(), tanstackStart({ router: { - virtualRouteConfig: cmsVirtualRoutes({ + virtualRouteConfig: createRoutes(definition, { rootFile: './__root.tsx', - include: { public: false }, - routes: { agent: './agent.tsx' }, - children: [ + public: false, + admin: { agent: './agent.tsx' }, + custom: [ index('./home.tsx'), route('/setup', './setup.tsx'), route('/collections', './collections.tsx'), diff --git a/app/prm/src/collections.ts b/app/prm/src/collections.ts index fda95a6d..343adbb2 100644 --- a/app/prm/src/collections.ts +++ b/app/prm/src/collections.ts @@ -14,8 +14,8 @@ * and priority (`high` | `medium` | `low` | `unranked`). * - `personSource` stores per-field provenance (`high` | `medium` | `low`). */ -import { defineCollection } from '@tanstack/cms-core' -import type { AccessRule } from '@tanstack/cms-core' +import { defineCollection } from '@tanstack/cms-core/definition' +import type { AccessRule } from '@tanstack/cms-core/definition' export const INTEREST_OPTIONS = [ 'agent-harness', diff --git a/app/prm/vite.config.ts b/app/prm/vite.config.ts index 0bc2425c..ef271e54 100644 --- a/app/prm/vite.config.ts +++ b/app/prm/vite.config.ts @@ -4,8 +4,9 @@ import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { route } from '@tanstack/virtual-file-routes' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' export default defineConfig({ plugins: [ @@ -13,10 +14,10 @@ export default defineConfig({ tailwindcss(), tanstackStart({ router: { - virtualRouteConfig: cmsVirtualRoutes({ + virtualRouteConfig: createRoutes(definition, { rootFile: './__root.tsx', - include: { public: false, admin: true, api: true }, - children: [ + public: false, + custom: [ route('/', './index.tsx'), route('/setup', './setup.tsx'), route('/login', './login.tsx'), diff --git a/docs/agents/on-page-editor.md b/docs/agents/on-page-editor.md index de48168a..2b8a7e60 100644 --- a/docs/agents/on-page-editor.md +++ b/docs/agents/on-page-editor.md @@ -93,7 +93,7 @@ Agents working off the page (the content agent, MCP, WebMCP) never get this dire ## Using the Components in Your Own Routes -If you replace the CMS `page` or `post` route (`cmsVirtualRoutes({ routes: { post: './my-post.tsx' } })`), render the interactive components to keep on-page editing: +If you replace the CMS `page` or `post` route (`createRoutes(definition, { public: { post: './my-post.tsx' } })`), render the interactive components to keep on-page editing: ```tsx validate=type import { diff --git a/docs/api/cli.md b/docs/api/cli.md index bfba29b5..141cdd03 100644 --- a/docs/api/cli.md +++ b/docs/api/cli.md @@ -52,7 +52,7 @@ tanstack-cms init [--dir ] [--force] Adds TanStack CMS to an existing TanStack Start app: - **Config**: writes `src/cms.definition.ts` (a `post` collection, importing only `@tanstack/cms-core/definition`) and `src/cms.config.ts` (`defineCms(definition, { … })` with a seed post and the `Register` augmentation for end-to-end types), or both in the app root when there is no `src` directory. If either file exists, both are kept unless `--force` is passed. -- **Vite**: in `vite.config.ts`, `.mts`, or `.js`, replaces a plain `tanstackStart()` call with `tanstackCms()` plus `tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } })` and adds the imports. A config that already passes options to `tanstackStart` is left alone and the snippet is printed instead. +- **Vite**: in `vite.config.ts`, `.mts`, or `.js`, replaces a plain `tanstackStart()` call with `tanstackCms()` plus `tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } })` and adds the imports (`definition` from `./src/cms.definition`). A config that already passes options to `tanstackStart` is left alone and the snippet is printed instead. - **Router**: adds `import './cms.config'` to `router.tsx` / `router.ts`, so the content model is registered before any loader or server function runs. - **`.gitignore`**: adds `.data/` (the default SQLite database and uploads directory). diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 6ca268e2..074dd6ae 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -219,7 +219,7 @@ export const cms = defineCms(definition, { blockTypes: [], dataDir: '.data' }) cms.collections.post.label // 'Posts' ``` -`pnpm test:definitions` (`scripts/verify-definitions.ts`) loads every `cms.definition.ts` under `app/`, `starters/`, and `examples/` in plain Node and reports any import of `react`, `react-dom`, a `.tsx` file, `@tanstack/react-start`, `@tanstack/react-router`, the `@tanstack/cms-ui-react` root, `@tanstack/cms-core/server`, or a `*.server.*` file. It also scaffolds what `tanstack-cms init` and a code-mode `tanstack-cms skill add` write and checks those definitions. It fails CI on any violation; `tsx scripts/verify-definitions.ts` without `--strict` only reports. +`pnpm test:definitions` (`scripts/verify-definitions.ts`) loads every `cms.definition.ts` under `app/`, `starters/`, and `examples/` in plain Node and reports any import of `react`, `react-dom`, a `.tsx` file, `@tanstack/react-start`, `@tanstack/react-router`, the `@tanstack/cms-ui-react` root, the `@tanstack/cms-core` root (Vite loads `vite.config.ts` in plain Node, which can't load it from workspace source), `@tanstack/cms-core/server`, or a `*.server.*` file. Collection modules a definition imports use `@tanstack/cms-core/definition` too. It also scaffolds what `tanstack-cms init` and a code-mode `tanstack-cms skill add` write and checks those definitions. It fails CI on any violation; `tsx scripts/verify-definitions.ts` without `--strict` only reports. ### `getCmsConfig()` @@ -396,7 +396,7 @@ interface CmsWebhook { | Option | Default | Description | | --- | --- | --- | -| `basePath?` | `''` | Admin URL prefix (e.g. `/admin`). Must match `cmsVirtualRoutes({ adminBasePath })`. | +| `basePath?` | `''` | Admin URL prefix (e.g. `/admin`). Set it in the definition: `createRoutes(definition)` mounts the admin routes under it. | | `locale?` | `'en'` | BCP 47 locale for admin dates and numbers. | | `messages?` | — | Admin string overrides keyed by message id (see `defaultAdminMessages` in `@tanstack/cms-ui-react`). `{name}` placeholders are interpolated. | @@ -447,7 +447,7 @@ interface CmsPluginDefinition { name: string // unique within the app collections?: ReadonlyArray adminNav?: Array<{ label: string; to: string; permission?: Permission }> - routes?: Array // read by cmsVirtualRoutes({ plugins }), not defineCms + routes?: Array // mounted by createRoutes(definition), not defineCms adminRoutes?: Array // same, mounted under admin.basePath } @@ -507,7 +507,7 @@ export const cms = defineCms({ ``` - **Admin nav** links appear after the built-in ones, for sessions with `permission` (default `content.read`). `to` is relative to the admin base path. -- **Routes** are compiled into the router, so give the same plugin to `cmsVirtualRoutes({ plugins: [analytics] })` in `vite.config.ts` (see [Routes](./routes-and-endpoints#cmsvirtualroutesoptions)). `routes` keep their paths as written. Put admin pages in `adminRoutes` instead: they are mounted under `adminBasePath`, matching `adminNav`, so `adminRoutes: [route('/analytics', …)]` serves `/admin/analytics` when the base path is `/admin`. A route file shipped inside the plugin's package is copied with the prefixed path, like the built-in admin routes. An admin page route should render inside `AdminShell`. +- **Routes** are compiled into the router: `createRoutes(definition)` in `vite.config.ts` mounts the routes of every plugin in `defineCmsDefinition({ plugins })` (see [Routes](./routes-and-endpoints#createroutesdefinition-spec)), so a plugin with routes must be in the definition. `routes` keep their paths as written. Put admin pages in `adminRoutes` instead: they are mounted under the definition's `admin.basePath`, matching `adminNav`, so `adminRoutes: [route('/analytics', …)]` serves `/admin/analytics` when the base path is `/admin`. A route file shipped inside the plugin's package is copied with the prefixed path, like the built-in admin routes. An admin page route should render inside `AdminShell`. - **`onEvent`** receives the same events as [`onCmsEvent`](./cms-core-server#oncmseventlistener), on the server only. `cms.config.ts` also runs in the browser, so keep server-only code (SDK clients, secrets) inside op `run` functions behind lazy `import()`s, as with your own ops. diff --git a/docs/api/cms-ui-react.md b/docs/api/cms-ui-react.md index 200b63a0..ed92f086 100644 --- a/docs/api/cms-ui-react.md +++ b/docs/api/cms-ui-react.md @@ -11,7 +11,8 @@ keywords: - MarkdownEditor - useCan - createMockAuth - - cmsVirtualRoutes + - createRoutes + - CmsRouteKey - tanstackCms vite plugin - admin i18n - ui primitives @@ -32,10 +33,10 @@ Peer dependencies: `react` and `react-dom` 19, `@tanstack/react-router`, `@tanst | `@tanstack/cms-ui-react` | Auth bindings, `AdminShell`, `MarkdownEditor`, `MediaImg`, admin i18n, `WebMcpBadge`. | | [`@tanstack/cms-ui-react/primitives`](#tanstackcms-ui-reactprimitives) | The admin's UI primitives (field editors, pickers, list, diff and review panels) for bespoke and generated admin screens. | | `@tanstack/cms-ui-react/site` | Public-site building blocks: `SiteShell`, `DocsLayout`, `BlocksView`/`BlockView`, and the stable on-page editor. | -| [`@tanstack/cms-ui-react/virtual-routes`](#tanstackcms-ui-reactvirtual-routes) | `cmsVirtualRoutes()`. | +| [`@tanstack/cms-ui-react/virtual-routes`](#tanstackcms-ui-reactvirtual-routes) | `createRoutes()` and the route key types. | | [`@tanstack/cms-ui-react/vite`](#tanstackcms-ui-reactvite) | `tanstackCms()` Vite plugin. | | [`@tanstack/cms-ui-react/styles.css`](#tanstackcms-ui-reactstylescss) | Tailwind entry with the theme token fallbacks. | -| `@tanstack/cms-ui-react/routes/*` | The route files `cmsVirtualRoutes()` mounts. Not meant to be imported directly. | +| `@tanstack/cms-ui-react/routes/*` | The route files `createRoutes()` mounts. Not meant to be imported directly. | --- @@ -360,23 +361,47 @@ type RelationSearch = ( ## `@tanstack/cms-ui-react/virtual-routes` ```ts -function cmsVirtualRoutes(options?: CmsVirtualRoutesOptions): VirtualRootRoute +function createRoutes( + definition: CmsDefinition, // from defineCmsDefinition() + spec?: CreateRoutesSpec, +): VirtualRootRoute + +interface CreateRoutesSpec { + public?: CmsRouteSurfaceSpec<'public'> + admin?: CmsRouteSurfaceSpec<'admin'> + api?: CmsRouteSurfaceSpec<'api'> + custom?: ReadonlyArray + rootFile?: string +} + +// true: every route; false: none; a key list: only those; +// an object: drop (false) or replace (a file path) single keys +type CmsRouteSurfaceSpec = + | boolean + | ReadonlyArray> + | { [K in CmsSurfaceRouteKey]?: boolean | string } // Re-exported from @tanstack/cms-core/definition (CMS_ROUTE_KEYS) +type CmsRouteSurface = 'public' | 'admin' | 'api' type CmsRouteKey = | 'index' | 'page' | 'post' | 'preview' | 'sitemap' | 'robots' | 'notFound' | 'content' | 'edit' | 'agent' | 'review' | 'settings' | 'apiWebMcp' | 'apiV1' | 'apiMcp' | 'apiMedia' | 'apiMediaFile' +type CmsSurfaceRouteKey // the keys of one surface ``` -The virtual route tree for the TanStack Router plugin: the public pages, the admin, and the API routes, plus your own `children`. Options, keys, and paths are listed in the [route table](./routes-and-endpoints#route-table); overriding and adding routes is covered in [Building Pages](../schema/building-pages). +The virtual route tree for the TanStack Router plugin: the public pages, the admin, and the API routes, plus your own `custom` routes. The admin base path and plugin routes come from the definition. A surface you leave out is mounted, so `createRoutes(definition)` mounts everything. Route keys are stable public API: renaming or removing one is a breaking change. Keys, paths, and options are listed in the [route table](./routes-and-endpoints#route-table); overriding and adding routes is covered in [Building Pages](../schema/building-pages). --- ## `@tanstack/cms-ui-react/vite` ```ts -function tanstackCms(options?: { packages?: Array }): CmsVitePlugin +function tanstackCms(options?: { + packages?: Array + routesDirectory?: string // default /src/routes + generatedDirectory?: string // where prefixed admin route copies are written +}): CmsVitePlugin interface CmsVitePlugin { name: string // 'tanstack-cms' @@ -388,16 +413,17 @@ interface CmsVitePlugin { } ``` -The CMS packages ship TanStack Start server functions and route files that your app's Start compiler must transform. The plugin keeps `@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, and `@tanstack/cms-client` (plus any `packages` you add) out of Vite's SSR externals and dependency pre-bundling, and bundles `@tanstack/ai*` into SSR alongside them. Add it before `tanstackStart()`. +The CMS packages ship TanStack Start server functions and route files that your app's Start compiler must transform. The plugin keeps `@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, and `@tanstack/cms-client` (plus any `packages` you add) out of Vite's SSR externals and dependency pre-bundling, and bundles `@tanstack/ai*` into SSR alongside them. `routesDirectory` and `generatedDirectory` are read by `createRoutes()`, which resolves route files when the config loads. Add it before `tanstackStart()`. ```ts validate=type import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' export default defineConfig({ - plugins: [tanstackCms(), tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } })], + plugins: [tanstackCms(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } })], }) ``` diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index 5d4ebe36..53db57b3 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -9,26 +9,28 @@ keywords: - rest api - openapi - api keys - - cmsVirtualRoutes + - createRoutes + - route keys - webhooks - x-cms-signature - mcp endpoint - media endpoint --- -TanStack CMS adds pages, admin screens, and API endpoints to your app through `cmsVirtualRoutes()` from `@tanstack/cms-ui-react/virtual-routes`. The API routes are thin wrappers over [`createCmsApiHandler()`](./cms-api#tanstackcms-apihttp), which you can also mount on any server that speaks Web `Request`/`Response`. +TanStack CMS adds pages, admin screens, and API endpoints to your app through `createRoutes(definition, spec?)` from `@tanstack/cms-ui-react/virtual-routes`. The API routes are thin wrappers over [`createCmsApiHandler()`](./cms-api#tanstackcms-apihttp), which you can also mount on any server that speaks Web `Request`/`Response`. --- ## Route table -`cmsVirtualRoutes()` returns the whole virtual route tree for the TanStack Router plugin. Each route has a key you can use to [override or drop it](../schema/building-pages). +`createRoutes()` returns the whole virtual route tree for the TanStack Router plugin. Every route has a **route key**. The keys are stable public API (`CmsRouteKey`, with the per-surface lists in `CMS_ROUTE_KEYS` from `@tanstack/cms-core/definition`): you name them to mount only some routes, drop one, or [replace one](../schema/building-pages) with your own file. Renaming or removing a key is a breaking change. -| Key | Group | Path | Package file | What it is | +| Key | Surface | Path | Package file | What it is | | --- | --- | --- | --- | --- | | `index` | public | `/` | `index.tsx` | Home page, rendered by `theme.variant`. | | `page` | public | `/p/$id` | `p.$id.tsx` | Page by slug or id, with `BlocksView`. | | `post` | public | `/post/$id` | `post.$id.tsx` | Post by slug or id. | +| `preview` | public | `/preview/$collection/$id` | `preview.$collection.$id.tsx` | Draft preview behind a preview token. | | `sitemap` | public | `/sitemap.xml` | `sitemap.xml.ts` | Generated sitemap. | | `robots` | public | `/robots.txt` | `robots.txt.ts` | Generated robots.txt. | | `notFound` | public | `/$` | `$.tsx` | Follows the redirects collection, else renders a 404. | @@ -43,37 +45,57 @@ TanStack CMS adds pages, admin screens, and API endpoints to your app through `c | `apiMedia` | api | `/api/media` | `api.media.ts` | Media upload. | | `apiMediaFile` | api | `/api/media/$name` | `api.media.$name.ts` | Media file serving and transforms. | -Admin paths move under `adminBasePath` when one is set (for example `/admin/content`); public and API paths never move. +Admin paths move under the definition's `admin.basePath` when one is set (for example `/admin/content`); public and API paths never move. -### `cmsVirtualRoutes(options?)` +### `createRoutes(definition, spec?)` + +`definition` is the `defineCmsDefinition` result from `src/cms.definition.ts`, the only app module `vite.config.ts` imports. Everything derivable comes from it: the admin routes mount under its `admin.basePath`, and its plugins' `routes` and `adminRoutes` are attached after the CMS routes (`adminRoutes` under the admin base path too). Neither is repeated in the spec. + +`spec` says what to mount. `createRoutes(definition)` mounts everything. | Option | Type | Default | Description | | --- | --- | --- | --- | -| `routesDirectory` | `string` | `/src/routes` | Your router's `routesDirectory`; package and override paths are resolved against it. | +| `public` | surface spec | `true` | The public routes. | +| `admin` | surface spec | `true` | The admin routes. | +| `api` | surface spec | `true` | The API routes. | +| `custom` | `Array` | none | Your app's own routes, built with `route()` / `index()` / `physical()` from `@tanstack/virtual-file-routes`, attached after the CMS and plugin routes. | | `rootFile` | `string` | package `__root.tsx` | Your own root route file. | -| `include` | `{ public?: boolean; admin?: boolean; api?: boolean }` | all `true` | Drop whole route groups. | -| `adminBasePath` | `string` | none | Mount the admin routes under a prefix such as `'/admin'`. Match `defineCms({ admin: { basePath } })`. | -| `generatedDirectory` | `string` | `/../.tanstack-cms` | Where prefixed admin route files are generated when `adminBasePath` is set. | -| `routes` | `Partial>` | none | Replace a route with your own file (relative to `routesDirectory`, or absolute; it must call `createFileRoute` with the same path) or drop it with `false`. | -| `children` | `Array` | none | Your own routes, built with `route()` / `physical()` from `@tanstack/virtual-file-routes`. | -| `plugins` | `Array` | none | Plugins whose `routes` and `adminRoutes` are attached after the CMS routes and before `children`; `adminRoutes` get the `adminBasePath` prefix (see [Plugins](./cms-core#plugins)). | + +Each surface takes the same values: + +| Value | Mounts | +| --- | --- | +| `true`, or leaving the surface out | Every route of the surface. | +| `false` | None of them. | +| `['review']` | Only these keys. | +| `{ agent: false, edit: './edit.tsx' }` | Every route, except that `false` drops a key and a path replaces its file with yours. | + +A replacement path is relative to your routes directory (or absolute), and the file must call `createFileRoute` with the same path as the route it replaces. A key from another surface, or an unknown one, throws. So does an option of the route builder `createRoutes()` replaced (`include`, `routes`, `adminBasePath`, `plugins`, `children`, `routesDirectory`, `generatedDirectory`); the error names its replacement, and [Upgrading](../deployment/upgrading) shows the rewrite. + +The routes directory and the location of the generated admin route copies are build settings, so they're options of the `tanstackCms()` Vite plugin. List it before `tanstackStart()`: + +| `tanstackCms()` option | Default | Description | +| --- | --- | --- | +| `routesDirectory` | `/src/routes` | Your router's `routesDirectory`; package and replacement paths are resolved against it. | +| `generatedDirectory` | inside `@tanstack/cms-ui-react` | Where prefixed admin route files are generated when the definition sets `admin.basePath`. | ```ts validate=type import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { physical, route } from '@tanstack/virtual-file-routes' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' export default defineConfig({ plugins: [ tanstackCms(), tanstackStart({ router: { - virtualRouteConfig: cmsVirtualRoutes({ - adminBasePath: '/admin', - routes: { post: 'blog-post.tsx', agent: false }, - children: [route('/pricing', 'pricing.tsx'), physical('/shop', 'shop')], + virtualRouteConfig: createRoutes(definition, { + public: { post: 'blog-post.tsx' }, + admin: { agent: false }, + custom: [route('/pricing', 'pricing.tsx'), physical('/shop', 'shop')], }), }, }), diff --git a/docs/architecture/data-layer.md b/docs/architecture/data-layer.md index b10a4587..93cbeba3 100644 --- a/docs/architecture/data-layer.md +++ b/docs/architecture/data-layer.md @@ -118,13 +118,14 @@ The data-layer examples mount the CMS admin and API but not the public pages, an ```ts // vite.config.ts (excerpt) import { route } from '@tanstack/virtual-file-routes' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { definition } from './src/cms.definition' tanstackStart({ router: { - virtualRouteConfig: cmsVirtualRoutes({ - include: { public: false, admin: true, api: true }, - children: [route('/', './home.tsx')], + virtualRouteConfig: createRoutes(definition, { + public: false, + custom: [route('/', './home.tsx')], }), }, }) diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index 575b4f22..e65dbcdb 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -17,12 +17,12 @@ TanStack CMS runs inside your TanStack Start app. Every surface (the admin, your ## Overview -`cmsVirtualRoutes()` mounts the admin, public, and API routes from the package. Each route calls the operations registry (`ops` in `@tanstack/cms-api`), which checks access and then calls the engine. +`createRoutes(definition)` mounts the admin, public, and API routes from the package. Each route calls the operations registry (`ops` in `@tanstack/cms-api`), which checks access and then calls the engine. ```mermaid flowchart LR subgraph start["Your TanStack Start app"] - routes["cmsVirtualRoutes()
@tanstack/cms-ui-react/virtual-routes"] + routes["createRoutes(definition)
@tanstack/cms-ui-react/virtual-routes"] admin["Admin UI
/content, /edit/$collection/$id,
/review, /agent"] app["App loaders and components"] http["HTTP API
/api/cms/v1"] diff --git a/docs/architecture/routes-in-a-package.md b/docs/architecture/routes-in-a-package.md index 752e7846..06fb0bc8 100644 --- a/docs/architecture/routes-in-a-package.md +++ b/docs/architecture/routes-in-a-package.md @@ -2,19 +2,19 @@ title: Routes in a Package id: routes-in-a-package order: 1 -description: "How @tanstack/cms-ui-react ships a complete TanStack Start route tree inside a package and mounts it in your app with cmsVirtualRoutes() and the tanstackCms() Vite plugin." +description: "How @tanstack/cms-ui-react ships a complete TanStack Start route tree inside a package and mounts it in your app with createRoutes(definition) and the tanstackCms() Vite plugin." keywords: - tanstack cms - - cmsVirtualRoutes + - createRoutes - virtualRouteConfig - virtual-file-routes - tanstackCms - - adminBasePath + - admin basePath - tanstack start - routeTree.gen.ts --- -A TanStack CMS app does not copy admin, public, or API route files into its own `src/routes/`. The routes physically live in `@tanstack/cms-ui-react`, written as ordinary TanStack Router file routes (`createFileRoute()`), and your app mounts them through TanStack Start's `virtualRouteConfig` with `cmsVirtualRoutes()`. +A TanStack CMS app does not copy admin, public, or API route files into its own `src/routes/`. The routes physically live in `@tanstack/cms-ui-react`, written as ordinary TanStack Router file routes (`createFileRoute()`), and your app mounts them through TanStack Start's `virtualRouteConfig` with `createRoutes(definition)`. Every app therefore shares one admin UI, review queue, and API surface, upgrades them by bumping a package version, and can still replace or drop any individual route. @@ -28,8 +28,9 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' export default defineConfig({ plugins: [ @@ -37,7 +38,7 @@ export default defineConfig({ tailwindcss(), tanstackStart({ router: { - virtualRouteConfig: cmsVirtualRoutes(), + virtualRouteConfig: createRoutes(definition), }, }), nitro(), @@ -46,8 +47,9 @@ export default defineConfig({ }) ``` -- **`tanstackCms()`** (from `@tanstack/cms-ui-react/vite`) keeps the CMS packages (`@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, `@tanstack/cms-client`) and `@tanstack/ai*` out of Vite's SSR externals and dependency pre-bundling. The packages ship TanStack Start server functions and route files that your app's Start compiler must transform, so the plugin is required when you consume the published packages. Pass `tanstackCms({ packages: [...] })` to treat additional packages the same way. In SSR it also serves `use-sync-external-store` (which `@tanstack/react-store` and `@tanstack/react-form` import) as ESM on React's own `useSyncExternalStore`. Otherwise, under pnpm, the production server bundle loads a second copy of React, and every server-rendered page fails with "Invalid hook call". -- **`cmsVirtualRoutes()`** (from `@tanstack/cms-ui-react/virtual-routes`) returns a virtual route tree built with `@tanstack/virtual-file-routes`. The router generator turns it into your app's `src/routeTree.gen.ts`, with imports pointing into the package. +- **`tanstackCms()`** (from `@tanstack/cms-ui-react/vite`) keeps the CMS packages (`@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, `@tanstack/cms-client`) and `@tanstack/ai*` out of Vite's SSR externals and dependency pre-bundling. The packages ship TanStack Start server functions and route files that your app's Start compiler must transform, so the plugin is required when you consume the published packages. Pass `tanstackCms({ packages: [...] })` to treat additional packages the same way. It also takes the route build's `routesDirectory` and `generatedDirectory` (see below), which is why it comes before `tanstackStart()`. In SSR it serves `use-sync-external-store` (which `@tanstack/react-store` and `@tanstack/react-form` import) as ESM on React's own `useSyncExternalStore`. Otherwise, under pnpm, the production server bundle loads a second copy of React, and every server-rendered page fails with "Invalid hook call". +- **`createRoutes(definition)`** (from `@tanstack/cms-ui-react/virtual-routes`) returns a virtual route tree built with `@tanstack/virtual-file-routes`. The router generator turns it into your app's `src/routeTree.gen.ts`, with imports pointing into the package. +- **`definition`** comes from `src/cms.definition.ts` (`defineCmsDefinition` from `@tanstack/cms-core/definition`): the collections, `admin.basePath`, and plugin definitions. It's the only app module the Vite config imports, so the config never loads auth, storage, AI, or React. `createRoutes` reads the admin base path and the plugins' routes from it. Your app's `src/router.tsx` imports `./cms.config` before `./routeTree.gen`, so `defineCms()` has registered the content model before any route loader or server function reads it: @@ -67,13 +69,14 @@ export const getRouter = () => ## The Route Table -Each route has a stable key you can use to override or remove it. +Each route has a stable key you can use to mount, replace, or drop it. The keys are public API (`CmsRouteKey`); renaming or removing one is a breaking change. -| Key | Path | Group | Purpose | +| Key | Path | Surface | Purpose | | --- | --- | --- | --- | | `index` | `/` | public | Home page (layout depends on `theme.variant`) | | `page` | `/p/$id` | public | Page renderer with the on-page editor | | `post` | `/post/$id` | public | Post renderer with the on-page editor | +| `preview` | `/preview/$collection/$id` | public | Shareable draft preview behind a preview token | | `sitemap` | `/sitemap.xml` | public | Sitemap of published documents from collections with a `path` | | `robots` | `/robots.txt` | public | `robots.txt` (disallows the admin routes) | | `notFound` | `/$` | public | Catch-all: follows the redirects collection, else renders a 404 | @@ -90,57 +93,61 @@ Each route has a stable key you can use to override or remove it. The root route (`__root.tsx`) resolves the session in `beforeLoad`, injects the theme CSS, and wraps the app in `` with the WebMCP badge. The API routes are thin wrappers over the handlers in `@tanstack/cms-api/http`; see [Routes & HTTP Endpoints](../api/routes-and-endpoints) for request and response details. -## `cmsVirtualRoutes()` Options +## `createRoutes(definition, spec?)` + +The spec says what to mount; with no spec, everything is mounted. | Option | Description | | --- | --- | -| `adminBasePath` | Mount the admin routes under a prefix, such as `/admin` | -| `routes` | Per-key overrides: a file path to replace a route, or `false` to drop it | -| `include` | Route groups to mount: `{ public?, admin?, api? }`, each defaulting to `true` | -| `children` | Extra virtual route nodes (your own routes or physical subtrees) attached to the root | +| `public`, `admin`, `api` | Per surface: `true` or left out (every route), `false` (none), `['review']` (only these keys), or `{ agent: false, edit: './edit.tsx' }` (drop or replace single keys) | +| `custom` | Your app's own routes (`route()`, `index()`, `physical()`), attached after the CMS and plugin routes | | `rootFile` | Your own root route instead of the package's `__root.tsx` | + +The admin base path and plugin routes aren't options: they come from the definition. The build directories are options of `tanstackCms()`: + +| `tanstackCms()` option | Description | +| --- | --- | | `routesDirectory` | Your routes directory, used to resolve relative paths (default `/src/routes`) | | `generatedDirectory` | Where prefixed admin route files are written (see below) | ### Replacing or Removing Routes -Paths in `routes` are relative to your routes directory (or absolute). A replacement file must call `createFileRoute` with the same path as the route it replaces. +Replacement paths are relative to your routes directory (or absolute). A replacement file must call `createFileRoute` with the same path as the route it replaces. ```ts validate=type -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' - -export const virtualRouteConfig = cmsVirtualRoutes({ - routes: { - // src/routes/my-post.tsx calls createFileRoute('/post/$id') - post: './my-post.tsx', - // No /agent route in this app - agent: false, - }, +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { definition } from './src/cms.definition' + +export const virtualRouteConfig = createRoutes(definition, { + // src/routes/my-post.tsx calls createFileRoute('/post/$id') + // No /agent route in this app + public: { post: './my-post.tsx' }, + admin: { agent: false }, }) ``` -Use `include` to compose a smaller server: `{ public: true, admin: false, api: true }` for a public site whose editors work elsewhere, or mount only the API with `createCmsApiHandler()` from `@tanstack/cms-api/http` in a non-Start server. +Leave whole surfaces out to compose a smaller server: `{ admin: false }` for a public site whose editors work elsewhere, `{ public: false, admin: ['review'] }` for a review-only admin, or mount only the API with `createCmsApiHandler()` from `@tanstack/cms-api/http` in a non-Start server. ### Mounting the Admin Under a Base Path -Set the same prefix in both places: `cmsVirtualRoutes({ adminBasePath })` builds the routes, and `defineCms({ admin: { basePath } })` makes the package's links, redirects, and `robots.txt` use it. +Set the prefix once, in the definition. `createRoutes(definition)` mounts the admin routes under it, and the runtime config built from the same definition makes the package's links, redirects, and `robots.txt` use it. ```ts validate=type -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { defineCmsDefinition } from '@tanstack/cms-core/definition' -// vite.config.ts: admin at /admin/content, /admin/edit/$collection/$id, /admin/review, ... -export const virtualRouteConfig = cmsVirtualRoutes({ adminBasePath: '/admin' }) +// src/cms.definition.ts +export const definition = defineCmsDefinition({ + collections: [], + admin: { basePath: '/admin' }, +}) ``` ```ts validate=type -import { defineCms } from '@tanstack/cms-core' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { definition } from './src/cms.definition' -// src/cms.config.ts -export const cms = defineCms({ - collections: [], - blockTypes: [], - admin: { basePath: '/admin' }, -}) +// vite.config.ts: admin at /admin/content, /admin/edit/$collection/$id, /admin/review, ... +export const virtualRouteConfig = createRoutes(definition) ``` Package components build admin links with `adminPath('/content')` from `@tanstack/cms-core`, which prefixes the configured base path. With the `Register` augmentation (`interface Register { cms: typeof cms }`), `adminPath` is typed with the prefix too, so links stay type-safe against your route tree. @@ -151,7 +158,7 @@ Only the admin group moves; public and API routes keep their paths. The TanStack Router generator rewrites the path literal inside `createFileRoute('...')` of every route file it processes so that it matches the file's position in the tree. Mounting the package's `content.tsx` at `/admin/content` in place would therefore rewrite a file inside `node_modules`. -So when `adminBasePath` is set, `cmsVirtualRoutes()` writes a prefixed copy of each admin route file and mounts the copies instead. Each copy has its `createFileRoute` path set to the prefixed URL, its relative imports pointed back at the package's original modules, and a `// @ts-nocheck` header. By default the copies go into a `.generated//` directory inside `@tanstack/cms-ui-react` (the hash is derived from your routes directory and base path), so they resolve the same dependencies as the originals. Set `generatedDirectory` to write them somewhere else. Copies are only rewritten when their content changes. +So when `admin.basePath` is set, `createRoutes()` writes a prefixed copy of each admin route file and mounts the copies instead. Each copy has its `createFileRoute` path set to the prefixed URL, its relative imports pointed back at the package's original modules, and a `// @ts-nocheck` header. By default the copies go into a `.generated//` directory inside `@tanstack/cms-ui-react` (the hash is derived from your routes directory and base path), so they resolve the same dependencies as the originals. Set `tanstackCms({ generatedDirectory })` to write them somewhere else. Plugin `adminRoutes` shipped inside a package get the same treatment. Copies are only rewritten when their content changes. ## Type-Checking Across the Package Boundary diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md index 1be17693..bb53d341 100644 --- a/docs/architecture/terminology.md +++ b/docs/architecture/terminology.md @@ -26,7 +26,7 @@ The core API is being refactored before 1.0. This page fixes the words used in t | [Live vs working copy](#live-vs-working-copy) | Implemented; the read mode on the context is planned | | [Access context](#access-context) and its modes | Planned | | [Actor](#actor) | Partly implemented; the shape is still being reviewed | -| [Definition vs runtime config](#definition-vs-runtime-config) | Planned | +| [Definition vs runtime config](#definition-vs-runtime-config) | Implemented | ## API cancer @@ -116,11 +116,11 @@ Planned builders: `publicContext()`, `accessContext({ session })`, `systemContex ## Definition vs runtime config -**Planned.** An app's CMS setup splits into two files: +**Implemented.** An app's CMS setup splits into two files: - **Definition** (`cms.definition.ts`, built with `defineCmsDefinition` from `@tanstack/cms-core/definition`): pure data. Collections, admin base path, plugin definitions. It imports no React, no TanStack Start and no server code, so build tools such as `createRoutes(definition, …)` and Vite can load it safely. It exposes derived accessors such as `adminBasePath()` and `collections()`. - **Runtime config** (`cms.config.ts`): extends the definition with auth, storage, AI, ops, event handlers and seed data: `defineCms(definition, { auth, storage, … })`. Nothing from the definition is repeated. A CI check loads every definition in plain Node to keep it light. An app whose config is already light may keep one file. -**Today:** one `cms.config.ts` built with `defineCms(...)`, imported by the server, plus separate route options passed to `cmsVirtualRoutes(...)`. +**Today:** `defineCms(config)` with one config still works, but `vite.config.ts` mounts the routes with `createRoutes(definition, spec?)`, which reads the admin base path and plugin routes from the definition, so every app has at least a minimal `cms.definition.ts`. diff --git a/docs/comparison/cms-landscape.md b/docs/comparison/cms-landscape.md index 1bca9867..c78038d2 100644 --- a/docs/comparison/cms-landscape.md +++ b/docs/comparison/cms-landscape.md @@ -26,7 +26,7 @@ TanStack CMS combines **schema-as-code**, **on-page visual + AI editing**, **rol | **Storage Engine** | Pluggable `StorageAdapter`: `node:sqlite` by default, libSQL / Turso via `@tanstack/cms-store-libsql`; media on local disk or S3 / R2 via `@tanstack/cms-media-s3` | MongoDB / Postgres / SQLite via Drizzle | SQLite / D1 | Files on disk | Hosted Content Lake | MySQL / MariaDB | | **Schema Definition** | TypeScript (`defineCms`): 20 field types, Standard Schema validation, collection hooks | TypeScript config files | JSON / TypeScript seed & SQL | Content Collections (Zod + frontmatter) | TypeScript / JS schema objects | PHP / MySQL post types + plugins (ACF) | | **Rich Text Storage** | GitHub-Flavored Markdown (incl. GFM tables & alerts) + typed `blocks` array | Lexical JSON AST | Portable Text JSON AST | `.md` / `.mdx` files on disk | Portable Text JSON AST | HTML + Gutenberg `` comments | -| **Routes Shipped from Package** | Yes (`cmsVirtualRoutes()` from `@tanstack/cms-ui-react`; override or drop any route, optional admin prefix) | Installs route files into Next.js `/app/(payload)` | Astro integration routes | Astro route integration | Studio mounted at route | Built-in PHP routing | +| **Routes Shipped from Package** | Yes (`createRoutes(definition)` from `@tanstack/cms-ui-react`; mount, replace, or drop any route by key, optional admin prefix) | Installs route files into Next.js `/app/(payload)` | Astro integration routes | Astro route integration | Studio mounted at route | Built-in PHP routing | | **On-Page Visual + AI Editing** | Built-in, stable (`Ctrl`/`Option` + click any block or field; inline + AI) | Live Preview (iframe) + separate admin forms | Admin UI forms | Static files (edit in IDE) | Presentation tool (visual editing) | Gutenberg block editor | | **Conversational Content Agent** | Built-in (`/agent` via `@tanstack/ai`, bring your own model) | Custom / plugin | External via MCP | None | AI Assist (field-level) | Third-party plugins | | **HTTP MCP Server** | Built-in (`/api/mcp`, authenticated with role-scoped API keys) | Community / custom | Built-in MCP server | None | Official MCP server | Community plugins | @@ -66,11 +66,11 @@ TanStack CMS enforces governance at the store boundary: ### 4. Routes Served from a Package -Consuming apps do not scaffold dozens of route files into their repository. `cmsVirtualRoutes()` from `@tanstack/cms-ui-react/virtual-routes` mounts the public, admin, and API routes through TanStack Start's `virtualRouteConfig`, alongside the app's own routes. Your app stays thin: +Consuming apps do not scaffold dozens of route files into their repository. `createRoutes(definition)` from `@tanstack/cms-ui-react/virtual-routes` mounts the public, admin, and API routes through TanStack Start's `virtualRouteConfig`, alongside the app's own routes. Your app stays thin: - `src/cms.config.ts` (your collections, blocks, seed, auth, AI adapters, storage, and media) - `src/router.tsx` (imports `./cms.config` and constructs the router) -- `vite.config.ts` (adds `tanstackCms()` and `cmsVirtualRoutes()`) +- `vite.config.ts` (adds `tanstackCms()` and `createRoutes(definition)`) `npx tanstack-cms init` writes or patches all three. Upgrading the packages upgrades every CMS route. When you need control, replace a single route with your own file, drop it, or move the admin under a prefix such as `/admin`. diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index e379dad9..c94bb8ed 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -65,24 +65,29 @@ Authors' saves are now staged in the review queue rather than committed. ```diff -import { cmsVirtualRoutes } from '@tanstack/cms-core/virtual-routes' -+import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' ++import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { tanstackCms } from '@tanstack/cms-ui-react/vite' ++import { definition } from './src/cms.definition' export default defineConfig({ plugins: [ + tanstackCms(), tailwindcss(), - tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } }), +- tanstackStart({ router: { virtualRouteConfig: cmsVirtualRoutes() } }), ++ tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro(), viteReact(), ], }) ``` -`cmsVirtualRoutes` is no longer exported from the `@tanstack/cms-ui-react` root -entry. `tanstackCms()` keeps the CMS packages out of SSR externals and -dependency pre-bundling, which the published packages need. Regenerate -`routeTree.gen.ts` after upgrading (start the dev server once). +The route builder is `createRoutes(definition, spec?)` from +`@tanstack/cms-ui-react/virtual-routes` (see [section 21](#21-createroutes-replaces-cmsvirtualroutes)), +and `definition` comes from `src/cms.definition.ts` (see +[section 20](#20-the-content-model-moves-to-cmsdefinitionts)). `tanstackCms()` +keeps the CMS packages out of SSR externals and dependency pre-bundling, which +the published packages need. Regenerate `routeTree.gen.ts` after upgrading +(start the dev server once). ### 4. The HTTP API is versioned @@ -272,6 +277,41 @@ Optional, and recommended. `defineCms(config)` with one config keeps working. Th `pnpm codemod definition-split `, run from a TanStack CMS checkout, writes `cms.definition.ts` next to each `cms.config.ts` and rewrites the config. It leaves hooks and access on the collections; move any that import server code into the runtime `collections` by hand. `tanstack-cms init` scaffolds both files. See [`defineCmsDefinition()`](../api/cms-core#the-cms-definition-definecmsdefinition). +### 21. `createRoutes` replaces `cmsVirtualRoutes` + +`cmsVirtualRoutes(options)` is removed. `createRoutes(definition, spec?)` takes the app's definition and reads the admin base path and plugin routes from it, so they're set once instead of in both the definition and `vite.config.ts`. The spec names routes by surface (`public`, `admin`, `api`), and each surface takes `true`, `false`, a list of route keys, or an object that drops (`false`) or replaces (a file path) single keys. A surface you leave out is mounted. + +| `cmsVirtualRoutes` option | `createRoutes` | +| --- | --- | +| `include: { public: false }` | `public: false` | +| `routes: { post: './post.tsx', agent: false }` | `public: { post: './post.tsx' }, admin: { agent: false }` | +| `adminBasePath: '/admin'` | `defineCmsDefinition({ admin: { basePath: '/admin' } })` | +| `plugins: [analytics]` | `defineCmsDefinition({ plugins: [analytics] })` | +| `children: [...]` | `custom: [...]` | +| `rootFile` | `rootFile` | +| `routesDirectory`, `generatedDirectory` | `tanstackCms({ routesDirectory, generatedDirectory })` | +| type `CmsVirtualRoutesOptions` | type `CreateRoutesSpec` | + +```ts +// before +cmsVirtualRoutes({ + adminBasePath: '/admin', + include: { public: false }, + routes: { agent: false }, + children: [route('/pricing', 'pricing.tsx')], +}) +// after +createRoutes(definition, { + public: false, + admin: { agent: false }, + custom: [route('/pricing', 'pricing.tsx')], +}) +``` + +`pnpm codemod create-routes `, run from a TanStack CMS checkout, rewrites the calls and imports in `vite.config.ts` and Markdown code blocks, and adds `import { definition } from './src/cms.definition'`. It warns where you have to finish by hand: an `adminBasePath` or `plugins` value has to be in the definition, and options it can't read statically are left for you. Run `pnpm codemod definition-split` first if the app has no `cms.definition.ts`. A leftover old option throws with its replacement in the message. + +`tanstackCms()` has to come before `tanstackStart()` in `plugins`, because `createRoutes()` reads its `routesDirectory` and `generatedDirectory` when Start loads the router config. The route keys (`CmsRouteKey`, and `CMS_ROUTE_KEYS` from `@tanstack/cms-core/definition`) are stable public API. + ## Versioning policy From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The diff --git a/docs/getting-started/agent-skills.md b/docs/getting-started/agent-skills.md index 6431b157..6f77a77d 100644 --- a/docs/getting-started/agent-skills.md +++ b/docs/getting-started/agent-skills.md @@ -36,7 +36,7 @@ Each skill follows the same seven-step workflow: 1. **Prerequisites** - Locate the source repo, seed file, or export and the target workspace directory. 2. **Discover the source** - Inventory collections, post types, fields, blocks, rich-text formats, media references, and features that need a decision (auth, taxonomies, custom hooks). -3. **Scaffold the target app** - Create a TanStack Start app that depends on `@tanstack/cms-core` and `@tanstack/cms-ui-react`, with a `vite.config.ts` that mounts `cmsVirtualRoutes()` from `@tanstack/cms-ui-react/virtual-routes`, a `tsconfig.json`, and a `src/router.tsx` that imports `./cms.config`. +3. **Scaffold the target app** - Create a TanStack Start app that depends on `@tanstack/cms-core` and `@tanstack/cms-ui-react`, with a `vite.config.ts` that mounts `createRoutes(definition)` from `@tanstack/cms-ui-react/virtual-routes`, a `tsconfig.json`, and a `src/router.tsx` that imports `./cms.config`. 4. **Map the schema (`src/cms.config.ts`)** - Translate source collections and fields into `defineCms({ collections, blockTypes, seed, theme })`. 5. **Migrate the data (`src/seed-data.ts`)** - Run the skill's converter script to transform source content and rich-text trees into `seedDocuments`, which the config passes as `seed: { documents: seedDocuments }`. 6. **Verify parity** - Run `tsc --noEmit`, boot the dev server, query `POST /api/cms/v1/ops/listDocumentSummaries` with `{"collection":"post","status":"all"}`, compare document counts and `published` flags against the source, and spot-check rendered pages at `/p/$id` and `/post/$id`. diff --git a/docs/getting-started/overview.md b/docs/getting-started/overview.md index 4dd287e9..f7e17586 100644 --- a/docs/getting-started/overview.md +++ b/docs/getting-started/overview.md @@ -46,7 +46,7 @@ Port an existing Payload, Astro Starlight, EmDash, or WordPress project with a m ## One Config File Per App -A consuming TanStack Start application does not copy admin components or route files into its own `src/`. It registers its content model once with `defineCms()`, mounts the CMS routes with `cmsVirtualRoutes()` in `vite.config.ts`, and imports the config from its router: +A consuming TanStack Start application does not copy admin components or route files into its own `src/`. It registers its content model once with `defineCms()`, mounts the CMS routes with `createRoutes(definition)` in `vite.config.ts`, and imports the config from its router: ```ts validate=type import { defineBlock, defineCms, defineCollection } from '@tanstack/cms-core' @@ -122,7 +122,7 @@ The operations registry (`ops`, `invokeOp`), the MCP server (`cmsMcp`), and AI c ### `@tanstack/cms-ui-react` -The React admin and public UI: `AdminShell`, `MarkdownEditor`, `MediaImg`, auth bindings (`CmsAuthProvider`, `useCmsAuth`, `useCan`, `createMockAuth`), and `unstable_WebMcpBadge` from `@tanstack/cms-ui-react`; public site shells (`SiteShell`, `DocsLayout`), block renderers (`BlocksView`, `BlockView`), and the on-page editors (`InteractiveDocument`, `InteractivePageContent`, `InteractivePostContent`, plus their `unstable_*` aliases) from `@tanstack/cms-ui-react/site`. Mount its routes with `cmsVirtualRoutes()` from `@tanstack/cms-ui-react/virtual-routes`, and add the `tanstackCms()` Vite plugin from `@tanstack/cms-ui-react/vite`. +The React admin and public UI: `AdminShell`, `MarkdownEditor`, `MediaImg`, auth bindings (`CmsAuthProvider`, `useCmsAuth`, `useCan`, `createMockAuth`), and `unstable_WebMcpBadge` from `@tanstack/cms-ui-react`; public site shells (`SiteShell`, `DocsLayout`), block renderers (`BlocksView`, `BlockView`), and the on-page editors (`InteractiveDocument`, `InteractivePageContent`, `InteractivePostContent`, plus their `unstable_*` aliases) from `@tanstack/cms-ui-react/site`. Mount its routes with `createRoutes(definition)` from `@tanstack/cms-ui-react/virtual-routes`, and add the `tanstackCms()` Vite plugin from `@tanstack/cms-ui-react/vite`. ### Optional packages diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md index 4e7358b3..4e877ad5 100644 --- a/docs/getting-started/quick-start.md +++ b/docs/getting-started/quick-start.md @@ -57,13 +57,13 @@ npx tanstack-cms init `init` makes four changes and prints what it did: 1. **Creates `src/cms.definition.ts` and `src/cms.config.ts`** (in the app root when there is no `src/` directory): the definition holds a starter `post` collection, and the config adds one seeded `hello-world` post and the `Register` declaration that types the rest of the CMS. If either file exists, both are left alone unless you pass `--force`. -2. **Patches `vite.config.ts`** (also `.mts` / `.js`). If the file calls `tanstackStart()` with no arguments, `init` adds the `tanstackCms()` plugin and `cmsVirtualRoutes()`. If `tanstackStart` already has options, it prints the snippet for you to add by hand. +2. **Patches `vite.config.ts`** (also `.mts` / `.js`). If the file calls `tanstackStart()` with no arguments, `init` adds the `tanstackCms()` plugin and `createRoutes(definition)`. If `tanstackStart` already has options, it prints the snippet for you to add by hand. 3. **Patches `src/router.tsx`** (or `router.ts`) to import `./cms.config` for its side effect. If there is no router module, it prints the import line instead. 4. **Adds `.data/` to `.gitignore`**, where the database and uploads live in development. ## 3. Check the Vite config -After `init`, your `vite.config.ts` should include `tanstackCms()` and pass `cmsVirtualRoutes()` to TanStack Start: +After `init`, your `vite.config.ts` should include `tanstackCms()` and pass `createRoutes(definition)` to TanStack Start: ```ts validate=type import { defineConfig } from 'vite' @@ -71,8 +71,9 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' export default defineConfig({ plugins: [ @@ -80,7 +81,7 @@ export default defineConfig({ tailwindcss(), tanstackStart({ router: { - virtualRouteConfig: cmsVirtualRoutes(), + virtualRouteConfig: createRoutes(definition), }, }), nitro(), @@ -90,14 +91,21 @@ export default defineConfig({ ``` - `tanstackCms()` keeps the CMS packages (and `@tanstack/ai*`) out of Vite's SSR externals and dependency pre-bundling. The packages ship TanStack Start server functions and route files that your app's Start compiler must transform, so this plugin is required. -- `cmsVirtualRoutes()` registers the CMS public, admin, and API routes without taking over your app's `routesDirectory`. Your own routes in `src/routes` keep working alongside them. +- `createRoutes(definition)` registers the CMS public, admin, and API routes without taking over your app's `routesDirectory`. Your own routes in `src/routes` keep working alongside them. `vite.config.ts` imports only `src/cms.definition.ts`, never the runtime config. -`cmsVirtualRoutes()` also accepts `adminBasePath` to move the admin under a prefix, `routes` to replace or drop individual CMS routes, `include` to mount only some route groups, and `children` for extra routes. To serve the admin at `/admin/content`, set the prefix in both places: +A second argument says what to mount. Each surface (`public`, `admin`, `api`) takes `true`, `false`, a list of route keys, or an object that drops (`false`) or replaces (a file path) single routes, and `custom` adds your own routes: ```ts -// vite.config.ts -virtualRouteConfig: cmsVirtualRoutes({ adminBasePath: '/admin' }) +createRoutes(definition, { + public: false, + admin: { agent: false }, + custom: [route('/pricing', 'pricing.tsx')], +}) +``` +The admin base path comes from the definition. To serve the admin at `/admin/content`, set it there: + +```ts // src/cms.definition.ts defineCmsDefinition({ /* ... */ admin: { basePath: '/admin' } }) ``` diff --git a/docs/mcp/webmcp.md b/docs/mcp/webmcp.md index 2ff5cb35..bf274319 100644 --- a/docs/mcp/webmcp.md +++ b/docs/mcp/webmcp.md @@ -29,7 +29,7 @@ The CMS root route renders the WebMCP badge inside ``, so apps 3. **Tool registration.** It registers every entry of `opSchemas` (the twelve [agent tools](./operations-registry#the-agent-tool-registry-opschemas)) on the in-page server. Each tool handler sends `POST /api/cms` with `{ op, input }` and returns the result, or the error object with `isError: true`. 4. **Status badge.** Once connected it shows a small "WebMCP · 12 tools" pill in the bottom-right corner. -If you replace the root route (`cmsVirtualRoutes({ rootFile })`), render the badge yourself inside your `CmsAuthProvider`: +If you replace the root route (`createRoutes(definition, { rootFile })`), render the badge yourself inside your `CmsAuthProvider`: ```tsx validate=type import type { ReactNode } from 'react' diff --git a/docs/migration/from-emdash.md b/docs/migration/from-emdash.md index 1636cec3..f8817066 100644 --- a/docs/migration/from-emdash.md +++ b/docs/migration/from-emdash.md @@ -23,7 +23,7 @@ EmDash and TanStack CMS are close neighbours: both are TypeScript, SQL-backed, a | Layer | EmDash | TanStack CMS | |---|---|---| -| **Framework** | Astro integration with page templates in your repo | TanStack Start; routes come from `@tanstack/cms-ui-react` through `cmsVirtualRoutes()` and can be replaced or dropped | +| **Framework** | Astro integration with page templates in your repo | TanStack Start; routes come from `@tanstack/cms-ui-react` through `createRoutes(definition)` and can be replaced or dropped | | **Runtime & storage** | Cloudflare Workers with D1, or SQLite/libSQL/Postgres | Node with `createSqliteStorage()` by default, `createD1Storage()` for Cloudflare D1, or `createLibsqlStorage()` for Turso; local or S3-compatible media (including R2) | | **Schema** | Collections described as JSON (`seed.json`, admin-editable) | TypeScript schema-as-code in `defineCms({ collections, blockTypes })` | | **Rich text** | Portable Text JSON | GitHub-Flavored Markdown plus typed blocks | diff --git a/docs/migration/from-payload.md b/docs/migration/from-payload.md index d72e5e63..d1573cad 100644 --- a/docs/migration/from-payload.md +++ b/docs/migration/from-payload.md @@ -23,7 +23,7 @@ Payload v3 and TanStack CMS are both **code-first TypeScript CMSs** with schema | Layer | Payload CMS (v3) | TanStack CMS | |---|---|---| -| **Framework & routing** | Next.js App Router; admin route files live in your app (`src/app/(payload)/...`) | TanStack Start; the admin, public, and API routes come from `@tanstack/cms-ui-react` through `cmsVirtualRoutes()`, and you can replace or drop any of them | +| **Framework & routing** | Next.js App Router; admin route files live in your app (`src/app/(payload)/...`) | TanStack Start; the admin, public, and API routes come from `@tanstack/cms-ui-react` through `createRoutes(definition)`, and you can replace or drop any of them | | **Database** | Adapters for Postgres, MongoDB, or SQLite (Drizzle) plus migration files | A `StorageAdapter`: `createSqliteStorage()` (`node:sqlite`) by default, `createLibsqlStorage()` for Turso/libSQL; versioned migrations run automatically | | **Schema** | Collection and global config objects + `payload generate:types` | `defineCms({ collections, blockTypes })` drives validation, admin forms, the renderer, the HTTP API, and MCP tools; types flow through the `Register` interface | | **Rich text** | Lexical JSON editor state | GitHub-Flavored Markdown in `markdown`/`richtext` fields, plus typed `blocks` | @@ -218,7 +218,7 @@ declare module '@tanstack/cms-core' { } ``` -Mount the routes in `vite.config.ts` with `tanstackCms()` from `@tanstack/cms-ui-react/vite` and `cmsVirtualRoutes({ adminBasePath: '/admin' })` from `@tanstack/cms-ui-react/virtual-routes`, so the admin stays at Payload's `/admin` URL. +Set `admin: { basePath: '/admin' }` in `defineCmsDefinition()` so the admin stays at Payload's `/admin` URL, and mount the routes in `vite.config.ts` with `tanstackCms()` from `@tanstack/cms-ui-react/vite` and `createRoutes(definition)` from `@tanstack/cms-ui-react/virtual-routes`. ## 2. Convert Lexical and Load the Content diff --git a/docs/migration/from-sanity.md b/docs/migration/from-sanity.md index 0754a991..8fd94164 100644 --- a/docs/migration/from-sanity.md +++ b/docs/migration/from-sanity.md @@ -26,7 +26,7 @@ Both define schemas in TypeScript. They differ in who hosts the data, how it's q |---|---|---| | **Storage** | Hosted Content Lake | Self-hosted `StorageAdapter`: `createSqliteStorage()` by default, `createLibsqlStorage()` for Turso | | **Querying** | GROQ (or GraphQL) + `sanity typegen` | `queryDocuments`/`readDocument` on the server, the REST API (`/api/cms/v1`, OpenAPI 3.1), and the typed `@tanstack/cms-client`; types flow from `defineCms()` through `Register` | -| **Studio** | A separate React app at `/studio` or hosted | Admin and public routes from `@tanstack/cms-ui-react`, mounted with `cmsVirtualRoutes()` | +| **Studio** | A separate React app at `/studio` or hosted | Admin and public routes from `@tanstack/cms-ui-react`, mounted with `createRoutes(definition)` | | **Rich text** | Portable Text | GitHub-Flavored Markdown plus typed blocks | | **Visual editing** | Presentation tool with stega-encoded strings | On-page editing of the rendered blocks and fields | | **Images** | Image CDN with `asset._ref` and URL transforms | A media library (local or `createS3Media()`) with `?w=` / `format=` transforms on `/api/media/` | diff --git a/docs/migration/from-wordpress.md b/docs/migration/from-wordpress.md index 17d7b5cb..8565c132 100644 --- a/docs/migration/from-wordpress.md +++ b/docs/migration/from-wordpress.md @@ -24,7 +24,7 @@ WordPress is a PHP monolith whose schema lives implicitly in `wp_posts`, `wp_pos | Layer | WordPress | TanStack CMS | |---|---|---| -| **Runtime** | PHP + MySQL/MariaDB, themes, and runtime plugin hooks | Node + TanStack Start; routes from `@tanstack/cms-ui-react` through `cmsVirtualRoutes()` | +| **Runtime** | PHP + MySQL/MariaDB, themes, and runtime plugin hooks | Node + TanStack Start; routes from `@tanstack/cms-ui-react` through `createRoutes(definition)` | | **Storage** | `wp_posts` + key-value `wp_postmeta` | Typed JSON documents in a `StorageAdapter` (`createSqliteStorage()` by default, `createLibsqlStorage()` for Turso), with revisions | | **Schema** | Post types, `register_post_type()`, ACF field groups | `defineCms({ collections, blockTypes })` drives validation, admin forms, the renderer, the HTTP API, and MCP tools | | **Content** | HTML with Gutenberg block comments, or classic HTML | GitHub-Flavored Markdown plus typed blocks | diff --git a/docs/migration/overview.md b/docs/migration/overview.md index f021ca97..4c758ec6 100644 --- a/docs/migration/overview.md +++ b/docs/migration/overview.md @@ -40,7 +40,7 @@ Every converter exports a `*ToMarkdown` function and a `*ToBlocks` function that | Layer | Typical incumbent | TanStack CMS | |---|---|---| -| **Routes & admin** | Route files scaffolded into your app, or a separate admin app | Routes from `@tanstack/cms-ui-react`, mounted with `cmsVirtualRoutes()` from `@tanstack/cms-ui-react/virtual-routes`; any route can be replaced (`routes: { post: './my-post.tsx' }`) or dropped (`false`), and the admin can move (`adminBasePath`) | +| **Routes & admin** | Route files scaffolded into your app, or a separate admin app | Routes from `@tanstack/cms-ui-react`, mounted with `createRoutes(definition, spec?)` from `@tanstack/cms-ui-react/virtual-routes`; any route can be replaced (`public: { post: './my-post.tsx' }`) or dropped (`false`), and the admin can move (`admin.basePath` in the definition) | | **Storage** | Postgres/MySQL/MongoDB, a hosted content lake, or git files | A `StorageAdapter`: `createSqliteStorage()` (`node:sqlite`) by default, `createLibsqlStorage()` from `@tanstack/cms-store-libsql` for Turso; media in `createLocalMedia()` or `createS3Media()` from `@tanstack/cms-media-s3` | | **Schema** | Framework config, PHP post types, or Studio schemas | `defineCms({ collections, blockTypes })` with field types from `text` to `relation`, `group`, and `array`, plus `required`, `unique`, `index`, `defaultValue`, `validate`, and field access | | **Rich text** | Lexical, Portable Text, or Gutenberg HTML | GitHub-Flavored Markdown plus typed `blocks` | @@ -52,7 +52,7 @@ Every converter exports a `*ToMarkdown` function and a `*ToBlocks` function that ### 1. Scaffold -Run `npx tanstack-cms init` in a TanStack Start app (from `@tanstack/cms-cli`), or copy [`examples/blog`](https://github.com/TanStack/tanstack-cms/blob/main/examples/blog). Dependencies are `@tanstack/cms-core` and `@tanstack/cms-ui-react` (which brings `@tanstack/cms-api`); `vite.config.ts` adds `tanstackCms()` from `@tanstack/cms-ui-react/vite` and passes `cmsVirtualRoutes()` to `tanstackStart({ router: { virtualRouteConfig } })`. +Run `npx tanstack-cms init` in a TanStack Start app (from `@tanstack/cms-cli`), or copy [`examples/blog`](https://github.com/TanStack/tanstack-cms/blob/main/examples/blog). Dependencies are `@tanstack/cms-core` and `@tanstack/cms-ui-react` (which brings `@tanstack/cms-api`); `vite.config.ts` adds `tanstackCms()` from `@tanstack/cms-ui-react/vite` and passes `createRoutes(definition)` to `tanstackStart({ router: { virtualRouteConfig } })`, with `definition` imported from `src/cms.definition.ts`. ### 2. Map the schema (`src/cms.definition.ts`) diff --git a/docs/schema/building-pages.md b/docs/schema/building-pages.md index 35d6cf88..db8d5942 100644 --- a/docs/schema/building-pages.md +++ b/docs/schema/building-pages.md @@ -2,12 +2,12 @@ title: Building Pages & Custom Routes id: building-pages order: 3 -description: "Render CMS content in TanStack Start: the built-in public routes, loading documents with @tanstack/cms-api/start server functions or @tanstack/cms-core/server queries, adding custom routes next to cmsVirtualRoutes(), overriding or dropping package routes, SEO with cmsHead, and moving the admin under a base path." +description: "Render CMS content in TanStack Start: the built-in public routes, loading documents with @tanstack/cms-api/start server functions or @tanstack/cms-core/server queries, adding custom routes next to createRoutes(), overriding or dropping package routes, SEO with cmsHead, and moving the admin under a base path." keywords: - tanstack cms - building pages - custom routes - - cmsVirtualRoutes + - createRoutes - BlocksView - cmsHead - cmsJsonLd @@ -16,20 +16,21 @@ keywords: - queryDocuments - readDocumentBySlug - readSingleton - - adminBasePath + - admin basePath --- TanStack CMS runs inside your TanStack Start app. You can use the public routes it ships, replace any of them, and add your own routes that read CMS content. ## The built-in public routes -`cmsVirtualRoutes()` from `@tanstack/cms-ui-react/virtual-routes` mounts these public routes (the full list, including admin and API routes, is in [Routes & HTTP Endpoints](../api/routes-and-endpoints)): +`createRoutes(definition)` from `@tanstack/cms-ui-react/virtual-routes` mounts these public routes (the full list, including admin and API routes, is in [Routes & HTTP Endpoints](../api/routes-and-endpoints)): | Key | Path | Renders | | --- | --- | --- | | `index` | `/` | Home page for the theme variant: published documents (`default`), a post grid (`blog`), or the page with slug `/` in the docs layout (`docs`). | | `page` | `/p/$id` | A document by id or slug, preferring the `page` collection, rendered with its blocks. | | `post` | `/post/$id` | A document by id or slug, preferring the `post` collection, rendered as an article. | +| `preview` | `/preview/$collection/$id` | A draft, behind a preview token. | | `sitemap` | `/sitemap.xml` | Published documents of collections that define `path`. | | `robots` | `/robots.txt` | Allows everything except admin and API paths; links the sitemap. | | `notFound` | `/$` | Follows the redirects collection, else renders a 404. | @@ -116,7 +117,7 @@ const { items } = await cms.collection('post').published({ limit: 10 }) ## Adding custom routes -`cmsVirtualRoutes()` produces the whole virtual route tree, so route files in `src/routes` are not discovered on their own. Add your routes with `children`, using the builders from `@tanstack/virtual-file-routes` (paths are relative to `src/routes`): +`createRoutes()` produces the whole virtual route tree, so route files in `src/routes` are not discovered on their own. Add your routes with `custom`, using the builders from `@tanstack/virtual-file-routes` (paths are relative to `src/routes`): ```ts validate=type // vite.config.ts @@ -126,8 +127,9 @@ import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { physical, route } from '@tanstack/virtual-file-routes' -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' +import { definition } from './src/cms.definition' export default defineConfig({ plugins: [ @@ -135,8 +137,8 @@ export default defineConfig({ tailwindcss(), tanstackStart({ router: { - virtualRouteConfig: cmsVirtualRoutes({ - children: [ + virtualRouteConfig: createRoutes(definition, { + custom: [ route('/pricing', './pricing.tsx'), route('/blog/$slug', './blog.$slug.tsx'), physical('/shop', 'shop'), // every file in src/routes/shop @@ -191,32 +193,27 @@ function BlogPost() { ## Overriding or dropping package routes -Replace any built-in route with your own file, or leave it out, with `routes`. Keys are listed in [Routes & HTTP Endpoints](../api/routes-and-endpoints#route-table). A replacement path is relative to `src/routes` (or absolute), and the file must call `createFileRoute` with the same path: +Replace any built-in route with your own file, or leave it out, under its surface (`public`, `admin`, or `api`). Keys are listed in [Routes & HTTP Endpoints](../api/routes-and-endpoints#route-table). A replacement path is relative to `src/routes` (or absolute), and the file must call `createFileRoute` with the same path: ```ts validate=type -import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { definition } from './src/cms.definition' -export const routeConfig = cmsVirtualRoutes({ - routes: { - index: './home.tsx', // your own home page at '/' - post: './my-post.tsx', // must be createFileRoute('/post/$id') - agent: false, // no content agent page - }, +export const routeConfig = createRoutes(definition, { + public: { index: './home.tsx', post: './my-post.tsx' }, + admin: { agent: false }, }) ``` -To leave out a whole group, use `include`: `cmsVirtualRoutes({ include: { public: false } })` mounts only the admin and API routes, for example when your site has its own public routes. +A surface also takes `false` or a list of keys. `createRoutes(definition, { public: false })` mounts only the admin and API routes, for example when your site has its own public routes, and `admin: ['content', 'edit']` mounts just those two admin routes. ## Moving the admin under a base path -Mount the admin at `/admin/content`, `/admin/edit/…`, and so on by setting the same prefix in both places: +Mount the admin at `/admin/content`, `/admin/edit/…`, and so on by setting the prefix in the definition. `createRoutes(definition)` reads it from there: ```ts -// vite.config.ts -cmsVirtualRoutes({ adminBasePath: '/admin' }) - -// src/cms.config.ts -defineCms({ collections, blockTypes, admin: { basePath: '/admin' } }) +// src/cms.definition.ts +defineCmsDefinition({ collections, admin: { basePath: '/admin' } }) ``` Package components build admin links with `adminPath('/content')`, which reads `admin.basePath` (and is typed from it when you register your config). `/robots.txt` disallows the prefix. Public and API routes do not move. diff --git a/docs/schema/theming-and-variants.md b/docs/schema/theming-and-variants.md index 53dd7c99..575809fe 100644 --- a/docs/schema/theming-and-variants.md +++ b/docs/schema/theming-and-variants.md @@ -129,7 +129,7 @@ export function Banner() { In Tailwind classes, reference the variables directly: `bg-[var(--cms-surface)]`, `text-[var(--cms-muted)]`, `rounded-[var(--cms-radius)]`. -If you replace the root route (`cmsVirtualRoutes({ rootFile })`), keep the theme working by importing `@tanstack/cms-ui-react/styles.css` and rendering `themeCss(getTheme())` into a `