diff --git a/.changeset/locators.md b/.changeset/locators.md new file mode 100644 index 00000000..86b90c5d --- /dev/null +++ b/.changeset/locators.md @@ -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. diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index 39e50af0..99ed36f8 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -142,7 +142,7 @@ function listAs(ctx: AccessContext, options?: ListOptions): Promise 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 @@ -161,6 +161,7 @@ interface ListOptions { interface ReadResult { id: string + locator: string | null // '' for the collection root; null when the strategy gives none collection: C doc: TDoc relations?: Record | null> // unless `populate: false` @@ -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`. diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 82bf281a..9dd9e140 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -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 | diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index d2e8d25d..555e43d8 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -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`). | diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md index 3325b390..bc908a11 100644 --- a/docs/architecture/terminology.md +++ b/docs/architecture/terminology.md @@ -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 | @@ -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 diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index ddc041cd..fa9dce5e 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -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 diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index 9740bd8d..686bd130 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -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 | diff --git a/docs/schema/collections-and-fields.md b/docs/schema/collections-and-fields.md index b43828d7..ce989a87 100644 --- a/docs/schema/collections-and-fields.md +++ b/docs/schema/collections-and-fields.md @@ -131,6 +131,7 @@ export const cms = defineCms({ | `readOnly?` | `boolean` | Disallow creating, updating, staging, or deleting documents in this collection (`FORBIDDEN`). Automatically `true` when `storage` is a read-only adapter such as `createMarkdownStorage()`. | | `storage?` | `StorageAdapter` | Per-collection storage adapter (for example `createMarkdownStorage({ dir: 'content/posts' })`), overriding the global `defineCms({ storage })` for this collection's documents. | | `slugField?` | `string` | Field used for slug lookups. Defaults to a field named `slug` (`getSlugField()`). | +| `locatorStrategy?` | `LocatorStrategy` | How a document's locator is derived (see [Locators](#locators)). Defaults to `slugOrId`. | | `blocksField?` | `string` | Field holding the page body. Defaults to the first `blocks` field (`getBlocksField()`). | | `imageField?` | `string` | Featured image for thumbnails, the on-page editor, `cmsHead`, and JSON-LD. Defaults to the first `image` field (`getImageField()`). | | `summaryField?` | `string` | Short summary for cards, meta descriptions, and the on-page editor (`getSummaryField()`). No default. | @@ -163,7 +164,7 @@ export const cms = defineCms({ | `date` | `string` | `''` | ISO date `YYYY-MM-DD`. | | `datetime` | `string` | `''` | ISO datetime. | | `json` | `JsonValue` | `{}` | Any JSON value, edited as validated JSON text. | -| `slug` | `string` | `''` | Lowercase kebab-case. When empty on save, generated from `from` (default: the collection's `titleField`). | +| `slug` | `string` | `''` | Lowercase kebab-case. When empty on save, generated from `from` (default: the collection's `titleField`). With `nested: true`, `/`-separated kebab-case segments (`guides/intro`), or `/` for the collection root. The slug is the document's [locator](#locators). | | `email` | `string` | `''` | Format-checked email address. | | `url` | `string` | `''` | `http(s):`, `mailto:`, `tel:`, or a path starting with `/`. | | `color` | `string` | `''` | Hex color (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`). | @@ -232,6 +233,7 @@ atomically and to upgrade older revisions when restored. | `many?` | `boolean` | `relation` stores an array of IDs. | | `fields?` | `Array` | Sub-fields of a `group` or `array`. | | `from?` | `string` | Source field for a `slug` (default: `titleField`). | +| `nested?` | `boolean` | `slug` only: allow `/` between segments. Each segment is validated and slugified on its own, and `/` alone is the collection root. | | `min?` / `max?` | `number` | The value for `number`, the length for text types, the item count for `multiselect`, `array`, and `relation` with `many`. | | `unique?` | `boolean` | Reject a value another document in the collection already has (top-level fields). Uniqueness spans every locale, so translations need distinct values. Empty values are ignored. | | `index?` | `boolean` | Create a database index on this top-level field for fast `where` filters and sorting. | @@ -544,6 +546,56 @@ Every document can carry these fields in addition to its own (`SystemMetadata`): Scheduled publishing and unpublishing run as the store is used and from `runScheduledPublishing()` (call it from a cron job for exact timing on idle sites). See [Drafts & workflow](../api/cms-core-server#workflow-drafts-review-queue-revisions-scheduling). +## Locators + +A document's locator is its lookup key within the collection, what `get({ collection, locator })` finds it by. It is not a document field: results carry it as `locator` next to `id`, so a field named `locator` never collides. + +By default (`slugOrId`) the locator is the slug, or the id when the document has no slug. Locators are normalized: leading, trailing and doubled `/` are dropped. Writes enforce three rules, failing with `VALIDATION_FAILED` on the slug field: + +- A locator is unique per collection and locale. Two documents in different locales may share one, and a `localized` slug gives a document one locator per locale. +- A single-segment slug may not be another document's id in the same locale. Ids never contain `/`, so nested slugs are never checked against ids. +- One document per collection and locale may be the collection root, the explicit `/` of a `nested: true` slug (locator `''`). + +A slug the engine generates (the field was empty on save) never fails these rules for being taken: it gets `-2`, `-3`, … on its last segment instead, checked against committed documents. A staged create keeps that slug when approved. A slug you give is never changed. + +A document at `guides` may sit next to documents at `guides/intro`. A trashed document gives up its locator, so restoring it fails while another document holds it. + +```ts validate=type +import { defineCollection } from '@tanstack/cms-core' +import type { LocatorStrategy } from '@tanstack/cms-core' + +const page = defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + // 'guides/intro', or '/' for the home page + { name: 'slug', label: 'Slug', type: 'slug', nested: true }, + ], +}) + +// Products located by SKU: `get({ collection: 'product', locator: 'sku/ab-12' })`. +const bySku: LocatorStrategy = { + name: 'bySku', + locate: ({ doc }) => (typeof doc.sku === 'string' && doc.sku ? `sku/${doc.sku}` : null), +} +const product = defineCollection({ + name: 'product', + label: 'Products', + titleField: 'title', + locatorStrategy: bySku, + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'sku', label: 'SKU', type: 'text' }, + ], +}) +void page +void product +``` + +A strategy's `locate({ collection, id, doc, locale })` must be pure and return a normalized locator, `''` for the root, or `null` for no locator in that locale. Storage keeps the locators in its own index, recomputed on every write. The engine fills it from the stored documents on first start and rebuilds it when the config changes how locators are derived (a new collection, a `locatorStrategy`, a slug field made `localized` or `nested`). Documents that already share a locator are logged as a warning: the first id keeps it, and saving another fails until its slug changes. + ## Content migrations Changing a collection's fields doesn't touch documents already stored. To reshape them, add a `migrations` step with a version and an `up(doc)` function: @@ -705,7 +757,9 @@ These client-safe helpers from `@tanstack/cms-core` read the registered config: | `scalarSchemaFor(collection)` | Zod object without `blocks` fields (for AI structured output) | | `emptyDoc(collection)` / `emptyBlock(type)` / `emptyArrayItem(field)` | New values with every field defaulted | | `fillDerivedFields(collection, doc)` | Fills empty `slug` fields from their source | -| `slugify(text)` | Lowercase kebab-case (`"Héllo, World!"` → `"hello-world"`) | +| `slugify(text, { nested? })` | Lowercase kebab-case (`"Héllo, World!"` → `"hello-world"`); with `nested`, per `/` segment | +| `normalizeLocator(text)` | A locator in canonical form (`"/guides//intro/"` → `"guides/intro"`, `"/"` → `""`) | +| `locatorStrategyOf(collection)` | The collection's `LocatorStrategy` (`slugOrId` unless it sets one) | | `normalizeFieldOptions(options)` | `Array<{ value, label }>` | See the [`@tanstack/cms-core` reference](../api/cms-core) for signatures. diff --git a/packages/api/src/outputs.ts b/packages/api/src/outputs.ts index 8a53e4a0..080c701b 100644 --- a/packages/api/src/outputs.ts +++ b/packages/api/src/outputs.ts @@ -56,10 +56,16 @@ export const redirectOutput = z export const publicDocumentOutput = docEntry.nullable() const readResult = docEntry.extend({ + locator: z + .string() + .nullable() + .describe('The document’s locator (`get` finds it by): its slug, or id.'), relations: z .record(z.string(), z.union([doc, z.array(doc), z.null()])) .optional() - .describe('With `populate`: related documents by relation field path.'), + .describe( + 'Related documents by relation field path, unless `populate: false`.', + ), }) export const getOutput = readResult.nullable() diff --git a/packages/api/tests/read-verbs.test.ts b/packages/api/tests/read-verbs.test.ts index aac334f0..8bddb643 100644 --- a/packages/api/tests/read-verbs.test.ts +++ b/packages/api/tests/read-verbs.test.ts @@ -103,6 +103,7 @@ describe('get and list over HTTP', () => { expect(got.status).toBe(200) expect(got.result).toEqual({ id: 'hello', + locator: 'hello-world', collection: 'post', doc: expect.objectContaining({ title: 'Hello' }), relations: { page: expect.objectContaining({ title: 'About' }) }, diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 8a0db7a5..3aa2e444 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -145,7 +145,8 @@ export interface CmsClient { /** The read mode the client asks for, when set. */ readonly mode?: ReadMode /** - * One document by `id` or `locator` (its slug), or `null` when it is + * One document by `id` or `locator` (its normalized slug, which may be + * nested like `guides/intro`; `''` is the collection root), or `null` when it is * missing or the caller can't see it. Typed from `Register`. Related * documents come back under `relations` unless `populate` is `false`; * read them with `related(result, path)`. diff --git a/packages/client/tests/client.test.ts b/packages/client/tests/client.test.ts index 59ca6e6a..f9b80ca8 100644 --- a/packages/client/tests/client.test.ts +++ b/packages/client/tests/client.test.ts @@ -84,6 +84,7 @@ describe('createCmsClient', () => { const anon = client() expect(await anon.get({ collection: 'post', locator: 'first' })).toEqual({ id: 'a', + locator: 'first', collection: 'post', doc: expect.objectContaining({ title: 'A' }), relations: {}, diff --git a/packages/core/src/definition.ts b/packages/core/src/definition.ts index 7469916f..bb58652e 100644 --- a/packages/core/src/definition.ts +++ b/packages/core/src/definition.ts @@ -67,6 +67,7 @@ export type { SystemMetadata, } from './schema.ts' export type { AssetFieldOptions } from './assets.ts' +export type { LocatorInput, LocatorStrategy } from './locator.ts' export type { AccessRule, AccessRuleContext, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 00a1d812..992b4999 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -130,6 +130,7 @@ export { emptyArrayItem, fillDerivedFields, slugify, + normalizeLocator, getBlocksField, getImageField, getSlugField, @@ -186,6 +187,10 @@ export type { } from './schema' export type { AssetMediaKind } from './schema' +// Locators: the per-locale lookup key behind `get({ collection, locator })`. +export { slugOrId, locatorStrategyOf } from './locator' +export type { LocatorStrategy, LocatorInput } from './locator' + // Assets as a first-class collection: the built-in `asset` collection and the // `asset` field type (a kind-narrowable relation to the asset collection). export { diff --git a/packages/core/src/locator.ts b/packages/core/src/locator.ts new file mode 100644 index 00000000..35f7c641 --- /dev/null +++ b/packages/core/src/locator.ts @@ -0,0 +1,57 @@ +/** + * Locators: the per-locale lookup key behind `get({ collection, locator })`. + * A locator is a normalized path within its collection (`guides/intro`), or + * `''` for the collection root. It is unique per collection and locale, and + * lives in the system namespace next to `id`, never inside `doc`. + * + * Client-safe. + */ +import { isLocalizedValue } from './i18n' +import { getSlugField, normalizeLocator } from './schema' +import type { Collection, Doc } from './schema' + +/** What a `LocatorStrategy` derives a locator from. */ +export interface LocatorInput { + collection: Collection + id: string + doc: Doc + /** The locale the locator is for (see `locatorLocales`). */ + locale: string +} + +/** + * How a collection derives its documents' locators + * (`defineCollection({ locatorStrategy })`). `locate` must be pure, and + * return a normalized locator (see `normalizeLocator`), `''` for the + * collection root, or `null` when the document has no locator in `locale`. + */ +export interface LocatorStrategy { + /** A stable name, e.g. `'slugOrId'`. */ + readonly name: string + locate: (input: LocatorInput) => string | null +} + +/** + * The default strategy: the slug field's value (the collection's + * `slugField`, or a field named `slug`), normalized; the id when the + * document has no slug in that locale. A `nested: true` slug of `/` is the + * collection root, `''`. + */ +export const slugOrId: LocatorStrategy = { + name: 'slugOrId', + locate({ collection, id, doc, locale }) { + const fieldName = getSlugField(collection) ?? 'slug' + const raw = doc[fieldName] ?? doc.slug + const value = isLocalizedValue(raw) ? raw.values[locale] : raw + if (typeof value !== 'string' || value.trim() === '') return id + const located = normalizeLocator(value) + if (located !== '') return located + const field = collection.fields.find((f) => f.name === fieldName) + return field?.type === 'slug' && field.nested ? '' : id + }, +} + +/** The collection's strategy, `slugOrId` unless it sets `locatorStrategy`. */ +export function locatorStrategyOf(collection: Collection): LocatorStrategy { + return collection.locatorStrategy ?? slugOrId +} diff --git a/packages/core/src/ops.ts b/packages/core/src/ops.ts index 3054c706..deafaae3 100644 --- a/packages/core/src/ops.ts +++ b/packages/core/src/ops.ts @@ -256,15 +256,16 @@ export const getInput = z .describe('The document id. Give `id` or `locator`, not both.'), locator: z .string() - .min(1) .optional() .describe( - 'The document’s locator: its slug, or its id (leading slashes ignored). Give `id` or `locator`, not both.', + 'The document’s locator: its slug (a nested slug keeps its "/", e.g. "guides/intro"), or its id when it has no slug; "/" or "" is the collection root. Leading, trailing and doubled slashes are ignored. Give `id` or `locator`, not both.', ), locale: z .string() .optional() - .describe('With `locator`: match the document in this locale.'), + .describe( + 'With `locator`: the locale to look it up in (locators are per locale). Without it, the default locale is tried first.', + ), staged: z .boolean() .optional() @@ -336,6 +337,12 @@ export interface ListOptions { /** One document as `get` and `list` return it. */ export interface ReadResult { id: string + /** + * The document's locator in the requested locale (or its own), next to + * `id`: what `get({ collection, locator })` finds it by. `''` is the + * collection root; `null` when its `locatorStrategy` gives none. + */ + locator: string | null collection: C doc: TDoc /** diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index 9234f8c4..26f82ee8 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -17,9 +17,11 @@ */ import { z } from 'zod' import { contentLocales, getCmsConfig } from './config' +import { isLocalizedValue } from './i18n' import type { CollectionAccess, FieldAccess } from './lib/access' import type { AccessContext } from './lib/access-context' import type { CmsSession } from './lib/auth' +import type { LocatorStrategy } from './locator' import type { StorageAdapter } from './storage/types' import type { AnyDocumentStateStrategy } from './document-state' import { isBuiltInFieldType } from './lib/authoring' @@ -227,6 +229,12 @@ export interface Field { access?: FieldAccess /** `slug` fields: the field to generate from when empty (default: the collection's `titleField`). */ from?: string + /** + * `slug` fields: allow nested slugs, `guides/widgets`. Each `/`-separated + * segment is lowercase-kebab-case; leading, trailing and doubled `/` are + * ignored, and `/` alone is the collection root (the home page). + */ + nested?: boolean /** Lower bound: the value for `number`, the length for text, the item count for lists. */ min?: number /** Upper bound, with the same meaning as `min`. */ @@ -448,6 +456,11 @@ export interface Collection { titleField: string /** Optional field name used for URL slugs (falls back to a field named `slug`). */ slugField?: string + /** + * How a document's locator (the lookup key behind `get({ locator })`) is + * derived. Default `slugOrId`: the slug, or the id when there is none. + */ + locatorStrategy?: LocatorStrategy /** Optional field name used for the block array body (falls back to the first `blocks` field). */ blocksField?: string /** @@ -847,6 +860,32 @@ function describeField(base: string, field: Field): string { } const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ + +/** + * A locator in its canonical form: leading, trailing and doubled `/` + * dropped, so `/guides//intro/` is `guides/intro` and `/` is `''`, the + * collection root. + */ +export function normalizeLocator(input: string): string { + return input + .split('/') + .filter((segment) => segment !== '') + .join('/') +} + +/** A valid `nested: true` slug: kebab-case segments, or `/` for the root. */ +function isNestedSlug(value: string): boolean { + const normalized = normalizeLocator(value) + if (normalized === '') return value.includes('/') + return normalized.split('/').every((segment) => SLUG_RE.test(segment)) +} + +const NESTED_SLUG_FORMAT = { + check: isNestedSlug, + message: + 'Use lowercase-kebab-case segments separated by "/" (or "/" alone for the collection root)', + hint: 'lowercase-kebab-case/path', +} const COLOR_RE = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ @@ -887,8 +926,19 @@ const FORMATS: Partial< }, } -/** Lowercase kebab-case for URLs: `"Héllo, World!"` → `"hello-world"`. */ -export function slugify(input: string): string { +/** + * Lowercase kebab-case for URLs: `"Héllo, World!"` → `"hello-world"`. With + * `nested`, each `/`-separated segment is slugified on its own: + * `"Guides/Getting Started"` → `"guides/getting-started"`. + */ +export function slugify(input: string, options?: { nested?: boolean }): string { + if (options?.nested) { + return input + .split('/') + .map((segment) => slugify(segment)) + .filter(Boolean) + .join('/') + } return input .normalize('NFKD') .replace(/[\u0300-\u036f]/g, '') @@ -1023,7 +1073,10 @@ function fieldZod(rawField: Field): z.ZodTypeAny { case 'email': case 'url': case 'color': { - const format = FORMATS[field.type as BuiltInFieldType] + const format = + field.type === 'slug' && field.nested + ? NESTED_SLUG_FORMAT + : FORMATS[field.type as BuiltInFieldType] const base = stringRules(field, format) const schema = field.required === true @@ -1554,9 +1607,13 @@ export function fillDerivedFields>( if (field.type !== 'slug') continue const current = doc[field.name] if (typeof current === 'string' && current !== '') continue + if (isLocalizedValue(current)) continue const source = doc[field.from ?? collection.titleField] if (typeof source !== 'string' || !source.trim()) continue - out = { ...out, [field.name]: slugify(source) } + out = { + ...out, + [field.name]: slugify(source, { nested: field.nested }), + } } return out } diff --git a/packages/core/src/server/indexing.ts b/packages/core/src/server/indexing.ts index 9d63e150..1e2bb384 100644 --- a/packages/core/src/server/indexing.ts +++ b/packages/core/src/server/indexing.ts @@ -8,6 +8,7 @@ import { contentLocales, getCmsConfig } from '../config' import { getSlugField } from '../schema' import { isLocalizedValue, primaryLocaleValue } from '../i18n' +import { documentLocators } from './locators' import type { Doc } from '../schema' import type { DocumentIndex } from '../storage/types' @@ -40,5 +41,6 @@ export function denormalize( unpublishAt: typeof unpublishAt === 'string' && unpublishAt ? unpublishAt : null, deletedAt: typeof deletedAt === 'string' && deletedAt ? deletedAt : null, + locators: documentLocators(collectionName, id, doc), } } diff --git a/packages/core/src/server/locator-index.ts b/packages/core/src/server/locator-index.ts new file mode 100644 index 00000000..90b17675 --- /dev/null +++ b/packages/core/src/server/locator-index.ts @@ -0,0 +1,131 @@ +/** + * Building the locator index from the documents already stored: once when + * the adapter first gains the index, and again whenever the config changes + * how locators are derived. It runs in the engine rather than in a schema + * migration because only the engine knows each collection's + * `locatorStrategy` and which slug fields are `localized`. + * + * Server-only. + */ +import { cmsLogger, getCmsConfig } from '../config' +import { locatorStrategyOf } from '../locator' +import { getSlugField, isCollectionReadOnly } from '../schema' +import { denormalize } from './indexing' +import { documentLocators } from './locators' +import type { Collection } from '../schema' +import type { DocumentLocator, StorageAdapter } from '../storage/types' + +const META_KEY = 'locator_index' + +/** Documents that derive the same locator in one collection and locale. */ +export interface LocatorDuplicate { + collection: string + locale: string + locator: string + /** Sorted; the first keeps the locator. */ + ids: Array +} + +function writable(): Array { + return Object.values(getCmsConfig().collections).filter( + (c) => !isCollectionReadOnly(c), + ) +} + +/** + * What the stored index was derived from. A change (a new collection, a + * `locatorStrategy`, a slug field turned `localized` or `nested`) rebuilds it. + */ +function fingerprint(collections: Array): string { + return JSON.stringify( + collections + .map((c) => { + const slugField = getSlugField(c) ?? 'slug' + const field = c.fields.find((f) => f.name === slugField) + return [ + c.name, + locatorStrategyOf(c).name, + slugField, + field?.localized === true, + field?.type === 'slug' && field.nested === true, + ] + }) + .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), + ) +} + +function report(duplicates: Array): string { + const shown = duplicates + .slice(0, 20) + .map( + (d) => + `${d.collection} (${d.locale}) "${d.locator}": ${d.ids.join(', ')}`, + ) + .join('; ') + const more = + duplicates.length > 20 ? ` …and ${duplicates.length - 20} more` : '' + return `These documents share a locator (their slug, or their id) in the same collection and locale: ${shown}${more}. Each locator goes to the first id listed; the others are still readable by id, and saving one fails until it has a distinct slug. If the slugs are only unique within a scope (a tenant, a version), give the collection a \`locatorStrategy\` that includes it.` +} + +/** + * Fill the adapter's locator index from its stored documents, unless it was + * already built for this config. Runs on first use of the storage, before + * seeding. Shared locators are a preflight finding, not a failure: the first + * id holds each one, the rest are reported, and the site keeps booting, as + * with `unique` field indexes. + */ +export async function ensureLocatorIndex( + adapter: StorageAdapter, +): Promise> { + if (adapter.readOnly || !adapter.findDocumentsByLocator) return [] + const collections = writable() + const want = fingerprint(collections) + if ((await adapter.getMeta(META_KEY)) === want) return [] + const duplicates: Array = [] + await adapter.transaction(async (tx) => { + for (const collection of collections) { + const { items } = await tx.queryDocuments({ + collections: [collection.name], + }) + const rows = [...items].sort((a, b) => a.id.localeCompare(b.id)) + const holders = new Map>() + const kept = new Map>() + for (const row of rows) { + const mine: Array = [] + for (const held of documentLocators(collection.name, row.id, row.doc)) { + const key = `${held.locale}\u0000${held.locator}` + const ids = holders.get(key) + if (ids) ids.push(row.id) + else { + holders.set(key, [row.id]) + mine.push(held) + } + } + kept.set(row.id, mine) + } + for (const row of rows) { + await tx.putDocument( + { + collection: collection.name, + id: row.id, + doc: row.doc, + updatedAt: row.updatedAt, + }, + { + ...denormalize(collection.name, row.id, row.doc), + locators: kept.get(row.id) ?? [], + }, + ) + } + for (const [key, ids] of holders) { + if (ids.length < 2) continue + const [locale = '', locator = ''] = key.split('\u0000') + duplicates.push({ collection: collection.name, locale, locator, ids }) + } + } + await tx.setMeta(META_KEY, want) + }) + if (duplicates.length) + cmsLogger().warn(`[tanstack-cms] ${report(duplicates)}`) + return duplicates +} diff --git a/packages/core/src/server/locators.ts b/packages/core/src/server/locators.ts new file mode 100644 index 00000000..8f9a30c0 --- /dev/null +++ b/packages/core/src/server/locators.ts @@ -0,0 +1,242 @@ +/** + * Locators on the server: computing a document's locators on write, + * matching a locator against storage, and the collision rules (unique per + * collection and locale; a single-segment locator may not be another + * document's id). The derivation itself is the collection's + * `LocatorStrategy` (`../locator`). + * + * Server-only. + */ +import { contentLocales, getCmsConfig } from '../config' +import { isLocalizedValue } from '../i18n' +import { locatorStrategyOf, slugOrId } from '../locator' +import { getSlugField, normalizeLocator } from '../schema' +import type { Collection, Doc } from '../schema' +import type { DocumentLocator, StorageOps } from '../storage/types' + +/** The locale a document's row is indexed under, as `denormalize` sets it. */ +export function documentLocale(doc: Doc): string { + return typeof doc.locale === 'string' && doc.locale ? doc.locale : 'en' +} + +/** + * The locales a document has locators in: every content locale when the + * slug field is `localized` (one document, one slug per locale), otherwise + * the document's own locale. + */ +export function locatorLocales( + collection: Collection, + doc: Doc, +): Array { + const slugField = getSlugField(collection) ?? 'slug' + const field = collection.fields.find((f) => f.name === slugField) + const i18n = contentLocales() + if (field?.localized && i18n) return i18n.locales.map((l) => l.code) + return [documentLocale(doc)] +} + +function collectionNamed(name: string): Collection | undefined { + try { + return getCmsConfig().collections[name] + } catch { + return undefined + } +} + +/** + * A document's locators, at most one per locale. A trashed document holds + * none, so its locator is free for another document until it is restored. + */ +export function documentLocators( + collectionName: string, + id: string, + doc: Doc, +): Array { + if (typeof doc.deletedAt === 'string' && doc.deletedAt) return [] + const collection = collectionNamed(collectionName) + if (!collection) return [] + const strategy = locatorStrategyOf(collection) + const out: Array = [] + for (const locale of locatorLocales(collection, doc)) { + const locator = strategy.locate({ collection, id, doc, locale }) + if (locator === null) continue + out.push({ locale, locator: normalizeLocator(locator) }) + } + return out +} + +/** + * The document's locator in `locale` (default: its own locale), or `null` + * when it has none there. + */ +export function locatorOf( + collectionName: string, + id: string, + doc: Doc, + locale?: string, +): string | null { + const collection = collectionNamed(collectionName) + if (!collection) return null + const located = locatorStrategyOf(collection).locate({ + collection, + id, + doc, + locale: locale ?? documentLocale(doc), + }) + return located === null ? null : normalizeLocator(located) +} + +/** + * Whether the slug column and the id find every holder of a locator. Not + * for a custom strategy, or a localized slug (the column holds the default + * locale's value). + */ +function slugColumnSuffices(collectionName: string): boolean { + const collection = collectionNamed(collectionName) + if (!collection) return true + if (locatorStrategyOf(collection) !== slugOrId) return false + const slugField = getSlugField(collection) ?? 'slug' + return !collection.fields.find((f) => f.name === slugField)?.localized +} + +/** + * The documents holding `locator` without `findDocumentsByLocator`: the + * slug and id matches, checked against the strategy, or every document of + * the collection for the root and when the slug column can't tell. + */ +async function scanLocator( + storage: StorageOps, + collection: string, + locator: string, + locale?: string, +): Promise> { + const candidates = new Map() + if (locator === '' || !slugColumnSuffices(collection)) { + const { items } = await storage.queryDocuments({ + collections: [collection], + }) + for (const row of items) candidates.set(row.id, row.doc) + } else { + for (const row of await storage.findDocumentsBySlug(collection, locator)) + candidates.set(row.id, row.doc) + if (!locator.includes('/')) { + const row = await storage.getDocument(collection, locator) + if (row && !row.deletedAt) candidates.set(row.id, row.doc) + } + } + const out: Array<{ id: string; locale: string }> = [] + for (const [id, doc] of candidates) { + for (const held of documentLocators(collection, id, doc)) { + if (held.locator !== locator) continue + if (locale !== undefined && held.locale !== locale) continue + out.push({ id, locale: held.locale }) + } + } + return out +} + +/** + * The documents holding `locator` (normalized) in `collection`, in `locale` + * or any locale: the default locale first, then by locale code. + */ +export async function locatorMatches( + storage: StorageOps, + collection: string, + locator: string, + locale?: string, +): Promise> { + const normalized = normalizeLocator(locator) + const found = storage.findDocumentsByLocator + ? await storage.findDocumentsByLocator(collection, normalized, locale) + : await scanLocator(storage, collection, normalized, locale) + const defaultLocale = contentLocales()?.defaultLocale ?? 'en' + const rank = (l: string) => (l === defaultLocale ? 0 : 1) + return [...found].sort( + (a, b) => + rank(a.locale) - rank(b.locale) || + a.locale.localeCompare(b.locale) || + a.id.localeCompare(b.id), + ) +} + +/** + * Collision issues for writing `doc` as `id`: each of its locators must be + * free in its locale, and a single-segment locator may not be another + * document's id in the same locale (ids never contain `/`). + */ +export async function locatorIssues( + storage: StorageOps, + collection: Collection, + id: string, + doc: Doc, +): Promise; message: string }>> { + const issues: Array<{ path: Array; message: string }> = [] + const path = [getSlugField(collection) ?? 'slug'] + const where = (locale: string) => + contentLocales() ? ` in locale "${locale}"` : '' + for (const { locale, locator } of documentLocators( + collection.name, + id, + doc, + )) { + const matches = await locatorMatches( + storage, + collection.name, + locator, + locale, + ) + const taken = matches.find((m) => m.id !== id) + if (taken) { + issues.push({ + path, + message: + locator === '' + ? `Another document (${taken.id}) is already the collection root${where(locale)}.` + : `"${locator}" is already the locator of another document (${taken.id})${where(locale)}.`, + }) + continue + } + if (locator === '' || locator === id || locator.includes('/')) continue + const other = await storage.getDocument(collection.name, locator) + if (other && !other.deletedAt && other.locale === locale) { + issues.push({ + path, + message: `"${locator}" is the id of another document${where(locale)}; use a different slug.`, + }) + } + } + return issues +} + +/** How many `-n` suffixes a generated slug tries before it is left to fail. */ +const MAX_SLUG_SUFFIX = 100 + +/** + * A slug the engine generated (the slug field was empty in `input`) whose + * locator is taken gets `-2`, `-3`, … on its last segment, against the + * committed locators. A slug the writer gave is returned as is, and fails + * `locatorIssues` if taken. + */ +export async function suffixGeneratedSlug( + storage: StorageOps, + collection: Collection, + id: string, + input: Record, + doc: Doc, +): Promise { + const name = getSlugField(collection) ?? 'slug' + if (collection.fields.find((f) => f.name === name)?.type !== 'slug') + return doc + const given = input[name] + if ((typeof given === 'string' && given !== '') || isLocalizedValue(given)) + return doc + const generated = doc[name] + if (typeof generated !== 'string' || generated === '') return doc + if (!(await locatorIssues(storage, collection, id, doc)).length) return doc + for (let n = 2; n <= MAX_SLUG_SUFFIX; n++) { + const candidate = { ...doc, [name]: `${generated}-${n}` } + if (!(await locatorIssues(storage, collection, id, candidate)).length) + return candidate + } + return doc +} diff --git a/packages/core/src/server/storage.ts b/packages/core/src/server/storage.ts index 8be77b7a..628054ae 100644 --- a/packages/core/src/server/storage.ts +++ b/packages/core/src/server/storage.ts @@ -23,6 +23,8 @@ import { createSqliteStorage, } from '../storage/node-sqlite' import { denormalize } from './indexing' +import { ensureLocatorIndex } from './locator-index' +import { locatorMatches } from './locators' import { countFor, groupByFor } from '../storage/aggregations' import type { ResolvedCmsConfig } from '../config' import type { Doc } from '../schema' @@ -210,6 +212,8 @@ function createCompositeStorage(cfg: ResolvedCmsConfig): StorageAdapter { forCollection(collection).getDocuments(collection, ids), findDocumentsBySlug: (collection, slug) => forCollection(collection).findDocumentsBySlug(collection, slug), + findDocumentsByLocator: (collection, locator, locale) => + locatorMatches(forCollection(collection), collection, locator, locale), count: (collection, filter) => countFor(forCollection(collection), collection, filter), groupBy: (collection, field, filter) => @@ -521,6 +525,8 @@ function createCompositeStorage(cfg: ResolvedCmsConfig): StorageAdapter { getDocuments: (col, ids) => txFor(col).getDocuments(col, ids), findDocumentsBySlug: (col, slug) => txFor(col).findDocumentsBySlug(col, slug), + findDocumentsByLocator: (col, locator, locale) => + locatorMatches(txFor(col), col, locator, locale), count: (col, filter) => countFor(txFor(col), col, filter), groupBy: (col, field, filter) => groupByFor(txFor(col), col, field, filter), @@ -738,6 +744,7 @@ export async function getStorage(options?: { await adapter.init() await adapter.ensureIndexes?.(indexedFields()) await ensureUniqueIndexes(adapter) + await ensureLocatorIndex(adapter) await seedIfNeeded(adapter) })() ready.set(adapter, init) diff --git a/packages/core/src/server/store/document-state.ts b/packages/core/src/server/store/document-state.ts index 61a9d85c..0f8c6fea 100644 --- a/packages/core/src/server/store/document-state.ts +++ b/packages/core/src/server/store/document-state.ts @@ -38,6 +38,7 @@ import { emitCmsEvent } from '../events' import { deleteAssetBlob } from '../media-store' import { queueNotification } from '../notifications' import { changedFields, enqueueDocumentChange, enqueueEvent } from '../outbox' +import { suffixGeneratedSlug } from '../locators' import { getStorage, notifyStorageCommit } from '../storage' import { applyPostRead, @@ -1535,15 +1536,19 @@ export async function prepareStagedChange( if (!before) await assertSingletonSlot(storage, collection, docId) const type: WriteType = before ? 'update' : 'create' const incoming = await upgradeIncomingDoc(collection.name, docId, doc as Doc) - let after = validate( + const input = await runPreValidate( collection, - await runPreValidate( - collection, - { ...emptyDoc(collection), ...incoming }, - docId, - type, - options.actor, - ), + { ...emptyDoc(collection), ...incoming }, + docId, + type, + options.actor, + ) + let after = await suffixGeneratedSlug( + storage, + collection, + docId, + input, + validate(collection, input), ) await checkFieldRules(storage, collection, docId, after) after = stampContentVersion(collection.name, after) diff --git a/packages/core/src/server/store/internal.ts b/packages/core/src/server/store/internal.ts index e296878b..0c09514c 100644 --- a/packages/core/src/server/store/internal.ts +++ b/packages/core/src/server/store/internal.ts @@ -19,6 +19,7 @@ import { isLocalizedValue, primaryLocaleValue } from '../../i18n' import { stampContentVersion, upgradeStoredDoc } from '../content-migrations' import { denormalize } from '../indexing' import { commitEvents, emitCmsEvent, stayedLive } from '../events' +import { locatorIssues } from '../locators' import { collectRelations } from './relations' import type { ChangeHookArgs, @@ -338,6 +339,7 @@ export async function checkFieldRules( await walk(collection.fields, doc, []) issues.push(...(await relationIssues(storage, collection, doc))) issues.push(...(await uniqueIssues(storage, collection, id, doc))) + issues.push(...(await locatorIssues(storage, collection, id, doc))) throwIssues(collection, issues) } diff --git a/packages/core/src/server/store/verbs.ts b/packages/core/src/server/store/verbs.ts index dae869d6..2f0bfd0d 100644 --- a/packages/core/src/server/store/verbs.ts +++ b/packages/core/src/server/store/verbs.ts @@ -8,10 +8,11 @@ */ import { getInput, listInput, validateWithStandardSchema } from '../../ops' import { canReadCollection, isLiveRead } from '../access-context' +import { locatorMatches, locatorOf } from '../locators' +import { getStorage } from '../storage' import { collections } from './internal' import { queryDocumentsAs } from './query' import { - readBySlug, readDocumentAs, readDocumentWithPendingAs, resolveRelationsAs, @@ -21,8 +22,10 @@ import type { AccessContext } from '../access-context' import type { GetOptions, ListOptions, ListResult, ReadResult } from '../../ops' /** - * One document as `ctx` reads it, by `id` or by `locator` (the slug, or the - * id; leading slashes ignored). A `live` context reads the published + * One document as `ctx` reads it, by `id` or by `locator`: the collection's + * locator index (`slugOrId` by default: the slug, or the id of a document + * without one; `''` or `/` is the collection root), in `locale` when given, + * otherwise the default locale first. A `live` context reads the published * version; `preview` and `edit` read the working copy, with staged changes * overlaid. `null` when the document is missing or `ctx` can't see it; the * returned document is redacted for `ctx`. Relations are populated unless @@ -36,24 +39,35 @@ export async function getAs( const { collection } = bag if (!collections()[collection] || !canReadCollection(ctx, collection)) return null - const id = - bag.id ?? - (await readBySlug(ctx, collection, bag.locator ?? '', false, bag.locale)) - ?.id - if (id === undefined) return null - const doc = - isLiveRead(ctx) || bag.staged === false - ? await readDocumentAs(ctx, collection, id) - : (await readDocumentWithPendingAs(ctx, collection, id)).doc - if (!doc) return null - const populate = bag.populate - if (!wantsRelations(populate)) return { id, collection, doc } - const [relations] = await resolveRelationsAs( - ctx, - [{ collection, doc }], - populate, - ) - return { id, collection, doc, relations: relations ?? {} } + const candidates: Array<{ id: string; locale?: string }> = + bag.id !== undefined + ? [{ id: bag.id, locale: bag.locale }] + : await locatorMatches( + await getStorage(), + collection, + bag.locator ?? '', + bag.locale, + ) + const tried = new Set() + for (const { id, locale } of candidates) { + if (tried.has(id)) continue + tried.add(id) + const doc = + isLiveRead(ctx) || bag.staged === false + ? await readDocumentAs(ctx, collection, id) + : (await readDocumentWithPendingAs(ctx, collection, id)).doc + if (!doc) continue + const locator = locatorOf(collection, id, doc, locale) + const populate = bag.populate + if (!wantsRelations(populate)) return { id, locator, collection, doc } + const [relations] = await resolveRelationsAs( + ctx, + [{ collection, doc }], + populate, + ) + return { id, locator, collection, doc, relations: relations ?? {} } + } + return null } /** @@ -81,6 +95,7 @@ export async function listAs( return { items: result.items.map((item) => ({ id: item.id, + locator: locatorOf(item.collection, item.id, item.doc, bag.locale), collection: item.collection, doc: item.doc, ...(item.relations ? { relations: item.relations } : {}), diff --git a/packages/core/src/server/store/write.ts b/packages/core/src/server/store/write.ts index da518a4e..2490e2e7 100644 --- a/packages/core/src/server/store/write.ts +++ b/packages/core/src/server/store/write.ts @@ -9,6 +9,7 @@ import { deleteAssetBlob } from '../media-store' import { CmsError } from '../../errors' import { assetCollectionName, emptyDoc } from '../../schema' import { upgradeIncomingDoc, upgradeStoredDoc } from '../content-migrations' +import { suffixGeneratedSlug } from '../locators' import { getStorage, notifyStorageCommit } from '../storage' import { assertExpectedRevision, @@ -92,9 +93,13 @@ export async function commitDocument( } const actor = options?.actor ?? 'human' const operation: 'create' | 'update' = existing ? 'update' : 'create' - const parsed = validate( + const input = await runPreValidate(collection, merged, id, operation, actor) + const parsed = await suffixGeneratedSlug( + storage, collection, - await runPreValidate(collection, merged, id, operation, actor), + id, + input, + validate(collection, input), ) await checkFieldRules(storage, collection, id, parsed) let next: Doc = await runPostValidate( diff --git a/packages/core/src/storage.ts b/packages/core/src/storage.ts index 6e186a55..45c7643e 100644 --- a/packages/core/src/storage.ts +++ b/packages/core/src/storage.ts @@ -54,6 +54,7 @@ export type { CommentRecord, DeadLetterRecord, DocumentIndex, + DocumentLocator, DocumentRecord, EventRecord, EventStatus, diff --git a/packages/core/src/storage/conformance.ts b/packages/core/src/storage/conformance.ts index 684bb20e..9ce387df 100644 --- a/packages/core/src/storage/conformance.ts +++ b/packages/core/src/storage/conformance.ts @@ -1001,6 +1001,63 @@ export function runStorageConformance( ).rejects.toMatchObject({ code: 'CONFLICT' }) })) + it('stores locators unique per collection and locale', () => + withStorage(async (s) => { + const find = s.findDocumentsByLocator + if (!find) return + const put = ( + ops: StorageOps, + collection: string, + id: string, + locators: Array<{ locale: string; locator: string }> | undefined, + ) => + ops.putDocument( + { collection, id, doc: { title: id } as never, updatedAt: now }, + { ...index(id), locators }, + ) + const ids = async ( + collection: string, + locator: string, + locale?: string, + ) => + (await find(collection, locator, locale)) + .map((m) => `${m.id}@${m.locale}`) + .sort() + await put(s, 'post', 'a', [ + { locale: 'en', locator: 'guides/intro' }, + { locale: 'fr', locator: 'guides/intro' }, + ]) + await put(s, 'post', 'home', [{ locale: 'en', locator: '' }]) + await put(s, 'page', 'p', [{ locale: 'en', locator: 'guides/intro' }]) + expect(await ids('post', 'guides/intro')).toEqual(['a@en', 'a@fr']) + expect(await ids('post', 'guides/intro', 'fr')).toEqual(['a@fr']) + expect(await ids('post', '')).toEqual(['home@en']) + expect(await ids('post', 'nope')).toEqual([]) + + await expect( + put(s, 'post', 'b', [{ locale: 'en', locator: 'guides/intro' }]), + ).rejects.toMatchObject({ code: 'VALIDATION_FAILED' }) + await expect( + s.transaction((tx) => + put(tx, 'post', 'c', [{ locale: 'en', locator: '' }]), + ), + ).rejects.toMatchObject({ code: 'VALIDATION_FAILED' }) + expect(await s.getDocument('post', 'c')).toBeNull() + + // Absent locators leave the stored ones; an empty list clears them. + await put(s, 'post', 'a', undefined) + expect(await ids('post', 'guides/intro', 'en')).toEqual(['a@en']) + await put(s, 'post', 'a', [{ locale: 'en', locator: 'moved' }]) + expect(await ids('post', 'guides/intro')).toEqual([]) + expect(await ids('post', 'moved')).toEqual(['a@en']) + await put(s, 'post', 'a', []) + expect(await ids('post', 'moved')).toEqual([]) + await put(s, 'post', 'b', [{ locale: 'en', locator: 'guides/intro' }]) + + await s.deleteDocument('post', 'home') + expect(await ids('post', '')).toEqual([]) + })) + it('stores API keys by hash', () => withStorage(async (s) => { // API-key ops are an optional capability; skip adapters without them. diff --git a/packages/core/src/storage/migrations.ts b/packages/core/src/storage/migrations.ts index aff2f98c..471a846e 100644 --- a/packages/core/src/storage/migrations.ts +++ b/packages/core/src/storage/migrations.ts @@ -559,6 +559,25 @@ export const SQL_MIGRATIONS: Array = [ } }, }, + { + // Version 16 is 4b's change-set state (#29); this one is numbered after it. + version: 17, + name: 'locators: one per collection, locale and locator', + up: async (db) => { + // Empty on purpose: the engine fills it on first use + // (`ensureLocatorIndex`), with each collection's locatorStrategy. + await db.exec(` + CREATE TABLE IF NOT EXISTS locators ( + collection TEXT NOT NULL, + locale TEXT NOT NULL, + locator TEXT NOT NULL, + doc_id TEXT NOT NULL, + PRIMARY KEY (collection, locale, locator) + ); + CREATE INDEX IF NOT EXISTS idx_locators_doc ON locators (collection, doc_id); + `) + }, + }, ] export const LATEST_SCHEMA_VERSION = diff --git a/packages/core/src/storage/sql-storage.ts b/packages/core/src/storage/sql-storage.ts index c84648c7..7719b30f 100644 --- a/packages/core/src/storage/sql-storage.ts +++ b/packages/core/src/storage/sql-storage.ts @@ -683,6 +683,16 @@ function opsFor(db: SqlExecutor): StorageOps { return rows.map(toDocRecord) }, + async findDocumentsByLocator(collection, locator, locale) { + return db.all<{ id: string; locale: string }>( + `SELECT doc_id AS id, locale FROM locators + WHERE collection = ? AND locator = ?${locale === undefined ? '' : ' AND locale = ?'}`, + locale === undefined + ? [collection, locator] + : [collection, locator, locale], + ) + }, + async queryDocuments(q) { if (q.collections.length === 0) return { items: [], total: 0 } const indexed = @@ -800,6 +810,17 @@ function opsFor(db: SqlExecutor): StorageOps { index.deletedAt, ], ) + if (!index.locators) return + await db.run(`DELETE FROM locators WHERE collection = ? AND doc_id = ?`, [ + record.collection, + record.id, + ]) + for (const { locale, locator } of index.locators) { + await db.run( + `INSERT INTO locators (collection, locale, locator, doc_id) VALUES (?, ?, ?, ?)`, + [record.collection, locale, locator, record.id], + ) + } }, async deleteDocument(collection, id) { @@ -807,6 +828,10 @@ function opsFor(db: SqlExecutor): StorageOps { collection, id, ]) + await db.run(`DELETE FROM locators WHERE collection = ? AND doc_id = ?`, [ + collection, + id, + ]) }, async getPending(id) { @@ -1408,9 +1433,19 @@ function uniqueIndexName(collection: string, field: string): string { return `${UNIQUE_INDEX_PREFIX}${collection.replace(/[^A-Za-z0-9_]/g, '_')}__${field}` } -/** A violated `ensureUniqueIndexes` index becomes `VALIDATION_FAILED`. */ +/** + * A violated `ensureUniqueIndexes` index, or a taken locator, becomes + * `VALIDATION_FAILED`. + */ function mapUniqueViolation(err: unknown, names: Map) { const message = err instanceof Error ? err.message : '' + if (/UNIQUE constraint failed: locators\./.test(message)) { + return new CmsError( + 'Another document already has this locator (its slug, or its id) in this collection and locale.', + 'VALIDATION_FAILED', + [{ path: ['locator'], message: 'Must be unique.' }], + ) + } const match = /UNIQUE constraint failed: index '([^']+)'/.exec(message) const spec = match?.[1] ? names.get(match[1]) : undefined if (!spec) return err diff --git a/packages/core/src/storage/types.ts b/packages/core/src/storage/types.ts index 9538d925..6caa2541 100644 --- a/packages/core/src/storage/types.ts +++ b/packages/core/src/storage/types.ts @@ -68,6 +68,20 @@ export interface DocumentIndex { unpublishAt: string | null /** ISO datetime the document was soft-deleted (in trash); `null` when live. */ deletedAt: string | null + /** + * The document's locators, at most one per locale; none while it is in + * the trash. Adapters with `findDocumentsByLocator` store them uniquely per + * collection, locale and locator, replacing the document's previous ones; + * when absent, the stored locators are left as they are. + */ + locators?: ReadonlyArray +} + +/** A document's locator in one locale (see `LocatorStrategy`). */ +export interface DocumentLocator { + locale: string + /** Normalized: no leading, trailing or doubled `/`; `''` is the collection root. */ + locator: string } export interface IndexedDocumentRecord extends DocumentRecord, DocumentIndex {} @@ -578,6 +592,18 @@ export interface StorageOps collection: string, slug: string, ) => Promise> + /** + * The documents holding `locator` in `collection`: in `locale` only when + * given, otherwise in any locale. Optional; without it the engine falls + * back to slug and id lookups, which only see the default locale of a + * localized slug. A second document taking a held (collection, locale, + * locator) must fail the write with `VALIDATION_FAILED`. + */ + findDocumentsByLocator?: ( + collection: string, + locator: string, + locale?: string, + ) => Promise> queryDocuments: (query: StorageQuery) => Promise /** Optional native aggregation capabilities, for faceted search. */ count?: (collection: string, filter?: StorageFilter) => Promise diff --git a/packages/core/tests/locators.test.ts b/packages/core/tests/locators.test.ts new file mode 100644 index 00000000..798b4eaf --- /dev/null +++ b/packages/core/tests/locators.test.ts @@ -0,0 +1,776 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + createCms, + defineCollection, + locatorStrategyOf, + makeLocalizedValue, + normalizeLocator, + schemaFor, + slugify, + slugOrId, +} from '../src/index' +import { + approve, + closeStore, + commitDocument, + deleteDocument, + getAs, + listAs, + restoreDocument, + stageWrite, +} from '../src/server' +import { publicContext, systemContext } from '../src/server/access-context' +import { getStorage } from '../src/server/storage' +import { + SQL_MIGRATIONS, + createNodeSqliteDriver, + createSqliteStorage, + runSqlMigrations, +} from '../src/storage' +import type { Cms, CmsConfig, LocatorStrategy } from '../src/index' +import type { StorageAdapter, StorageOps } from '../src/storage' + +const dirs: Array = [] + +afterEach(async () => { + await closeStore() + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +const page = defineCollection({ + name: 'page', + label: 'Pages', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'slug', label: 'Slug', type: 'slug', nested: true }, + ], +}) + +const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'slug', label: 'Slug', type: 'slug' }, + ], +}) + +const note = defineCollection({ + name: 'note', + label: 'Notes', + titleField: 'title', + fields: [{ name: 'title', label: 'Title', type: 'text' }], +}) + +const article = defineCollection({ + name: 'article', + label: 'Articles', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'slug', label: 'Slug', type: 'slug', localized: true }, + ], +}) + +const byCode: LocatorStrategy = { + name: 'byCode', + locate: ({ doc }) => + typeof doc.code === 'string' && doc.code ? `codes/${doc.code}` : null, +} + +const product = defineCollection({ + name: 'product', + label: 'Products', + titleField: 'title', + locatorStrategy: byCode, + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'code', label: 'Code', type: 'text' }, + ], +}) + +const i18n = { + locales: [{ code: 'en' }, { code: 'fr' }], + defaultLocale: 'en', +} + +function config(extra?: Partial): CmsConfig { + const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-locators-')) + dirs.push(dataDir) + return { + dataDir, + collections: [page, post, note, article, product], + blockTypes: [], + ...extra, + } +} + +async function failure(p: Promise) { + try { + await p + } catch (e) { + return e as { + code: string + message: string + details: Array<{ path: Array; message: string }> + } + } + throw new Error('expected a validation failure') +} + +const system = () => systemContext('locator tests') + +function run(cms: Cms, fn: () => Promise): Promise { + return cms.run(fn) +} + +describe('nested slugs', () => { + it('validates each segment, and accepts "/" only on nested fields', () => { + createCms(config()) + const nested = schemaFor(page) + for (const slug of ['guides', 'guides/intro', '/guides/intro/', '/']) + expect(nested.safeParse({ title: 'x', slug }).success).toBe(true) + for (const slug of ['Guides/intro', 'guides/in tro', 'guides/-x']) + expect(nested.safeParse({ title: 'x', slug }).success).toBe(false) + + const flat = schemaFor(post) + expect(flat.safeParse({ title: 'x', slug: 'guides' }).success).toBe(true) + for (const slug of ['guides/intro', '/']) + expect(flat.safeParse({ title: 'x', slug }).success).toBe(false) + }) + + it('slugifies per segment', () => { + expect(slugify('Guides/Getting Started', { nested: true })).toBe( + 'guides/getting-started', + ) + expect(slugify('/A//B/', { nested: true })).toBe('a/b') + expect(slugify('Guides/Getting Started')).toBe('guides-getting-started') + }) + + it('normalizes locators', () => { + expect(normalizeLocator('/guides//intro/')).toBe('guides/intro') + expect(normalizeLocator('/')).toBe('') + expect(normalizeLocator('')).toBe('') + expect(normalizeLocator('hello')).toBe('hello') + }) +}) + +describe('get({ locator })', () => { + it('finds nested, folder and root documents through the locator', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('page', 'home', { title: 'Home', slug: '/' }) + await commitDocument('page', 'guides', { title: 'G', slug: 'guides' }) + await commitDocument('page', 'intro', { + title: 'Intro', + slug: 'guides/intro', + }) + const ctx = system() + const got = await getAs(ctx, { + collection: 'page', + locator: '/guides//intro/', + }) + expect(got).toMatchObject({ id: 'intro', locator: 'guides/intro' }) + expect( + (await getAs(ctx, { collection: 'page', locator: 'guides' }))?.id, + ).toBe('guides') + for (const locator of ['', '/']) { + expect(await getAs(ctx, { collection: 'page', locator })).toMatchObject( + { id: 'home', locator: '' }, + ) + } + expect( + await getAs(ctx, { collection: 'page', locator: 'guides/missing' }), + ).toBeNull() + }) + }) + + it("uses the id of a document without a slug, and not a slugged document's id", async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('note', 'n1', { title: 'Note' }) + await commitDocument('post', 'p1', { title: 'P', slug: 'hello' }) + const ctx = system() + expect( + await getAs(ctx, { collection: 'note', locator: 'n1' }), + ).toMatchObject({ id: 'n1', locator: 'n1' }) + expect(await getAs(ctx, { collection: 'post', locator: 'p1' })).toBeNull() + expect( + (await getAs(ctx, { collection: 'post', locator: 'hello' }))?.id, + ).toBe('p1') + const listed = await listAs(ctx, { collection: 'post' }) + expect(listed.items.map((i) => [i.id, i.locator])).toEqual([ + ['p1', 'hello'], + ]) + }) + }) + + it('follows a slug change and releases the old locator', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'p1', { title: 'P', slug: 'old' }) + await commitDocument('post', 'p1', { title: 'P', slug: 'new' }) + const ctx = system() + expect( + await getAs(ctx, { collection: 'post', locator: 'old' }), + ).toBeNull() + expect( + (await getAs(ctx, { collection: 'post', locator: 'new' }))?.id, + ).toBe('p1') + await commitDocument('post', 'p2', { title: 'Q', slug: 'old' }) + expect( + (await getAs(ctx, { collection: 'post', locator: 'old' }))?.id, + ).toBe('p2') + }) + }) + + it('skips documents the context cannot read', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'p1', { title: 'P', slug: 'draft' }) + expect( + await getAs(publicContext(), { collection: 'post', locator: 'draft' }), + ).toBeNull() + await commitDocument('post', 'p1', { + title: 'P', + slug: 'draft', + published: true, + }) + expect( + (await getAs(publicContext(), { collection: 'post', locator: 'draft' })) + ?.id, + ).toBe('p1') + }) + }) + + it('uses a custom locatorStrategy', async () => { + expect(locatorStrategyOf(post)).toBe(slugOrId) + expect(locatorStrategyOf(product)).toBe(byCode) + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('product', 'x1', { title: 'X', code: 'abc' }) + await commitDocument('product', 'x2', { title: 'Y' }) + const ctx = system() + expect( + await getAs(ctx, { collection: 'product', locator: 'codes/abc' }), + ).toMatchObject({ id: 'x1', locator: 'codes/abc' }) + expect( + await getAs(ctx, { collection: 'product', locator: 'x2' }), + ).toBeNull() + expect( + await getAs(ctx, { collection: 'product', id: 'x2' }), + ).toMatchObject({ id: 'x2', locator: null }) + const dup = await failure( + commitDocument('product', 'x3', { title: 'Z', code: 'abc' }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + }) + }) +}) + +describe('collisions', () => { + it('rejects a taken locator in the same collection and locale', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'p1', { title: 'P', slug: 'hello' }) + await commitDocument('post', 'p1', { title: 'P again', slug: 'hello' }) + const dup = await failure( + commitDocument('post', 'p2', { title: 'Q', slug: 'hello' }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + expect(dup.details).toEqual([ + { + path: ['slug'], + message: expect.stringContaining('"hello" is already the locator'), + }, + ]) + // Another collection is another namespace. + await commitDocument('page', 'p2', { title: 'Q', slug: 'hello' }) + }) + }) + + it('compares the normalized locator', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('page', 'a', { title: 'A', slug: 'guides/intro' }) + const dup = await failure( + commitDocument('page', 'b', { title: 'B', slug: '/guides//intro/' }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + }) + }) + + it('allows one collection root per collection', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('page', 'home', { title: 'Home', slug: '/' }) + const dup = await failure( + commitDocument('page', 'home2', { title: 'Home 2', slug: '/' }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + expect(dup.details[0]?.message).toMatch(/already the collection root/) + }) + }) + + it("rejects a single-segment slug that is another document's id", async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('page', 'about', { title: 'About', slug: 'company' }) + const clash = await failure( + commitDocument('page', 'p2', { title: 'X', slug: 'about' }), + ) + expect(clash.code).toBe('VALIDATION_FAILED') + expect(clash.details[0]?.message).toMatch(/is the id of another document/) + // Multi-segment locators can't be ids, and a document may use its own id. + await commitDocument('page', 'p3', { title: 'Y', slug: 'about/team' }) + await commitDocument('page', 'p4', { title: 'Z', slug: 'p4' }) + }) + }) + + it('treats a slugless document as holding its id', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'intro', { title: 'No slug' }) + const dup = await failure( + commitDocument('post', 'p2', { title: 'Q', slug: 'intro' }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + }) + }) + + it('frees the locator of a trashed document until it is restored', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'p1', { title: 'P', slug: 'hello' }) + await deleteDocument('post', 'p1') + await commitDocument('post', 'p2', { title: 'Q', slug: 'hello' }) + const ctx = system() + expect( + (await getAs(ctx, { collection: 'post', locator: 'hello' }))?.id, + ).toBe('p2') + const restore = await failure(restoreDocument('post', 'p1')) + expect(restore.code).toBe('VALIDATION_FAILED') + await commitDocument('post', 'p2', { title: 'Q', slug: 'other' }) + await restoreDocument('post', 'p1') + expect( + (await getAs(ctx, { collection: 'post', locator: 'hello' }))?.id, + ).toBe('p1') + }) + }) + + it('lets only one of two concurrent writes claim a locator', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'warm', { title: 'W', slug: 'warm' }) + const results = await Promise.allSettled([ + commitDocument('post', 'a', { title: 'A', slug: 'race' }), + commitDocument('post', 'b', { title: 'B', slug: 'race' }), + ]) + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1) + const rejected = results.find((r) => r.status === 'rejected') + expect((rejected as PromiseRejectedResult).reason.code).toBe( + 'VALIDATION_FAILED', + ) + }) + }) + + it('rejects a duplicate the storage index catches', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'p1', { title: 'P', slug: 'hello' }) + const storage = await getStorage() + const row = await storage.getDocument('post', 'p1') + const err = await failure( + storage.transaction((tx) => + tx.putDocument( + { + collection: 'post', + id: 'p2', + doc: { ...row!.doc, title: 'Q' }, + updatedAt: row!.updatedAt, + }, + { + published: false, + locale: 'en', + slug: 'hello', + title: 'Q', + publishAt: null, + unpublishAt: null, + deletedAt: null, + locators: [{ locale: 'en', locator: 'hello' }], + }, + ), + ), + ) + expect(err.code).toBe('VALIDATION_FAILED') + }) + }) +}) + +describe('generated slugs', () => { + const slugOf = async (collection: string, id: string) => + (await getAs(system(), { collection, id }))?.doc.slug + + it('get -2, -3 when their locator is taken; explicit slugs still fail', async () => { + const cms = createCms(config()) + await run(cms, async () => { + for (const id of ['p1', 'p2', 'p3']) + await commitDocument('post', id, { title: 'Update' }) + expect(await slugOf('post', 'p1')).toBe('update') + expect(await slugOf('post', 'p2')).toBe('update-2') + expect(await slugOf('post', 'p3')).toBe('update-3') + // Re-saving keeps a document's own locator. + await commitDocument('post', 'p2', { title: 'Update' }) + expect(await slugOf('post', 'p2')).toBe('update-2') + const explicit = await failure( + commitDocument('post', 'p4', { title: 'Update', slug: 'update' }), + ) + expect(explicit.code).toBe('VALIDATION_FAILED') + // A generated slug that is another document's id is suffixed too. + await commitDocument('page', 'about', { title: 'Company' }) + await commitDocument('page', 'p2', { title: 'About' }) + expect(await slugOf('page', 'p2')).toBe('about-2') + }) + }) + + it('suffix the last segment of a nested slug', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('page', 'a', { title: 'Guides/Intro' }) + await commitDocument('page', 'b', { title: 'Guides/Intro' }) + expect(await slugOf('page', 'a')).toBe('guides/intro') + expect(await slugOf('page', 'b')).toBe('guides/intro-2') + }) + }) + + it('keep their suffix through review, and a clash at approval fails', async () => { + const cms = createCms(config()) + await run(cms, async () => { + await commitDocument('post', 'p1', { title: 'Update' }) + const staged = await stageWrite({ + collection: 'post', + docId: 'p2', + type: 'create', + doc: { title: 'Update' }, + actor: 'agent', + }) + expect(staged.after.slug).toBe('update-2') + await approve(staged.id) + expect(await slugOf('post', 'p2')).toBe('update-2') + + const first = await stageWrite({ + collection: 'post', + docId: 'q1', + type: 'create', + doc: { title: 'Fresh' }, + actor: 'agent', + }) + const second = await stageWrite({ + collection: 'post', + docId: 'q2', + type: 'create', + doc: { title: 'Fresh' }, + actor: 'agent', + }) + expect(second.after.slug).toBe('fresh') + await approve(first.id) + const clash = await failure(approve(second.id)) + expect(clash.code).toBe('VALIDATION_FAILED') + }) + }) +}) + +describe('locales', () => { + it('keeps locators per document locale', async () => { + const cms = createCms(config({ i18n })) + await run(cms, async () => { + await commitDocument('post', 'en1', { title: 'E', slug: 'hello' }) + await commitDocument('post', 'fr1', { + title: 'F', + slug: 'hello', + locale: 'fr', + }) + const ctx = system() + expect( + (await getAs(ctx, { collection: 'post', locator: 'hello' }))?.id, + ).toBe('en1') + expect( + ( + await getAs(ctx, { + collection: 'post', + locator: 'hello', + locale: 'fr', + }) + )?.id, + ).toBe('fr1') + const dup = await failure( + commitDocument('post', 'fr2', { + title: 'F2', + slug: 'hello', + locale: 'fr', + }), + ) + expect(dup.details[0]?.message).toMatch(/in locale "fr"/) + }) + }) + + it('indexes each locale of a field-localized slug', async () => { + const cms = createCms(config({ i18n })) + await run(cms, async () => { + await commitDocument('article', 'a1', { + title: 'A', + slug: makeLocalizedValue({ en: 'hello', fr: 'bonjour' }), + }) + const ctx = system() + expect( + await getAs(ctx, { + collection: 'article', + locator: 'bonjour', + locale: 'fr', + }), + ).toMatchObject({ id: 'a1', locator: 'bonjour' }) + expect( + await getAs(ctx, { collection: 'article', locator: 'bonjour' }), + ).toMatchObject({ id: 'a1', locator: 'bonjour' }) + expect( + await getAs(ctx, { + collection: 'article', + locator: 'hello', + locale: 'fr', + }), + ).toBeNull() + expect( + (await getAs(ctx, { collection: 'article', locator: 'hello' }))?.id, + ).toBe('a1') + const dup = await failure( + commitDocument('article', 'a2', { + title: 'B', + slug: makeLocalizedValue({ en: 'other', fr: 'bonjour' }), + }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + await commitDocument('article', 'a3', { + title: 'C', + slug: makeLocalizedValue({ en: 'bonjour', fr: 'salut' }), + }) + }) + }) +}) + +describe('adapters without findDocumentsByLocator', () => { + function withoutLocatorIndex(inner: StorageAdapter): StorageAdapter { + const strip = (ops: StorageOps): StorageOps => ({ + ...ops, + findDocumentsByLocator: undefined, + }) + return { + ...inner, + findDocumentsByLocator: undefined, + transaction: (fn) => inner.transaction((tx) => fn(strip(tx))), + } + } + + it('fall back to slug and id lookups, with the same rules', async () => { + const base = config() + const cms = createCms({ + ...base, + storage: withoutLocatorIndex( + createSqliteStorage({ path: join(base.dataDir!, 'cms.db') }), + ), + }) + await run(cms, async () => { + expect((await getStorage()).findDocumentsByLocator).toBeUndefined() + await commitDocument('page', 'home', { title: 'Home', slug: '/' }) + await commitDocument('page', 'intro', { + title: 'Intro', + slug: 'guides/intro', + }) + await commitDocument('note', 'n1', { title: 'Note' }) + const ctx = system() + expect((await getAs(ctx, { collection: 'page', locator: '/' }))?.id).toBe( + 'home', + ) + expect( + (await getAs(ctx, { collection: 'page', locator: 'guides/intro' }))?.id, + ).toBe('intro') + expect( + (await getAs(ctx, { collection: 'note', locator: 'n1' }))?.id, + ).toBe('n1') + expect( + await getAs(ctx, { collection: 'page', locator: 'intro' }), + ).toBeNull() + const dup = await failure( + commitDocument('page', 'home2', { title: 'H', slug: '/' }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + }) + }) +}) + +describe('building the locator index from stored documents', () => { + const locatorVersion = SQL_MIGRATIONS.find((m) => + m.name.startsWith('locators'), + )!.version + + /** A database written before the locator index, with these rows. */ + async function legacyDb( + rows: Array<{ + collection?: string + id: string + doc: Record + locale?: string + trashed?: boolean + }>, + ) { + const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-locators-')) + dirs.push(dataDir) + const path = join(dataDir, 'cms.db') + const driver = createNodeSqliteDriver(path) + await runSqlMigrations( + driver, + SQL_MIGRATIONS.filter((m) => m.version < locatorVersion), + ) + for (const row of rows) { + const slug = typeof row.doc.slug === 'string' ? row.doc.slug : null + await driver.run( + `INSERT INTO documents (collection, id, doc, updated_at, published, locale, slug, title, deleted_at) + VALUES (?, ?, ?, '2026-01-01T00:00:00.000Z', 1, ?, ?, ?, ?)`, + [ + row.collection ?? 'post', + row.id, + JSON.stringify({ + ...row.doc, + locale: row.locale ?? 'en', + published: true, + }), + row.locale ?? 'en', + slug, + row.id, + row.trashed ? '2026-01-02T00:00:00.000Z' : null, + ], + ) + } + await driver.run( + `INSERT OR REPLACE INTO meta (key, value) VALUES ('seeded', '1')`, + ) + await driver.close() + return { dataDir, path } + } + + function open( + db: { dataDir: string; path: string }, + extra?: Partial, + ) { + const warnings: Array = [] + const cms = createCms({ + ...config(extra), + dataDir: db.dataDir, + storage: createSqliteStorage({ path: db.path }), + logger: { + warn: (message: string) => warnings.push(message), + error: () => {}, + }, + }) + return { cms, warnings } + } + + it('fills the index on first use, the first id keeping a shared locator', async () => { + const db = await legacyDb([ + { id: 'a', doc: { title: 'A', slug: 'hello' } }, + { id: 'b', doc: { title: 'B', slug: 'hello' } }, + { id: 'c', doc: { title: 'C' } }, + { id: 'd', doc: { title: 'D', slug: 'c' } }, + { id: 'f', doc: { title: 'F', slug: 'hello' }, locale: 'fr' }, + { id: 'g', doc: { title: 'G', slug: 'hello' }, trashed: true }, + { + collection: 'page', + id: 'intro', + doc: { title: 'I', slug: '/guides//intro/' }, + }, + ]) + const { cms, warnings } = open(db, { i18n }) + await run(cms, async () => { + const ctx = system() + const id = async (collection: string, locator: string, locale?: string) => + (await getAs(ctx, { collection, locator, locale }))?.id + expect(await id('post', 'hello')).toBe('a') + expect(await id('post', 'hello', 'fr')).toBe('f') + expect(await id('post', 'c')).toBe('c') + expect(await id('page', 'guides/intro')).toBe('intro') + expect(warnings).toHaveLength(1) + expect(warnings[0]).toContain('post (en) "hello": a, b') + expect(warnings[0]).toContain('post (en) "c": c, d') + expect(warnings[0]).not.toContain('(fr)') + // The others stay readable by id; saving one needs a distinct slug. + expect( + (await getAs(ctx, { collection: 'post', id: 'b' }))?.doc.title, + ).toBe('B') + const dup = await failure( + commitDocument('post', 'b', { title: 'B', slug: 'hello' }), + ) + expect(dup.code).toBe('VALIDATION_FAILED') + await commitDocument('post', 'b', { title: 'B', slug: 'bye' }) + expect(await id('post', 'bye')).toBe('b') + }) + await closeStore() + const again = open(db, { i18n }) + await run(again.cms, async () => { + expect( + await getAs(system(), { collection: 'post', locator: 'hello' }), + ).toMatchObject({ id: 'a' }) + }) + expect(again.warnings).toEqual([]) + }) + + it('indexes every locale of a localized slug and follows strategy changes', async () => { + const db = await legacyDb([ + { + collection: 'article', + id: 'a1', + doc: { + title: 'A', + slug: makeLocalizedValue({ en: 'hello', fr: 'bonjour' }), + }, + }, + { collection: 'product', id: 'x1', doc: { title: 'X', code: 'abc' } }, + ]) + const first = open(db, { i18n }) + await run(first.cms, async () => { + expect( + await getAs(system(), { + collection: 'article', + locator: 'bonjour', + locale: 'fr', + }), + ).toMatchObject({ id: 'a1' }) + expect( + (await getAs(system(), { collection: 'product', locator: 'codes/abc' })) + ?.id, + ).toBe('x1') + }) + await closeStore() + const plain = defineCollection({ + name: 'product', + label: 'Products', + titleField: 'title', + fields: product.fields, + }) + const second = open(db, { + i18n, + collections: [page, post, note, article, plain], + }) + await run(second.cms, async () => { + expect( + await getAs(system(), { collection: 'product', locator: 'codes/abc' }), + ).toBeNull() + expect( + (await getAs(system(), { collection: 'product', locator: 'x1' }))?.id, + ).toBe('x1') + }) + }) +}) diff --git a/packages/core/tests/migrations.test.ts b/packages/core/tests/migrations.test.ts index 18accd80..29eba56f 100644 --- a/packages/core/tests/migrations.test.ts +++ b/packages/core/tests/migrations.test.ts @@ -34,6 +34,39 @@ describe('sql migrations', () => { await driver.close() } }) + it('applies every migration once and in order, fresh or from v15', async () => { + const versions = SQL_MIGRATIONS.map((migration) => migration.version) + expect(versions).toEqual(versions.map((_, i) => i + 1)) + const fresh = createNodeSqliteDriver(':memory:') + try { + expect(await runSqlMigrations(fresh)).toEqual(versions) + expect(await runSqlMigrations(fresh)).toEqual([]) + } finally { + await fresh.close() + } + const old = createNodeSqliteDriver(':memory:') + try { + await runSqlMigrations( + old, + SQL_MIGRATIONS.filter((migration) => migration.version <= 15), + ) + expect(await runSqlMigrations(old)).toEqual( + versions.filter((version) => version > 15), + ) + const pending = await old.all<{ name: string }>( + `SELECT name FROM pragma_table_info('pending')`, + ) + expect(pending.map((c) => c.name)).toContain('workflow_state') + expect( + await old.all( + `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'locators'`, + ), + ).toHaveLength(1) + } finally { + await old.close() + } + }) + it('enforces unique revision numbers per document', async () => { const driver = createNodeSqliteDriver(':memory:') try { diff --git a/packages/core/tests/read-verbs.test.ts b/packages/core/tests/read-verbs.test.ts index 2c5c5941..9e038dc1 100644 --- a/packages/core/tests/read-verbs.test.ts +++ b/packages/core/tests/read-verbs.test.ts @@ -182,6 +182,7 @@ describe('get', () => { const byId = await pub.get({ collection: 'post', id: 'hello' }) expect(byId).toEqual({ id: 'hello', + locator: 'hello', collection: 'post', doc: expect.objectContaining({ title: 'Hello' }), relations: { author: expect.objectContaining({ name: 'Ada' }) }, @@ -338,6 +339,7 @@ describe('list', () => { expect(page.total).toBe(2) expect(page.items[0]).toEqual({ id: 'hello', + locator: 'hello', collection: 'post', doc: expect.not.objectContaining({ secret: 's1' }), relations: { author: expect.objectContaining({ name: 'Ada' }) }, diff --git a/packages/core/tests/transfer.test.ts b/packages/core/tests/transfer.test.ts index feed37ce..f99ee0e0 100644 --- a/packages/core/tests/transfer.test.ts +++ b/packages/core/tests/transfer.test.ts @@ -29,6 +29,7 @@ import { } from '../src/server' import { createSqliteStorage } from '../src/storage' import type { CmsConfig } from '../src/index' +import { SQL_MIGRATIONS } from '../src/storage/migrations' const dirs: Array = [] @@ -259,7 +260,7 @@ describe('seed, migrate, backup', () => { expect(before).toMatchObject({ storage: 'sqlite', current: 0 }) const migrated = await migrateStorage() expect(migrated.current).toBe(migrated.latest) - expect(migrated.applied.length).toBe(migrated.latest) + expect(migrated.applied).toEqual(SQL_MIGRATIONS.map((m) => m.version)) expect((await migrateStorage()).applied).toEqual([]) }) diff --git a/packages/store-postgres/src/index.ts b/packages/store-postgres/src/index.ts index dcefe353..bc939290 100644 --- a/packages/store-postgres/src/index.ts +++ b/packages/store-postgres/src/index.ts @@ -267,6 +267,18 @@ export function createPostgresStorage( if (!error || typeof error !== 'object') return error const pg = error as { code?: string; constraint?: string; message?: string } if (pg.code === '23505') { + if (pg.constraint === prefix + 'locators_unique') + return new CmsError( + 'Another document already has this locator (its slug, or its id) in this collection and locale.', + 'VALIDATION_FAILED', + [ + { + path: ['locator'], + message: 'Must be unique.', + reason: 'unique_violation', + }, + ], + ) const spec = uniqueIndexes.get(pg.constraint ?? '') if (spec) return new CmsError( @@ -431,6 +443,14 @@ export function createPostgresStorage( ) ).map(toDocument) }, + async findDocumentsByLocator(collection, locator, locale) { + return q<{ id: string; locale: string }>( + `SELECT doc_id AS id, locale FROM ${t('locators')} WHERE collection = $1 AND locator = $2${locale === undefined ? '' : ' AND locale = $3'}`, + locale === undefined + ? [collection, locator] + : [collection, locator, locale], + ) + }, async queryDocuments(filter) { if (!filter.collections.length) return { items: [], total: 0 } const p = new Parameters() @@ -487,7 +507,7 @@ export function createPostgresStorage( record.collection, record.id, JSON.stringify(record.doc), - JSON.stringify(index), + JSON.stringify({ ...index, locators: undefined }), record.updatedAt, index.publishAt, index.unpublishAt, @@ -496,6 +516,22 @@ export function createPostgresStorage( index.deletedAt ?? null, ], ) + if (!index.locators) return + await q( + `DELETE FROM ${t('locators')} WHERE collection = $1 AND doc_id = $2`, + [record.collection, record.id], + ) + if (index.locators.length === 0) return + await q( + `INSERT INTO ${t('locators')}(collection, locale, locator, doc_id) + SELECT $1, locale, locator, $2 FROM unnest($3::text[], $4::text[]) AS l(locale, locator)`, + [ + record.collection, + record.id, + index.locators.map((l) => l.locale), + index.locators.map((l) => l.locator), + ], + ) }, async deleteDocument(collection, id) { await lock('document', JSON.stringify([collection, id]), explicit) diff --git a/packages/store-postgres/src/migrations.ts b/packages/store-postgres/src/migrations.ts index ebca6236..b224f3c4 100644 --- a/packages/store-postgres/src/migrations.ts +++ b/packages/store-postgres/src/migrations.ts @@ -386,6 +386,29 @@ export const POSTGRES_MIGRATIONS: ReadonlyArray = [ `) }, }, + { + // Version 8 is 4b's change-set state (#29); this one is numbered after it. + version: 9, + name: 'locators: one per collection, locale and locator', + async up({ client, table: t }) { + // Empty on purpose: the engine fills it on first use + // (`ensureLocatorIndex`), with each collection's locatorStrategy. + await client.query(` + CREATE TABLE ${t('locators')} ( + collection TEXT NOT NULL, + locale TEXT NOT NULL, + locator TEXT NOT NULL, + doc_id TEXT NOT NULL, + CONSTRAINT ${t('locators_unique')} PRIMARY KEY (collection, locale, locator), + FOREIGN KEY (collection, doc_id) REFERENCES ${t('documents')}(collection, id) ON DELETE CASCADE + ); + CREATE INDEX ${t('idx_locators_doc')} ON ${t('locators')}(collection, doc_id); + `) + }, + async down({ client, table: t }) { + await client.query(`DROP TABLE ${t('locators')}`) + }, + }, ] export const LATEST_POSTGRES_SCHEMA_VERSION = diff --git a/packages/store-postgres/tests/postgres.test.ts b/packages/store-postgres/tests/postgres.test.ts index aa4f1d56..e52b3534 100644 --- a/packages/store-postgres/tests/postgres.test.ts +++ b/packages/store-postgres/tests/postgres.test.ts @@ -765,6 +765,87 @@ describe.skipIf(!url)('Postgres migrations', () => { }) }) + it('numbers migrations in order and upgrades a v7 database through every later one', async () => { + expect(versions).toEqual(versions.map((_, i) => i + 1)) + const s = createStorage(newPrefix()) + expect(await s.migrateTo(7)).toEqual(versions.filter((v) => v <= 7)) + expect(await s.migrate()).toEqual(versions.filter((v) => v > 7)) + expect(await s.schemaStatus()).toEqual({ current: LATEST, latest: LATEST }) + }) + + it('adds an empty locator index that the engine fills on first use', async () => { + const locatorVersion = POSTGRES_MIGRATIONS.find((m) => + m.name.startsWith('locators'), + )!.version + const before = Math.max( + ...versions.filter((version) => version < locatorVersion), + ) + const prefix = newPrefix() + const s = createStorage(prefix) + await s.migrateTo(before) + const put = ( + id: string, + extra: { slug?: string | null; locale?: string }, + ) => + s.putDocument( + { + collection: 'post', + id, + doc: { + headline: id, + locale: extra.locale ?? 'en', + ...(extra.slug ? { slug: extra.slug } : {}), + }, + updatedAt: now, + }, + index(id, extra), + ) + await put('a', { slug: 'hello' }) + await put('b', { slug: 'hello' }) + await put('c', { slug: null }) + await put('f', { slug: 'hello', locale: 'fr' }) + await s.setMeta('seeded', '1') + expect(await s.migrate()).toEqual([locatorVersion]) + const located = async (locator: string, locale?: string) => + (await s.findDocumentsByLocator!('post', locator, locale)) + .map((m) => `${m.id}@${m.locale}`) + .sort() + expect(await located('hello')).toEqual([]) + + const warnings: Array = [] + const cms = defineCms({ + storage: s, + collections: [ + { + name: 'post', + label: 'Posts', + titleField: 'headline', + fields: [ + { name: 'headline', label: 'Headline', type: 'text' }, + { name: 'slug', label: 'Slug', type: 'slug' }, + ], + }, + ], + blockTypes: [], + i18n: { locales: [{ code: 'en' }, { code: 'fr' }], defaultLocale: 'en' }, + logger: { warn: (m: string) => warnings.push(m), error: () => {} }, + }) + await runWithCmsConfig(cms, async () => { + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.headline, + ).toBe('a') + expect(await located('hello')).toEqual(['a@en', 'f@fr']) + expect(await located('c')).toEqual(['c@en']) + expect(warnings.join('\n')).toContain('post (en) "hello": a, b') + await expect( + commitDocument('post', 'b', { headline: 'b', slug: 'hello' }), + ).rejects.toMatchObject({ code: 'VALIDATION_FAILED' }) + await deleteDocument('post', 'a', { purge: true }) + expect(await located('hello')).toEqual(['f@fr']) + }) + expect(await s.migrateTo(before)).toEqual([locatorVersion]) + }) + it('times out on a held migration lock and recovers after release', async () => { const prefix = newPrefix() const client = await pool?.connect() diff --git a/starters/documentation-kb/src/cms.definition.ts b/starters/documentation-kb/src/cms.definition.ts index e8593a9b..6ea0573a 100644 --- a/starters/documentation-kb/src/cms.definition.ts +++ b/starters/documentation-kb/src/cms.definition.ts @@ -12,6 +12,13 @@ export const definition = defineCmsDefinition({ bodyField: 'body', path: (doc, id) => `/docs/${String(doc.version ?? 'v2')}/${String(doc.slug ?? id)}`, + // Slugs repeat across releases (v1/install, v2/install), so the + // version is part of the locator. + locatorStrategy: { + name: 'versionedSlug', + locate: ({ id, doc }) => + `${String(doc.version ?? 'v2')}/${typeof doc.slug === 'string' && doc.slug ? doc.slug : id}`, + }, fields: [ { name: 'title', label: 'Page Title', type: 'text', required: true }, { name: 'slug', label: 'Slug', type: 'slug', from: 'title' }, diff --git a/starters/headless-api/tests/contract.test.ts b/starters/headless-api/tests/contract.test.ts index 3ca4b8d2..5f5d6141 100644 --- a/starters/headless-api/tests/contract.test.ts +++ b/starters/headless-api/tests/contract.test.ts @@ -87,7 +87,11 @@ describe('starter-headless-api — Seam S3 & S5 acceptance tests', () => { arguments: { collection: 'contentItem', id: 'item-mcp', - doc: { title: 'Omnichannel Item', channel: 'agent', priority: 3 }, + doc: { + title: 'Omnichannel Item (agent)', + channel: 'agent', + priority: 3, + }, }, }, }), diff --git a/starters/multi-tenant-fleet/src/cms.definition.ts b/starters/multi-tenant-fleet/src/cms.definition.ts index 7c2ea812..344c9bb7 100644 --- a/starters/multi-tenant-fleet/src/cms.definition.ts +++ b/starters/multi-tenant-fleet/src/cms.definition.ts @@ -25,6 +25,12 @@ export const definition = defineCmsDefinition({ label: 'Tenant Pages', titleField: 'title', bodyField: 'body', + // Each tenant has its own `home`, so the tenant is part of the locator. + locatorStrategy: { + name: 'tenantSlug', + locate: ({ id, doc }) => + `${String(doc.tenantId)}/${typeof doc.slug === 'string' && doc.slug ? doc.slug : id}`, + }, fields: [ { name: 'tenantId',