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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/locators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-client': minor
'@tanstack/cms-store-postgres': minor
---

Locators and nested slugs. Every document has a locator, its lookup key within the collection, derived by the collection's `locatorStrategy`. The default, `slugOrId`, uses the normalized slug, or the id when there is none. Locators are unique per collection and locale and are stored in their own index. `get({ collection, locator })` resolves through it, and `get`/`list` results carry `locator` next to `id`. A slug generated from the title (the field was empty) gets `-2`, `-3`, … on its last segment when its locator is taken; a given slug fails instead. Slug fields take `nested: true` for `/`-separated slugs (`guides/intro`), each segment validated and slugified on its own, and `/` alone is the collection root (locator `''`). New exports: `slugOrId`, `locatorStrategyOf`, `normalizeLocator`, and the `LocatorStrategy` and `LocatorInput` types. Storage adapters may implement the optional `findDocumentsByLocator` and store `DocumentIndex.locators`; adapters without them fall back to slug and id lookups.

**Breaking:**

- SQLite schema v17 and Postgres schema v9 add an empty `locators` table, unique on collection, locale and locator. The engine fills it from the stored documents on first start (and rebuilds it when the config changes how locators are derived). Documents that already share a locator are logged as a warning: the first id keeps it, and saving another fails until its slug changes. Collections whose slugs are only unique within a scope need a `locatorStrategy` that includes the scope.
- Writes (commit, stage, approve, restore) fail with `VALIDATION_FAILED` when the slug is another document's locator in the same collection and locale, or when a single-segment slug is another document's id.
- `get({ locator })` no longer finds a slugged document by its id. Use `get({ id })`.
- A `localized` slug field keeps its per-locale value on save instead of being regenerated from the title.
5 changes: 3 additions & 2 deletions docs/api/cms-core-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ function listAs(ctx: AccessContext, options?: ListOptions): Promise<ListResult>
type GetOptions = {
collection: string
staged?: boolean // `false`: the committed document, without staged changes
locale?: string // with `locator`: match the document in this locale
locale?: string // with `locator`: look it up in this locale (default locale first otherwise)
populate?: PopulateSelection // default true
} & ({ id: string } | { locator: string }) // exactly one

Expand All @@ -161,6 +161,7 @@ interface ListOptions {

interface ReadResult<TDoc = Doc, C extends string = string> {
id: string
locator: string | null // '' for the collection root; null when the strategy gives none
collection: C
doc: TDoc
relations?: Record<string, Doc | Array<Doc> | null> // unless `populate: false`
Expand Down Expand Up @@ -196,7 +197,7 @@ export async function addToCart(cartId: string, variantId: string) {
}
```

A `locator` is the document's slug or its id, with leading slashes ignored. A document that is missing, or that `ctx` can't see, is `null` from `get` and absent from `list`. Documents are redacted for `ctx`, and filtering or sorting on a field it can't read is `FORBIDDEN`. Both functions validate the bag (`getInput`, `listInput` from `@tanstack/cms-core`) and throw `BAD_REQUEST` for an invalid one.
A `locator` is the document's lookup key within its collection, from the collection's `locatorStrategy`. The default, `slugOrId`, uses the slug, or the id when the document has no slug. A `nested: true` slug keeps its slashes (`guides/intro`), and `/` or `''` is the collection root. Leading, trailing and doubled slashes are ignored, and matching is exact otherwise. Locators are per locale: with `locale` the lookup stays in that locale, otherwise the default locale is tried first, then the others. A slugged document isn't found by its id as a locator; use `id` for that. Each result carries its `locator` next to `id`. A document that is missing, or that `ctx` can't see, is `null` from `get` and absent from `list`. Documents are redacted for `ctx`, and filtering or sorting on a field it can't read is `FORBIDDEN`. Both functions validate the bag (`getInput`, `listInput` from `@tanstack/cms-core`) and throw `BAD_REQUEST` for an invalid one.

Both verbs populate relations by default. The related documents come back beside the document, under `relations`, keyed by relation field path (`author`, `seo.image`, `blocks.2.author`); `doc` keeps the ids. Population is one level deep: a related document's own relation fields stay ids, so cycles and self-references can't recurse. A related document is read and redacted as `ctx` reads it. A missing, trashed or hidden target is `null`, or dropped from a `many` array, whether the document or its whole collection is hidden, so a reader can't tell hidden from missing. `list` batches the reads: one storage read per target collection for the whole page, not one per row. Pass `populate: false` for ids only, or an array of paths to populate just those (and the relations under them). `related(result, path)` from `@tanstack/cms-core` reads one relation back, typed from `Register`: a registered relation field gives the target's document type, or an array for `many: true`.

Expand Down
14 changes: 14 additions & 0 deletions docs/api/cms-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -1265,6 +1265,20 @@ and `where`; `StorageGroup` is `{ value: unknown, count: number }`. Bucket order
is unspecified. Null and missing values share a bucket; arrays are grouped as
whole values.

Locators: the engine passes each document's locators to `putDocument` as
`DocumentIndex.locators` (`Array<{ locale, locator }>`, empty for a trashed
document). An adapter that stores them replaces the document's set on each
put, drops it with `deleteDocument`, rejects a `{ collection, locale, locator }`
another document holds with `VALIDATION_FAILED`, and implements the optional
`findDocumentsByLocator(collection, locator, locale?)`, returning
`Array<{ id, locale }>`. When `locators` is absent the stored set is left
alone. The engine fills an adapter's index from its stored documents on first
use (and after config changes to how locators are derived), with
`putDocument`. The SQL adapters and Postgres implement it; an adapter without
it, such as `createMarkdownStorage()`, falls back to slug and id lookups, or a
scan of the collection for the root, a custom `locatorStrategy`, or a
`localized` slug.

### Record and query types

| Type | Description |
Expand Down
2 changes: 1 addition & 1 deletion docs/api/routes-and-endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/
| Operation | Method | Access | Input | Result |
| --- | --- | --- | --- | --- |
| `getAuthSession` | GET | public | `{}` | The caller's `CmsSession` plus `ai: { text, image }` capabilities. |
| `get` | GET | public | `{ collection, id \| locator, staged?, locale?, populate? }` | `{ id, collection, doc, relations? }` or `null`. The canonical read ([`getAs`](./cms-core-server#getasctx-options-and-listasctx-options)): published only, except for callers who may read drafts of the collection and don't ask for `live`; drafts are read with staged changes overlaid, unless `staged` is `false`. Relations are populated one level deep unless `populate` is `false` (or a list of paths). |
| `get` | GET | public | `{ collection, id \| locator, staged?, locale?, populate? }` | `{ id, locator, collection, doc, relations? }` or `null`. The canonical read ([`getAs`](./cms-core-server#getasctx-options-and-listasctx-options)): published only, except for callers who may read drafts of the collection and don't ask for `live`; drafts are read with staged changes overlaid, unless `staged` is `false`. Relations are populated one level deep unless `populate` is `false` (or a list of paths). |
| `list` | GET | public | `{ collection?, locale?, where?, sort?: { field, dir? }, limit? (1–500, default 100), offset?, cursor?, populate? }` | `{ items: [{ id, collection, doc, relations? }], total, nextCursor? }`. The canonical list, with the same visibility and populate default as `get`. |
| `save` | POST | `content.write` | `{ collection, id, doc, create?, publish?, expectedRevision?, expectedPendingVersion?, instruction? }` | `{ id, collection, doc, state: { label, published, revision, changeSet }, availableActions }`. The canonical write ([`saveAs`](./cms-core-server#saveasctx-options-and-actasctx-options)): `doc` is a patch merged onto the caller's working copy. It commits for publishers (a draft of a published document unless `publish` is set) and is submitted for review otherwise. `CONFLICT` for a stale `expectedRevision` / `expectedPendingVersion`, or `create` on an existing id. |
| `act` | POST | `content.read` | `{ collection, id, action, publishAt?: string \| null, reason?, expectedVersion? }` | As `save`, with `doc` `null` once the document is gone. Runs an action the document's strategy offers the caller (`FORBIDDEN` otherwise); `edit`, `submit`, `draft` and `import` are `save`'s (`BAD_REQUEST`). |
Expand Down
10 changes: 5 additions & 5 deletions docs/architecture/terminology.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ The core API is being refactored before 1.0. This page fixes the words used in t
| Term | Status |
| --- | --- |
| [API cancer](#api-cancer) | A name for the problem, not code |
| [Locator](#locator) and [nested slugs](#nested-slugs) | Planned |
| [Locator](#locator) and [nested slugs](#nested-slugs) | Implemented; the default public path is planned |
| [Document state strategy](#document-state-strategy) | Planned |
| [Change set](#change-set) | Implemented as the pending row; strategy state planned |
| [Effect](#effect) | Planned |
Expand All @@ -36,17 +36,17 @@ Examples (before the refactor): five read verbs (`getPublicDocument`, `readDocum

## Locator

**Planned.** A document's canonical public lookup key, generated for every document. By default it is the slug when there is one, otherwise the id (the default `slugOrId` strategy). A collection can replace that rule with a `locatorStrategy`, for example products located by SKU. The default public path derives from the locator, and `path()` becomes an override for custom cases.
**Implemented**, except the public path. A document's canonical public lookup key, generated for every document. By default it is the slug when there is one, otherwise the id (the default `slugOrId` strategy). A collection can replace that rule with a `locatorStrategy`, for example products located by SKU. The default public path derives from the locator, and `path()` becomes an override for custom cases.

The locator lives in the system namespace next to `id`, so a user field named `locator` never collides. It is unique per collection and locale. Lookup by `id` stays available next to lookup by locator.

**Today:** a `slug` field plus `getPublicDocument({ slugOrId })`, which tries the id first and then the slug. Public URLs come from each collection's `path()`, which mostly uses the id.
**Today:** `get({ collection, locator })` resolves through the locator index, and results carry `locator` next to `id`. See [Locators](../schema/collections-and-fields#locators). The default public path and catch-all routes are still planned; public URLs come from each collection's `path()`. The older `getPublicDocument({ slugOrId })` keeps trying the id first and then the slug.

### Nested slugs

**Planned.** A slug field with `nested: true` may contain slashes (`guides/widgets`). Each segment is validated and slugified on its own. The full locator must be unique, so `guides/intro` and `intro` are different documents. A doc at `guides` may sit next to docs at `guides/intro`. A collection's home page has an explicit empty locator.
**Implemented.** A slug field with `nested: true` may contain slashes (`guides/widgets`). Each segment is validated and slugified on its own. The full locator must be unique, so `guides/intro` and `intro` are different documents. A doc at `guides` may sit next to docs at `guides/intro`. A collection's home page has an explicit empty locator, the slug `/`.

**Today:** the `slug` field type rejects `/`. Hierarchy lives in `path()` or in plain text fields.
**Today:** without `nested: true`, the `slug` field type still rejects `/`.

## Document state strategy

Expand Down
40 changes: 40 additions & 0 deletions docs/deployment/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,46 @@ older verbs still populate only when asked.
- **`populate` takes a list of paths** as well as a boolean, on every verb
that accepts it.

### 29. Locators and nested slugs

`get({ collection, locator })` now looks the document up in a locator index.
A locator is the slug, or the id of a document without one, and is unique
per collection and locale. Results carry it as `locator` next to `id`. Slug
fields take `nested: true` for `guides/intro`-style slugs, with `/` as the
collection root, and a collection can derive locators its own way with
`locatorStrategy`. See [Locators](../schema/collections-and-fields#locators).

- **The locator index is built on first start.** SQLite schema v17 and
Postgres schema v9 add an empty `locators` table with a unique key on
collection, locale and locator. The engine then fills it from the stored
documents, using each collection's `locatorStrategy` and every locale of a
`localized` slug, and rebuilds it whenever the config changes how
locators are derived. Before filling it, it checks for documents that
share a locator (the same slug, or one's slug equal to a slugless
document's id). Those are logged as a warning and the site keeps booting:
the first id keeps the locator, the others stay readable by id, and saving
one fails until it has a distinct slug. If your slugs are only unique
within a scope, such as a tenant or a product version, give the collection
a `locatorStrategy` that includes it, as `starters/multi-tenant-fleet` and
`starters/documentation-kb` now do.
- **Writes reject a taken locator.** A commit, stage, approval or restore
whose slug another document in the collection and locale already uses
fails with `VALIDATION_FAILED` on the slug field, and so does a
single-segment slug that is another document's id.
- **A locator no longer matches a slugged document's id.**
`get({ locator: 'abc123' })` used to find a document with id `abc123`
whatever its slug; now it finds only a document whose locator is
`abc123`. Use `get({ id })` for ids. The older slug-or-id verbs still try the id
first.
- **A localized slug is kept on save.** A `localized` slug field given a
per-locale value used to be regenerated from the title.
- **A slug generated from a title gets a suffix when it's taken.** When
the slug field is empty, the generated slug becomes `update-2`,
`update-3`, … (the last segment of a nested slug) if another document in
the collection and locale already has `update`. A slug you give is never
changed; it fails instead. Two staged creates that generate the same slug
both stage, and the second approval fails until the reviewer edits it.

## Versioning policy

From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The
Expand Down
2 changes: 1 addition & 1 deletion docs/mcp/operations-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/
| --- | --- | --- |
| `list_collections` | read | Collections and their fields |
| `list_documents` | read | The canonical `list`: documents of one collection (or every readable one) with `locale`, `where`, `sort`, paging (`limit`, `offset`, `cursor`) and `populate` (default `false`: relation fields stay ids). Returns `{ items: [{ id, collection, doc, relations? }], total, nextCursor? }` |
| `get_document` | read | The canonical `get`: one document by `id` or `locator`, including staged creates and updates in the agent's `edit` mode, with its relations populated (`populate: false` for ids only). Returns `{ id, collection, doc, relations }` or `null` |
| `get_document` | read | The canonical `get`: one document by `id` or `locator`, including staged creates and updates in the agent's `edit` mode, with its relations populated (`populate: false` for ids only). Returns `{ id, locator, collection, doc, relations }` or `null` |
| `read_document` | read | Deprecated, use `get_document`. One document by id, including staged creates and updates; `NOT_FOUND` when missing |
| `search_documents` | read | Full-text search and structured `where` / `sort` queries with collection, locale, a read `mode` (`live` for published only; never wider than the caller's), pagination (`limit`, `offset`, `cursor`), and `populate` (default `false`) |
| `list_revisions` | read | Revision history, newest first |
Expand Down
Loading
Loading