Skip to content

Commit 4a0017d

Browse files
cursoragentjherr
andcommitted
feat!: locator routes — publicPrefix, per-collection catch-all routes from createRoutes, shadowed-locator checks, and redirects when a published URL moves (3c(ii)) (#43)
Chain step 21 of the linear merge chain onto main 3b4a112: this PR's own changes, resolved against the PRs before it in the merge order. Co-authored-by: jherr <jherr@pobox.com>
1 parent a82e4de commit 4a0017d

49 files changed

Lines changed: 1715 additions & 153 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.changeset/locator-routes.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@tanstack/cms-core': minor
3+
'@tanstack/cms-ui-react': minor
4+
---
5+
6+
Collections served at their locators. A collection's `publicPrefix` (`'/docs'`, or `'/'` for the site root) serves each document at `{publicPrefix}/{locator}`: `createRoutes()` mounts a catch-all `{publicPrefix}/$` per such collection (the new `collections` spec key drops, limits or replaces them), and the prefix gives the collection a default `path`, so the sitemap, "View" links and page navigation use the same URL. `definition.collections()` carries `publicPrefix`. New exports: `documentPath`, `publicPrefixOf` and `normalizePublicPrefix` from `@tanstack/cms-core`, and `normalizePublicPrefix`, `SHADOWED_LOCATORS_KEY` and the `ShadowedLocators` type from `@tanstack/cms-core/definition`. `tanstackCms()` passes the route segments that shadow each collection's locators to the build as a `define`.
7+
8+
**Breaking:**
9+
10+
- When a commit, approval or scheduled publish changes the URL of a published document (from `path` or `publicPrefix`), the engine adds a permanent redirect from the old URL to the new one in the redirects collection, in the same transaction, and retargets redirects that pointed at the old URL. This applies to existing `path` functions built from the slug too, and only when the CMS has a redirects collection.
11+
- Writes to a `publicPrefix` collection fail with `VALIDATION_FAILED` when the locator's first segment is another route under the prefix (`api` or the admin base path at the site root, an app or plugin route, another collection's prefix). A generated slug steps past it.
12+
- A collection with `publicPrefix: '/'` mounts its catch-all at `/$` in place of `notFound`. `createRoutes()` throws when `notFound` is replaced by your own file, when a catch-all path is another route's, or when a prefix starts inside the admin or API routes. `defineCmsDefinition()` and `defineCms()` throw when two collections share a prefix.
13+
- When the `page` collection has a `publicPrefix`, the home page, site nav and docs sidebar link to its locator URLs instead of `/p/<id>`.

‎.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,10 @@ rules that need server code attach there by collection name
9393
(`defineCms({ collections, … })`).
9494

9595
One Starlight `docs` collection → one core collection. **Name it `page`** with
96-
a `blocks` field: the public renderer (`/p/$id`), the docs layout, and the
97-
on-page editor are wired to the `page`-with-`blocks` convention. Set
96+
a `blocks` field: the docs layout and the on-page editor are wired to the
97+
`page`-with-`blocks` convention. Give it `publicPrefix: '/docs'` (or `'/'` to
98+
serve the docs at the site root, where Starlight had them): `createRoutes`
99+
mounts a catch-all `/docs/$` that serves each page at its slug. Set
98100
`theme: { variant: 'docs' }`: the docs layout builds the sidebar from the
99101
`page` collection — grouped by the first slug segment, ordered by
100102
`sidebarOrder`, labelled by `sidebarLabel` (falling back to the title) — so a
@@ -106,21 +108,27 @@ Starlight `autogenerate` sidebar survives without extra code.
106108
| --------------------- | -------------- | ------------------------------------------------- | ------------------------------------------------------ |
107109
| `title` | `title` | `text`, `required: true` | `titleField: 'title'` |
108110
| `description` | `description` | `textarea` | `summaryField: 'description'` (the meta description) |
109-
| (file path) / `slug` | `slug` | `text`, `unique: true` | derived path, e.g. `/start/installation` |
111+
| (file path) / `slug` | `slug` | `slug`, `nested: true`, `required: true` | derived path, e.g. `/start/installation`; `/` = root |
110112
| `sidebar.label` | `sidebarLabel` | `text` | used by the docs sidebar |
111113
| `sidebar.order` | `sidebarOrder` | `number` | used by the docs sidebar |
112114
| `sidebar.badge` | `sidebarBadge` | `text` or `select` | stored; the built-in sidebar doesn't render badges |
113115
| `draft: true` | `published` | `boolean` | inverted: `published = draft !== true` |
114116
| `lastUpdated` | `lastUpdated` | `date` | optional |
115117
| custom `extend` keys | by type | `select`, `multiselect`, `date`, `url`, `json`, … | Zod `enum` → `select`, arrays of enums → `multiselect` |
116118
| body (Markdown) | `blocks` | `blocks` | one `richText` block, `markdown` = the body |
117-
| (old URL) | `redirect` doc | `redirectsCollection()` | `/start/installation/` → `/p/start-installation` |
119+
| (old URL) | `redirect` doc | `redirectsCollection()` | `/start/installation/` → `/docs/start/installation` |
118120

119121
Declare `summaryField: 'description'` on the collection: `cmsHead` reads the
120-
meta description from the summary role. Add a `path` that returns `/` for the root page and `/p/<id>` otherwise, so the
121-
sitemap lists every published page, and add `redirectsCollection()` to `collections` so
122-
the old Starlight URLs (and the cross-page links inside the Markdown) 301 to
123-
the new ones — the catch-all route follows the redirects collection.
122+
meta description from the summary role. The nested slug is the page's
123+
locator (unique per locale; `/` is the collection root), so with
124+
`publicPrefix` each page's URL — in the sidebar, the sitemap, and the admin's
125+
public link — is its slug under the prefix, with no `path` to write. Add
126+
`redirectsCollection()` to `collections` so the old Starlight URLs (and the
127+
cross-page links inside the Markdown) 301 to the new ones — the catch-all
128+
routes follow the redirects collection — and so moving a published page
129+
later leaves a redirect behind. With `publicPrefix: '/'` the old URLs need no
130+
redirects, but a slug can't start with a segment another route owns (`api`,
131+
`content`, `edit`, `p`, …; the engine rejects it).
124132

125133
`template: splash`, `hero`, `banner`, `prev`/`next`, `tableOfContents`, and
126134
i18n `locales` have no direct field mapping → gap report (a `hero` can become
@@ -138,8 +146,8 @@ renderers module (`defineRenderers({ blocks })`, named by
138146
Copy `scripts/read-frontmatter.mjs`, `scripts/mdx-to-markdown.mjs`, and
139147
`scripts/migrate-starlight.mjs` from this skill into the target app's
140148
`scripts/`. Edit the `CONFIG` block in `migrate-starlight.mjs` if your
141-
collection name, slug, or URL rules differ (`toSlug`, `toId`, `toUrl`,
142-
`REDIRECTS`). Then, pointing at the Starlight source directory:
149+
collection name, slug, or URL rules differ (`toSlug`, `toId`,
150+
`PUBLIC_PREFIX`, `REDIRECTS`). Then, pointing at the Starlight source directory:
143151

144152
```bash
145153
node scripts/migrate-starlight.mjs ../<name>-before --export cms-export.json
@@ -191,9 +199,10 @@ components themselves are the gap. Self-test: `node scripts/mdx-to-markdown.mjs`
191199
works (`seedContent({ force: true })` or `parseCmsExport` +
192200
`importContent`, then `listAs`/`getAs`); and
193201
`resolveRedirect('/start/installation/')` from `@tanstack/cms-core/server`
194-
returns the new URL. `closeStore()` after each test.
202+
returns the new URL, and `get({ collection: 'page', locator })` finds each
203+
redirect's target. `closeStore()` after each test.
195204
- Live check: `pnpm --filter <app> dev`; the sidebar matches Starlight's,
196-
`/p/home` and `/p/start-installation` render, `curl -I localhost:<port>/start/installation/`
205+
`/docs` and `/docs/start/installation` render, `curl -I localhost:<port>/start/installation/`
197206
answers 301, and `/sitemap.xml` lists the published pages.
198207
- Report counts, not just "done".
199208

‎.claude/skills/astro-starlight-to-tanstack-cms/scripts/migrate-starlight.mjs‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,9 @@ const OUT = join(here, '..', 'src', 'seed-data.ts')
4040
// ===========================================================================
4141
// CONFIG — the target core collection and how Starlight frontmatter maps onto
4242
// its fields. The body is always one `richText` block (markdown). Named `page`
43-
// so the core's public renderer (/p/:id) and on-page agent — both wired to the
44-
// `page` convention — work unchanged.
43+
// so the docs layout and on-page agent — both wired to the `page` convention —
44+
// work unchanged. The slug is a nested `slug` field, so `createRoutes` serves
45+
// each page at its locator under the collection's publicPrefix.
4546
// ===========================================================================
4647
const TARGET = 'page'
4748

@@ -58,9 +59,11 @@ const toSlug = (relPath) => {
5859
// with "/" → "-".
5960
const toId = (slug) =>
6061
slug === '/' ? 'home' : slug.replace(/^\//, '').replace(/\//g, '-')
61-
// The page's URL in the new app; the old Starlight URL (= its slug) redirects
62-
// here. REDIRECTS is the redirectsCollection() name (null to skip).
63-
const toUrl = (id) => `/p/${id}`
62+
// The page's URL in the new app — its slug under the collection's
63+
// publicPrefix — where the old Starlight URL (= its slug) redirects.
64+
// REDIRECTS is the redirectsCollection() name (null to skip).
65+
const PUBLIC_PREFIX = '/docs'
66+
const toUrl = (slug) => (slug === '/' ? PUBLIC_PREFIX : PUBLIC_PREFIX + slug)
6467
const REDIRECTS = 'redirect'
6568
// ===========================================================================
6669

@@ -112,7 +115,7 @@ function main() {
112115
if (REDIRECTS && slug !== '/' && data.draft !== true) {
113116
documents[REDIRECTS][toId(slug)] = {
114117
from: slug,
115-
to: toUrl(toId(slug)),
118+
to: toUrl(slug),
116119
permanent: true,
117120
}
118121
}

‎docs/api/cms-core.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,13 +188,13 @@ The definition's accessors are derived from it, never written by hand, and retur
188188
| Accessor | Returns |
189189
| --- | --- |
190190
| `adminBasePath()` | The normalized `admin.basePath`: `''` or `/segment` without a trailing slash. |
191-
| `collections()` | `{ name }` for each app and plugin collection, in order. Public URL prefixes come later. |
191+
| `collections()` | `{ name, publicPrefix? }` for each app and plugin collection, in order. `publicPrefix` is normalized (`'/docs'`, or `''` for the site root) and present only when the collection sets one; `createRoutes()` mounts a [catch-all](./routes-and-endpoints#collection-routes) for each. Two collections with the same prefix throw. |
192192
| `pluginRoutes()` | `{ routes, adminRoutes }`, each entry `{ plugin, route }`: the plugins' route nodes, tagged with the plugin name. |
193193
| `routeKeys()` | Every CMS route key (`index`, `content`, `edit`, `review`, `apiV1`, …). The list is `CMS_ROUTE_KEYS`, grouped by surface (`public`, `admin`, `api`); `CmsRouteKey` is its union. |
194194

195195
`definition.config` is the config as written. `isCmsDefinition(value)` tells a definition apart from a config.
196196

197-
`@tanstack/cms-core/definition` also exports the pure authoring helpers, so collection modules never need the package root: `defineCollection`, `defineInterfaceCollection`, `defineBlock`, `defineFieldType`, `definePluginDefinition`, `seoField`, `assetField`, `redirectsCollection`, `isSafeRedirectTarget`, and `isBuiltInFieldType`. These are the same functions the root exports. The entry also exports the types collections use, including `Collection`, `Field`, `BlockType`, `InferDoc`, `CollectionAccess`, `FieldAccess`, and `CmsPluginDefinition`. `definePlugin` stays root-only, because a plugin's runtime half carries ops and event handlers.
197+
`@tanstack/cms-core/definition` also exports the pure authoring helpers, so collection modules never need the package root: `defineCollection`, `defineInterfaceCollection`, `defineBlock`, `defineFieldType`, `definePluginDefinition`, `seoField`, `assetField`, `redirectsCollection`, `isSafeRedirectTarget`, `isBuiltInFieldType`, and `normalizePublicPrefix`. These are the same functions the root exports. The entry also exports the types collections use, including `Collection`, `Field`, `BlockType`, `InferDoc`, `CollectionAccess`, `FieldAccess`, `CmsPluginDefinition`, `LocatorStrategy`, and `LocatorInput`. `definePlugin` stays root-only, because a plugin's runtime half carries ops and event handlers.
198198

199199
```ts validate=type
200200
import { defineCms } from '@tanstack/cms-core'
@@ -779,7 +779,7 @@ function isFieldVisible(field: Field, siblings: Record<string, JsonValue | undef
779779
| `FieldValidator` | `StandardSchemaV1Like \| FieldValidatorFn`. |
780780
| `FieldValidatorFn` | `(value, { doc, id, collection }) => string \| true \| null \| undefined \| void` (or a Promise of it). A non-empty string is an error. |
781781
| `StandardSchemaV1Like` | The subset of the Standard Schema v1 interface the engine calls (`'~standard'.validate`). |
782-
| `Collection` | A collection definition (`name`, `label`, `titleField`, `fields`, `path?`, `isSingleton?`, `readOnly?`, `storage?`, `migrations?`, `access?`, `hooks?`, `admin?`, and field-role overrides). See [Collection options](../schema/collections-and-fields#collection-options). |
782+
| `Collection` | A collection definition (`name`, `label`, `titleField`, `fields`, `path?`, `publicPrefix?`, `locatorStrategy?`, `isSingleton?`, `readOnly?`, `storage?`, `migrations?`, `access?`, `hooks?`, `admin?`, and field-role overrides). See [Collection options](../schema/collections-and-fields#collection-options). |
783783
| `CollectionAdmin` | `{ columns?: Array<string>; defaultSort?: { field: string; dir?: 'asc' \| 'desc' } }`. |
784784
| `CollectionHooks` | Pre-commit lifecycle hooks: `preValidate`, `postValidate`, `preDelete`, plus the `postRead` response transform. `afterChange` / `afterDelete` are deprecated in favour of `defineEventHandler`. See [Events & Hooks](../architecture/events-and-hooks). |
785785
| `ChangeHookArgs` | `{ doc, id, operation, actor }` — what a pre-commit mutating hook receives. |

‎docs/api/cms-ui-react.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,11 @@ interface CreateRoutesSpec {
471471
public?: CmsRouteSurfaceSpec<'public'>
472472
admin?: CmsRouteSurfaceSpec<'admin'>
473473
api?: CmsRouteSurfaceSpec<'api'>
474+
// catch-alls at {publicPrefix}/$; default true unless public is false
475+
collections?:
476+
| boolean
477+
| ReadonlyArray<string>
478+
| { [collection: string]: boolean | string }
474479
custom?: ReadonlyArray<VirtualRouteNode>
475480
rootFile?: string
476481
renderers?: string // the app's renderers module, relative to the routes directory
@@ -492,7 +497,7 @@ type CmsRouteKey =
492497
type CmsSurfaceRouteKey<S extends CmsRouteSurface> // the keys of one surface
493498
```
494499

495-
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. `renderers` is the path of a module that exports `renderers = defineRenderers({ … })`; the CMS routes render blocks with it. It is a path rather than an import so `vite.config.ts` never loads React, and it must exist when the config loads. 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).
500+
The virtual route tree for the TanStack Router plugin: the public pages, the admin, and the API routes, a catch-all per collection with a `publicPrefix`, 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. `renderers` is the path of a module that exports `renderers = defineRenderers({ … })`; the CMS routes render blocks with it. It is a path rather than an import so `vite.config.ts` never loads React, and it must exist when the config loads. 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).
496501

497502
---
498503

@@ -511,6 +516,9 @@ interface CmsVitePlugin {
511516
config: () => {
512517
ssr: { noExternal: Array<string | RegExp> }
513518
optimizeDeps: { exclude: Array<string> }
519+
// set once createRoutes() has run: the route segments under each
520+
// collection's publicPrefix that its locators can't use
521+
define?: { __TANSTACK_CMS_SHADOWED_LOCATORS__: string }
514522
}
515523
resolveId: (
516524
id: string,
@@ -521,7 +529,7 @@ interface CmsVitePlugin {
521529
}
522530
```
523531

524-
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. In SSR, `resolveId` and `load` serve `use-sync-external-store` as ESM on React's own `useSyncExternalStore`, so a production server bundle under pnpm loads one React. `routesDirectory` and `generatedDirectory` are read by `createRoutes()`, which resolves route files when the config loads. When `createRoutes(definition, { renderers })` names a renderers module, the plugin's `load` hook serves the package's `app-renderers` module (which every CMS page route imports) as code that binds it. Add it before `tanstackStart()`.
532+
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. In SSR, `resolveId` and `load` serve `use-sync-external-store` as ESM on React's own `useSyncExternalStore`, so a production server bundle under pnpm loads one React. `routesDirectory` and `generatedDirectory` are read by `createRoutes()`, which resolves route files when the config loads. In return, the plugin passes the build the route segments that [shadow a collection's locators](./routes-and-endpoints#collection-routes), so writes can reject them. When `createRoutes(definition, { renderers })` names a renderers module, the plugin's `load` hook serves the package's `app-renderers` module (which every CMS page route imports) as code that binds it. Add it before `tanstackStart()`.
525533

526534
```ts validate=type
527535
import { defineConfig } from 'vite'

0 commit comments

Comments
 (0)