diff --git a/.changeset/write-verbs-save-act.md b/.changeset/write-verbs-save-act.md new file mode 100644 index 00000000..81940e35 --- /dev/null +++ b/.changeset/write-verbs-save-act.md @@ -0,0 +1,17 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-client': minor +--- + +`save` and `act` are the canonical writes, rooted in the operations registry beside `get` and `list` (`writeVerbs`, `saveInput`, `actInput` in `@tanstack/cms-core`). Every write is an action of the collection's document state strategy, and both return `{ id, collection, doc, state: { label, published, revision, changeSet }, availableActions }`. + +- Server: `cmsAs(cms, ctx).save({ collection, id, doc, create?, publish?, expectedRevision?, expectedPendingVersion?, instruction? })` and `.act({ collection, id, action, publishAt?, reason?, expectedVersion? })`, and the argument forms `saveAs(ctx, options)` and `actAs(ctx, options)`. `save` merges `doc`, a patch, onto the caller's own open change set or the live document. The caller picks the action: an agent `submit`s for review, a publisher `edit`s (a draft of a published document unless `publish` is set), and anyone else `submit`s. `act` runs an action the strategy offers the caller (`approve`, `reject`, `discard`, `schedule`, or a custom step). `documentWriteState(collection, id)` reads the `state` on its own. +- HTTP and Start: the `save` (`content.write`) and `act` operations, and Start server functions. +- Client: `client.save(options)` and `client.act(options)`, typed from `Register`. +- Agents: `save_document`, named `_` from the registry. An agent's save is always staged for review. `act` is not an agent tool. +- Reads that feed a write: `get` takes `staged: false` (in `getInput`, so on every surface) to read the committed document without its staged changes, published or not. It is the canonical form of `readDocumentAs` in an `edit` or system context. + +**Breaking:** `save`, `act` and `save_document` are reserved operation names, so an app op with one of these names fails as a duplicate. + +`saveDoc`, `createDoc` and `actOnChange` (operations), and `create_document` and `update_document` (agent tools), are deprecated in favour of `save` and `act`. They now run on the same path and keep their bags and results. diff --git a/docs/agents/content-agent.md b/docs/agents/content-agent.md index 751c843c..e58e19dc 100644 --- a/docs/agents/content-agent.md +++ b/docs/agents/content-agent.md @@ -88,7 +88,7 @@ const reply = await chat({ ### Tools and Permissions -The agent uses the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `get_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`. +The agent uses the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `get_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `save_document`, `create_document` and `update_document` (deprecated), `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`. The tools run with the signed-in user's session, so the agent sees only the collections and fields that user may read, and preserves fields they may not write. Every write is **staged** in the [review queue](./review-queue) with `actor: 'content-agent'`, even when an admin is chatting. When the agent stages something, the page shows a **Review changes** link to `/review`. diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index 15857220..a645c4c9 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -80,7 +80,7 @@ An agent often makes several edits to the same document before anyone reviews th The pending change belongs to the door that opened it: an agent proposal (`agent`), an author's save (`review`) or a publisher's draft (`draft`). While it is open, a write through another door fails with `CONFLICT` and `details: { pendingId, source }` naming it. Approve, reject or discard it first. -Agents can read their own staged work. `get_document` (in the agent's `edit` mode) and `update_document` read the pending version, including a document that hasn't been committed yet, so an agent can create a document, read it back, and refine it before anyone approves. `list_documents` lists committed documents; staged creates appear in the review queue. +Agents can read their own staged work. `get_document` (in the agent's `edit` mode), `save_document` and `update_document` read the pending version, including a document that hasn't been committed yet, so an agent can create a document, read it back, and refine it before anyone approves. `list_documents` lists committed documents; staged creates appear in the review queue. ## Reviewing Changes diff --git a/docs/api/cms-client.md b/docs/api/cms-client.md index 8b4d46c7..31480390 100644 --- a/docs/api/cms-client.md +++ b/docs/api/cms-client.md @@ -84,6 +84,31 @@ console.log(about?.doc, first.items.length, next?.total) `get` resolves to `{ id, collection, doc }`, or `null` when the document is missing or the caller can't see it. `list` resolves to `{ items: [{ id, collection, doc }], total, nextCursor? }`. Both are public: anonymous callers read published documents, and callers who may read drafts see the working copy unless the client's `mode` is `live`. +### `save(options)` and `act(options)` + +The canonical writes, the `save` and `act` operations, with the bags of [`saveAs` and `actAs`](./cms-core-server#saveasctx-options-and-actasctx-options). `save` takes a patch: only the fields to change. Both resolve to `{ id, collection, doc, state, availableActions }`. `state.label` names where the document stands (`Published`, `Draft`, `Pending Review`), and `state.revision` and `state.changeSet?.version` are what the next save sends as `expectedRevision` and `expectedPendingVersion`. + +```ts validate=type +import { createCmsClient } from '@tanstack/cms-client' + +const cms = createCmsClient({ + baseUrl: 'https://cms.example.com', + getAuthHeader: () => 'Bearer tscms_example', +}) + +const saved = await cms.save({ collection: 'post', id: 'hello', doc: { title: 'Hello again' } }) +if (saved.availableActions.some((a) => a.type === 'approve')) + await cms.act({ collection: 'post', id: 'hello', action: 'approve' }) +const next = await cms.save({ + collection: 'post', + id: 'hello', + doc: { excerpt: 'Short' }, + expectedRevision: saved.state.revision, + expectedPendingVersion: saved.state.changeSet?.version ?? 0, +}) +console.log(next.state.label) +``` + ### `op(name, input)` and `call(name, input?)` `op(name, input)` calls any built-in operation by name: a `POST` with a JSON body to `/api/cms/v1/ops/`, resolving to the `result`. Input and output are typed per operation. `call(name, input?)` hits the same endpoint for untyped or dynamic operations — including agent tools (`list_documents`, `search_documents`, …) and app-defined operations registered with `defineCms({ ops })`. The list of operations and their access levels is in [Routes & HTTP Endpoints](./routes-and-endpoints#operations). @@ -101,7 +126,7 @@ console.log(found?.collection, redirect?.to, custom.count) ### `collection(name)` -Typed helpers for one collection, wrapping the older document operations. Its `list` and `get` are the admin editor's reads; for content, use the client's `get` and `list`: +Typed helpers for one collection, wrapping the older document operations. Its `list` and `get` are the admin editor's reads, and `save` and `create` the deprecated `saveDoc` and `createDoc`; for content, use the client's `get`, `list` and `save`: | Method | Operation | Access | Returns | | --- | --- | --- | --- | diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index 4dc62b10..8e0b2f2a 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -73,10 +73,10 @@ Contexts are frozen and come from the builders. A copied object is not a context ### `cmsAs(cms, ctx)` ```ts -function cmsAs(cms: Cms | CmsConfig, ctx: AccessContext): CmsReads +function cmsAs(cms: Cms | CmsConfig, ctx: AccessContext): CmsAs // CmsReads & CmsWrites ``` -The read verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned). `get` and `list` are the canonical reads (see [`getAs` and `listAs`](#getasctx-options-and-listasctx-options)). The older vocabulary is bound too: `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the `…As` functions below, without the context. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`. +The read and write verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned). `get` and `list` are the canonical reads (see [`getAs` and `listAs`](#getasctx-options-and-listasctx-options)), and `save` and `act` the canonical writes (see [`saveAs` and `actAs`](#saveasctx-options-and-actasctx-options)). The older vocabulary is bound too: `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the `…As` functions below, without the context. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`. ```ts validate=type import { defineCms } from '@tanstack/cms-core' @@ -110,7 +110,7 @@ export async function sitemapIds() { } ``` -Each verb also has an argument form taking the context first: `getAs(ctx, options)`, `listAs(ctx, options)`, `queryDocumentsAs(ctx, options)`, `readDocumentAs(ctx, collection, id)`, `readDocumentBySlugAs`, `findDocumentBySlugAs`, `readSingletonAs`, `readDocumentWithPendingAs`, `queryDocumentSummariesAs`, `listDocumentsAs`, `groupDocumentsAs`, `populateRelationsAs`, `findReferencesAs`, `listTranslationsAs` and `listRevisionsAs`. These read against the registered CMS. +Each verb also has an argument form taking the context first: `getAs(ctx, options)`, `listAs(ctx, options)`, `saveAs(ctx, options)`, `actAs(ctx, options)`, `queryDocumentsAs(ctx, options)`, `readDocumentAs(ctx, collection, id)`, `readDocumentBySlugAs`, `findDocumentBySlugAs`, `readSingletonAs`, `readDocumentWithPendingAs`, `queryDocumentSummariesAs`, `listDocumentsAs`, `groupDocumentsAs`, `populateRelationsAs`, `findReferencesAs`, `listTranslationsAs` and `listRevisionsAs`. These run against the registered CMS. ### Checks @@ -139,6 +139,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 populate?: boolean // default false } & ({ id: string } | { locator: string }) // exactly one @@ -168,10 +169,28 @@ interface ListResult { } ``` -The canonical reads. One bag each, the same at every layer: the store (`cmsAs(cms, ctx).get/list`), HTTP and Start (the `get` and `list` operations), `@tanstack/cms-client` (`client.get/list`), and the agent tools (`get_document`, `list_documents`). The bag carries no visibility. The context decides it: +The canonical reads. One bag each, the same at every layer: the store (`cmsAs(cms, ctx).get/list`), HTTP and Start (the `get` and `list` operations), `@tanstack/cms-client` (`client.get/list`), and the agent tools (`get_document`, `list_documents`). The writes, `save` and `act`, follow the same pattern. The bag carries no visibility. The context decides it: - A `live` context reads published documents only. - A `preview` or `edit` context reads the working copy, with staged changes overlaid. +- `get` with `staged: false` reads the committed document instead, published or not: the row a write must see. Use it for a read that feeds a write, such as a read-modify-write or a check for an existing document before a create. + +```ts validate=type +import { commitDocument, getAs, systemContext } from '@tanstack/cms-core/server' + +const CARTS = systemContext('carts are server-owned records') + +export async function addToCart(cartId: string, variantId: string) { + const cart = await getAs(CARTS, { collection: 'cart', id: cartId, staged: false }) + const items = JSON.parse(String(cart?.doc.itemsJson ?? '[]')) as Array + await commitDocument( + 'cart', + cartId, + { ...cart?.doc, itemsJson: JSON.stringify([...items, variantId]) }, + { expectedRevision: Number(cart?.doc._revision ?? 0) }, + ) +} +``` 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. @@ -464,6 +483,83 @@ How a save behaves depends on the document and the caller: Every commit records a revision and bumps `_revision`. Pass the revision you loaded as `expectedRevision` to fail with `CONFLICT` when someone else saved in the meantime. +`saveAs` and `actAs` are the canonical writes: they pick the door from the caller and report where the document stands. The functions after them are the doors themselves. + +### `saveAs(ctx, options)` and `actAs(ctx, options)` + +```ts +function saveAs(ctx: AccessContext, options: SaveOptions): Promise +function actAs(ctx: AccessContext, options: ActOptions): Promise + +interface SaveOptions { + collection: string + id: string + doc: Record // the fields to change; `null` clears one + create?: boolean // fail with CONFLICT when the document exists + publish?: boolean // a published document: go live now instead of a draft + expectedRevision?: number // the live `_revision` you loaded (0 for none) + expectedPendingVersion?: number // the open change set's version (0 for none) + instruction?: string // review queue note and revision summary +} + +interface ActOptions { + collection: string + id: string + action: string // one of the document's `availableActions` + publishAt?: string | null // `schedule` + reason?: string // for the audit trail + expectedVersion?: number // the open change set's version you loaded +} + +interface WriteResult { + id: string + collection: string + doc: TDoc // the working copy: the open change set, else live (redacted) + state: { + label: string // the strategy's name for the state: 'Published', 'Draft', 'Pending Review', … + published: boolean + revision: number // the next `expectedRevision` + changeSet: { id: string; version: number; source: 'agent' | 'review' | 'draft'; publishAt: string | null } | null + } + availableActions: Array // what ctx can do next +} + +type ActResult = Omit, 'doc'> & { doc: TDoc | null } +``` + +The canonical writes, one bag each at every layer: the store (`cmsAs(cms, ctx).save/act`), HTTP and Start (the `save` and `act` operations), `@tanstack/cms-client` (`client.save/act`), and the agent tool `save_document`. Each is an action of the collection's [document state strategy](../agents/review-queue#choosing-the-flow-document-state-strategies). + +`save` merges `doc`, a patch, onto the caller's working copy: their own open change set, else the live document. A missing document is created, with the collection's field defaults. Who the caller is picks the action: + +- **An agent** (an agent context, or the `save_document` tool) `submit`s: the change is staged for review, and `publish` is ignored. +- **A caller who may publish the collection** (or a system context) `edit`s: the change commits, except that a published document gets a draft unless `publish` is set (as `commitDocument` and `saveDraft` do). +- **Anyone else** (an author) `submit`s for review. + +Another door's open change set refuses the save with `CONFLICT` until it's resolved. A public context is `UNAUTHORIZED`. + +`act` runs one of the actions the strategy offers `ctx` now (`approve`, `reject`, `discard`, `schedule`, or a custom one such as `approve:legal`). An action that isn't offered is `FORBIDDEN`, and the change-carrying actions (`edit`, `submit`, `draft`, `import`) are `save`'s. Its `doc` is `null` once the document is gone (a rejected create, an applied delete). + +The result feeds straight back into an editor: `doc` is the next baseline, and `state.revision` and `state.changeSet?.version` are the next save's `expectedRevision` and `expectedPendingVersion`. + +```ts validate=type +import { accessContext, cmsAs, resolveSession } from '@tanstack/cms-core/server' +import type { Cms } from '@tanstack/cms-core' + +export async function rename(cms: Cms, request: Request, id: string, title: string) { + const db = cmsAs(cms, accessContext({ session: await resolveSession(request) })) + const current = await db.get({ collection: 'post', id }) + const saved = await db.save({ + collection: 'post', + id, + doc: { title }, + expectedRevision: typeof current?.doc._revision === 'number' ? current.doc._revision : 0, + }) + if (saved.availableActions.some((a) => a.type === 'approve')) + await db.act({ collection: 'post', id, action: 'approve' }) + return saved.state.label +} +``` + ### `commitDocument(collection, id, doc, options?)` ```ts diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index b98e9b2d..494dd4a7 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -809,7 +809,7 @@ interface OpSchema { const opSchemas: Array ``` -The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP: `list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations` (read), and `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document` (write, always staged for review). The server runs them with `runOp()` from `@tanstack/cms-core/server`. See [Shared Operation Registry](../mcp/operations-registry). +The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP: `list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations` (read), and `save_document`, `create_document` (deprecated), `update_document` (deprecated), `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document` (write, always staged for review). The server runs them with `runOp()` from `@tanstack/cms-core/server`. See [Shared Operation Registry](../mcp/operations-registry). These agent tools are separate from the HTTP API operations (`saveDoc`, `getPublicDocument`, …) in [`@tanstack/cms-api`](./cms-api). diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index 5dea234e..dba38b78 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -237,8 +237,10 @@ 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, 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. | +| `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`. | | `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 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`). | | `listDocumentSummaries` | GET | `content.read` | `{ collection, search?, status?: 'all' \| 'published' \| 'draft' \| 'scheduled', locale?, ids? (≤ 500), sort?: { field, dir? }, limit? (1–500, default 50), offset?, columns? (≤ 20) }` | `{ items: DocSummary[], total }` | | `getDocument` | GET | `content.read` | `{ collection, id }` | `{ doc, isPending, pendingId?, pendingSource?, livePublished }`, including any staged change. | | `resolveRedirect` | GET | public | `{ path }` | `{ to, status }` or `null` | @@ -246,15 +248,15 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/ | `listPublishedDocuments` | GET | public | `{ collection, where?, sort?: { field, dir? }, limit? (≤ 500, default 100), offset?, cursor? }` | `{ items: [{ id, doc }], total, nextCursor? }` | | `getDocEditorMeta` | GET | `content.read` | `{ collection, id }` | `{ revisions, translations, references }` | | `restoreDocRevision` | POST | `content.publish` | `{ collection, id, revisionId }` | `{ ok, doc }` | -| `saveDoc` | POST | `content.write` | `{ collection, id, doc, expectedRevision?, publish? }` | `{ ok, staged, draft?, pendingId?, doc }`. Staged for review without publish rights; a draft when the document is published and `publish` is not set. | -| `createDoc` | POST | `content.write` | `{ collection, id, doc? }` | As `saveDoc`. `CONFLICT` when the id exists. | +| `saveDoc` | POST | `content.write` | `{ collection, id, doc, expectedRevision?, publish? }` | `{ ok, staged, draft?, pendingId?, doc }`. Deprecated: use `save`. Staged for review without publish rights; a draft when the document is published and `publish` is not set. | +| `createDoc` | POST | `content.write` | `{ collection, id, doc? }` | As `saveDoc`. Deprecated: use `save` with `create: true`. `CONFLICT` when the id exists. | | `discardDraft` | POST | `content.write` | `{ collection, id }` | `{ ok }`. Also needs publish rights. | | `deleteDoc` | POST | `content.delete` | `{ collection, id, force? }` | `{ ok }` | | `bulkDocuments` | POST | `content.write` | `{ collection, ids (1–100), action: 'publish' \| 'unpublish' \| 'delete' }` | `{ ok, results: [{ id, ok, error?: { code, message } }] }`. `delete` also needs `content.delete`; `publish` and `unpublish` need publish rights. One failed item doesn't stop the rest. | | `reviewSnapshot` | GET | `content.read` | `{}` | `{ pending, audit }`. Each pending change carries `review: { label, actions, stranded? }` from its strategy, for the caller. Drafts are excluded unless stranded. | | `approveChange` | POST | `review.decide` | `{ id, publish?, force? }` | The approved pending change. A reviewer without `content.publish` moves it to **Approved** for a publisher to publish. `CONFLICT` when the document changed since the proposal was staged, unless `force` is set. | | `rejectChange` | POST | `review.decide` | `{ id }` | The rejected pending change. | -| `actOnChange` | POST | `content.read` | `{ id, action, publishAt?: string \| null, reason?, expectedVersion? }` | `{ ok, effects, label }`. Runs only an action the change set's strategy offers the caller now (`FORBIDDEN` otherwise); actions that carry a document (`edit`, `submit`, `draft`, `import`) are `BAD_REQUEST`. `CONFLICT` when `expectedVersion` is stale. | +| `actOnChange` | POST | `content.read` | `{ id, action, publishAt?: string \| null, reason?, expectedVersion? }` | `{ ok, effects, label }`. Deprecated: use `act`. Runs only an action the change set's strategy offers the caller now (`FORBIDDEN` otherwise); actions that carry a document (`edit`, `submit`, `draft`, `import`) are `BAD_REQUEST`. `CONFLICT` when `expectedVersion` is stale. | | `proposeEdit` | POST | `agent.use` | `{ collection, id, instruction, current }` | The AI-proposed document (not saved). | | `agentChat` | POST | `agent.use` | `{ messages: [{ role: 'user' \| 'assistant', content }], includeToolResults? }` | `{ reply, toolResults? }`. Actual tool receipts are opt-in; record writes are staged. | | `editPageBlocks` | POST | `agent.use` | `{ id, collection?, blocksField?, instruction }` | `{ blocks }` (not saved) | @@ -280,7 +282,7 @@ Operations that need `agent.use` also count against the `ai` rate limit and retu ### `/api/mcp` -A [Model Context Protocol](../mcp/http-mcp-server) server over Streamable HTTP (`GET`, `POST`, `DELETE`), exposing the agent tools (`list_documents`, `get_document`, `create_document`, …). Write tools stage their changes for review. +A [Model Context Protocol](../mcp/http-mcp-server) server over Streamable HTTP (`GET`, `POST`, `DELETE`), exposing the agent tools (`list_documents`, `get_document`, `save_document`, …). Write tools stage their changes for review. Access is granted to: diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index faf36680..e2bbcaa0 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -451,6 +451,42 @@ and a later alpha moves the starters and docs over. - **`get` and `list` are reserved operation names**: an app op with either name now fails as a duplicate. +### 27. One write vocabulary: `save` and `act` + +`save` and `act` are the canonical writes, rooted in the operations registry +beside `get` and `list`: `cmsAs(cms, ctx).save/act` (or `saveAs`/`actAs`) on +the server, the `save` and `act` operations over HTTP and Start, +`client.save/act`, and the agent tool `save_document`. Every write is an +action of the collection's document state strategy, and both return +`{ id, collection, doc, state, availableActions }`. See +[`saveAs` and `actAs`](../api/cms-core-server#saveasctx-options-and-actasctx-options). + +```ts +const { doc, state } = await cmsAs(cms, ctx).save({ + collection: 'post', + id: 'hello', + doc: { title: 'Hello again' }, // only the fields to change + expectedRevision: 3, +}) +``` + +The older writes keep working as they did and are removed in a later alpha: + +- **`saveDoc`, `createDoc` and `actOnChange`** are deprecated in favour of + `save`, `save` with `create: true`, and `act`. They keep their bags and + results. `client.collection(name).save/create` call them. +- **`create_document` and `update_document`** are deprecated in favour of + `save_document`, which takes only the changed fields and returns the + document's state. They keep their bags and results. +- **`save`, `act` and `save_document` are reserved operation names**: an app + op with one of these names now fails as a duplicate. + +A read that feeds a write (a read-modify-write, or a check for an existing +document before a create) must see the committed document, not the working +copy. `get` takes `staged: false` for that, so +`readDocumentAs(ctx, collection, id)` in an `edit` or system context becomes +`(await getAs(ctx, { collection, id, staged: false, populate: false }))?.doc ?? null`. + ## Versioning policy From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The diff --git a/docs/mcp/http-mcp-server.md b/docs/mcp/http-mcp-server.md index 3ba86ed4..24cf6097 100644 --- a/docs/mcp/http-mcp-server.md +++ b/docs/mcp/http-mcp-server.md @@ -37,7 +37,7 @@ export const cmsMcp = createMCPServer({ - `GET /api/mcp` opens the server-to-client stream. - `DELETE /api/mcp` ends a session. -The tools are the agent tools listed in the [Operations Registry](./operations-registry#the-agent-tool-registry-opschemas): the read tools (`list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations`) and six write tools that stage changes (`create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`). +The tools are the agent tools listed in the [Operations Registry](./operations-registry#the-agent-tool-registry-opschemas): the read tools (`list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations`) and the write tools that stage changes (`save_document`, `create_document` and `update_document` (deprecated), `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document`). ## Who Can Connect diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index de3461cb..7f60e017 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -170,8 +170,9 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/ | `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), and pagination (`limit`, `offset`, `cursor`) | | `list_revisions` | read | Revision history, newest first | | `list_translations` | read | A document's locale variants | -| `create_document` | write | Stage a new document | -| `update_document` | write | Stage an update (merged over the current document) | +| `save_document` | write | Stage a new document or a change: `doc` holds only the fields to change, `create: true` refuses an existing id. Returns `{ id, collection, doc, state, availableActions }` | +| `create_document` | write | Deprecated: use `save_document` with `create: true`. Stage a new document | +| `update_document` | write | Deprecated: use `save_document`. Stage an update (merged over the current document) | | `delete_document` | write | Stage a deletion | | `unpublish_document` | write | Stage unpublishing | | `restore_revision` | write | Stage restoring a revision | @@ -179,9 +180,11 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/ The read tools come from the canonical read vocabulary, `readVerbs`: each verb's agent tool name is derived as `_` (`get` → `get_document`, `list` → `list_documents`, see `agentToolName`), and its input schema is the verb's bag (`getInput`, `listInput`), the same one the `get` and `list` operations, `client.get/list` and `cmsAs(cms, ctx).get/list` take. Full-text search stays its own tool, `search_documents`. +The write tool comes from the canonical write vocabulary, `writeVerbs`, the same way: `save` → `save_document`, with the `saveInput` bag the `save` operation, `client.save` and `cmsAs(cms, ctx).save` take. An agent's save is always the strategy's `submit`, so it is staged for review. `act` (approve, reject, discard, …) is not an agent tool: review decisions stay with people. + Two server-side pieces in `@tanstack/cms-core/server` attach behavior: -- **`runOp(name, input, actor, access)`** executes a tool as an access context (every transport builds one per request; a call without one throws `UNAUTHORIZED`). With a session-bearing context, it requires `content.read` for read tools and `content.write` for write tools (`content.delete` for `delete_document` and `content.publish` for `unpublish_document`, matching the human operations), checks the collection's `access` rules and API key scope, hides collections the session cannot read, redacts unreadable fields, and preserves fields the session cannot write. Write tools never commit: they call `stageWrite()`, so the change waits in the [review queue](../agents/review-queue) with `actor` recorded. +- **`runOp(name, input, actor, access)`** executes a tool as an access context (every transport builds one per request; a call without one throws `UNAUTHORIZED`). With a session-bearing context, it requires `content.read` for read tools and `content.write` for write tools (`content.delete` for `delete_document` and `content.publish` for `unpublish_document`, matching the human operations), checks the collection's `access` rules and API key scope, hides collections the session cannot read, redacts unreadable fields, and preserves fields the session cannot write. Write tools never commit: they stage the change (`save_document` through `saveAs`, the others through `stageWrite()`), so it waits in the [review queue](../agents/review-queue) with `actor` recorded. - **`cmsTools(actor, { access })`** wraps every agent tool (`agentOpSchemas()`: `opSchemas` plus your ops marked `agent`) as a `@tanstack/ai` server tool bound to an actor and a context. A host serving many callers from one tool set passes each call's context under `CMS_ACCESS_KEY` instead. | Surface | How it uses the tools | Actor | diff --git a/docs/tutorials/mcp-and-webmcp.md b/docs/tutorials/mcp-and-webmcp.md index 65978da6..2aa3a6af 100644 --- a/docs/tutorials/mcp-and-webmcp.md +++ b/docs/tutorials/mcp-and-webmcp.md @@ -14,7 +14,7 @@ keywords: - unstable_WebMcpBadge --- -Every TanStack CMS app exposes the same content tools (`list_collections`, `list_documents`, `get_document`, `create_document`, `update_document`, `delete_document`, `unpublish_document`, `search_documents`, `list_revisions`, `restore_revision`, `schedule_document`, `list_translations`) across three agent surfaces: +Every TanStack CMS app exposes the same content tools (`list_collections`, `list_documents`, `get_document`, `save_document`, `delete_document`, `unpublish_document`, `search_documents`, `list_revisions`, `restore_revision`, `schedule_document`, `list_translations`) across three agent surfaces: 1. **In-app content agent** at `/agent` (actor `content-agent`; needs a text adapter in `defineCms({ ai })`) 2. **HTTP MCP server** at `/api/mcp` (actor `mcp`) diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 75778825..9e55025c 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -18,6 +18,7 @@ import { z } from 'zod' import { DEFAULT_UNCONFIGURED_SESSION, + actInput, aiBlocksSchema, blockTypeMap, blockTypes, @@ -33,14 +34,15 @@ import { listInput, normalizeBlocks, resolveDocumentLocale, + saveInput, scalarSchemaFor, schemaFor, sortInput, validateWithStandardSchema, whereInput, + writeVerbs, } from '@tanstack/cms-core' import { - actOnDocument, agentOps, approve, availableDocumentActions, @@ -50,10 +52,8 @@ import { runOp, cmsTools, loadTanstackAi, - commitDocument, resolveRedirect, discardDraft, - saveDraft, deleteDocument, restoreDocument, listAudit, @@ -67,6 +67,8 @@ import { queryDocumentSummariesAs, getAs, listAs, + runAct, + runSave, accessContext, systemContext, assertReadable, @@ -76,7 +78,6 @@ import { previewContext, redactFor, withMode, - protectWrite, assertCollectionAccess, createApiKey, listApiKeys, @@ -91,7 +92,6 @@ import { createDbUser, setDbUserDisabled, getPending, - submitWrite, listComments, resolveComment, deleteComment, @@ -107,6 +107,7 @@ import { aiCapabilities, requireTextAdapter } from './ai' import { mediaOps } from './media-ops' import { interfaceOps } from './interface-ops' import { + actResultOutput, documentOutput, documentSummariesOutput, getOutput, @@ -116,6 +117,7 @@ import { publishedDocumentsOutput, redirectOutput, writeOutput, + writeResultOutput, } from './outputs' import type { ActionDescriptor, @@ -128,6 +130,7 @@ import type { GetOptions, OpAccess, ReadVerbName, + WriteVerbName, } from '@tanstack/cms-core' import type { AccessContext, @@ -284,9 +287,6 @@ const actOnChangeInput = z.object({ expectedVersion: z.number().int().min(0).optional(), }) -/** Actions that carry a document: they go through `saveDoc`, not `actOnChange`. */ -const CHANGE_CARRYING_ACTIONS = new Set(['edit', 'submit', 'draft', 'import']) - /** What the review queue shows about a change set: from its strategy, for the caller. */ export interface ChangeSetReview { /** The strategy's label for the change set's state. */ @@ -446,7 +446,8 @@ function canPublish( } /** - * Save on behalf of a human. With publish rights it commits; otherwise it is + * `save` on behalf of a human, with the `saveDoc` result: with publish rights + * it commits (or keeps a draft of a published document); otherwise it is * staged for review (an author's edit). */ async function saveAsHuman( @@ -462,98 +463,65 @@ async function saveAsHuman( publish?: boolean }, ) { - const { session } = ctx - const existing = opts.create - ? null - : await readDocumentAs(OP_READ, collection, id) - assertCollectionAccess( - session, - collection, - existing ? 'update' : 'create', - existing ?? doc, - ) - const open = existing - ? await readDocumentWithPendingAs(OP_READ, collection, id) - : null - // A re-save merges onto this door's own open change set; another door's is - // refused by the strategy executor until it's resolved. - const ownSource = canPublish(session, collection, existing ?? (doc as Doc)) - ? 'draft' - : 'review' - const base = open?.pendingSource === ownSource ? open.doc : existing - const safe = protectWrite( - collection, - { ...base, ...doc } as Doc, - existing, - session, - ) - if (!canPublish(session, collection, existing ?? safe)) { - const outcome = await submitWrite({ + const saved = await runSave( + editing(ctx), + { collection, - docId: id, - type: existing || !opts.create ? 'update' : 'create', - doc: safe, - actor: 'human', - source: 'review', + id, + doc, + ...(opts.create ? { create: true } : {}), + ...(opts.publish ? { publish: true } : {}), + expectedRevision: opts.expectedRevision, expectedPendingVersion: opts.expectedPendingVersion, - instruction: opts.summary, - expectedRevision: - opts.expectedRevision ?? - (typeof existing?._revision === 'number' ? existing._revision : 0), - }) - if (outcome.committed || !outcome.pending) { - return { - ok: true, - staged: false, - doc: redactFor( - ctx.access, - collection, - (outcome.committed ?? outcome.change.doc) as Doc, - ), - } - } - return { - ok: true, - staged: true, - pendingId: outcome.pending.id, - doc: redactFor(ctx.access, collection, outcome.pending.after as Doc), - } - } - const isDraft = - existing?.published === true && safe.published !== false && !opts.publish - if (isDraft) { - const pending = await saveDraft(collection, id, safe, { - expectedPendingVersion: opts.expectedPendingVersion, - actor: 'human', - expectedRevision: - opts.expectedRevision ?? - (typeof existing?._revision === 'number' ? existing._revision : 0), - summary: opts.summary, - }) + ...(opts.summary ? { instruction: opts.summary } : {}), + }, + { by: 'human', door: 'human' }, + ) + const out = saved.result.doc + if (saved.door === 'draft' && saved.pending) return { - ok: true, + ok: true as const, staged: false, draft: true, - pendingId: pending.id, - doc: redactFor(ctx.access, collection, pending.after as Doc), + pendingId: saved.pending.id, + doc: out, } - } - const committed = await commitDocument(collection, id, safe, { - session, - expectedPendingVersion: opts.expectedPendingVersion, - actor: 'human', - expectedRevision: - opts.expectedRevision ?? - (typeof existing?._revision === 'number' ? existing._revision : 0), - summary: opts.summary, - }) - return { - ok: true, - staged: false, - doc: redactFor(ctx.access, collection, committed), - } + if (saved.door === 'submit' && saved.pending && !saved.committed) + return { + ok: true as const, + staged: true, + pendingId: saved.pending.id, + doc: out, + } + return { ok: true as const, staged: false, doc: out } } +/** + * The write verbs as operations, one per `writeVerbs` entry: the `satisfies` + * keeps each op's name the registry's. + */ +const writeVerbOps = { + save: { + method: 'POST', + access: 'content.write', + description: writeVerb('save').description, + input: saveInput, + output: writeResultOutput, + run: async (input: z.infer, ctx: CmsOpContext) => + (await runSave(editing(ctx), input, { by: ctx.actor })).result, + }, + act: { + method: 'POST', + access: 'content.read', + description: `${writeVerb('act').description} The document's workflow decides which actions you may take.`, + input: actInput, + output: actResultOutput, + run: async (input: z.infer, ctx: CmsOpContext) => + (await runAct(ctx.access, input)).result, + }, + // oxlint-disable-next-line no-explicit-any -- per-op types are preserved via typeof writeVerbOps +} satisfies Record> + const _ops = { ...interfaceOps, getAuthSession: { @@ -647,6 +615,8 @@ const _ops = { listAs(readerContext(ctx, input.collection), input), }, + ...writeVerbOps, + getPublicDocument: { method: 'GET', access: 'public', @@ -858,7 +828,7 @@ const _ops = { method: 'POST', access: 'content.write', description: - 'Save a document (human inline edit). Commits with publish rights; otherwise stages it for review.', + 'Save a document (human inline edit). Commits with publish rights; otherwise stages it for review. Deprecated: use `save`.', input: saveDocInput, output: writeOutput, run: async (input: z.infer, ctx: CmsOpContext) => @@ -893,34 +863,15 @@ const _ops = { createDoc: { method: 'POST', access: 'content.write', - description: 'Create a document.', + description: + 'Create a document. Deprecated: use `save` with `create: true`.', input: createDocInput, output: writeOutput, - run: async (input: z.infer, ctx: CmsOpContext) => { - const collection = getCmsConfig().collections[input.collection] - if (!collection) { - throw new CmsError( - `Unknown collection: ${input.collection}`, - 'NOT_FOUND', - ) - } - const existing = ( - await readDocumentWithPendingAs(OP_READ, input.collection, input.id) - ).doc - if (existing) { - throw new CmsError( - `Document "${input.id}" already exists in ${input.collection}.`, - 'CONFLICT', - ) - } - return saveAsHuman( - ctx, - input.collection, - input.id, - { ...emptyDoc(collection), ...(input.doc ?? {}) }, - { summary: 'Created document', create: true }, - ) - }, + run: async (input: z.infer, ctx: CmsOpContext) => + saveAsHuman(ctx, input.collection, input.id, input.doc ?? {}, { + summary: 'Created document', + create: true, + }), }, deleteDoc: { @@ -1307,69 +1258,26 @@ const _ops = { method: 'POST', access: 'content.read', description: - "Run an action the change set's document state strategy offers the caller (a custom approval, a discard, a schedule).", + "Run an action the change set's document state strategy offers the caller (a custom approval, a discard, a schedule). Deprecated: use `act`.", input: actOnChangeInput, run: async (input: z.infer, ctx: CmsOpContext) => { const pending = await getPending(input.id) if (!pending) throw new CmsError(`Unknown pending change: ${input.id}`, 'NOT_FOUND') - if ( - input.expectedVersion !== undefined && - (pending.version ?? 0) !== input.expectedVersion - ) - throw new CmsError( - 'This change set changed since you loaded it. Reload and try again.', - 'CONFLICT', - { pendingId: pending.id }, - ) - const access = editing(ctx) - assertReadable(access, pending.collection, { - id: pending.docId, - doc: - (await readDocumentAs(OP_READ, pending.collection, pending.docId)) ?? - pending.before ?? - pending.after, - }) - if (CHANGE_CARRYING_ACTIONS.has(input.action)) - throw new CmsError( - `"${input.action}" carries a document: save it with saveDoc.`, - 'BAD_REQUEST', - ) - const offered = await availableDocumentActions( - access, - pending.collection, - pending.docId, - ) - if (!offered.some((a) => a.type === input.action)) - throw new CmsError( - `"${input.action}" is not available to you on this change set.`, - 'FORBIDDEN', - ) - if ( - typeof input.publishAt === 'string' && - Number.isNaN(Date.parse(input.publishAt)) - ) - throw new CmsError( - `Invalid publishAt datetime: "${input.publishAt}"`, - 'BAD_REQUEST', - ) - const outcome = await actOnDocument(access, { + const acted = await runAct(ctx.access, { collection: pending.collection, id: pending.docId, - action: { - type: input.action, - input: { - ...(input.publishAt !== undefined - ? { publishAt: input.publishAt } - : {}), - ...(input.reason ? { reason: input.reason } : {}), - }, - }, + action: input.action, + ...(input.publishAt !== undefined + ? { publishAt: input.publishAt } + : {}), + ...(input.reason ? { reason: input.reason } : {}), + expectedVersion: input.expectedVersion, }) return { ok: true, - effects: outcome.effects.map((e) => e.type), - label: await documentStateLabel(pending.collection, pending.docId), + effects: acted.outcome.effects.map((e) => e.type), + label: acted.result.state.label, } }, }, @@ -2223,6 +2131,13 @@ function readVerb(name: ReadVerbName) { return verb } +/** A canonical write verb from the registry. */ +function writeVerb(name: WriteVerbName) { + const verb = writeVerbs.find((v) => v.name === name) + if (!verb) throw new Error(`Unknown write verb: ${name}`) + return verb +} + const onPageSystem = () => `You edit the blocks of a CMS page in place. Given the current blocks and an ` + `instruction, return the COMPLETE updated blocks array. Keep blocks the ` + diff --git a/packages/api/src/outputs.ts b/packages/api/src/outputs.ts index 0d9e72d4..8a53e4a0 100644 --- a/packages/api/src/outputs.ts +++ b/packages/api/src/outputs.ts @@ -105,6 +105,39 @@ export const writeOutput = z.object({ doc, }) +const writeState = z.object({ + label: z.string().describe("The workflow's label for the state."), + published: z.boolean(), + revision: z + .number() + .describe( + 'The live `_revision` (0 for none): the next `expectedRevision`.', + ), + changeSet: z + .object({ + id: z.string(), + version: z.number().describe('The next save’s `expectedPendingVersion`.'), + source: z.enum(['agent', 'review', 'draft']), + publishAt: z.string().nullable(), + }) + .nullable(), +}) + +const actionDescriptor = z.object({ + type: z.string(), + label: z.string(), + tone: z.enum(['default', 'primary', 'danger']).optional(), +}) + +export const writeResultOutput = docEntry.extend({ + state: writeState, + availableActions: z.array(actionDescriptor), +}) + +export const actResultOutput = writeResultOutput.extend({ + doc: doc.nullable(), +}) + export const mediaListOutput = z.object({ items: z.array(mediaItem), total: z.number(), diff --git a/packages/api/src/start.ts b/packages/api/src/start.ts index 2f4eba17..846510a2 100644 --- a/packages/api/src/start.ts +++ b/packages/api/src/start.ts @@ -124,6 +124,14 @@ export const list = createServerFn({ method: 'GET' }) .validator(ops.list.input) .handler(async ({ data }) => invokeOp('list', data, await req())) +export const save = createServerFn({ method: 'POST' }) + .validator(ops.save.input) + .handler(async ({ data }) => invokeOp('save', data, await req())) + +export const act = createServerFn({ method: 'POST' }) + .validator(ops.act.input) + .handler(async ({ data }) => invokeOp('act', data, await req())) + export const listDocumentSummaries = createServerFn({ method: 'GET' }) .validator(ops.listDocumentSummaries.input) .handler(async ({ data }) => diff --git a/packages/api/tests/write-verbs.test.ts b/packages/api/tests/write-verbs.test.ts new file mode 100644 index 00000000..a6392905 --- /dev/null +++ b/packages/api/tests/write-verbs.test.ts @@ -0,0 +1,202 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { actInput, saveInput, writeVerbs } from '@tanstack/cms-core' +import { + commitDocument, + listAudit, + listPending, + readDocumentAs, + systemContext, +} from '@tanstack/cms-core/server' +import { createCmsApiHandler } from '../src/http' +import { allOps, ops } from '../src/ops' +import { cleanup, req, setupCms } from './helpers' +import type { CmsConfig, WriteResult } from '@tanstack/cms-core' + +afterEach(cleanup) + +const handler = createCmsApiHandler() + +async function call(name: string, input: unknown, role?: string) { + const res = await handler( + req(`/api/cms/v1/ops/${name}`, { + method: 'POST', + role, + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(input), + }), + ) + const body = (await res.json()) as { + result?: unknown + error?: { code: string } + } + return { status: res.status, result: body.result, code: body.error?.code } +} + +const collections: Partial = { + collections: [ + { + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'body', label: 'Body', type: 'textarea' }, + { + name: 'internalNotes', + label: 'Internal notes', + type: 'text', + access: { read: ['editor', 'admin'] }, + }, + ], + }, + ], +} + +const live = (id: string) => readDocumentAs(systemContext('test'), 'post', id) + +describe('save and act over HTTP', () => { + it('are registry ops with the canonical bags', () => { + expect(ops.save.input).toBe(saveInput) + expect(ops.act.input).toBe(actInput) + const all = allOps() + for (const verb of writeVerbs) { + expect(all[verb.name]?.description).toContain(verb.description) + expect(all[`${verb.name}_${verb.noun}`]?.input).toBe( + verb.agent ? verb.input : undefined, + ) + } + }) + + it('save takes a patch and returns the state an editor sends back', async () => { + setupCms(collections) + await commitDocument('post', 'p', { + title: 'Live', + body: 'Body', + published: true, + }) + const first = await call( + 'save', + { collection: 'post', id: 'p', doc: { title: 'Draft title' } }, + 'editor', + ) + expect(first.status).toBe(200) + const draft = first.result as WriteResult + expect(draft.doc).toMatchObject({ title: 'Draft title', body: 'Body' }) + expect(draft.state).toMatchObject({ + label: 'Draft', + revision: 1, + changeSet: { source: 'draft', version: 1 }, + }) + const stale = await call( + 'save', + { + collection: 'post', + id: 'p', + doc: { body: 'x' }, + expectedPendingVersion: 0, + }, + 'editor', + ) + expect(stale).toMatchObject({ status: 409, code: 'CONFLICT' }) + const published = ( + await call( + 'save', + { + collection: 'post', + id: 'p', + doc: { body: 'New body' }, + publish: true, + expectedRevision: draft.state.revision, + expectedPendingVersion: draft.state.changeSet?.version, + }, + 'editor', + ) + ).result as WriteResult + expect(published.state).toMatchObject({ + label: 'Published', + revision: 2, + changeSet: null, + }) + expect(await live('p')).toMatchObject({ + title: 'Draft title', + body: 'New body', + }) + expect((await listAudit())[0]).toMatchObject({ actor: 'api' }) + }) + + it('an author’s save is a proposal an editor approves with act', async () => { + setupCms(collections) + await commitDocument('post', 'p', { + title: 'Live', + internalNotes: 'secret', + published: true, + }) + const proposed = ( + await call( + 'save', + { collection: 'post', id: 'p', doc: { title: 'Proposal' } }, + 'author', + ) + ).result as WriteResult + expect(proposed.state).toMatchObject({ + label: 'Pending Review', + changeSet: { source: 'review' }, + }) + expect(proposed.availableActions.map((a) => a.type)).toEqual(['submit']) + expect(proposed.doc).not.toHaveProperty('internalNotes') + const title = async (staged?: boolean) => + ( + (await call('get', { collection: 'post', id: 'p', staged }, 'editor')) + .result as { doc: { title: string } } + ).doc.title + expect(await title()).toBe('Proposal') + expect(await title(false)).toBe('Live') + + expect( + await call( + 'act', + { collection: 'post', id: 'p', action: 'approve' }, + 'author', + ), + ).toMatchObject({ status: 403, code: 'FORBIDDEN' }) + const approved = await call( + 'act', + { + collection: 'post', + id: 'p', + action: 'approve', + expectedVersion: proposed.state.changeSet?.version, + }, + 'editor', + ) + expect(approved.result).toMatchObject({ + doc: { title: 'Proposal', _revision: 2 }, + state: { label: 'Published', changeSet: null }, + }) + expect(await listPending()).toEqual([]) + expect(await live('p')).toMatchObject({ internalNotes: 'secret' }) + }) + + it('refuses anonymous writes', async () => { + setupCms(collections) + expect( + await call('save', { collection: 'post', id: 'p', doc: { title: 'x' } }), + ).toMatchObject({ status: 401 }) + }) + + it('save and act are reserved operation names', async () => { + setupCms({ + ...collections, + ops: [ + { + name: 'save', + access: 'public', + description: 'clash', + input: saveInput, + run: async () => null, + }, + ], + }) + expect(() => allOps()).toThrow(/Duplicate CMS operation name: "save"/) + }) +}) diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 9f3ea65c..b9b3566c 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -12,17 +12,21 @@ * const cms = createCmsClient({ baseUrl: 'https://cms.example.com', mode: 'live' }) * const { items } = await cms.list({ collection: 'post', limit: 10 }) * const post = await cms.get({ collection: 'post', locator: 'hello' }) + * const { doc, state } = await cms.save({ collection: 'post', id: 'hello', doc: { title: 'Hi' } }) * ``` * - * `get` and `list` are the canonical reads (the `get` and `list` operations). - * `collection(name)` keeps the older helpers: `published` (the - * `listPublishedDocuments` operation) and the admin editor's `list`/`get`. + * `get` and `list` are the canonical reads, `save` and `act` the canonical + * writes (the operations of the same names). `collection(name)` keeps the + * older helpers: `published` (the `listPublishedDocuments` operation), the + * admin editor's `list`/`get`, and `save`/`create`/`delete`. * * Document types come from the `Register` augmentation of * `@tanstack/cms-core` (`interface Register { cms: typeof cms }`). */ import type { CmsOpName, OpInput, OpOutput } from '@tanstack/cms-api' import type { + ActOptions, + ActResult, CmsErrorCode, GetOptions, ListOptions, @@ -33,6 +37,8 @@ import type { RegisteredOpInput, RegisteredOpName, RegisteredOpOutput, + SaveOptions, + WriteResult, } from '@tanstack/cms-core' import type { ReadMode } from '@tanstack/cms-core/server' @@ -146,6 +152,19 @@ export interface CmsClient { list: ( options?: ListOptions, ) => Promise>> + /** + * Create or change a document: `doc` holds the fields to change. Returns + * the working copy, the state (its `revision` and `changeSet.version` are + * the next save's `expectedRevision` / `expectedPendingVersion`), and the + * actions the caller can take next. + */ + save: ( + options: SaveOptions, + ) => Promise>> + /** Run an action from a document's `availableActions` (approve, reject, discard, …). */ + act: ( + options: ActOptions, + ) => Promise>> /** * Call a CMS operation by name. POSTs a JSON body to * `/api/cms/v1/ops/:name`. Fully typed per operation. @@ -264,6 +283,8 @@ export function createCmsClient(options: CmsClientOptions): CmsClient { call, get: (opts) => call('get', opts), list: (opts) => call('list', opts ?? {}), + save: (opts) => call('save', opts), + act: (opts) => call('act', opts), collection, cacheScope: options.cacheScope, ...(options.mode && { mode: options.mode }), diff --git a/packages/client/tests/client.test.ts b/packages/client/tests/client.test.ts index 20c6ca75..94ce88ab 100644 --- a/packages/client/tests/client.test.ts +++ b/packages/client/tests/client.test.ts @@ -107,6 +107,41 @@ describe('createCmsClient', () => { expect(err.code).toBe('BAD_REQUEST') }) + it('writes with the canonical save and act', async () => { + const editor = client('Bearer editor') + const created = await editor.save({ + collection: 'post', + id: 'n', + doc: { title: 'New', published: true }, + create: true, + }) + expect(created).toMatchObject({ + id: 'n', + doc: { title: 'New', _revision: 1 }, + state: { label: 'Published', revision: 1, changeSet: null }, + }) + const drafted = await editor.save({ + collection: 'post', + id: 'n', + doc: { title: 'Next' }, + expectedRevision: created.state.revision, + }) + expect(drafted.state.changeSet).toMatchObject({ source: 'draft' }) + const discarded = await editor.act({ + collection: 'post', + id: 'n', + action: 'discard', + }) + expect(discarded).toMatchObject({ + doc: { title: 'New' }, + state: { label: 'Published', changeSet: null }, + }) + const err = (await client() + .save({ collection: 'post', id: 'n', doc: { title: 'x' } }) + .catch((e: unknown) => e)) as CmsApiError + expect(err.code).toBe('UNAUTHORIZED') + }) + it('surfaces structured errors', async () => { const err = await client() .collection('post') diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 986a3740..69a64307 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -215,6 +215,7 @@ export type { LocalizedValue } from './i18n' // The CMS operation registry (client-safe: names, descriptions, input schemas). export { + actInput, agentOpSchemas, agentToolName, configuredOps, @@ -223,11 +224,15 @@ export { listInput, opSchemas, readVerbs, + saveInput, sortInput, validateWithStandardSchema, whereInput, + writeVerbs, } from './ops' export type { + ActOptions, + ActResult, CmsOpContext, CmsOpDefinition, CmsToolResult, @@ -242,6 +247,10 @@ export type { ReadResult, ReadVerbName, Relations, + SaveOptions, + WriteResult, + WriteState, + WriteVerbName, } from './ops' // Async events: the post-commit, durable half of the eventing design. The diff --git a/packages/core/src/ops.ts b/packages/core/src/ops.ts index a3c008cf..586f9c77 100644 --- a/packages/core/src/ops.ts +++ b/packages/core/src/ops.ts @@ -16,6 +16,7 @@ import { z } from 'zod' import { getCmsConfig } from './config' import { CmsError } from './errors' +import type { ActionDescriptor } from './document-state' import type { Permission } from './lib/access' import type { AccessContext } from './lib/access-context' import type { CmsSession } from './lib/auth' @@ -27,6 +28,7 @@ import type { StandardSchemaV1, StandardSchemaV1Issue, } from './schema' +import type { PendingSource } from './storage/types' export interface OpSchema { name: string @@ -247,6 +249,12 @@ export const getInput = z .string() .optional() .describe('With `locator`: match the document in this locale.'), + staged: z + .boolean() + .optional() + .describe( + 'Preview and edit readers: `false` reads the committed document without its staged changes, for a read that feeds a write. A live reader never sees staged changes.', + ), populate: populateInput, }) .refine((v) => (v.id === undefined) !== (v.locator === undefined), { @@ -289,6 +297,8 @@ export type Relations = Record | null> /** `get`'s options: `collection` plus exactly one of `id` or `locator`. */ export type GetOptions = { collection: C + /** `false`: the committed document, without staged changes (see `getInput`). */ + staged?: boolean locale?: string populate?: boolean } & ({ id: string; locator?: never } | { locator: string; id?: never }) @@ -348,7 +358,166 @@ export const readVerbs = [ export type ReadVerbName = (typeof readVerbs)[number]['name'] -/** The agent tool name of a read verb: `get` → `get_document`, `list` → `list_documents`. */ +/** + * The `save` bag: a patch of top-level fields merged onto the writer's + * working copy (their own open change set, else the live document). A field + * set to `null` is cleared. A missing document is created. + */ +export const saveInput = z.object({ + collection: z.string().min(1).describe('Collection name, e.g. "post".'), + id: z + .string() + .min(1) + .describe('The document id: url-safe, lowercase and hyphenated.'), + doc: docFields.describe( + 'The fields to change. Fields you leave out keep their current values.', + ), + create: z + .boolean() + .optional() + .describe( + 'Only create: fail with CONFLICT when the document already exists.', + ), + publish: z + .boolean() + .optional() + .describe( + 'For a published document: put the changes live now instead of saving them as a draft. Needs publish rights; ignored for agents.', + ), + expectedRevision: z + .number() + .int() + .min(0) + .optional() + .describe( + 'The live `_revision` you loaded (0 for none): CONFLICT if it moved.', + ), + expectedPendingVersion: z + .number() + .int() + .min(0) + .optional() + .describe( + 'The open change set’s version you loaded (0 for none): CONFLICT if it moved.', + ), + instruction: z + .string() + .optional() + .describe( + 'Short note on what was requested, shown in the review queue and the revision history.', + ), +}) + +/** The `act` bag: one of the actions the document's strategy offers. */ +export const actInput = z.object({ + collection: z.string().min(1).describe('Collection name, e.g. "post".'), + id: z.string().min(1).describe('The document id.'), + action: z + .string() + .min(1) + .describe( + 'An action from the document’s `availableActions`, e.g. `approve`, `reject`, `discard`, `schedule`, or a custom step such as `approve:legal`.', + ), + publishAt: z + .string() + .nullable() + .optional() + .describe('`schedule`: an ISO 8601 time to go live, or null to clear it.'), + reason: z + .string() + .max(2000) + .optional() + .describe('Why, for the audit trail (a rejection’s reason).'), + expectedVersion: z + .number() + .int() + .min(0) + .optional() + .describe( + 'The open change set’s version you loaded: CONFLICT if it moved.', + ), +}) + +/** `save`'s options (see `saveInput`). */ +export type SaveOptions = Omit< + z.input, + 'collection' +> & { collection: C } + +/** `act`'s options (see `actInput`). */ +export type ActOptions = Omit< + z.input, + 'collection' +> & { collection: C } + +/** Where a document stands after a write, as its strategy describes it. */ +export interface WriteState { + /** The strategy's label for the state (`Published`, `Draft`, `Pending Review`, …). */ + label: string + /** Whether the live document is published. */ + published: boolean + /** The live `_revision`; 0 when nothing is live yet. Send it as `expectedRevision`. */ + revision: number + /** The open change set, or `null`. Send `version` as `expectedPendingVersion`. */ + changeSet: { + id: string + version: number + /** Which door opened it: `agent`, `review` (an author's save) or `draft`. */ + source: PendingSource + /** When the scheduler publishes it, if scheduled. */ + publishAt: string | null + } | null +} + +/** + * What `save` and `act` return: the writer's working copy, where the + * document stands, and what the writer can do next. `doc` is the next + * baseline for an editor; `state` holds the versions its next save sends. + */ +export interface WriteResult { + id: string + collection: string + /** The working copy as the writer now sees it (the open change set, else live), redacted. */ + doc: TDoc + state: WriteState + availableActions: Array +} + +/** What `act` returns: as `WriteResult`, with `doc` `null` once the document is gone (a rejected create, an applied delete). */ +export type ActResult = Omit, 'doc'> & { + doc: TDoc | null +} + +/** + * The canonical write vocabulary, beside `readVerbs`. Each transport derives + * its name from this registry: the store (`cmsAs(cms, ctx).save`), HTTP and + * Start (`save`), the client (`client.save`) and, for verbs with `agent`, + * the agent tools (`save_document`, via `agentToolName`). Every write is an + * action of the document's state strategy: `save` is the `edit`, `draft` or + * `submit` action the writer's rights choose; `act` runs any other action. + */ +export const writeVerbs = [ + { + name: 'save', + noun: 'document', + agent: true, + description: + 'Create or change a document. `doc` holds only the fields to change; the rest keep their values. An agent’s save is staged for human approval in the review queue; a person’s save goes live, becomes a draft, or is submitted for review, as their rights and the collection’s workflow decide. Returns { id, collection, doc, state, availableActions }.', + input: saveInput, + }, + { + name: 'act', + noun: 'document', + agent: false, + description: + 'Run one of the actions the document’s workflow offers you (its `availableActions`): approve, reject, discard, schedule, or a custom step. Saving content is `save`. Returns { id, collection, doc, state, availableActions }, with doc null once the document is gone.', + input: actInput, + }, +] as const + +export type WriteVerbName = (typeof writeVerbs)[number]['name'] + +/** The agent tool name of a verb: `get` → `get_document`, `list` → `list_documents`, `save` → `save_document`. */ export function agentToolName(verb: { name: string; noun: string }): string { return `${verb.name}_${verb.noun}` } @@ -367,6 +536,18 @@ export const opSchemas: Array = [ description: verb.description, inputSchema: verb.input, })), + ...writeVerbs.flatMap((verb): Array => + verb.agent + ? [ + { + name: agentToolName(verb), + kind: 'write', + description: verb.description, + inputSchema: verb.input, + }, + ] + : [], + ), { name: 'read_document', kind: 'read', @@ -381,7 +562,7 @@ export const opSchemas: Array = [ name: 'create_document', kind: 'write', description: - 'Propose creating a new document. The write is STAGED for human approval and is not published until a person approves it in the review queue. Provide a url-safe id (lowercase, hyphenated) and every field for the collection.', + 'Deprecated: use save_document with create: true. Propose creating a new document. The write is STAGED for human approval and is not published until a person approves it in the review queue. Provide a url-safe id (lowercase, hyphenated) and every field for the collection.', inputSchema: z.object({ collection: z.string(), id: z.string().describe('url-safe id, lowercase and hyphenated'), @@ -398,7 +579,7 @@ export const opSchemas: Array = [ name: 'update_document', kind: 'write', description: - 'Propose updating an existing document. Read it first, then send the COMPLETE updated document (every field, not just the changed ones). The write is STAGED for human approval.', + 'Deprecated: use save_document, which takes only the changed fields. Propose updating an existing document. Read it first, then send the COMPLETE updated document (every field, not just the changed ones). The write is STAGED for human approval.', inputSchema: z.object({ collection: z.string(), id: z.string(), diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index ef9a6216..2d276764 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -65,8 +65,11 @@ export { availableDocumentActions, documentStateLabel, documentStateStrategy, + documentWriteState, listStrandedChangeSets, readChangeSet, + runAct, + runSave, } from './server/store' // Optional storage-capability narrowing (auth users / api keys / user roles). export { requireStorageCapability } from './storage/capabilities' @@ -108,6 +111,9 @@ export type { RefusalRule, StrandedChangeSet, StrategyOutcome, + ActOutcome, + RunSaveOptions, + SaveOutcome, } from './server/store' export { interfaceCollectionName, @@ -279,11 +285,13 @@ export type { TrustedActorKind, } from './server/access-context' export { cmsAs } from './server/cms-as' -export type { CmsReads } from './server/cms-as' -// The read verbs' context forms, underneath `cmsAs`. +export type { CmsAs, CmsReads, CmsWrites } from './server/cms-as' +// The read and write verbs' context forms, underneath `cmsAs`. export { + actAs, getAs, listAs, + saveAs, queryDocumentsAs, groupDocumentsAs, queryDocumentSummariesAs, diff --git a/packages/core/src/server/cms-as.ts b/packages/core/src/server/cms-as.ts index 95d8604f..cdd39834 100644 --- a/packages/core/src/server/cms-as.ts +++ b/packages/core/src/server/cms-as.ts @@ -1,16 +1,22 @@ /** - * The bound read handle: the read verbs with an access context bound once, - * scoped to one CMS instance. This is the idiom for reading content on the - * server; the store's `…As(ctx, …)` verbs are the argument form underneath. + * The bound handle: the read and write verbs with an access context bound + * once, scoped to one CMS instance. This is the idiom for reading and + * writing content on the server; the store's `…As(ctx, …)` verbs are the + * argument form underneath. * * ```ts * const db = cmsAs(cms, accessContext({ session: await resolveSession(request) })) * const post = await db.get({ collection: 'post', locator: 'hello' }) * const { items } = await db.list({ collection: 'post', limit: 10 }) + * const { doc, state, availableActions } = await db.save({ + * collection: 'post', + * id: 'hello', + * doc: { title: 'Hello again' }, + * }) * ``` * - * `get` and `list` are the canonical verbs; the others are the older - * vocabulary, kept until the codemod moves callers over. + * `get`, `list`, `save` and `act` are the canonical verbs; the other reads + * are the older vocabulary, kept until the codemod moves callers over. * * It is a function rather than a `cms.as(ctx)` method because `Cms` lives in * the client-safe config module, which must not reach the server read verbs. @@ -33,8 +39,18 @@ import { } from './store/read' import { listRevisionsAs } from './store/revisions' import { getAs, listAs } from './store/verbs' +import { actAs, saveAs } from './store/write-verbs' import type { Cms, RegisteredDoc, ResolvedCmsConfig } from '../config' -import type { GetOptions, ListOptions, ListResult, ReadResult } from '../ops' +import type { + ActOptions, + ActResult, + GetOptions, + ListOptions, + ListResult, + ReadResult, + SaveOptions, + WriteResult, +} from '../ops' import type { AccessContext } from './access-context' type Bound = F extends (ctx: AccessContext, ...args: infer A) => infer R @@ -67,6 +83,21 @@ export interface CmsReads { listRevisions: Bound } +/** The write verbs bound to one context (see `cmsAs`). */ +export interface CmsWrites { + /** Create or change a document as a strategy action (see `saveAs`). */ + save: ( + options: SaveOptions, + ) => Promise>> + /** Run an action the document's strategy offers (see `actAs`). */ + act: ( + options: ActOptions, + ) => Promise>> +} + +/** What `cmsAs` returns: the read and write verbs bound to one context. */ +export type CmsAs = CmsReads & CmsWrites + function isCmsInstance(cms: Cms | ResolvedCmsConfig): cms is Cms { return ( typeof (cms as Partial).run === 'function' && @@ -76,16 +107,13 @@ function isCmsInstance(cms: Cms | ResolvedCmsConfig): cms is Cms { } /** - * Bind `ctx` to `cms`'s read verbs. `cms` is a `createCms` instance or the + * Bind `ctx` to `cms`'s read and write verbs. `cms` is a `createCms` instance or the * config `defineCms` returned. Every call runs with that config in scope and * reads with `ctx`'s visibility and redaction: a `live` context sees * published documents only, fields `ctx` can't read are removed, and a * document it can't see reads as missing. */ -export function cmsAs( - cms: Cms | ResolvedCmsConfig, - ctx: AccessContext, -): CmsReads { +export function cmsAs(cms: Cms | ResolvedCmsConfig, ctx: AccessContext): CmsAs { const config = isCmsInstance(cms) ? cms.config : cms const bind = , R>( @@ -97,6 +125,8 @@ export function cmsAs( context: ctx, get: bind(getAs) as CmsReads['get'], list: bind(listAs) as CmsReads['list'], + save: bind(saveAs) as CmsWrites['save'], + act: bind(actAs) as CmsWrites['act'], queryDocuments: bind(queryDocumentsAs), groupDocuments: bind(groupDocumentsAs), queryDocumentSummaries: bind(queryDocumentSummariesAs), diff --git a/packages/core/src/server/cms-ops.ts b/packages/core/src/server/cms-ops.ts index efc91dfb..50cb228e 100644 --- a/packages/core/src/server/cms-ops.ts +++ b/packages/core/src/server/cms-ops.ts @@ -13,7 +13,6 @@ import { CmsError } from '../errors' import { configuredOps, opSchemas, validateWithStandardSchema } from '../ops' import { getCmsConfig } from '../config' -import { protectWrite } from './access' import { bypassesRules, canReadCollection, @@ -63,6 +62,30 @@ function staged(pending: store.Pending, status: string) { const QUEUED = 'Staged for human approval in the review queue.' +/** The deprecated `create_document` / `update_document` result. */ +function stagedToolResult( + ctx: AccessContext, + saved: store.SaveOutcome, + actor: string, + input: { collection: string; id: string; instruction?: string }, +) { + if (!saved.submitted) + throw new CmsError('The write was not staged.', 'CONFLICT') + const pending = store.stagedPending( + { + collection: input.collection, + docId: input.id, + actor, + instruction: input.instruction, + }, + saved.submitted, + ) + return { + ...staged(pending, QUEUED), + resultingDocument: redactFor(ctx, input.collection, pending.after), + } +} + /** * Agent tools that need more than `content.write`, mirroring the human ops: * proposing a delete needs delete rights, proposing an unpublish needs publish rights. @@ -71,6 +94,7 @@ const TOOL_ACCESS: Record< string, { permission: Permission; action: CollectionAction } > = { + save_document: { permission: 'content.write', action: 'create' }, create_document: { permission: 'content.write', action: 'create' }, update_document: { permission: 'content.write', action: 'update' }, delete_document: { permission: 'content.delete', action: 'delete' }, @@ -441,7 +465,7 @@ export async function runOp( assertCollectionAccess( session, data.collection, - name === 'create_document' && existing + (name === 'create_document' || name === 'save_document') && existing ? 'update' : (TOOL_ACCESS[name]?.action ?? (kind === 'write' ? 'update' : 'read')), @@ -499,41 +523,37 @@ async function dispatch( return found.doc } + case 'save_document': + return (await store.runSave(ctx, input, { by: actor, door: 'agent' })) + .result + case 'create_document': { - const doc = session - ? protectWrite(input.collection, input.doc ?? {}, null, session) - : input.doc - const pending = await store.stageWrite({ - collection: input.collection, - docId: input.id, - type: 'create', - doc, - actor, - instruction: input.instruction, - }) - return { - ...staged(pending, QUEUED), - resultingDocument: redactFor(ctx, input.collection, pending.after), - } + const saved = await store.runSave( + ctx, + { + collection: input.collection, + id: input.id, + doc: input.doc ?? {}, + instruction: input.instruction, + }, + { by: actor, door: 'agent', base: 'empty' }, + ) + return stagedToolResult(ctx, saved, actor, input) } case 'update_document': { - const existing = await readOrPending(input.collection, input.id) - const merged = { ...existing, ...input.doc } - const pending = await store.stageWrite({ - collection: input.collection, - docId: input.id, - type: 'update', - doc: session - ? protectWrite(input.collection, merged, existing, session) - : merged, - actor, - instruction: input.instruction, - }) - return { - ...staged(pending, QUEUED), - resultingDocument: redactFor(ctx, input.collection, pending.after), - } + await readOrPending(input.collection, input.id) + const saved = await store.runSave( + ctx, + { + collection: input.collection, + id: input.id, + doc: input.doc, + instruction: input.instruction, + }, + { by: actor, door: 'agent' }, + ) + return stagedToolResult(ctx, saved, actor, input) } case 'delete_document': { diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index 0112b39f..e36d1154 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -77,8 +77,15 @@ export type { QueryDocumentsResult, } from './store/query' export { getAs, listAs } from './store/verbs' +export { actAs, runAct, runSave, saveAs } from './store/write-verbs' +export type { + ActOutcome, + RunSaveOptions, + SaveOutcome, +} from './store/write-verbs' export { stageWrite, + stagedPending, submitWrite, listPending, getPending, @@ -94,6 +101,7 @@ export { availableDocumentActions, documentStateLabel, documentStateStrategy, + documentWriteState, listStrandedChangeSets, readChangeSet, } from './store/document-state' diff --git a/packages/core/src/server/store/document-state.ts b/packages/core/src/server/store/document-state.ts index 9a525927..61a9d85c 100644 --- a/packages/core/src/server/store/document-state.ts +++ b/packages/core/src/server/store/document-state.ts @@ -59,6 +59,7 @@ import { import { commitDeletion } from './write' import { systemContext } from '../access-context' import type { ResolvedCmsConfig } from '../../config' +import type { WriteState } from '../../ops' import type { Action, ActionDescriptor, @@ -263,6 +264,32 @@ export async function documentStateLabel( return strategy.label(view.changeSet?.workflow?.state, view) } +/** Where a document stands, as `save` and `act` report it (see `WriteState`). */ +export async function documentWriteState( + collection: string, + docId: string, +): Promise { + const storage = await getStorage() + const strategy = documentStateStrategy(collection) + const { view } = await loadView(storage, strategy, collection, docId) + const cs = view.changeSet + return { + label: cs?.stranded + ? 'Stranded' + : strategy.label(cs?.workflow?.state, view), + published: view.live?.published ?? false, + revision: view.live?.revision ?? 0, + changeSet: cs + ? { + id: cs.id, + version: cs.version, + source: cs.source, + publishAt: cs.publishAt, + } + : null, + } +} + /** * The document's open change set as its strategy reads it (state upgraded by * `migrate`, `stranded` set when it can't be read), or `null`. diff --git a/packages/core/src/server/store/review.ts b/packages/core/src/server/store/review.ts index 2fbd6f10..5ce11b68 100644 --- a/packages/core/src/server/store/review.ts +++ b/packages/core/src/server/store/review.ts @@ -104,7 +104,23 @@ export async function submitWrite( * document coalesces into the existing pending entry. */ export async function stageWrite(args: StageWriteArgs): Promise { - const outcome = await submitWrite(args) + return stagedPending(args, await submitWrite(args)) +} + +/** + * The change set a submit staged, or, when the strategy committed it without + * staging (`direct`), one describing the change the way a staged-and-approved + * one reads. + * + * @internal + */ +export function stagedPending( + args: Pick< + StageWriteArgs, + 'collection' | 'docId' | 'actor' | 'instruction' | 'source' + >, + outcome: StrategyOutcome & { change: IncomingChange }, +): Pending { const pending = outcome.pending if (pending) return outcome.committed @@ -114,8 +130,6 @@ export async function stageWrite(args: StageWriteArgs): Promise { throw new CmsError('The write was not staged.', 'CONFLICT', { effects: outcome.effects, }) - // The strategy committed without staging (`direct`): describe the change - // the way a staged-and-approved one reads. return { id: randomUUID(), version: 1, diff --git a/packages/core/src/server/store/verbs.ts b/packages/core/src/server/store/verbs.ts index 3099b962..fa1fe242 100644 --- a/packages/core/src/server/store/verbs.ts +++ b/packages/core/src/server/store/verbs.ts @@ -39,9 +39,10 @@ export async function getAs( (await readBySlug(ctx, collection, bag.locator ?? '', false, bag.locale)) ?.id if (id === undefined) return null - const doc = isLiveRead(ctx) - ? await readDocumentAs(ctx, collection, id) - : (await readDocumentWithPendingAs(ctx, collection, id)).doc + const doc = + isLiveRead(ctx) || bag.staged === false + ? await readDocumentAs(ctx, collection, id) + : (await readDocumentWithPendingAs(ctx, collection, id)).doc if (!doc) return null return { id, diff --git a/packages/core/src/server/store/write-verbs.ts b/packages/core/src/server/store/write-verbs.ts new file mode 100644 index 00000000..48903404 --- /dev/null +++ b/packages/core/src/server/store/write-verbs.ts @@ -0,0 +1,321 @@ +/** + * The canonical write verbs, `saveAs` and `actAs`. Their bags are the + * registry's (`saveInput`, `actInput` in `../../ops`). Every write is an + * action of the document's state strategy: `save` is the `edit`, `draft` or + * `submit` the writer's rights choose, and `act` runs any other action the + * strategy offers. Both return where the document stands and what the + * writer can do next. + * + * Server-only. + */ +import { CmsError } from '../../errors' +import { actorOf } from '../../document-state' +import { canAccessCollection } from '../../lib/access' +import { actInput, saveInput, validateWithStandardSchema } from '../../ops' +import { protectWrite } from '../access' +import { + assertReadable, + bypassesRules, + redactFor, + systemContext, + withMode, +} from '../access-context' +import { assertCollectionAccess } from '../auth' +import { + actOnDocument, + availableDocumentActions, + documentWriteState, +} from './document-state' +import { requireWritableCollection } from './internal' +import { readDocumentAs, readDocumentWithPendingAs } from './read' +import { saveDraft, submitWrite } from './review' +import { commitDocument } from './write' +import type { ActOptions, ActResult, SaveOptions, WriteResult } from '../../ops' +import type { Doc } from '../../schema' +import type { AccessContext } from '../access-context' +import type { IncomingChange, StrategyOutcome } from './document-state' +import type { Pending } from './internal' + +/** The verbs read their targets whole; the caller's access is checked by the verb. */ +const WRITE_VERB_READ = systemContext('write verb: checked by the verb') + +/** Actions that carry a document: `save` runs them, `act` doesn't. */ +const CHANGE_CARRYING_ACTIONS = new Set(['edit', 'submit', 'draft', 'import']) + +/** How `save` ran, for the deprecated write operations' result shapes. @internal */ +export interface SaveOutcome { + result: WriteResult + /** `commit` went live, `draft` saved a publisher's draft, `submit` asked for review. */ + door: 'commit' | 'draft' | 'submit' + /** The change set the save opened or updated. */ + pending: Pending | null + /** The document the save committed (a `submit` the strategy approved at once included). */ + committed: Doc | null + /** `submit`: the prepared change and the strategy's outcome. */ + submitted?: StrategyOutcome & { change: IncomingChange } +} + +/** Options the deprecated write operations pass to `runSave`. @internal */ +export interface RunSaveOptions { + /** Attribution for revisions, audit and the review queue (default: the context's actor). */ + by?: string + /** `agent` stages the save as an agent proposal whoever the context's actor is (the agent tools). */ + door?: 'agent' | 'human' + /** `empty`: build on the collection's empty document instead of the working copy (`create_document`). */ + base?: 'working' | 'empty' +} + +/** How `act` ran, for the deprecated `actOnChange` operation. @internal */ +export interface ActOutcome { + result: ActResult + outcome: StrategyOutcome +} + +function assertCanWrite(ctx: AccessContext): void { + if (ctx.scope) + throw new CmsError( + 'Forbidden: a preview context cannot write.', + 'FORBIDDEN', + ) + if (actorOf(ctx).type === 'public') + throw new CmsError('Forbidden: sign in to write.', 'UNAUTHORIZED') +} + +async function writeResult( + ctx: AccessContext, + collection: string, + id: string, + doc: Doc | null, +): Promise { + const [state, actions] = await Promise.all([ + documentWriteState(collection, id), + availableDocumentActions(ctx, collection, id), + ]) + return { + id, + collection, + doc: doc ? redactFor(ctx, collection, doc) : null, + state, + availableActions: actions.map((a) => ({ ...a })), + } +} + +/** + * `saveAs` with how it ran. The door follows the writer: an agent's save is + * the strategy's `submit` from an agent; a person who may publish the + * collection saves with `edit` (live, or `draft` while a published document + * keeps its live version unless `publish` is set); anyone else `submit`s + * for review. A trusted context saves as a publisher. + * + * @internal + */ +export async function runSave( + ctx: AccessContext, + options: SaveOptions, + run: RunSaveOptions = {}, +): Promise { + const bag = await validateWithStandardSchema(saveInput, options) + const { collection: name, id } = bag + const collection = requireWritableCollection(name) + assertCanWrite(ctx) + const writer = withMode(ctx, 'edit') + const actor = actorOf(ctx) + const by = run.by ?? actor.id + const session = bypassesRules(ctx) ? undefined : ctx.session + const agent = run.door ? run.door === 'agent' : actor.type === 'agent' + + const live = await readDocumentAs(WRITE_VERB_READ, name, id) + const open = await readDocumentWithPendingAs(WRITE_VERB_READ, name, id) + if (bag.create && (live || open.doc)) + throw new CmsError( + `Document "${id}" already exists in ${name}.`, + 'CONFLICT', + ) + const patch = bag.doc as Doc + if (session) + assertCollectionAccess( + session, + name, + live && !bag.create ? 'update' : 'create', + live ?? patch, + ) + const publisher = (doc: Doc) => + !agent && + (!session || canAccessCollection(session, collection, 'publish', doc)) + // A save merges onto the writer's own open change set; another door's is + // refused by the strategy until it's resolved. + const ownSource = agent + ? 'agent' + : publisher(live ?? patch) + ? 'draft' + : 'review' + const working = + run.base === 'empty' + ? null + : open.pendingSource === ownSource + ? open.doc + : live + const merged: Doc = { ...working, ...patch } + const safe = session + ? protectWrite(name, merged, run.base === 'empty' ? null : live, session) + : merged + const expectedRevision = + bag.expectedRevision ?? + (typeof live?._revision === 'number' ? live._revision : 0) + + if (agent || !publisher(live ?? safe)) { + const submitted = await submitWrite({ + collection: name, + docId: id, + type: live ? 'update' : 'create', + doc: safe, + actor: by, + source: agent ? 'agent' : 'review', + ...(bag.instruction ? { instruction: bag.instruction } : {}), + expectedRevision: agent ? bag.expectedRevision : expectedRevision, + expectedPendingVersion: bag.expectedPendingVersion, + // The agent tools stage as the named agent, as `stageWrite` does. + ...(run.door === 'agent' && actor.type !== 'agent' + ? {} + : { ctx: writer }), + }) + const doc = + submitted.committed ?? submitted.pending?.after ?? submitted.change.doc + return { + result: (await writeResult(writer, name, id, doc)) as WriteResult, + door: 'submit', + pending: submitted.pending, + committed: submitted.committed, + submitted, + } + } + + const keepLive = + live?.published === true && safe.published !== false && !bag.publish + if (keepLive) { + const pending = await saveDraft(name, id, safe, { + actor: by, + expectedRevision, + expectedPendingVersion: bag.expectedPendingVersion, + ...(bag.instruction ? { summary: bag.instruction } : {}), + ctx: writer, + }) + return { + result: (await writeResult( + writer, + name, + id, + pending.after, + )) as WriteResult, + door: 'draft', + pending, + committed: null, + } + } + const committed = await commitDocument(name, id, safe, { + actor: by, + expectedRevision, + expectedPendingVersion: bag.expectedPendingVersion, + ...(bag.instruction ? { summary: bag.instruction } : {}), + ...(session ? { session } : {}), + ctx: writer, + }) + return { + result: (await writeResult(writer, name, id, committed)) as WriteResult, + door: 'commit', + pending: null, + committed, + } +} + +/** + * Save `doc`, a patch of top-level fields, as `ctx`: merged onto the + * writer's own open change set, else onto the live document; a missing + * document is created (`create: true` refuses an existing one). The + * strategy decides what the save does: an agent's is staged for review; a + * publisher's goes live, or becomes a draft of a published document unless + * `publish` is set; anyone else's is submitted for review. Returns the + * working copy (the next baseline for an editor), the state, and the + * actions `ctx` can take next. + */ +export async function saveAs( + ctx: AccessContext, + options: SaveOptions, +): Promise { + return (await runSave(ctx, options)).result +} + +/** + * `actAs` with the strategy's outcome. + * + * @internal + */ +export async function runAct( + ctx: AccessContext, + options: ActOptions, +): Promise { + const bag = await validateWithStandardSchema(actInput, options) + const { collection, id, action } = bag + requireWritableCollection(collection) + assertCanWrite(ctx) + const access = withMode(ctx, 'edit') + const open = await readDocumentWithPendingAs(WRITE_VERB_READ, collection, id) + const live = await readDocumentAs(WRITE_VERB_READ, collection, id) + assertReadable(access, collection, { id, doc: live ?? open.doc }) + if ( + bag.expectedVersion !== undefined && + (open.pendingVersion ?? 0) !== bag.expectedVersion + ) + throw new CmsError( + 'This change set changed since you loaded it. Reload and try again.', + 'CONFLICT', + open.pendingId ? { pendingId: open.pendingId } : undefined, + ) + if (CHANGE_CARRYING_ACTIONS.has(action)) + throw new CmsError( + `"${action}" carries a document: save it with save.`, + 'BAD_REQUEST', + ) + const offered = await availableDocumentActions(access, collection, id) + if (!offered.some((a) => a.type === action)) + throw new CmsError( + `"${action}" is not available to you on this document.`, + 'FORBIDDEN', + ) + if ( + typeof bag.publishAt === 'string' && + Number.isNaN(Date.parse(bag.publishAt)) + ) + throw new CmsError( + `Invalid publishAt datetime: "${bag.publishAt}"`, + 'BAD_REQUEST', + ) + const outcome = await actOnDocument(access, { + collection, + id, + action: { + type: action, + input: { + ...(bag.publishAt !== undefined ? { publishAt: bag.publishAt } : {}), + ...(bag.reason ? { reason: bag.reason } : {}), + }, + }, + }) + const after = await readDocumentWithPendingAs(WRITE_VERB_READ, collection, id) + return { + result: await writeResult(access, collection, id, after.doc), + outcome, + } +} + +/** + * Run `action`, one of the actions the document's strategy offers `ctx` + * (`approve`, `reject`, `discard`, `schedule`, or a custom step), and + * return where the document stands. Saving content is `saveAs`. + */ +export async function actAs( + ctx: AccessContext, + options: ActOptions, +): Promise { + return (await runAct(ctx, options)).result +} diff --git a/packages/core/tests/write-verbs.test.ts b/packages/core/tests/write-verbs.test.ts new file mode 100644 index 00000000..25f2fd38 --- /dev/null +++ b/packages/core/tests/write-verbs.test.ts @@ -0,0 +1,410 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + agentToolName, + createCms, + defineCollection, + normalizeSession, + opSchemas, + saveInput, + writeVerbs, +} from '../src/index' +import { + actAs, + closeStore, + commitDocument, + listPending, + readDocumentAs, + runOp, + saveAs, +} from '../src/server' +import { + accessContext, + publicContext, + systemContext, +} from '../src/server/access-context' +import { cmsAs } from '../src/server/cms-as' +import type { Cms, CmsConfig, WriteResult } from '../src/index' + +const dirs: Array = [] + +afterEach(async () => { + await closeStore() + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +const as = (role: string) => + normalizeSession({ + isAuthenticated: true, + isAdmin: role === 'admin', + user: { id: `u-${role}`, name: role, role }, + }) + +const user = (role: string) => + accessContext({ session: as(role), mode: 'edit' }) + +const post = defineCollection({ + name: 'post', + label: 'Posts', + titleField: 'title', + fields: [ + { name: 'title', label: 'Title', type: 'text' }, + { name: 'body', label: 'Body', type: 'textarea' }, + { name: 'rank', label: 'Rank', type: 'number', defaultValue: 3 }, + ], +}) + +function config(): CmsConfig { + const dataDir = mkdtempSync(join(tmpdir(), 'tanstack-cms-write-verbs-')) + dirs.push(dataDir) + return { dataDir, collections: [post], blockTypes: [] } +} + +async function withCms(fn: (cms: Cms) => Promise): Promise { + const cms = createCms(config()) + await cms.run(() => fn(cms)) +} + +const types = (result: WriteResult) => + result.availableActions.map((a) => a.type) + +describe('the write registry', () => { + it('derives the agent tool from the canonical verbs; act is not an agent tool', () => { + expect(writeVerbs.map((v) => v.name)).toEqual(['save', 'act']) + const tool = (name: string) => opSchemas.find((s) => s.name === name) + expect(tool('save_document')).toMatchObject({ + kind: 'write', + inputSchema: saveInput, + }) + expect(writeVerbs.filter((v) => v.agent).map(agentToolName)).toEqual([ + 'save_document', + ]) + expect(tool('act_document')).toBeUndefined() + expect(tool('create_document')?.description).toMatch(/^Deprecated/) + expect(tool('update_document')?.description).toMatch(/^Deprecated/) + }) +}) + +describe('saveAs', () => { + it('a publisher creates live, keeps a draft of a published document, and publishes on request', async () => { + await withCms(async () => { + const editor = user('editor') + const created = await saveAs(editor, { + collection: 'post', + id: 'hello', + doc: { title: 'Hello', published: true }, + create: true, + }) + expect(created).toMatchObject({ + id: 'hello', + collection: 'post', + doc: { title: 'Hello', rank: 3, published: true, _revision: 1 }, + state: { + label: 'Published', + published: true, + revision: 1, + changeSet: null, + }, + }) + expect(types(created)).toContain('edit') + + const drafted = await saveAs(editor, { + collection: 'post', + id: 'hello', + doc: { body: 'Draft body' }, + expectedRevision: created.state.revision, + }) + expect(drafted.doc).toMatchObject({ title: 'Hello', body: 'Draft body' }) + expect(drafted.state).toMatchObject({ + label: 'Draft', + revision: 1, + changeSet: { source: 'draft', version: 1 }, + }) + expect(types(drafted)).toEqual( + expect.arrayContaining(['edit', 'draft', 'discard']), + ) + + // A second patch merges onto the draft, as an editor's next submit does. + const published = await saveAs(editor, { + collection: 'post', + id: 'hello', + doc: { title: 'Hello again' }, + publish: true, + expectedRevision: drafted.state.revision, + expectedPendingVersion: drafted.state.changeSet?.version, + }) + expect(published.doc).toMatchObject({ + title: 'Hello again', + body: 'Draft body', + _revision: 2, + }) + expect(published.state).toMatchObject({ + label: 'Published', + revision: 2, + changeSet: null, + }) + }) + }) + + it('refuses a stale revision or change set version, and create on an existing document', async () => { + await withCms(async () => { + const editor = user('editor') + await commitDocument('post', 'p', { title: 'Live', published: true }) + await expect( + saveAs(editor, { + collection: 'post', + id: 'p', + doc: { title: 'x' }, + expectedRevision: 0, + }), + ).rejects.toMatchObject({ code: 'CONFLICT' }) + await expect( + saveAs(editor, { + collection: 'post', + id: 'p', + doc: { title: 'x' }, + create: true, + }), + ).rejects.toMatchObject({ code: 'CONFLICT' }) + await saveAs(editor, { collection: 'post', id: 'p', doc: { body: 'd' } }) + await expect( + saveAs(editor, { + collection: 'post', + id: 'p', + doc: { body: 'e' }, + expectedPendingVersion: 0, + }), + ).rejects.toMatchObject({ code: 'CONFLICT' }) + }) + }) + + it('an author submits for review; a re-save merges onto the proposal', async () => { + await withCms(async () => { + const author = user('author') + await commitDocument('post', 'p', { title: 'Live', published: true }) + const first = await saveAs(author, { + collection: 'post', + id: 'p', + doc: { title: 'Proposed' }, + }) + expect(first.state).toMatchObject({ + label: 'Pending Review', + published: true, + revision: 1, + changeSet: { source: 'review', version: 1 }, + }) + expect(types(first)).toEqual(['submit']) + const second = await saveAs(author, { + collection: 'post', + id: 'p', + doc: { body: 'More' }, + expectedPendingVersion: first.state.changeSet?.version, + }) + expect(second.doc).toMatchObject({ title: 'Proposed', body: 'More' }) + expect(second.state.changeSet).toMatchObject({ + id: first.state.changeSet?.id, + version: 2, + }) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p'))?.title, + ).toBe('Live') + }) + }) + + it('an agent’s save is staged even with publish rights; publish is ignored', async () => { + await withCms(async () => { + await commitDocument('post', 'p', { title: 'Live', published: true }) + const bot = accessContext({ + session: as('editor'), + agent: 'bot', + mode: 'edit', + }) + const saved = await saveAs(bot, { + collection: 'post', + id: 'p', + doc: { title: 'Bot edit' }, + publish: true, + }) + expect(saved.state).toMatchObject({ + label: 'Pending Review', + revision: 1, + changeSet: { source: 'agent' }, + }) + expect((await listPending())[0]).toMatchObject({ actor: 'bot' }) + }) + }) + + it('serves save_document as an agent tool that always stages', async () => { + await withCms(async () => { + const saved = (await runOp( + 'save_document', + { collection: 'post', id: 'new-one', doc: { title: 'New' } }, + 'mcp', + systemContext('test'), + )) as WriteResult + expect(saved).toMatchObject({ + id: 'new-one', + doc: { title: 'New', rank: 3 }, + state: { label: 'Pending Review', changeSet: { source: 'agent' } }, + }) + expect((await listPending())[0]).toMatchObject({ + actor: 'mcp', + type: 'create', + }) + expect( + await readDocumentAs(systemContext('test'), 'post', 'new-one'), + ).toBeNull() + }) + }) + + it('reports an auto-approved save as live', async () => { + const cms = createCms({ ...config(), review: { autoApprove: true } }) + await cms.run(async () => { + const bot = accessContext({ + session: as('author'), + agent: 'bot', + mode: 'edit', + }) + const saved = await saveAs(bot, { + collection: 'post', + id: 'auto', + doc: { title: 'Auto', published: true }, + }) + expect(saved).toMatchObject({ + doc: { title: 'Auto' }, + state: { label: 'Published', published: true, changeSet: null }, + }) + expect(await listPending()).toEqual([]) + }) + }) + + it('refuses a public visitor', async () => { + await withCms(async () => { + await expect( + saveAs(publicContext(), { + collection: 'post', + id: 'p', + doc: { title: 'x' }, + }), + ).rejects.toMatchObject({ code: 'UNAUTHORIZED' }) + }) + }) +}) + +describe('get with staged: false', () => { + it('reads the committed document a write must see, on every surface', async () => { + await withCms(async (cms) => { + await commitDocument('post', 'p', { title: 'Live', published: true }) + await commitDocument('post', 'u', { title: 'Unpublished' }) + await saveAs(user('author'), { + collection: 'post', + id: 'p', + doc: { title: 'Proposed' }, + }) + await saveAs(user('author'), { + collection: 'post', + id: 'idea', + doc: { title: 'Idea' }, + }) + const db = cmsAs(cms, user('editor')) + const title = async (id: string, staged?: boolean) => + (await db.get({ collection: 'post', id, staged }))?.doc.title ?? null + + expect(await title('p')).toBe('Proposed') + expect(await title('p', false)).toBe('Live') + expect(await title('idea')).toBe('Idea') + expect(await title('idea', false)).toBeNull() + expect(await title('u', false)).toBe('Unpublished') + + const system = cmsAs(cms, systemContext('test')) + const committed = await system.get({ + collection: 'post', + id: 'p', + staged: false, + }) + expect(committed?.doc).toMatchObject({ title: 'Live', _revision: 1 }) + + const live = cmsAs(cms, publicContext()) + expect( + (await live.get({ collection: 'post', id: 'p', staged: false }))?.doc + .title, + ).toBe('Live') + expect( + await live.get({ collection: 'post', id: 'u', staged: false }), + ).toBeNull() + + const tool = (await runOp( + 'get_document', + { collection: 'post', id: 'p', staged: false }, + 'mcp', + systemContext('test'), + )) as { doc: { title: string } } + expect(tool.doc.title).toBe('Live') + }) + }) +}) + +describe('actAs', () => { + it('runs an offered action and reports the new state', async () => { + await withCms(async (cms) => { + await commitDocument('post', 'p', { title: 'Live', published: true }) + const proposed = await saveAs(user('author'), { + collection: 'post', + id: 'p', + doc: { title: 'Proposed' }, + }) + await expect( + actAs(user('author'), { + collection: 'post', + id: 'p', + action: 'approve', + }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }) + await expect( + actAs(user('editor'), { collection: 'post', id: 'p', action: 'edit' }), + ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) + await expect( + actAs(user('editor'), { + collection: 'post', + id: 'p', + action: 'approve', + expectedVersion: 7, + }), + ).rejects.toMatchObject({ code: 'CONFLICT' }) + + const approved = await cmsAs(cms, user('editor')).act({ + collection: 'post', + id: 'p', + action: 'approve', + expectedVersion: proposed.state.changeSet?.version, + }) + expect(approved).toMatchObject({ + doc: { title: 'Proposed', _revision: 2 }, + state: { label: 'Published', revision: 2, changeSet: null }, + }) + expect(approved.availableActions.map((a) => a.type)).toContain('edit') + }) + }) + + it('a rejected create leaves no document', async () => { + await withCms(async (cms) => { + await saveAs(user('author'), { + collection: 'post', + id: 'idea', + doc: { title: 'Idea' }, + }) + const rejected = await cmsAs(cms, user('editor')).act({ + collection: 'post', + id: 'idea', + action: 'reject', + reason: 'Not now', + }) + expect(rejected).toMatchObject({ + doc: null, + state: { label: 'New', revision: 0, changeSet: null }, + }) + }) + }) +})