From 79e31267e5fede621017945c2a248b04717304be Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 6 Nov 2026 14:24:05 +0000 Subject: [PATCH] refactor: starters, examples and docs read with get/list; read-verbs codemod (3d) (#39) Chain step 19 of the linear merge chain onto main 3b4a112: this PR's own changes, resolved against the PRs before it in the merge order. Co-authored-by: jherr --- .changeset/cli-read-verbs.md | 5 + .../astro-starlight-to-tanstack-cms/SKILL.md | 2 +- .../skills/emdash-to-tanstack-cms/SKILL.md | 6 +- .../skills/payload-to-tanstack-cms/SKILL.md | 60 +- .claude/skills/voting/SKILL.md | 68 +- .../skills/wordpress-to-tanstack-cms/SKILL.md | 4 +- app/base/e2e/base.spec.ts | 4 + app/base/src/operations.server.ts | 15 +- app/base/tests/base.test.ts | 25 + app/prm/bakeoff/README.md | 22 +- app/prm/bakeoff/latest.json | 180 +--- docs/agents/on-page-editor.md | 2 +- docs/api/cli.md | 2 +- docs/api/cms-api.md | 14 +- docs/api/cms-core-server.md | 28 +- docs/api/cms-core.md | 2 +- docs/api/routes-and-endpoints.md | 6 +- docs/architecture/authentication.md | 2 +- docs/architecture/data-layer.md | 7 +- docs/architecture/terminology.md | 2 +- docs/deployment/upgrading.md | 33 +- docs/mcp/operations-registry.md | 12 +- docs/migration/from-emdash.md | 2 +- docs/migration/from-payload.md | 4 +- docs/migration/from-sanity.md | 6 +- docs/migration/from-wordpress.md | 2 +- docs/migration/overview.md | 2 +- docs/schema/building-pages.md | 50 +- examples/astro-starlight-after/MIGRATION.md | 2 +- .../src/migration.test.ts | 31 +- examples/blog-voting/README.md | 10 +- examples/blog-voting/src/voting/votes.ts | 47 +- examples/db-markdown/README.md | 4 +- examples/db-markdown/src/docs.functions.ts | 28 +- examples/emdash-after/MIGRATION.md | 4 +- examples/emdash-after/src/migration.test.ts | 37 +- examples/payload-after/MIGRATION.md | 4 +- examples/payload-after/src/migration.test.ts | 45 +- examples/wordpress-after/MIGRATION.md | 2 +- .../wordpress-after/src/migration.test.ts | 26 +- packages/cli/src/commands/atproto.ts | 12 +- .../__fixtures__/read-verbs/calls.input.ts | 40 + .../__fixtures__/read-verbs/calls.output.ts | 31 + .../__fixtures__/read-verbs/docs.input.md | 18 + .../__fixtures__/read-verbs/docs.output.md | 19 + .../__fixtures__/read-verbs/dynamic.input.ts | 14 + .../__fixtures__/read-verbs/dynamic.output.ts | 15 + .../read-verbs/dynamic.warnings.json | 3 + .../__fixtures__/read-verbs/handle.input.ts | 12 + .../__fixtures__/read-verbs/handle.output.ts | 13 + .../read-verbs/handle.warnings.json | 3 + .../__fixtures__/read-verbs/todos.input.ts | 30 + .../__fixtures__/read-verbs/todos.output.ts | 29 + .../read-verbs/todos.warnings.json | 9 + .../read-verbs/untouched.input.ts | 31 + .../read-verbs/untouched.warnings.json | 9 + scripts/codemods/index.ts | 2 + scripts/codemods/read-verbs.ts | 860 ++++++++++++++++++ scripts/dialect-inventory.baseline.json | 32 +- starters/documentation-kb/CMS-INTEGRATION.md | 6 +- starters/documentation-kb/src/cms.config.ts | 4 +- .../ecommerce-storefront/CMS-INTEGRATION.md | 6 +- .../ecommerce-storefront/src/cms.config.ts | 13 +- .../editorial-publication/CMS-INTEGRATION.md | 10 +- .../editorial-publication/src/cms.config.ts | 18 +- starters/membership-course/CMS-INTEGRATION.md | 8 +- starters/membership-course/src/cms.config.ts | 16 +- .../multi-tenant-fleet/CMS-INTEGRATION.md | 8 +- starters/multi-tenant-fleet/src/cms.config.ts | 8 +- starters/runtime-tables/CMS-INTEGRATION.md | 2 +- starters/runtime-tables/src/cms.config.ts | 4 +- 71 files changed, 1655 insertions(+), 437 deletions(-) create mode 100644 .changeset/cli-read-verbs.md create mode 100644 scripts/codemods/__fixtures__/read-verbs/calls.input.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/calls.output.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/docs.input.md create mode 100644 scripts/codemods/__fixtures__/read-verbs/docs.output.md create mode 100644 scripts/codemods/__fixtures__/read-verbs/dynamic.input.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/dynamic.output.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/dynamic.warnings.json create mode 100644 scripts/codemods/__fixtures__/read-verbs/handle.input.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/handle.output.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/handle.warnings.json create mode 100644 scripts/codemods/__fixtures__/read-verbs/todos.input.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/todos.output.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/todos.warnings.json create mode 100644 scripts/codemods/__fixtures__/read-verbs/untouched.input.ts create mode 100644 scripts/codemods/__fixtures__/read-verbs/untouched.warnings.json create mode 100644 scripts/codemods/read-verbs.ts diff --git a/.changeset/cli-read-verbs.md b/.changeset/cli-read-verbs.md new file mode 100644 index 00000000..ccbbe9e3 --- /dev/null +++ b/.changeset/cli-read-verbs.md @@ -0,0 +1,5 @@ +--- +'@tanstack/cms-cli': patch +--- + +`tanstack-cms atproto publish` reads the document with `getAs` instead of the deprecated `readDocumentAs`. Behaviour is unchanged: it still reads the published document as the public. diff --git a/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md b/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md index 0fd5480f..99f27118 100644 --- a/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md +++ b/.claude/skills/astro-starlight-to-tanstack-cms/SKILL.md @@ -189,7 +189,7 @@ components themselves are the gap. Self-test: `node scripts/mdx-to-markdown.mjs` naming the files); key frontmatter, slugs, sidebar fields, and a body survived byte-for-byte (minus flattened MDX); loading through the engine works (`seedContent({ force: true })` or `parseCmsExport` + - `importContent`, then `queryDocuments`/`readDocument`); and + `importContent`, then `listAs`/`getAs`); and `resolveRedirect('/start/installation/')` from `@tanstack/cms-core/server` returns the new URL. `closeStore()` after each test. - Live check: `pnpm --filter dev`; the sidebar matches Starlight's, diff --git a/.claude/skills/emdash-to-tanstack-cms/SKILL.md b/.claude/skills/emdash-to-tanstack-cms/SKILL.md index 6a58b9c3..974921c0 100644 --- a/.claude/skills/emdash-to-tanstack-cms/SKILL.md +++ b/.claude/skills/emdash-to-tanstack-cms/SKILL.md @@ -223,8 +223,8 @@ Self-test: `node scripts/portable-text-to-markdown.mjs`. `content` (hardcode them with a comment naming the file); titles, slugs, excerpts, and a Portable Text body survived; and loading through the engine works (`seedContent({ force: true })` or `parseCmsExport` + `importContent`, - then `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` and - `readDocumentAs`/`queryDocuments` with `populate: true` resolving `authors`). + then `listAs(ctx, { where: { tags: 'opinion' } })` and `getAs`, whose + default `relations` resolve `authors`). `closeStore()` after each test. - Live check: `pnpm --filter dev`, then `curl -X POST localhost:/api/cms/v1/ops/listDocumentSummaries -H 'content-type: application/json' -d '{"collection":"post","status":"all"}'` @@ -240,7 +240,7 @@ tables you used, the Portable Text coverage, how the content was loaded, and a - **Hierarchical taxonomies** — flattened into a `multiselect` (parents lost), or modelled as a collection + `relation`. Taxonomy archive pages - (`/category/`) need an app route (`queryDocumentsAs(ctx, { where })`). + (`/category/`) need an app route (`listAs(ctx, { where })`). - **Bylines** — the built-in post page renders the plain-text `author` field (declared as `bylineField`), not the `authors` relation; byline roles and ordering beyond the array order need app work. diff --git a/.claude/skills/payload-to-tanstack-cms/SKILL.md b/.claude/skills/payload-to-tanstack-cms/SKILL.md index f4dc6ea9..1bfe0e7d 100644 --- a/.claude/skills/payload-to-tanstack-cms/SKILL.md +++ b/.claude/skills/payload-to-tanstack-cms/SKILL.md @@ -116,31 +116,31 @@ functions (AI adapter factories, `webhooks[].secret: () => process.env.X`). **Field types** (Payload → core `type`): -| Payload | core `type` | Notes | -| --------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------- | -| `text` | `text` | | -| `textarea` | `textarea` | | -| `email` | `email` | format-validated | -| `number` | `number` | `min`/`max` carry over | -| `checkbox` | `boolean` | | -| `select`, `radio` | `select` with `options` | `{ label, value }` options carry over as-is | -| `select` with `hasMany` | `multiselect` with `options` | | -| `date` | `datetime` (or `date` for day-only) | Payload stores ISO datetimes | -| `code` | `textarea` | or a `code` block inside `blocks` | -| `json` | `json` | | -| `point` | `json` or a `group` of two numbers | no geo queries | -| `upload` (`relationTo: 'media'`) | `image` | stores the media URL string | -| `relationship` (one target) | `relation` + `collection` | stores the target id | -| `relationship` with `hasMany` | `relation` + `many: true` | array of ids; `populateRelations` / `populate: true` resolves them | -| `relationship` polymorphic (`relationTo: []`) | — | split into one `relation` per target, or `json` — gap report | -| `richText` (Lexical), flat | `richtext` (or `markdown`) | both store Markdown; see §5 | -| `richText` (Lexical), in a block | `richText` block `markdown` | see §5 | -| `blocks` | `blocks` | map each block type → core block (below); keep blocks one level deep | -| `group` | `group` with `fields` | nested object | -| `array` | `array` with `fields` | list of nested objects; `minRows`/`maxRows` → `min`/`max` | -| `tabs` (named) | `group` per tab | unnamed tabs, `row`, `collapsible` are layout only → flatten their fields | -| a text slug (`/about` paths) | `text` + `unique: true` | use `slug` only for kebab-case values (it validates the format) | -| `join`, `ui` | — | `join` is a computed reverse lookup: `queryDocumentsAs(ctx, { where })` instead | +| Payload | core `type` | Notes | +| --------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------- | +| `text` | `text` | | +| `textarea` | `textarea` | | +| `email` | `email` | format-validated | +| `number` | `number` | `min`/`max` carry over | +| `checkbox` | `boolean` | | +| `select`, `radio` | `select` with `options` | `{ label, value }` options carry over as-is | +| `select` with `hasMany` | `multiselect` with `options` | | +| `date` | `datetime` (or `date` for day-only) | Payload stores ISO datetimes | +| `code` | `textarea` | or a `code` block inside `blocks` | +| `json` | `json` | | +| `point` | `json` or a `group` of two numbers | no geo queries | +| `upload` (`relationTo: 'media'`) | `image` | stores the media URL string | +| `relationship` (one target) | `relation` + `collection` | stores the target id | +| `relationship` with `hasMany` | `relation` + `many: true` | array of ids; `populateRelations` / `populate: true` resolves them | +| `relationship` polymorphic (`relationTo: []`) | — | split into one `relation` per target, or `json` — gap report | +| `richText` (Lexical), flat | `richtext` (or `markdown`) | both store Markdown; see §5 | +| `richText` (Lexical), in a block | `richText` block `markdown` | see §5 | +| `blocks` | `blocks` | map each block type → core block (below); keep blocks one level deep | +| `group` | `group` with `fields` | nested object | +| `array` | `array` with `fields` | list of nested objects; `minRows`/`maxRows` → `min`/`max` | +| `tabs` (named) | `group` per tab | unnamed tabs, `row`, `collapsible` are layout only → flatten their fields | +| a text slug (`/about` paths) | `text` + `unique: true` | use `slug` only for kebab-case values (it validates the format) | +| `join`, `ui` | — | `join` is a computed reverse lookup: `listAs(ctx, { where })` instead | **Field options:** `required` → `required: true`; `unique` → `unique: true`; `index` → `index: true`; `defaultValue` → `defaultValue`; `admin.description` → @@ -176,9 +176,9 @@ Payload `{ data, originalDoc, req, operation }` → core `{ doc, id }` (`postRead`), `{ id, actor }` (`preDelete`). Return the transformed doc from `preValidate` / `postValidate` / `postRead`; throw to abort a write. Keep hooks under about 50ms. Replace `req.payload.find(…)` with -`queryDocuments`/`readDocumentAs` from `@tanstack/cms-core/server`, and attach -those hooks in the runtime config -(`defineCms(definition, { collections: { post: { hooks } } })`). Hooks that +`listAs`/`getAs` from `@tanstack/cms-core/server`, and attach those hooks in +the runtime config (`defineCms(definition, { collections: { post: { hooks } } })`). +Hooks that only fan out to other systems (cache purges, search indexing) usually become `defineCms({ webhooks })` instead. No equivalent: `beforeOperation`, `afterOperation`, `beforeRead`, `afterError`, auth hooks. @@ -271,8 +271,8 @@ custom nodes and list what isn't converted in the gap report. Self-test: where they came from, e.g. the Payload REST `totalDocs`); key fields survived (titles, slugs, a Lexical-converted body); and loading through the engine works (`seedContent({ force: true })` or `parseCmsExport` + - `importContent` from `@tanstack/cms-core/server`, then `queryDocuments` / - `readDocumentAs`, with `populate: true` for relations). `closeStore()` after + `importContent` from `@tanstack/cms-core/server`, then `listAs` / `getAs`, + which populate relations by default). `closeStore()` after each test. - Live check: `pnpm --filter dev`, then `curl -X POST localhost:/api/cms/v1/ops/listDocumentSummaries -H 'content-type: application/json' -d '{"collection":"post","status":"all"}'` diff --git a/.claude/skills/voting/SKILL.md b/.claude/skills/voting/SKILL.md index 5511af2b..74617b16 100644 --- a/.claude/skills/voting/SKILL.md +++ b/.claude/skills/voting/SKILL.md @@ -1,6 +1,6 @@ --- name: voting -description: Build a native upvote/downvote (voting) feature on a TanStack CMS 1.0 (@tanstack/cms-core) app. Use when the user asks to add voting, likes, reactions, upvotes, "hacker news style" ranking, or "reddit style" scores to posts or any collection. Produces schema additions, a vote write path with one-vote-per-user semantics, indexed read paths (counts, top-N), a vote UI component, and tests — all native to the CMS (collections, queryDocuments, revisions) rather than a bolted-on plugin. +description: Build a native upvote/downvote (voting) feature on a TanStack CMS 1.0 (@tanstack/cms-core) app. Use when the user asks to add voting, likes, reactions, upvotes, "hacker news style" ranking, or "reddit style" scores to posts or any collection. Produces schema additions, a vote write path with one-vote-per-user semantics, indexed read paths (counts, top-N), a vote UI component, and tests — all native to the CMS (collections, get/list reads, revisions) rather than a bolted-on plugin. --- # Voting on TanStack CMS @@ -20,10 +20,13 @@ they sort and filter through the indexed read path), and the write path is a server function composed from the same store primitives the admin uses. All store functions from `@tanstack/cms-core/server` are **async** — -`await` every `readDocumentAs`, `queryDocumentsAs`, `commitDocument`, and +`await` every `getAs`, `listAs`, `readDocumentAs`, `commitDocument`, and `deleteDocument`. Every read takes an access context: `publicContext()` for what a visitor may see (published posts), and a named -`systemContext(reason)` for the server-owned vote records. +`systemContext(reason)` for the server-owned vote records. Reads that feed a +write (the existing vote, the post whose tally you commit) use +`readDocumentAs`, which returns the stored row; `getAs` in a system (edit) +context returns the working copy, with any staged changes overlaid. ## 0. Prerequisites @@ -78,7 +81,7 @@ And on `post`, add: ``` Vote documents are never `published`, so they don't appear in the public -read paths (`listPublishedDocuments`, `getPublicDocument`); `access.read` +read paths (`get`, `list`, and the older `listPublishedDocuments`); `access.read` then keeps them out of non-admin API and MCP reads. **Deterministic vote ids.** Enforce one-vote-per-user with the id itself: @@ -126,8 +129,9 @@ import { createServerFn } from '@tanstack/react-start' import { commitDocument, deleteDocument, + getAs, + listAs, publicContext, - queryDocumentsAs, readDocumentAs, requireAuthenticated, systemContext, @@ -143,7 +147,12 @@ export async function castVoteForVoter( ) { if (value !== 1 && value !== -1) throw new Error('Invalid vote') // Voters only ever see published posts. - if (!(await readDocumentAs(publicContext(), 'post', postId))) { + const visible = await getAs(publicContext(), { + collection: 'post', + id: postId, + populate: false, + }) + if (!visible) { throw new Error('Post not found') } @@ -159,13 +168,25 @@ export async function castVoteForVoter( { actor: voterId }, ) } - // Recount from source; never trust client-supplied counts. - const votes = await queryDocumentsAs(VOTES, { - collection: 'vote', - where: { post: postId }, - }) - const upvotes = votes.items.filter((v) => Number(v.doc.value) > 0).length - const downvotes = votes.items.filter((v) => Number(v.doc.value) < 0).length + // Recount from source; never trust client-supplied counts. A list page + // holds at most 500 documents, so page through every vote. + let upvotes = 0 + let downvotes = 0 + let cursor: string | undefined + do { + const votes = await listAs(VOTES, { + collection: 'vote', + where: { post: postId }, + limit: 500, + cursor, + populate: false, + }) + for (const v of votes.items) { + if (Number(v.doc.value) > 0) upvotes++ + else if (Number(v.doc.value) < 0) downvotes++ + } + cursor = votes.nextCursor + } while (cursor) // Re-read the stored post: a public read may leave out fields the commit // would then drop. const post = await readDocumentAs(VOTES, 'post', postId) @@ -190,8 +211,10 @@ export const castVote = createServerFn({ method: 'POST' }) }) ``` -The worked example also resolves posts by slug (`readDocumentBySlugAs`) so -links using either form work. +The worked example reads the post with +`getAs(publicContext(), { collection: 'post', id: postId })`, then +`{ locator: postId }` (the slug) when no post has that id, so links using +either form work. **Atomicity gap (report it, don't hide it).** `commitDocument` and `deleteDocument` each run in their own storage transaction, so the vote write @@ -228,7 +251,13 @@ report (§8). Concurrent votes on the same post can also race the tally ```ts // What the UI needs for one post: export async function getVoteState(postId: string, voterId?: string) { - const post = await readDocumentAs(publicContext(), 'post', postId) + const post = ( + await getAs(publicContext(), { + collection: 'post', + id: postId, + populate: false, + }) + )?.doc const mine = voterId ? await readDocumentAs(VOTES, 'vote', voteId(postId, voterId)) : null @@ -242,10 +271,11 @@ export async function getVoteState(postId: string, voterId?: string) { // Top posts — score is an indexed number field: export async function getTopPosts(limit = 10) { - return queryDocumentsAs(publicContext(), { + return listAs(publicContext(), { collection: 'post', sort: { field: 'score', dir: 'desc' }, limit, + populate: false, }) } ``` @@ -300,11 +330,11 @@ a temp `dataDir` per test via `defineCms({ dataDir, collections: [...] })` and - invalid value / unknown post / malformed voter id throw - `getVoteState` reports the caller's own vote - `getTopPosts` orders by score desc -- vote docs appear in `queryDocumentsAs(VOTES, { collection: 'vote' })` (auditability) +- vote docs appear in `listAs(VOTES, { collection: 'vote' })` (auditability) Then write the **gap report**: every place where you reached for something the core doesn't have. Known ones in 1.0: composable transactions across document writes, composite uniqueness, aggregation queries ("top voters", -"votes today" mean scanning with `queryDocuments`), and app-defined rate-limit +"votes today" mean scanning with `listAs`), and app-defined rate-limit buckets. Be specific: name the primitive, the use case, and the workaround you used. diff --git a/.claude/skills/wordpress-to-tanstack-cms/SKILL.md b/.claude/skills/wordpress-to-tanstack-cms/SKILL.md index 5dc8ca57..7da4f86f 100644 --- a/.claude/skills/wordpress-to-tanstack-cms/SKILL.md +++ b/.claude/skills/wordpress-to-tanstack-cms/SKILL.md @@ -198,7 +198,7 @@ WXR reader (`parseWxr`, `resolveFeaturedImages`). Self-tests: titles, slugs, authors, terms, featured images, and a Gutenberg and a classic body survived; loading through the engine works (`seedContent({ force: true })` or `parseCmsExport` + `importContent`, then - `queryDocumentsAs(ctx, { where: { categories: '' } })` and `readDocumentAs`); + `listAs(ctx, { where: { categories: '' } })` and `getAs`); and `resolveRedirect('//')` from `@tanstack/cms-core/server` returns the new URL. `closeStore()` after each test. - Live check: `pnpm --filter dev`, then @@ -216,7 +216,7 @@ tables you used, the HTML/Gutenberg coverage, how the content was loaded, and a - **Taxonomy archives and hierarchy** — categories/tags are `multiselect` values (parents flattened); `/category/` and `/tag/` archive - pages need app routes (`queryDocumentsAs(ctx, { where })`). + pages need app routes (`listAs(ctx, { where })`). - **Media bytes** — `hero`/inline images migrate as URLs pointing at the old `wp-content/uploads` (or CDN). Re-home them into the media library (`/api/media`, local or `s3Media()`) and rewrite references before the old diff --git a/app/base/e2e/base.spec.ts b/app/base/e2e/base.spec.ts index 607d9638..a5e8d8d1 100644 --- a/app/base/e2e/base.spec.ts +++ b/app/base/e2e/base.spec.ts @@ -63,6 +63,10 @@ test('first-run owner setup, sign-out, and API protection', async ({ { data: { collection: 'products' } }, ) expect(denied.status()).toBe(401) + const deniedList = await page.request.get('/api/cms/v1/ops/list', { + params: { input: JSON.stringify({ collection: 'products' }) }, + }) + expect(deniedList.status()).toBe(401) }) test('key-free onboarding exposes definitions and saves preferences', async ({ diff --git a/app/base/src/operations.server.ts b/app/base/src/operations.server.ts index 57da6e3f..6d4de339 100644 --- a/app/base/src/operations.server.ts +++ b/app/base/src/operations.server.ts @@ -23,7 +23,7 @@ import { accessContext, systemContext, readDocumentAs, - queryDocumentsAs, + listAs, withMode, } from '@tanstack/cms-core/server' import { evacuateWordPress } from '@tanstack/cms-migrate-wp' @@ -56,10 +56,11 @@ async function committed(name: string, id: string, ctx: CmsOpContext) { } export async function dashboard(ctx: CmsOpContext) { const shop = await committed('shop', 'settings', ctx) - const reports = await queryDocumentsAs( - accessContext({ session: ctx.session }), - { collection: 'reports', limit: 50 }, - ) + const reports = await listAs(accessContext({ session: ctx.session }), { + collection: 'reports', + limit: 50, + populate: false, + }) return { shop, interfaces: await listInterfaces(ctx), @@ -156,9 +157,9 @@ async function reportData(endDate: string, ctx: CmsOpContext) { const result: Array = [] let cursor: string | undefined do { - const page = await queryDocumentsAs( + const page = await listAs( accessContext({ session: ctx.session, mode: 'edit' }), - { collection: name, limit: 500, cursor }, + { collection: name, limit: 500, cursor, populate: false }, ) for (const row of page.items) { const parsed = schema.safeParse(redactDoc(name, row.doc, ctx.session)) diff --git a/app/base/tests/base.test.ts b/app/base/tests/base.test.ts index ab65018f..c9a72958 100644 --- a/app/base/tests/base.test.ts +++ b/app/base/tests/base.test.ts @@ -419,6 +419,13 @@ describe('coffee shop and reports', () => { ) )?.status, ).toBe(401) + expect( + ( + await guardApiRequest( + new Request('http://localhost/api/cms/v1/ops/list'), + ) + )?.status, + ).toBe(401) }) it('protects public-site query operations from scoped snapshot leaks', async () => { const staged = await submitReport({ endDate: DEMO_END_DATE }, context()) @@ -443,6 +450,24 @@ describe('coffee shop and reports', () => { }, ), ).rejects.toThrow() + await expect( + invokeAnyOp( + 'list', + { collection: 'reports' }, + { + access: accessContext({ session: scoped.session, mode: 'edit' }), + }, + ), + ).rejects.toThrow() + await expect( + invokeAnyOp( + 'get', + { collection: 'reports', id: staged.reportId }, + { + access: accessContext({ session: scoped.session, mode: 'edit' }), + }, + ), + ).rejects.toThrow() }) it('rejects hidden fields and rechecks snapshot source permissions', async () => { const ctx = context() diff --git a/app/prm/bakeoff/README.md b/app/prm/bakeoff/README.md index 48f2699a..2ee1e367 100644 --- a/app/prm/bakeoff/README.md +++ b/app/prm/bakeoff/README.md @@ -5,15 +5,15 @@ - **Exa avg fact recall:** 100.0% · **Primary-domain hits:** 11/50 - **Tavily avg fact recall:** 67.5% · **Primary-domain hits:** 11/50 -| Subject | Exa | Tavily | Top Exa Source | -|---|---|---|---| -| Sunil Pai | 100% (2 primary) | 100% (2 primary) | `https://sunilpai.dev/about` | -| Kent C. Dodds | 100% (1 primary) | 75% (1 primary) | `https://github.com/kentcdodds` | +| Subject | Exa | Tavily | Top Exa Source | +| --------------- | ---------------- | ---------------- | ----------------------------------- | +| Sunil Pai | 100% (2 primary) | 100% (2 primary) | `https://sunilpai.dev/about` | +| Kent C. Dodds | 100% (1 primary) | 75% (1 primary) | `https://github.com/kentcdodds` | | David Khourshid | 100% (1 primary) | 100% (1 primary) | `https://github.com/davidkhourshid` | -| Victor Savkin | 100% (1 primary) | 67% (1 primary) | `https://github.com/victorsavkin` | -| Tanner Linsley | 100% (1 primary) | 67% (1 primary) | `https://github.com/tannerlinsley` | -| Eugene Sergueev | 100% (1 primary) | 67% (1 primary) | `https://github.com/eugenesergueev` | -| Dominik Kundel | 100% (1 primary) | 50% (1 primary) | `https://github.com/dominikkundel` | -| Maya Shavin | 100% (1 primary) | 50% (1 primary) | `https://github.com/mayashavin` | -| Kiriti Badam | 100% (1 primary) | 50% (1 primary) | `https://github.com/kiritibadam` | -| Sachin Malhotra | 100% (1 primary) | 50% (1 primary) | `https://github.com/sachinmalhotra` | +| Victor Savkin | 100% (1 primary) | 67% (1 primary) | `https://github.com/victorsavkin` | +| Tanner Linsley | 100% (1 primary) | 67% (1 primary) | `https://github.com/tannerlinsley` | +| Eugene Sergueev | 100% (1 primary) | 67% (1 primary) | `https://github.com/eugenesergueev` | +| Dominik Kundel | 100% (1 primary) | 50% (1 primary) | `https://github.com/dominikkundel` | +| Maya Shavin | 100% (1 primary) | 50% (1 primary) | `https://github.com/mayashavin` | +| Kiriti Badam | 100% (1 primary) | 50% (1 primary) | `https://github.com/kiritibadam` | +| Sachin Malhotra | 100% (1 primary) | 50% (1 primary) | `https://github.com/sachinmalhotra` | diff --git a/app/prm/bakeoff/latest.json b/app/prm/bakeoff/latest.json index e1cbee47..c6f69185 100644 --- a/app/prm/bakeoff/latest.json +++ b/app/prm/bakeoff/latest.json @@ -20,12 +20,7 @@ "allowedUrlRate": 1, "primaryIdentityHits": 2, "factRecallRate": 1, - "matchedFacts": [ - "cloudflare", - "partykit", - "react", - "glamor" - ], + "matchedFacts": ["cloudflare", "partykit", "react", "glamor"], "sampleUrls": [ "https://sunilpai.dev/about", "https://kentcdodds.com/chats/01/20/sunil-pai" @@ -38,12 +33,7 @@ "allowedUrlRate": 1, "primaryIdentityHits": 2, "factRecallRate": 1, - "matchedFacts": [ - "cloudflare", - "partykit", - "react", - "glamor" - ], + "matchedFacts": ["cloudflare", "partykit", "react", "glamor"], "sampleUrls": [ "https://sunilpai.dev/about", "https://kentcdodds.com/chats/01/20/sunil-pai" @@ -59,15 +49,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "epicweb", - "testing", - "kody", - "react" - ], - "sampleUrls": [ - "https://github.com/kentcdodds" - ] + "matchedFacts": ["epicweb", "testing", "kody", "react"], + "sampleUrls": ["https://github.com/kentcdodds"] }, "tavily": { "name": "Kent C. Dodds", @@ -76,14 +59,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.75, - "matchedFacts": [ - "epicweb", - "testing", - "kody" - ], - "sampleUrls": [ - "https://github.com/kentcdodds" - ] + "matchedFacts": ["epicweb", "testing", "kody"], + "sampleUrls": ["https://github.com/kentcdodds"] } }, { @@ -95,14 +72,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "stately", - "xstate", - "state" - ], - "sampleUrls": [ - "https://github.com/davidkhourshid" - ] + "matchedFacts": ["stately", "xstate", "state"], + "sampleUrls": ["https://github.com/davidkhourshid"] }, "tavily": { "name": "David Khourshid", @@ -111,14 +82,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "stately", - "xstate", - "state" - ], - "sampleUrls": [ - "https://github.com/davidkhourshid" - ] + "matchedFacts": ["stately", "xstate", "state"], + "sampleUrls": ["https://github.com/davidkhourshid"] } }, { @@ -130,14 +95,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "nx", - "nrwl", - "monorepo" - ], - "sampleUrls": [ - "https://github.com/victorsavkin" - ] + "matchedFacts": ["nx", "nrwl", "monorepo"], + "sampleUrls": ["https://github.com/victorsavkin"] }, "tavily": { "name": "Victor Savkin", @@ -146,13 +105,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.6666666666666666, - "matchedFacts": [ - "nx", - "nrwl" - ], - "sampleUrls": [ - "https://github.com/victorsavkin" - ] + "matchedFacts": ["nx", "nrwl"], + "sampleUrls": ["https://github.com/victorsavkin"] } }, { @@ -164,14 +118,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "tanstack", - "query", - "router" - ], - "sampleUrls": [ - "https://github.com/tannerlinsley" - ] + "matchedFacts": ["tanstack", "query", "router"], + "sampleUrls": ["https://github.com/tannerlinsley"] }, "tavily": { "name": "Tanner Linsley", @@ -180,13 +128,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.6666666666666666, - "matchedFacts": [ - "tanstack", - "query" - ], - "sampleUrls": [ - "https://github.com/tannerlinsley" - ] + "matchedFacts": ["tanstack", "query"], + "sampleUrls": ["https://github.com/tannerlinsley"] } }, { @@ -198,14 +141,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "flo", - "ai", - "agent" - ], - "sampleUrls": [ - "https://github.com/eugenesergueev" - ] + "matchedFacts": ["flo", "ai", "agent"], + "sampleUrls": ["https://github.com/eugenesergueev"] }, "tavily": { "name": "Eugene Sergueev", @@ -214,13 +151,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.6666666666666666, - "matchedFacts": [ - "flo", - "ai" - ], - "sampleUrls": [ - "https://github.com/eugenesergueev" - ] + "matchedFacts": ["flo", "ai"], + "sampleUrls": ["https://github.com/eugenesergueev"] } }, { @@ -232,13 +164,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "developer", - "experience" - ], - "sampleUrls": [ - "https://github.com/dominikkundel" - ] + "matchedFacts": ["developer", "experience"], + "sampleUrls": ["https://github.com/dominikkundel"] }, "tavily": { "name": "Dominik Kundel", @@ -247,12 +174,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": [ - "developer" - ], - "sampleUrls": [ - "https://github.com/dominikkundel" - ] + "matchedFacts": ["developer"], + "sampleUrls": ["https://github.com/dominikkundel"] } }, { @@ -264,13 +187,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "frontend", - "accessibility" - ], - "sampleUrls": [ - "https://github.com/mayashavin" - ] + "matchedFacts": ["frontend", "accessibility"], + "sampleUrls": ["https://github.com/mayashavin"] }, "tavily": { "name": "Maya Shavin", @@ -279,12 +197,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": [ - "frontend" - ], - "sampleUrls": [ - "https://github.com/mayashavin" - ] + "matchedFacts": ["frontend"], + "sampleUrls": ["https://github.com/mayashavin"] } }, { @@ -296,13 +210,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "runtime", - "ai" - ], - "sampleUrls": [ - "https://github.com/kiritibadam" - ] + "matchedFacts": ["runtime", "ai"], + "sampleUrls": ["https://github.com/kiritibadam"] }, "tavily": { "name": "Kiriti Badam", @@ -311,12 +220,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": [ - "runtime" - ], - "sampleUrls": [ - "https://github.com/kiritibadam" - ] + "matchedFacts": ["runtime"], + "sampleUrls": ["https://github.com/kiritibadam"] } }, { @@ -328,13 +233,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": [ - "observability", - "telemetry" - ], - "sampleUrls": [ - "https://github.com/sachinmalhotra" - ] + "matchedFacts": ["observability", "telemetry"], + "sampleUrls": ["https://github.com/sachinmalhotra"] }, "tavily": { "name": "Sachin Malhotra", @@ -343,12 +243,8 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": [ - "observability" - ], - "sampleUrls": [ - "https://github.com/sachinmalhotra" - ] + "matchedFacts": ["observability"], + "sampleUrls": ["https://github.com/sachinmalhotra"] } } ] diff --git a/docs/agents/on-page-editor.md b/docs/agents/on-page-editor.md index 2b8a7e60..98c87314 100644 --- a/docs/agents/on-page-editor.md +++ b/docs/agents/on-page-editor.md @@ -116,7 +116,7 @@ export function BlogPost({ id, doc }: { id: string; doc: Doc }) { } ``` -Load the document in your route loader (for example with the `getPublicDocument` server function from `@tanstack/cms-api/start`), and render the components inside the CMS root route's `CmsAuthProvider`, which supplies the session they gate on. +Load the document in your route loader (for example with the `get` server function from `@tanstack/cms-api/start`), and render the components inside the CMS root route's `CmsAuthProvider`, which supplies the session they gate on. ## Next Steps diff --git a/docs/api/cli.md b/docs/api/cli.md index 36f0331b..6110a0aa 100644 --- a/docs/api/cli.md +++ b/docs/api/cli.md @@ -220,7 +220,7 @@ import { loadCms } from '@tanstack/cms-cli' const { core } = await loadCms(process.cwd()) try { - const { total } = await core.queryDocumentsAs(core.publicContext(), { collection: 'post', limit: 1 }) + const { total } = await core.listAs(core.publicContext(), { collection: 'post', limit: 1, populate: false }) console.log(`${total} published posts`) } finally { await core.closeStore() diff --git a/docs/api/cms-api.md b/docs/api/cms-api.md index e8cf79d9..62932a00 100644 --- a/docs/api/cms-api.md +++ b/docs/api/cms-api.md @@ -96,8 +96,8 @@ Runs an operation the way every transport does: import { invokeOp, ops } from '@tanstack/cms-api' export async function publishedPosts(request: Request) { - const input = ops.listPublishedDocuments.input.parse({ collection: 'post', limit: 10 }) - const { items, total } = await invokeOp('listPublishedDocuments', input, { request }) + const input = ops.list.input.parse({ collection: 'post', limit: 10, populate: false }) + const { items, total } = await invokeOp('list', input, { request }) return { posts: items.map((i) => ({ id: i.id, title: String(i.doc.title ?? '') })), total } } ``` @@ -109,7 +109,7 @@ function requestAccessContext(request?: Request, options?: { mode?: ReadMode; de const READ_MODE_HEADER = 'x-cms-read-mode' ``` -Builds the access context for one request: `accessContext({ session: await resolveSession(request), mode })` from [`@tanstack/cms-core/server`](./cms-core-server#access-contexts). `mode` is `options.mode`, else the `x-cms-read-mode` header, else `options.defaultMode` (`edit`). Every HTTP handler builds its context this way. Use it in hosts other than TanStack Start, and pass the result as `ctx.access` or to `cmsAs`. An `edit` request context is the widest the caller may read. The public operations (`getPublicDocument`, `listPublishedDocuments`) serve drafts only to callers who may read them, and a `live` header narrows them to published documents. +Builds the access context for one request: `accessContext({ session: await resolveSession(request), mode })` from [`@tanstack/cms-core/server`](./cms-core-server#access-contexts). `mode` is `options.mode`, else the `x-cms-read-mode` header, else `options.defaultMode` (`edit`). Every HTTP handler builds its context this way. Use it in hosts other than TanStack Start, and pass the result as `ctx.access` or to `cmsAs`. An `edit` request context is the widest the caller may read. The public read operations (`get`, `list`, and the older `getPublicDocument` and `listPublishedDocuments`) serve drafts only to callers who may read them, and a `live` header narrows them to published documents. `agentActorName(surface, session?)` names the agent actor for a surface (`mcp`, `webmcp`, `content-agent`). It appends the session's `x-cms-agent` name, as in `mcp:claude`. @@ -132,7 +132,7 @@ The caller's session plus the available AI features. This is the `getAuthSession | `ResolvedOp` | Any resolved operation from `allOps()` (`source: 'builtin' \| 'agent' \| 'app'`). | | `OpAccess` | `'public' \| Permission`. | | `CmsContext` | `{ request?: Request; actor?: string; access?: AccessContext }`, the transport context. | -| `CmsOpContext` | `CmsContext & { session: CmsSession; actor: string; access: AccessContext }`, what `run` receives. Read through `access` (`cmsAs`, `queryDocumentsAs`, `assertReadable`). | +| `CmsOpContext` | `CmsContext & { session: CmsSession; actor: string; access: AccessContext }`, what `run` receives. Read through `access` (`cmsAs`, `getAs`, `listAs`, `assertReadable`). | | `MediaItem` | Re-exported from `@tanstack/cms-core/server`. | --- @@ -145,10 +145,10 @@ Call them with `{ data }`: ```tsx import { createFileRoute } from '@tanstack/react-router' -import { listPublishedDocuments } from '@tanstack/cms-api/start' +import { list } from '@tanstack/cms-api/start' export const Route = createFileRoute('/blog')({ - loader: () => listPublishedDocuments({ data: { collection: 'post', limit: 20 } }), + loader: () => list({ data: { collection: 'post', limit: 20, populate: false } }), component: Blog, }) @@ -171,6 +171,8 @@ function Blog() { | `getAuthSession` | GET | public | | `listDocumentSummaries` | GET | `content.read` | | `getDocument` | GET | `content.read` | +| `get` | GET | public | +| `list` | GET | public | | `getPublicDocument` | GET | public | | `listPublishedDocuments` | GET | public | | `resolveRedirect` | GET | public | diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index fcedad83..39e50af0 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -10,6 +10,8 @@ keywords: - access context - cmsAs - systemContext + - getAs + - listAs - queryDocuments - commitDocument - stageWrite @@ -101,7 +103,7 @@ export async function postPage(slug: string) { export async function editorDrafts(request: Request) { const session = await resolveSession(request) const db = cmsAs(cms, accessContext({ session, mode: 'edit' })) - return db.queryDocuments({ collection: 'post', where: { published: false } }) + return db.list({ collection: 'post', where: { published: false } }) } export async function sitemapIds() { @@ -174,7 +176,7 @@ 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 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. +- A `preview` or `edit` context also reads unpublished documents. `get` returns the working copy, with staged changes overlaid. `list` returns the committed documents. - `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 @@ -254,6 +256,8 @@ interface QueryDocumentsResult { } ``` +Prefer `listAs` for listing and filtering. `queryDocumentsAs` stays for what `list` doesn't do: full-text `query`, a `collections` list, and `title` and `published` on each item. Without `limit` it returns every match. + The general-purpose query over committed documents, as `ctx` sees them. A `live` context sees published documents only. Documents, titles, and populated relations are redacted for `ctx` after read hooks; collection access and visible search @@ -290,7 +294,7 @@ The operators: - `startsWith`, a case-sensitive prefix match. - `exists`, which takes `true` or `false`. -An unknown operator, a malformed field path, or a bad value is rejected with `BAD_REQUEST` rather than ignored. The same filters are available over HTTP: pass `where`, `sort`, and `cursor` to `listPublishedDocuments` and the agent `search_documents` tool. Over HTTP, filtering or sorting on a field the caller can't read is `FORBIDDEN`. +An unknown operator, a malformed field path, or a bad value is rejected with `BAD_REQUEST` rather than ignored. `listAs` takes the same filters. So does HTTP: pass `where`, `sort`, and `cursor` to the `list` operation (or the older `listPublishedDocuments`) and the agent `search_documents` tool. Over HTTP, filtering or sorting on a field the caller can't read is `FORBIDDEN`. #### Paging @@ -299,11 +303,11 @@ An unknown operator, a malformed field path, or a bad value is rejected with `BA > **Note:** a cursor encodes a position (offset) into the result set, not a keyset. If documents are inserted or deleted — or re-sorted under a mutable sort like `updatedAt` — while you page, rows at the shifting boundary can be skipped or seen twice. For a consistent snapshot of a large, changing collection (e.g. an export), collect ids first and then fetch, rather than relying on cursor stability across concurrent writes. ```ts validate=type -import { systemContext, queryDocumentsAs } from '@tanstack/cms-core/server' +import { listAs, systemContext } from '@tanstack/cms-core/server' let cursor: string | undefined do { - const page = await queryDocumentsAs(systemContext('export every post'), { collection: 'post', limit: 100, cursor }) + const page = await listAs(systemContext('export every post'), { collection: 'post', limit: 100, cursor, populate: false }) // ... cursor = page.nextCursor } while (cursor) @@ -352,7 +356,7 @@ function readDocumentAs(ctx: AccessContext, collectionName: string, id: string): function readDocument(collectionName: string, id: string): Promise // deprecated: reads as publicContext() ``` -The committed document, after `postRead` hooks, redacted for `ctx`. `null` when it doesn't exist or `ctx` can't read it. +The committed document, after `postRead` hooks, redacted for `ctx`. `null` when it doesn't exist or `ctx` can't read it. For a page read, prefer `getAs(ctx, { collection, id })`. Unlike `getAs`, `readDocumentAs` returns the committed row in an `edit` or `preview` context too, with no staged changes overlaid. A read that feeds `commitDocument` wants exactly that. ### `readDocumentWithPendingAs(ctx, collection, id)` @@ -379,7 +383,7 @@ function readDocumentBySlugAs( ): Promise<{ id: string; doc: Doc; relations?: Record | null> } | null> ``` -Reads by id, else by the collection's slug field (leading slashes ignored). An id match wins. Access is checked on the matched document, so a draft `ctx` can't read is `null` like a missing one. The deprecated `readDocumentBySlug(collection, slugOrId, options?)` reads as `publicContext()`. +Reads by id, else by the collection's slug field (leading slashes ignored). An id match wins. Access is checked on the matched document, so a draft `ctx` can't read is `null` like a missing one. With `get` it's `getAs(ctx, { collection, id })`, then `getAs(ctx, { collection, locator })` when that is `null`. The deprecated `readDocumentBySlug(collection, slugOrId, options?)` reads as `publicContext()`. ### `findDocumentBySlugAs(ctx, slugOrId, options?)` @@ -391,7 +395,7 @@ function findDocumentBySlugAs( ): Promise<{ collection: string; id: string; doc: Doc } | null> ``` -`readDocumentBySlugAs` across every collection `ctx` can read, trying `preferred` collections first. The public `/p/$id` and `/post/$id` routes use it. The deprecated `findDocumentBySlug(slugOrId, options?)` reads as `publicContext()`. +`readDocumentBySlugAs` across every collection `ctx` can read, trying `preferred` collections first. The public `/p/$id` and `/post/$id` routes use it. `getAs` takes one collection, so this cross-collection lookup has no `get` form. The deprecated `findDocumentBySlug(slugOrId, options?)` reads as `publicContext()`. ### `readSingletonAs(ctx, collection)` @@ -429,7 +433,7 @@ Summaries across one or all collections `ctx` can read, including pending create function listPublicDocuments(collectionName?: string): Promise>> ``` -Every published document grouped by collection and id. Loads whole collections; prefer `queryDocuments` with `limit` on large sites. +Every published document grouped by collection and id. Loads whole collections; prefer `listAs` with `limit` and `cursor` on large sites. ### `findReferencesAs(ctx, collection, id)` @@ -1228,7 +1232,7 @@ Guards throw `CmsError` with `UNAUTHORIZED` for anonymous callers and `FORBIDDEN import { accessContext, assertReadable, - queryDocumentsAs, + listAs, requirePermission, } from '@tanstack/cms-core/server' @@ -1236,8 +1240,8 @@ export async function listDrafts(request: Request, collection: string) { const session = await requirePermission('content.read', request) const ctx = accessContext({ session, mode: 'edit' }) assertReadable(ctx, collection) - const { items } = await queryDocumentsAs(ctx, { collection, limit: 50 }) - return items.filter((i) => !i.published).map((i) => ({ id: i.id, doc: i.doc })) + const { items } = await listAs(ctx, { collection, where: { published: false }, limit: 50, populate: false }) + return items.map((i) => ({ id: i.id, doc: i.doc })) } ``` diff --git a/docs/api/cms-core.md b/docs/api/cms-core.md index 9dce8f85..82bf281a 100644 --- a/docs/api/cms-core.md +++ b/docs/api/cms-core.md @@ -811,7 +811,7 @@ 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 `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). +These agent tools are separate from the HTTP API operations (`saveDoc`, `get`, `list`, …) in [`@tanstack/cms-api`](./cms-api). ### `related(result, path)` diff --git a/docs/api/routes-and-endpoints.md b/docs/api/routes-and-endpoints.md index 2f57df31..d2e8d25d 100644 --- a/docs/api/routes-and-endpoints.md +++ b/docs/api/routes-and-endpoints.md @@ -195,7 +195,7 @@ The operation catalog. No authentication required. { "version": "v1", "ops": [ - { "name": "listPublishedDocuments", "description": "…", "method": "GET", "access": "public", "source": "builtin" } + { "name": "list", "description": "…", "method": "GET", "access": "public", "source": "builtin" } ] } ``` @@ -244,8 +244,8 @@ Every operation is also a TanStack Start server function in [`@tanstack/cms-api/ | `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` | -| `getPublicDocument` | GET | public | `{ slugOrId, preferred?: string[] }` | `{ collection, id, doc }` or `null`. Published only, except for callers with `content.read`. | -| `listPublishedDocuments` | GET | public | `{ collection, where?, sort?: { field, dir? }, limit? (≤ 500, default 100), offset?, cursor? }` | `{ items: [{ id, doc }], total, nextCursor? }` | +| `getPublicDocument` | GET | public | `{ slugOrId, preferred?: string[] }` | `{ collection, id, doc }` or `null`. Published only, except for callers with `content.read`. A slug-or-id lookup across collections, trying `preferred` first; `get` reads one collection. | +| `listPublishedDocuments` | GET | public | `{ collection, where?, sort?: { field, dir? }, limit? (≤ 500, default 100), offset?, cursor? }` | `{ items: [{ id, doc }], total, nextCursor? }`. The older form of `list`; it never populates. | | `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 }`. Deprecated: use `save`. Staged for review without publish rights; a draft when the document is published and `publish` is not set. | diff --git a/docs/architecture/authentication.md b/docs/architecture/authentication.md index 2b81c275..6fd418fe 100644 --- a/docs/architecture/authentication.md +++ b/docs/architecture/authentication.md @@ -187,7 +187,7 @@ Function-valued `read` rules are evaluated against each stored document. Collect Filtering and sorting on a field with a function-valued `access.read` rule is conservatively forbidden: the database cannot evaluate that predicate before querying, and a predicate that allows an absent document must not enable probes of hidden values. Use a role allow-list for queryable protected fields, or filter on unrestricted fields. -`read` governs admin and API reads (including drafts, the review queue, and revisions). Published documents are still served to anonymous visitors by the public read operations (`getPublicDocument`, `listPublishedDocuments`); use field `access.read` to keep data out of public responses. +`read` governs admin and API reads (including drafts, the review queue, and revisions). Published documents are still served to anonymous visitors by the public read operations (`get`, `list`, and the older `getPublicDocument` and `listPublishedDocuments`); use field `access.read` to keep data out of public responses. ## Field Access Rules diff --git a/docs/architecture/data-layer.md b/docs/architecture/data-layer.md index 5e95c358..44c924e1 100644 --- a/docs/architecture/data-layer.md +++ b/docs/architecture/data-layer.md @@ -133,7 +133,7 @@ tanstackStart({ ## Markdown Files as a Collection -`createMarkdownStorage()` from [`@tanstack/cms-core/storage`](../api/cms-core#read-only-markdown-files-markdownstorage) mounts a directory of `.md` files with YAML frontmatter as a read-only CMS collection (`readOnly: true`). You can configure it for the whole CMS or on an individual collection (`collection.storage`), then query it with `queryDocumentsAs(ctx, …)` inside a Start server function (`examples/db-markdown`): +`createMarkdownStorage()` from [`@tanstack/cms-core/storage`](../api/cms-core#read-only-markdown-files-markdownstorage) mounts a directory of `.md` files with YAML frontmatter as a read-only CMS collection (`readOnly: true`). You can configure it for the whole CMS or on an individual collection (`collection.storage`), then query it with `listAs(ctx, …)` inside a Start server function (`examples/db-markdown`): ```ts // src/cms.config.ts @@ -172,13 +172,14 @@ export const cms = defineCms({ ```ts // src/docs.functions.ts import { createServerFn } from '@tanstack/react-start' -import { publicContext, queryDocumentsAs } from '@tanstack/cms-core/server' +import { listAs, publicContext } from '@tanstack/cms-core/server' import './cms.config' export const listMarkdownDocs = createServerFn({ method: 'GET' }).handler(async () => { - const { items } = await queryDocumentsAs(publicContext(), { + const { items } = await listAs(publicContext(), { collection: 'post', sort: { field: 'date', dir: 'desc' }, + limit: 500, // the most one page holds; page on with `nextCursor` }) return items.map(({ id, doc }) => ({ id, ...doc })) }) diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md index fb2d375e..3325b390 100644 --- a/docs/architecture/terminology.md +++ b/docs/architecture/terminology.md @@ -101,7 +101,7 @@ Rules core enforces on every decision, whatever the strategy: ## Access context -**Implemented for reads.** A value passed explicitly to every read and write that says who is asking and what they may see. It's built once per request by the host app, never read from the request by core. The usual idiom is a bound handle: `const db = cmsAs(cms, ctx)`, then `db.queryDocuments({ collection: 'post' })` (the planned spelling is `cms.as(ctx)` and `db.list`). With the `…As(ctx, …)` verbs, forgetting the context is a type error; the deprecated verbs without one read as public, so a forgotten context fails closed. Hooks and event handlers receive it as an argument. +**Implemented for reads.** A value passed explicitly to every read and write that says who is asking and what they may see. It's built once per request by the host app, never read from the request by core. The usual idiom is a bound handle: `const db = cmsAs(cms, ctx)`, then `db.list({ collection: 'post' })` (the planned spelling is `cms.as(ctx)`). With the `…As(ctx, …)` verbs, forgetting the context is a type error; the deprecated verbs without one read as public, so a forgotten context fails closed. Hooks and event handlers receive it as an argument. Its **mode** decides which version a read returns: diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index 798b92a3..ddc041cd 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -119,14 +119,15 @@ the access context to read as (see [step 25](#25-reads-take-an-access-context)): | 0.x | 1.0 | | --- | --- | -| `getStore().documents.post` | `queryDocumentsAs(ctx, { collection: 'post', where, sort, limit, offset })` | +| `getStore().documents.post` | `listAs(ctx, { collection: 'post', where, sort, limit, cursor })` | | `listDocs('post')` | `queryDocumentSummariesAs(ctx, { collection: 'post', status, search, limit, offset })` | -| `getStore().documents.post[id]` | `readDocumentAs(ctx, 'post', id)` | -| find by slug in one collection | `readDocumentBySlugAs(publicContext(), 'post', slug)` | +| `getStore().documents.post[id]` | `getAs(ctx, { collection: 'post', id })` | +| find by slug in one collection | `getAs(publicContext(), { collection: 'post', locator: slug })` | | find by slug across collections | `findDocumentBySlugAs(ctx, slug, { preferred: ['page', 'post'] })` | All of them return promises, and the list queries return a page plus a -`total`. +`total`. `getAs` and `listAs` resolve to `{ id, collection, doc, relations }` +results, so read the document from `.doc`. ### 6. AI adapters are passed in @@ -437,7 +438,29 @@ const { items, nextCursor } = await cmsAs(cms, ctx).list({ collection: 'post', l The older verbs (`queryDocumentsAs`, `readDocumentBySlugAs`, `listPublishedDocuments`, `getPublicDocument`, …) keep working as they did, -and a later alpha moves the starters and docs over. +and a later alpha removes them. The starters, examples and docs read with +`get` and `list`. + +`pnpm codemod read-verbs` rewrites `queryDocumentsAs`, `readDocumentAs` and +`readDocumentBySlugAs` (their `cmsAs` methods, and the deprecated forms without +a context) to `listAs` and `getAs`. A slug read becomes `get` by `id`, then +by `locator` when that is `null`, the same id-first lookup. It pins +`populate: false` so results keep their relation ids, and leaves a +`TODO(read-verbs)` comment where the result can still differ: + +- `list` returns at most 100 items unless `limit` is set. The older verb + returned every match. Page with `nextCursor`. +- `list` items are `{ id, collection, doc, relations? }`, without `title` or + `published`. +- In a `preview` or `edit` context, `get` returns the working copy, with staged + changes overlaid. `readDocumentAs` returns the committed row. Keep + `readDocumentAs` for a read that feeds `commitDocument` or `stageWrite`. +- A slug read whose key isn't a plain name, member or literal (or that isn't + awaited) becomes one `locator` read, which isn't sure to find a slugged + document by its id. + +It leaves `findDocumentBySlugAs` (a cross-collection lookup), full-text `query` +and multi-collection `collections` reads as they are, with a warning. - **`list_documents` is the canonical `list`.** It takes the `list` bag (`where`, `sort`, `cursor` and `populate` are new; `limit` defaults to 100) diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index 1b2fdbdb..9740bd8d 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -43,8 +43,10 @@ interface CmsOperation { | Operation | Method | Access | Purpose | | --- | --- | --- | --- | | `getAuthSession` | GET | public | Current session and AI capabilities | -| `getPublicDocument` | GET | public | Resolve a document by slug or id (drafts only for readers) | -| `listPublishedDocuments` | GET | public | Paginated published documents of a collection | +| `get` | GET | public | One document by id or locator, with its relations (drafts only for readers) | +| `list` | GET | public | Paginated documents, filtered and sorted, with their relations (drafts only for readers) | +| `getPublicDocument` | GET | public | Resolve a document by slug or id across collections (the older form of `get`) | +| `listPublishedDocuments` | GET | public | Paginated published documents of a collection (the older form of `list`) | | `resolveRedirect` | GET | public | Look up a path in the redirects collection | | `listDocumentSummaries` | GET | `content.read` | Admin list with search, status filter, sort, and pagination | | `getDocument` | GET | `content.read` | One document for editing, with any pending version overlaid | @@ -95,8 +97,8 @@ import { invokeOp } from '@tanstack/cms-api' export async function latestPosts(request: Request) { const { items } = await invokeOp( - 'listPublishedDocuments', - { collection: 'post', limit: 5, offset: 0 }, + 'list', + { collection: 'post', limit: 5, populate: false }, { request }, ) return items.map((item) => ({ id: item.id, title: item.doc.title })) @@ -124,7 +126,7 @@ Responses are `{ result }` on success and `{ error: { code, message, details? } ```bash # Public: no credentials needed -curl 'https://cms.example.com/api/cms/v1/ops/listPublishedDocuments?input=%7B%22collection%22%3A%22post%22%7D' +curl 'https://cms.example.com/api/cms/v1/ops/list?input=%7B%22collection%22%3A%22post%22%7D' # Authenticated with an API key curl -X POST https://cms.example.com/api/cms/v1/ops/saveDoc \ diff --git a/docs/migration/from-emdash.md b/docs/migration/from-emdash.md index 5ebeb683..245a365b 100644 --- a/docs/migration/from-emdash.md +++ b/docs/migration/from-emdash.md @@ -187,7 +187,7 @@ The migrator also writes `src/seed-data.ts`; `defineCms({ seed: { documents: see ## 3. Verify 1. `pnpm --filter emdash-after test:types` and `build`. -2. `pnpm --filter emdash-after test:lib` runs `src/migration.test.ts`. It checks that every document passes `schemaFor(collection)`; that the counts match `emdash-before/seed/seed.json` (1 page, 8 posts with 7 published, 2 authors); that titles, slugs, excerpts, terms, and Portable Text bodies survived; that `seedContent()` and `importContent()` load queryable documents; that `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` finds 4 posts; and that `populate: true` resolves `authors` to their display names. +2. `pnpm --filter emdash-after test:lib` runs `src/migration.test.ts`. It checks that every document passes `schemaFor(collection)`; that the counts match `emdash-before/seed/seed.json` (1 page, 8 posts with 7 published, 2 authors); that titles, slugs, excerpts, terms, and Portable Text bodies survived; that `seedContent()` and `importContent()` load queryable documents; that `listAs(ctx, { where: { tags: 'opinion' } })` finds 4 posts; and that `getAs(ctx, { collection: 'post', locator })` populates `authors` with their display names. 3. Live: compare `total` from `POST /api/cms/v1/ops/listDocumentSummaries` (`{"collection":"post","status":"all"}`) with `seed.json`, then open `/`, `/post/`, and `/sitemap.xml`. ## Remaining Gaps diff --git a/docs/migration/from-payload.md b/docs/migration/from-payload.md index 5e2d05b1..81655549 100644 --- a/docs/migration/from-payload.md +++ b/docs/migration/from-payload.md @@ -89,7 +89,7 @@ Payload v3 and TanStack CMS are both **code-first TypeScript CMSs** with schema | `blocks` | `blocks` | One `defineBlock` per `blockType` | | `group`, `array` | `group`, `array` | `minRows`/`maxRows` → `min`/`max` | | `tabs`, `row`, `collapsible` | Flatten (named tabs → `group`) | Layout only | -| `join`, `ui` | — | `join` becomes a `queryDocumentsAs(ctx, { where })` call | +| `join`, `ui` | — | `join` becomes a `listAs(ctx, { where })` call | Field options carry over by name: `required`, `unique`, `index`, `defaultValue`, `admin.description` → `description`, length and row limits → `min`/`max`, `validate` → `validate(value, { doc, id, collection })` (or a Standard Schema), field `access.read` → `access.read`, and field `access.create`/`update` → `access.write`. @@ -98,7 +98,7 @@ Field options carry over by name: `required`, `unique`, `index`, `defaultValue`, - `({ req: { user } }) => Boolean(user)` becomes `({ session }) => session.isAuthenticated`; a role check becomes a role array such as `['editor', 'admin']`. - Published documents are always publicly readable, so Payload's common `read: () => true` needs no rule. `access.read` governs drafts and admin reads. - Public writes (form submissions) belong in an app server function that calls `commitDocument` from `@tanstack/cms-core/server`. -- Hook arguments change from `{ data, originalDoc, req, operation }` to `{ doc, id, operation, actor }`. Return the transformed doc from `preValidate` / `postValidate` hooks and throw to abort. Replace `req.payload.find()` with `queryDocumentsAs(ctx, …)` or `readDocumentAs(ctx, …)`. Fan-out hooks (cache purges, search sync) often become `defineCms({ webhooks })`. +- Hook arguments change from `{ data, originalDoc, req, operation }` to `{ doc, id, operation, actor }`. Return the transformed doc from `preValidate` / `postValidate` hooks and throw to abort. Replace `req.payload.find()` with `listAs(ctx, …)` or `getAs(ctx, …)`. Fan-out hooks (cache purges, search sync) often become `defineCms({ webhooks })`. ### Blocks (`pages.layout` → `page.blocks`) diff --git a/docs/migration/from-sanity.md b/docs/migration/from-sanity.md index ddba6396..f7db58b3 100644 --- a/docs/migration/from-sanity.md +++ b/docs/migration/from-sanity.md @@ -25,7 +25,7 @@ Both define schemas in TypeScript. They differ in who hosts the data, how it's q | Layer | Sanity | TanStack CMS | |---|---|---| | **Storage** | Hosted Content Lake | Self-hosted `StorageAdapter`: `createSqliteStorage()` by default, `createLibsqlStorage()` for Turso | -| **Querying** | GROQ (or GraphQL) + `sanity typegen` | `queryDocuments`/`readDocumentAs` on the server, the REST API (`/api/cms/v1`, OpenAPI 3.1), and the typed `@tanstack/cms-client`; types flow from `defineCms()` through `Register` | +| **Querying** | GROQ (or GraphQL) + `sanity typegen` | `listAs`/`getAs` on the server, the REST API (`/api/cms/v1`, OpenAPI 3.1), and the typed `@tanstack/cms-client`; types flow from `defineCms()` through `Register` | | **Studio** | A separate React app at `/studio` or hosted | Admin and public routes from `@tanstack/cms-ui-react`, mounted with `createRoutes(definition)` | | **Rich text** | Portable Text | GitHub-Flavored Markdown plus typed blocks | | **Visual editing** | Presentation tool with stega-encoded strings | On-page editing of the rendered blocks and fields | @@ -43,7 +43,7 @@ Both define schemas in TypeScript. They differ in who hosts the data, how it's q ### Cons & Tradeoffs -- **No GROQ projections or reverse references.** Use `relation` fields with `populate: true`, and `queryDocumentsAs(ctx, { where })` for reverse lookups. +- **No GROQ projections or reverse references.** Use `relation` fields, which `getAs` and `listAs` populate by default, and `listAs(ctx, { where })` for reverse lookups. - **No real-time multiplayer editing.** Saves use optimistic concurrency (`expectedRevision`) and revisions. - **No hotspot/crop.** Image transforms resize and re-encode, but don't crop to a focal point. - **Studio customizations don't transfer.** Custom inputs and desk structure need rebuilding or dropping. @@ -188,7 +188,7 @@ Copy the parity test from [`examples/emdash-after/src/migration.test.ts`](https: ## Remaining Gaps -- **Frontend queries**: replace `client.fetch(groq)` with server functions using `queryDocuments`, or with `@tanstack/cms-client`. +- **Frontend queries**: replace `client.fetch(groq)` with server functions using `getAs` and `listAs`, or with `@tanstack/cms-client` (`client.get` and `client.list`). - **Image assets**: upload the files from `images/` into the media library and rewrite URLs to `/api/media/`; hotspot and crop data is lost. - **Pending drafts on published documents**: the sketch above keeps the published version; import pending drafts separately if you need them. - **Polymorphic references** (`to: [a, b]`): split per target collection. diff --git a/docs/migration/from-wordpress.md b/docs/migration/from-wordpress.md index f4cff954..41ba1e64 100644 --- a/docs/migration/from-wordpress.md +++ b/docs/migration/from-wordpress.md @@ -159,7 +159,7 @@ The migrator also writes `src/seed-data.ts`; `defineCms({ seed: { documents: see ## 3. Verify 1. `pnpm --filter wordpress-after test:types` and `build`. -2. `pnpm --filter wordpress-after test:lib` runs `src/migration.test.ts`. It checks that every document passes `schemaFor(collection)`; that the counts match `wordpress-before/export.wxr.xml` (1 published page, 5 posts with 4 published, and 5 redirects); that titles, authors, terms, both featured images, and Gutenberg and classic bodies survived; that `seedContent()` and `importContent()` load queryable documents; that `queryDocumentsAs(ctx, { where: { categories: 'growing' } })` finds 3 posts; and that `resolveRedirect()` maps `/starting-a-garden-journal/` and `/about` to the new URLs. +2. `pnpm --filter wordpress-after test:lib` runs `src/migration.test.ts`. It checks that every document passes `schemaFor(collection)`; that the counts match `wordpress-before/export.wxr.xml` (1 published page, 5 posts with 4 published, and 5 redirects); that titles, authors, terms, both featured images, and Gutenberg and classic bodies survived; that `seedContent()` and `importContent()` load queryable documents; that `listAs(ctx, { where: { categories: 'growing' } })` finds 3 posts; and that `resolveRedirect()` maps `/starting-a-garden-journal/` and `/about` to the new URLs. 3. Live: compare `total` from `POST /api/cms/v1/ops/listDocumentSummaries` (`{"collection":"post","status":"all"}`) with the WXR, request an old permalink (301), and check `/sitemap.xml`. ## Remaining Gaps diff --git a/docs/migration/overview.md b/docs/migration/overview.md index a666479f..82886938 100644 --- a/docs/migration/overview.md +++ b/docs/migration/overview.md @@ -79,7 +79,7 @@ The migrators also write `src/seed-data.ts`. Passing it as `defineCms({ seed: { ### 4. Verify and report 1. `test:types` (`tsc --noEmit`) and `build`. -2. A **parity test** (`src/migration.test.ts`, run by `test:lib`) in each worked example. Against a temp `dataDir`, it checks that every migrated document passes `schemaFor(collection)` from `@tanstack/cms-core`, that per-collection counts match the source (hardcoded with a comment naming where they came from), that key fields survived, and that `seedContent()` or `importContent()` from `@tanstack/cms-core/server` loads documents that `queryDocumentsAs(ctx, …)` and `readDocumentAs(ctx, …)` can read, with relations and redirects resolving. +2. A **parity test** (`src/migration.test.ts`, run by `test:lib`) in each worked example. Against a temp `dataDir`, it checks that every migrated document passes `schemaFor(collection)` from `@tanstack/cms-core`, that per-collection counts match the source (hardcoded with a comment naming where they came from), that key fields survived, and that `seedContent()` or `importContent()` from `@tanstack/cms-core/server` loads documents that `listAs(ctx, …)` and `getAs(ctx, …)` can read, with relations and redirects resolving. 3. A live check: `POST /api/cms/v1/ops/listDocumentSummaries` with `{"collection":"post","status":"all"}` returns `total` to compare with the source; then open the pages, old URLs, and `/sitemap.xml`. 4. `MIGRATION.md` with the mapping tables and a **gap report** of everything dropped, flattened, or left for a person to decide. diff --git a/docs/schema/building-pages.md b/docs/schema/building-pages.md index a20dece0..98814f5a 100644 --- a/docs/schema/building-pages.md +++ b/docs/schema/building-pages.md @@ -11,10 +11,10 @@ keywords: - BlocksView - cmsHead - cmsJsonLd + - get + - list + - related - getPublicDocument - - listPublishedDocuments - - queryDocuments - - readDocumentBySlug - readSingleton - cmsAs - access context @@ -45,20 +45,27 @@ There are three ways to read content from a route loader. All of them respect dr ### 1. The CMS server functions -`@tanstack/cms-api/start` exports one TanStack Start server function per CMS operation. Call them with `{ data }`; they run in-process on the server and over RPC from the client, and resolve the caller's session from the request. The public ones are: +`@tanstack/cms-api/start` exports one TanStack Start server function per CMS operation. Call them with `{ data }`; they run in-process on the server and over RPC from the client, and resolve the caller's session from the request. The public reads are: -- `getPublicDocument({ data: { slugOrId, preferred? } })` → `{ collection, id, doc } | null` — find a document by id or slug across collections, trying `preferred` collections first. -- `listPublishedDocuments({ data: { collection, sort?, limit?, offset? } })` → `{ items: Array<{ id, doc }>, total }` — one collection, paginated (`limit` default 100, max 500). +- `get({ data: { collection, id | locator, locale?, populate? } })` → `{ id, collection, doc, relations? } | null`: one document by `id`, or by `locator` (its slug, or the id of a document without one). +- `list({ data: { collection?, where?, sort?, limit?, offset?, cursor?, locale?, populate? } })` → `{ items: Array<{ id, collection, doc, relations? }>, total, nextCursor? }`: one page of documents (`limit` default 100, max 500). - `resolveRedirect({ data: { path } })` → `{ to, status } | null`. +Visitors read published documents; sessions that may read drafts get the working copy. Both reads populate relations by default (see below); pass `populate: false` for ids only. `getPublicDocument({ data: { slugOrId, preferred? } })` still finds a document across every collection, trying `preferred` collections first, which `get` doesn't do. `listPublishedDocuments` is the older `list`, without relations. + ```ts validate=type -import { getPublicDocument, listPublishedDocuments } from '@tanstack/cms-api/start' +import { get, list } from '@tanstack/cms-api/start' export async function loadLanding(slug: string) { const [page, posts] = await Promise.all([ - getPublicDocument({ data: { slugOrId: slug, preferred: ['page'] } }), - listPublishedDocuments({ - data: { collection: 'post', sort: { field: 'updatedAt', dir: 'desc' }, limit: 5 }, + get({ data: { collection: 'page', locator: slug } }), + list({ + data: { + collection: 'post', + sort: { field: 'updatedAt', dir: 'desc' }, + limit: 5, + populate: false, + }, }), ]) return { page, posts: posts.items } @@ -69,7 +76,7 @@ See [`@tanstack/cms-api`](../api/cms-api#tanstackcms-apistart) for every server ### 2. Your own server function over the store -For filters, relations, singletons, or anything the built-in operations don't cover, write your own `createServerFn` that reads through `cmsAs(cms, ctx)` from `@tanstack/cms-core/server`. It binds the store's read verbs (`queryDocuments`, `readDocument`, `readDocumentBySlug`, `readSingleton`, `findDocumentBySlug`, `populateRelations`, …) to an **access context**: who is reading, and in which mode. Every read returns only what that context may see. Documents it can't read come back as missing, and fields it can't read are removed. All reads are async. +For singletons, cross-collection lookups, or anything the built-in operations don't cover, write your own `createServerFn` that reads through `cmsAs(cms, ctx)` from `@tanstack/cms-core/server`. It binds the store's read verbs (`get`, `list`, `readSingleton`, `findDocumentBySlug`, `populateRelations`, …) to an **access context**: who is reading, and in which mode. Every read returns only what that context may see. Documents it can't read come back as missing, and fields it can't read are removed. All reads are async. ```ts validate=type import { createServerFn } from '@tanstack/react-start' @@ -82,13 +89,12 @@ export const getChangelog = createServerFn({ method: 'GET' }) .handler(async ({ data }) => { const db = cmsAs(cms, publicContext()) const settings = await db.readSingleton('settings') - const releases = await db.queryDocuments({ + const releases = await db.list({ collection: 'post', where: data.category ? { category: data.category } : undefined, sort: { field: 'publishedDate', dir: 'desc' }, limit: 10, offset: ((data.page ?? 1) - 1) * 10, - populate: true, }) return { settings: settings?.doc ?? null, releases } }) @@ -96,9 +102,9 @@ export const getChangelog = createServerFn({ method: 'GET' }) export const getArticle = createServerFn({ method: 'GET' }) .validator((data: { slug: string }) => data) .handler(async ({ data }) => { - // The visitor's own session: editors see drafts they may read. + // The visitor's own session: editors see the working copy of drafts they may read. const db = cmsAs(cms, await getCmsAccessContext({ mode: 'edit' })) - return db.readDocumentBySlug('post', data.slug, { populate: true }) + return db.get({ collection: 'post', locator: data.slug }) }) ``` @@ -108,9 +114,11 @@ Pick the context that matches the reader: - `getCmsAccessContext()` from `@tanstack/cms-api/start` reads as the current request's session. It defaults to `live` (published only), and `{ mode: 'edit' }` adds the drafts that session may read. Outside TanStack Start, build it yourself with `accessContext({ session: await resolveSession(request), mode })`. - `systemContext(reason)` bypasses every access rule. Use it for trusted jobs such as build scripts, sitemaps and imports, never with a visitor's input. The `reason` is required, so each bypass says why it exists. -Each verb also exists in argument form (`queryDocumentsAs(ctx, …)`, `readDocumentAs(ctx, …)`) for code that passes the context along. The plain functions without a context (`queryDocuments`, `readDocumentBySlug`, …) are deprecated and read as `publicContext()`. +In `edit` and `preview` mode, `get` returns the working copy, with staged changes overlaid; `list` returns the stored documents. + +Each verb also exists in argument form (`getAs(ctx, …)`, `listAs(ctx, …)`, `readSingletonAs(ctx, …)`) for code that passes the context along. The older verbs (`queryDocuments`, `readDocument`, `readDocumentBySlug`, and their `…As` forms) keep their old defaults (no relations, no default `limit`) and are deprecated. -With `populate: true`, each result carries `relations`: a map from each `relation` field name to the target document (or array of documents for `many: true`). The stored IDs are left as they are. `db.populateRelations(collection, doc)` does the same for a document you already have. +`get` and `list` populate relations by default: each result carries `relations`, keyed by relation field path (`author`, `blocks.2.author`), holding the target document (or an array for `many: true`). The stored ids stay in `doc`, and a target the reader can't see is `null`. Read them with `related(result, 'author')` from `@tanstack/cms-core`. Pass `populate: false` for ids only, or a list of paths (`['author']`). `db.populateRelations(collection, doc)` does the same for a document you already have. ### 3. The HTTP client @@ -120,7 +128,7 @@ From another app, a script, or a mobile client, use [`@tanstack/cms-client`](../ import { createCmsClient } from '@tanstack/cms-client' const cms = createCmsClient({ baseUrl: 'https://cms.example.com' }) -const { items } = await cms.collection('post').published({ limit: 10 }) +const { items } = await cms.list({ collection: 'post', limit: 10 }) ``` ## Adding custom routes @@ -166,14 +174,14 @@ A custom route is an ordinary TanStack Router file. This one renders a page's bl // src/routes/blog.$slug.tsx import { createFileRoute, notFound } from '@tanstack/react-router' import { cmsHead } from '@tanstack/cms-core' -import { getPublicDocument } from '@tanstack/cms-api/start' +import { get } from '@tanstack/cms-api/start' import { BlocksView, SiteShell } from '@tanstack/cms-ui-react/site' import type { Block } from '@tanstack/cms-core' export const Route = createFileRoute('/blog/$slug')({ loader: async ({ params }) => { - const found = await getPublicDocument({ - data: { slugOrId: params.slug, preferred: ['post'] }, + const found = await get({ + data: { collection: 'post', locator: params.slug, populate: false }, }) if (!found) throw notFound() return found diff --git a/examples/astro-starlight-after/MIGRATION.md b/examples/astro-starlight-after/MIGRATION.md index e5798a3a..d1b0298e 100644 --- a/examples/astro-starlight-after/MIGRATION.md +++ b/examples/astro-starlight-after/MIGRATION.md @@ -98,7 +98,7 @@ Against a temp `dataDir`, `src/migration.test.ts` checks: - frontmatter, slugs, sidebar fields, and bodies survived, with no `` tags left in the home page's Markdown; - `seedContent({ force: true })` and `importContent()` load 10 documents that - `queryDocuments`/`readDocument` return, and + `listAs`/`getAs` return, and `resolveRedirect('/start/installation/')` gives `/p/start-installation` with status 301, while the draft's old URL has no redirect. diff --git a/examples/astro-starlight-after/src/migration.test.ts b/examples/astro-starlight-after/src/migration.test.ts index 8c07a1e2..d9f274d5 100644 --- a/examples/astro-starlight-after/src/migration.test.ts +++ b/examples/astro-starlight-after/src/migration.test.ts @@ -24,8 +24,8 @@ import { seedContent, publicContext, systemContext, - queryDocumentsAs, - readDocumentAs, + listAs, + getAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -142,14 +142,22 @@ describe('astro starlight → tanstack cms parity', () => { const { seeded } = await seedContent({ force: true }) expect(seeded).toBe(EXPECTED.page.total + EXPECTED.redirect.total) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'page' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'page', + }) + ).total, ).toBe(6) + expect((await listAs(publicContext(), { collection: 'page' })).total).toBe( + 5, + ) expect( - (await queryDocumentsAs(publicContext(), { collection: 'page' })).total, - ).toBe(5) - expect( - await readDocumentAs(systemContext('test'), 'page', 'start-installation'), + ( + await getAs(systemContext('test'), { + collection: 'page', + id: 'start-installation', + }) + )?.doc, ).toMatchObject({ title: 'Installation', slug: '/start/installation', @@ -162,8 +170,11 @@ describe('astro starlight → tanstack cms parity', () => { const result = await importContent(data) expect(result.created).toBe(EXPECTED.page.total + EXPECTED.redirect.total) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'page' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'page', + }) + ).total, ).toBe(6) expect(await resolveRedirect('/start/installation/')).toEqual({ to: '/p/start-installation', diff --git a/examples/blog-voting/README.md b/examples/blog-voting/README.md index a6cb7625..b4abb573 100644 --- a/examples/blog-voting/README.md +++ b/examples/blog-voting/README.md @@ -15,7 +15,7 @@ the worked reference for the [`voting` skill](../../.claude/skills/voting/SKILL. - **Cached tallies** (`upvotes`/`downvotes`/`score` on `post`), recomputed from the vote collection after every write — never trusted from the client. - **Indexed reads**: `getTopPosts` sorts published posts by the `score` - number field through `queryDocuments`. + number field through `listAs`. - **Extension without forking**: the `/top` page (`src/routes/top.tsx`) is added via `createRoutes(definition, { custom })` in `vite.config.ts`. No package route was modified. @@ -23,8 +23,10 @@ the worked reference for the [`voting` skill](../../.claude/skills/voting/SKILL. the voter id comes from the session, never from client input. The demo uses `createMockAuth()` from `@tanstack/cms-ui-react`. -All store calls (`readDocument`, `queryDocuments`, `commitDocument`, -`deleteDocument`) are async in 1.0 and awaited. +All store calls (`getAs`, `listAs`, `readDocumentAs`, `commitDocument`, +`deleteDocument`) are async in 1.0 and awaited. The vote and tally writes +read the stored row with `readDocumentAs`, because `getAs` in an edit context +returns the working copy. ## Run it @@ -58,7 +60,7 @@ Things TanStack CMS 1.0 doesn't provide, found by following the skill: 2. **No composite uniqueness.** Field `unique: true` covers single fields (slugs, emails); "one vote per (post, voter)" still relies on the id. 3. **No aggregation queries.** "Total votes today", "top voters", or a - histogram mean scanning with `queryDocuments`. The cached `score` field + histogram mean scanning with `listAs`. The cached `score` field covers per-post ranking. 4. **No app-defined rate-limit buckets.** `rateLimit()` from `@tanstack/cms-core/server` has fixed buckets (`ai`, `upload`, `mcp`, diff --git a/examples/blog-voting/src/voting/votes.ts b/examples/blog-voting/src/voting/votes.ts index 516a7fdd..9cf4b93b 100644 --- a/examples/blog-voting/src/voting/votes.ts +++ b/examples/blog-voting/src/voting/votes.ts @@ -21,9 +21,9 @@ import { requireAuthenticated, publicContext, systemContext, + getAs, + listAs, readDocumentAs, - readDocumentBySlugAs, - queryDocumentsAs, } from '@tanstack/cms-core/server' import type { Doc } from '@tanstack/cms-core' @@ -60,25 +60,37 @@ const VOTES = systemContext('voting: votes and tallies are server-owned') /** A published post by id or slug: voters only ever see published posts. */ async function resolvePost(postId: string): Promise<{ id: string; doc: Doc }> { - const direct = await readDocumentAs(publicContext(), 'post', postId) - if (direct) return { id: postId, doc: direct } - const bySlug = await readDocumentBySlugAs(publicContext(), 'post', postId) - if (bySlug) return { id: bySlug.id, doc: bySlug.doc } + const ctx = publicContext() + const post = + (await getAs(ctx, { collection: 'post', id: postId, populate: false })) ?? + (await getAs(ctx, { + collection: 'post', + locator: postId, + populate: false, + })) + if (post) return { id: post.id, doc: post.doc } throw new Error(`Post not found: ${postId}`) } async function tallyVotes(postId: string): Promise { - const votes = await queryDocumentsAs(VOTES, { - collection: 'vote', - where: { post: postId }, - }) let upvotes = 0 let downvotes = 0 - for (const v of votes.items) { - const val = Number((v.doc as Record).value) - if (val > 0) upvotes++ - else if (val < 0) downvotes++ - } + let cursor: string | undefined + do { + const votes = await listAs(VOTES, { + collection: 'vote', + where: { post: postId }, + limit: 500, + cursor, + populate: false, + }) + for (const v of votes.items) { + const val = Number((v.doc as Record).value) + if (val > 0) upvotes++ + else if (val < 0) downvotes++ + } + cursor = votes.nextCursor + } while (cursor) return { upvotes, downvotes, score: upvotes - downvotes } } @@ -158,16 +170,17 @@ export async function getTopPosts(limit = 10): Promise< downvotes: number }> > { - const { items } = await queryDocumentsAs(publicContext(), { + const { items } = await listAs(publicContext(), { collection: 'post', sort: { field: 'score', dir: 'desc' }, limit, + populate: false, }) return items.map((i) => { const rec = i.doc as Record return { id: i.id, - title: i.title, + title: typeof rec.title === 'string' && rec.title ? rec.title : i.id, score: Number(rec.score ?? 0), upvotes: Number(rec.upvotes ?? 0), downvotes: Number(rec.downvotes ?? 0), diff --git a/examples/db-markdown/README.md b/examples/db-markdown/README.md index e4214af7..7ad5224b 100644 --- a/examples/db-markdown/README.md +++ b/examples/db-markdown/README.md @@ -13,8 +13,8 @@ the `.md` files on disk are the CMS store. becomes fields, and the Markdown body becomes `body`. (For standalone file reading outside a CMS collection, `@tanstack/cms-api/markdown` also exports `loadMarkdownDir()`.) - **A Start server function as the loader.** `src/docs.functions.ts` queries the - collection on the server with `queryDocumentsAs(publicContext(), { collection: 'post' })` - from `@tanstack/cms-core/server`, so only published posts leave the server; + collection on the server with `listAs(publicContext(), { collection: 'post', limit: 500, cursor })` + from `@tanstack/cms-core/server`, paging with `nextCursor`, so only published posts leave the server; the client never touches `node:fs`. - **One query collection, many live queries.** `src/collections.ts` wraps the server function in a `queryCollectionOptions` collection. The index filters diff --git a/examples/db-markdown/src/docs.functions.ts b/examples/db-markdown/src/docs.functions.ts index f9779f12..c602bf5e 100644 --- a/examples/db-markdown/src/docs.functions.ts +++ b/examples/db-markdown/src/docs.functions.ts @@ -4,7 +4,7 @@ * through a TanStack Start server function. */ import { createServerFn } from '@tanstack/react-start' -import { publicContext, queryDocumentsAs } from '@tanstack/cms-core/server' +import { listAs, publicContext } from '@tanstack/cms-core/server' import './cms.config' type Json = @@ -19,13 +19,23 @@ export const listMarkdownDocs = createServerFn({ method: 'GET' }).handler( async (): Promise< Array & { id: string; body: string }> > => { - const { items } = await queryDocumentsAs(publicContext(), { - collection: 'post', - }) - return items.map((item) => ({ - ...(item.doc as Record), - id: item.id, - body: String(item.doc.body ?? ''), - })) + const docs: Array & { id: string; body: string }> = [] + let cursor: string | undefined + do { + const page = await listAs(publicContext(), { + collection: 'post', + limit: 500, + cursor, + }) + for (const item of page.items) { + docs.push({ + ...(item.doc as Record), + id: item.id, + body: String(item.doc.body ?? ''), + }) + } + cursor = page.nextCursor + } while (cursor) + return docs }, ) diff --git a/examples/emdash-after/MIGRATION.md b/examples/emdash-after/MIGRATION.md index 3d2e52c8..c055f9ae 100644 --- a/examples/emdash-after/MIGRATION.md +++ b/examples/emdash-after/MIGRATION.md @@ -100,8 +100,8 @@ Against a temp `dataDir`, `src/migration.test.ts` checks: - titles, slugs, excerpts, featured images, terms, bylines, and Portable Text `h2` headings survived; - `seedContent({ force: true })` and `importContent()` load 11 documents; - `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` finds 4 posts; and - `populate: true` resolves `building-for-the-long-term`'s `authors` to + `listAs(ctx, { where: { tags: 'opinion' } })` finds 4 posts; and + `getAs` (populated by default) resolves `building-for-the-long-term`'s `authors` to "EmDash Editorial" and "Guest Contributor". ## Gap report diff --git a/examples/emdash-after/src/migration.test.ts b/examples/emdash-after/src/migration.test.ts index 76461d5a..831eeff0 100644 --- a/examples/emdash-after/src/migration.test.ts +++ b/examples/emdash-after/src/migration.test.ts @@ -21,9 +21,8 @@ import { seedContent, publicContext, systemContext, - queryDocumentsAs, - readDocumentAs, - readDocumentBySlugAs, + listAs, + getAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -138,22 +137,30 @@ describe('emdash → tanstack cms parity', () => { const { seeded } = await seedContent({ force: true }) expect(seeded).toBe(TOTAL) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'post' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'post', + }) + ).total, ).toBe(8) - expect( - (await queryDocumentsAs(publicContext(), { collection: 'post' })).total, - ).toBe(7) + expect((await listAs(publicContext(), { collection: 'post' })).total).toBe( + 7, + ) expect( ( - await queryDocumentsAs(systemContext('test'), { + await listAs(systemContext('test'), { collection: 'post', where: { tags: 'opinion' }, }) ).total, ).toBe(4) expect( - await readDocumentAs(systemContext('test'), 'page', 'about'), + ( + await getAs(systemContext('test'), { + collection: 'page', + id: 'about', + }) + )?.doc, ).toMatchObject({ title: 'About', }) @@ -164,12 +171,10 @@ describe('emdash → tanstack cms parity', () => { const data = parseCmsExport(JSON.parse(JSON.stringify(asCmsExport()))) const result = await importContent(data) expect(result.created).toBe(TOTAL) - const found = await readDocumentBySlugAs( - systemContext('test'), - 'post', - 'building-for-the-long-term', - { populate: true }, - ) + const found = await getAs(systemContext('test'), { + collection: 'post', + locator: 'building-for-the-long-term', + }) const authors = found?.relations?.authors as Array<{ name: string }> expect(authors.map((a) => a.name)).toEqual([ 'EmDash Editorial', diff --git a/examples/payload-after/MIGRATION.md b/examples/payload-after/MIGRATION.md index 862888b9..c0347366 100644 --- a/examples/payload-after/MIGRATION.md +++ b/examples/payload-after/MIGRATION.md @@ -94,9 +94,9 @@ Against a temp `dataDir`, `src/migration.test.ts` checks: **2 posts** (1 published); `users` and `media` aren't content; - titles, slugs, authors, the home page's hero + richText blocks, and a Lexical heading + paragraph converted to Markdown; -- `seedContent({ force: true })` writes 4 documents that `queryDocuments` +- `seedContent({ force: true })` writes 4 documents that `listAs` returns with the right published counts, and `importContent()` of the same - documents as a CMS export creates 4 documents readable with `readDocument`. + documents as a CMS export creates 4 documents readable with `getAs`. ## Gap report diff --git a/examples/payload-after/src/migration.test.ts b/examples/payload-after/src/migration.test.ts index 466aa598..ddaf5f88 100644 --- a/examples/payload-after/src/migration.test.ts +++ b/examples/payload-after/src/migration.test.ts @@ -21,8 +21,8 @@ import { seedContent, publicContext, systemContext, - queryDocumentsAs, - readDocumentAs, + listAs, + getAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -121,15 +121,23 @@ describe('payload → tanstack cms parity', () => { expect(seeded).toBe(4) for (const [name, expected] of Object.entries(EXPECTED)) { expect( - (await queryDocumentsAs(systemContext('test'), { collection: name })) - .total, + ( + await listAs(systemContext('test'), { + collection: name, + }) + ).total, ).toBe(expected.total) - expect( - (await queryDocumentsAs(publicContext(), { collection: name })).total, - ).toBe(expected.published) + expect((await listAs(publicContext(), { collection: name })).total).toBe( + expected.published, + ) } expect( - await readDocumentAs(systemContext('test'), 'page', 'home'), + ( + await getAs(systemContext('test'), { + collection: 'page', + id: 'home', + }) + )?.doc, ).toMatchObject({ title: 'Welcome', }) @@ -141,15 +149,26 @@ describe('payload → tanstack cms parity', () => { const result = await importContent(data) expect(result.created).toBe(4) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'page' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'page', + }) + ).total, ).toBe(2) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'post' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'post', + }) + ).total, ).toBe(2) expect( - await readDocumentAs(systemContext('test'), 'post', 'hello-world'), + ( + await getAs(systemContext('test'), { + collection: 'post', + id: 'hello-world', + }) + )?.doc, ).toMatchObject({ title: 'Hello world', body: 'There is not much here yet.', diff --git a/examples/wordpress-after/MIGRATION.md b/examples/wordpress-after/MIGRATION.md index d313dae5..0c3ae44f 100644 --- a/examples/wordpress-after/MIGRATION.md +++ b/examples/wordpress-after/MIGRATION.md @@ -100,7 +100,7 @@ Against a temp `dataDir`, `src/migration.test.ts` checks: - titles, slugs, authors, terms, the 2 featured images, and the Gutenberg, code-block, and classic-editor bodies survived; - `seedContent({ force: true })` and `importContent()` load 11 documents; - `queryDocumentsAs(ctx, { where: { categories: 'growing' } })` finds 3 posts; and + `listAs(ctx, { where: { categories: 'growing' } })` finds 3 posts; and `resolveRedirect()` maps `/starting-a-garden-journal/` to `/post/starting-a-garden-journal` and `/about` to `/p/about` (301), while the draft has none. diff --git a/examples/wordpress-after/src/migration.test.ts b/examples/wordpress-after/src/migration.test.ts index 6f426b80..7c56f2af 100644 --- a/examples/wordpress-after/src/migration.test.ts +++ b/examples/wordpress-after/src/migration.test.ts @@ -24,8 +24,8 @@ import { seedContent, publicContext, systemContext, - queryDocumentsAs, - readDocumentAs, + listAs, + getAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -144,22 +144,30 @@ describe('wordpress → tanstack cms parity', () => { const { seeded } = await seedContent({ force: true }) expect(seeded).toBe(TOTAL) expect( - (await queryDocumentsAs(systemContext('test'), { collection: 'post' })) - .total, + ( + await listAs(systemContext('test'), { + collection: 'post', + }) + ).total, ).toBe(5) - expect( - (await queryDocumentsAs(publicContext(), { collection: 'post' })).total, - ).toBe(4) + expect((await listAs(publicContext(), { collection: 'post' })).total).toBe( + 4, + ) expect( ( - await queryDocumentsAs(systemContext('test'), { + await listAs(systemContext('test'), { collection: 'post', where: { categories: 'growing' }, }) ).total, ).toBe(3) expect( - await readDocumentAs(systemContext('test'), 'page', 'about'), + ( + await getAs(systemContext('test'), { + collection: 'page', + id: 'about', + }) + )?.doc, ).toMatchObject({ title: 'About The Garden Path', }) diff --git a/packages/cli/src/commands/atproto.ts b/packages/cli/src/commands/atproto.ts index 86cf1622..91c28d77 100644 --- a/packages/cli/src/commands/atproto.ts +++ b/packages/cli/src/commands/atproto.ts @@ -129,11 +129,13 @@ export async function atprotoCommand( return 1 } try { - const doc = await core.readDocumentAs( - core.publicContext(), - collection, - id, - ) + const doc = ( + await core.getAs(core.publicContext(), { + collection, + id, + populate: false, + }) + )?.doc if (!doc) { io.error(`No published document: ${collection}/${id}`) return 1 diff --git a/scripts/codemods/__fixtures__/read-verbs/calls.input.ts b/scripts/codemods/__fixtures__/read-verbs/calls.input.ts new file mode 100644 index 00000000..9bdf60a1 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/calls.input.ts @@ -0,0 +1,40 @@ +import { + accessContext, + publicContext, + queryDocuments, + queryDocumentsAs, + readDocumentAs, + readDocumentBySlugAs, + systemContext, +} from '@tanstack/cms-core/server' +import type { CmsSession } from '@tanstack/cms-core' + +export async function page(session: CmsSession, slug: string, id: string) { + const { items } = await queryDocumentsAs(publicContext(), { + collection: 'post', + where: { featured: true }, + limit: 10, + }) + const titles = items.map((item) => String(item.doc.title)) + const page = await queryDocumentsAs(accessContext({ session }), { + collections: ['post'], + sort: { field: 'title' }, + limit: 20, + populate: true, + }) + for (const item of page.items) console.log(item.id, item.relations) + const total = (await queryDocuments({ collection: 'tag', limit: 5 })).total + const count = (await queryDocumentsAs(publicContext(), { collection: 'tag' })) + .total + const first = ( + await queryDocumentsAs(publicContext(), { collection: 'tag', limit: 1 }) + ).items[0]?.doc + const post = await readDocumentAs(publicContext(), 'post', id) + if (!(await readDocumentAs(systemContext('audit', { mode: 'live' }), 'post', id))) + return null + const bySlug = await readDocumentBySlugAs(publicContext(), 'post', slug, { + populate: true, + }) + const bare = await readDocumentBySlugAs(publicContext(), 'post', slug) + return { titles, total, count, first, post, bySlug, bare, pages: page.total } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/calls.output.ts b/scripts/codemods/__fixtures__/read-verbs/calls.output.ts new file mode 100644 index 00000000..646fb33f --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/calls.output.ts @@ -0,0 +1,31 @@ +import { accessContext, publicContext, systemContext, listAs, getAs } from '@tanstack/cms-core/server' +import type { CmsSession } from '@tanstack/cms-core' + +export async function page(session: CmsSession, slug: string, id: string) { + const { items } = await listAs(publicContext(), { + collection: 'post', + where: { featured: true }, + limit: 10, + populate: false, + }) + const titles = items.map((item) => String(item.doc.title)) + const page = await listAs(accessContext({ session }), { + collection: 'post', + sort: { field: 'title' }, + limit: 20, + populate: true, + }) + for (const item of page.items) console.log(item.id, item.relations) + const total = (await listAs(publicContext(), { collection: 'tag', limit: 5, populate: false })).total + const count = (await listAs(publicContext(), { collection: 'tag', populate: false })) + .total + const first = ( + await listAs(publicContext(), { collection: 'tag', limit: 1, populate: false }) + ).items[0]?.doc + const post = (await getAs(publicContext(), { collection: 'post', id, populate: false }))?.doc ?? null + if (!((await getAs(systemContext('audit', { mode: 'live' }), { collection: 'post', id, populate: false }))?.doc ?? null)) + return null + const bySlug = (await getAs(publicContext(), { collection: 'post', id: slug })) ?? (await getAs(publicContext(), { collection: 'post', locator: slug })) + const bare = (await getAs(publicContext(), { collection: 'post', id: slug, populate: false })) ?? (await getAs(publicContext(), { collection: 'post', locator: slug, populate: false })) + return { titles, total, count, first, post, bySlug, bare, pages: page.total } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/docs.input.md b/scripts/codemods/__fixtures__/read-verbs/docs.input.md new file mode 100644 index 00000000..0a4f1b5d --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/docs.input.md @@ -0,0 +1,18 @@ +# Reading posts + +```ts +import { publicContext, queryDocumentsAs } from '@tanstack/cms-core/server' + +const { items } = await queryDocumentsAs(publicContext(), { + collection: 'post', + limit: 10, +}) +``` + +- In a list item: + + ```ts + import { publicContext, readDocumentAs } from '@tanstack/cms-core/server' + + const post = await readDocumentAs(publicContext(), 'post', 'hello') + ``` diff --git a/scripts/codemods/__fixtures__/read-verbs/docs.output.md b/scripts/codemods/__fixtures__/read-verbs/docs.output.md new file mode 100644 index 00000000..364af807 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/docs.output.md @@ -0,0 +1,19 @@ +# Reading posts + +```ts +import { publicContext, listAs } from '@tanstack/cms-core/server' + +const { items } = await listAs(publicContext(), { + collection: 'post', + limit: 10, + populate: false, +}) +``` + +- In a list item: + + ```ts + import { publicContext, getAs } from '@tanstack/cms-core/server' + + const post = (await getAs(publicContext(), { collection: 'post', id: 'hello', populate: false }))?.doc ?? null + ``` diff --git a/scripts/codemods/__fixtures__/read-verbs/dynamic.input.ts b/scripts/codemods/__fixtures__/read-verbs/dynamic.input.ts new file mode 100644 index 00000000..7dc71cf6 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/dynamic.input.ts @@ -0,0 +1,14 @@ +export async function importPeople(ids: Array) { + const { stageWrite, systemContext, readDocumentAs } = + await import('@tanstack/cms-core/server') + const existing = systemContext('import: create or update') + for (const id of ids) { + const person = await readDocumentAs(existing, 'person', id) + await stageWrite({ + collection: 'person', + docId: id, + type: person ? 'update' : 'create', + doc: { name: id }, + }) + } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/dynamic.output.ts b/scripts/codemods/__fixtures__/read-verbs/dynamic.output.ts new file mode 100644 index 00000000..be5e9928 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/dynamic.output.ts @@ -0,0 +1,15 @@ +export async function importPeople(ids: Array) { + const { stageWrite, systemContext, getAs } = + await import('@tanstack/cms-core/server') + const existing = systemContext('import: create or update') + for (const id of ids) { + // TODO(read-verbs): unless this context is live, get returns the working copy (staged changes overlaid), not the stored row + const person = (await getAs(existing, { collection: 'person', id, populate: false }))?.doc ?? null + await stageWrite({ + collection: 'person', + docId: id, + type: person ? 'update' : 'create', + doc: { name: id }, + }) + } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/dynamic.warnings.json b/scripts/codemods/__fixtures__/read-verbs/dynamic.warnings.json new file mode 100644 index 00000000..a79c3138 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/dynamic.warnings.json @@ -0,0 +1,3 @@ +[ + "dynamic.ts:6:26: TODO: unless this context is live, get returns the working copy (staged changes overlaid), not the stored row" +] diff --git a/scripts/codemods/__fixtures__/read-verbs/handle.input.ts b/scripts/codemods/__fixtures__/read-verbs/handle.input.ts new file mode 100644 index 00000000..4ed6145a --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/handle.input.ts @@ -0,0 +1,12 @@ +import { accessContext, cmsAs, resolveSession } from '@tanstack/cms-core/server' +import { cms } from './cms' + +export async function loader(request: Request, slug: string) { + const db = cmsAs(cms, accessContext({ session: await resolveSession(request) })) + const post = await db.readDocumentBySlug('post', slug, { populate: true }) + const { items } = await db.queryDocuments({ collection: 'post', limit: 10 }) + const author = await db.readDocument('author', 'a1') + const editor = cmsAs(cms, accessContext({ session: null, mode: 'edit' })) + const draft = await editor.readDocument('post', 'p1') + return { post, items: items.map((i) => i.doc), author, draft } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/handle.output.ts b/scripts/codemods/__fixtures__/read-verbs/handle.output.ts new file mode 100644 index 00000000..2ab449f6 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/handle.output.ts @@ -0,0 +1,13 @@ +import { accessContext, cmsAs, resolveSession } from '@tanstack/cms-core/server' +import { cms } from './cms' + +export async function loader(request: Request, slug: string) { + const db = cmsAs(cms, accessContext({ session: await resolveSession(request) })) + const post = (await db.get({ collection: 'post', id: slug })) ?? (await db.get({ collection: 'post', locator: slug })) + const { items } = await db.list({ collection: 'post', limit: 10, populate: false }) + const author = (await db.get({ collection: 'author', id: 'a1', populate: false }))?.doc ?? null + const editor = cmsAs(cms, accessContext({ session: null, mode: 'edit' })) + // TODO(read-verbs): unless this context is live, get returns the working copy (staged changes overlaid), not the stored row + const draft = (await editor.get({ collection: 'post', id: 'p1', populate: false }))?.doc ?? null + return { post, items: items.map((i) => i.doc), author, draft } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/handle.warnings.json b/scripts/codemods/__fixtures__/read-verbs/handle.warnings.json new file mode 100644 index 00000000..bf0451f7 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/handle.warnings.json @@ -0,0 +1,3 @@ +[ + "handle.ts:10:23: TODO: unless this context is live, get returns the working copy (staged changes overlaid), not the stored row" +] diff --git a/scripts/codemods/__fixtures__/read-verbs/todos.input.ts b/scripts/codemods/__fixtures__/read-verbs/todos.input.ts new file mode 100644 index 00000000..9c2f6d6a --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/todos.input.ts @@ -0,0 +1,30 @@ +import { + commitDocument, + queryDocumentsAs, + readDocumentAs, + readDocumentBySlugAs, + systemContext, +} from '@tanstack/cms-core/server' +import type { CmsOpContext } from '@tanstack/cms-core' + +const SERVER = systemContext('orders: server-owned records') + +export async function addItem(cartId: string, ctx: CmsOpContext, n: number) { + const cart = await readDocumentAs(SERVER, 'cart', cartId) + await commitDocument('cart', cartId, { ...cart, items: [] }) + const res = await queryDocumentsAs(ctx.access, { + collection: 'order', + where: { cartId }, + }) + const recent = await queryDocumentsAs(ctx.access, { + collection: 'order', + limit: n, + }) + const titles = recent.items.map((i) => i.title) + const product = await readDocumentBySlugAs( + ctx.access, + 'product', + decodeURIComponent(cartId), + ) + return { items: res.items, titles, product } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/todos.output.ts b/scripts/codemods/__fixtures__/read-verbs/todos.output.ts new file mode 100644 index 00000000..4002a7c3 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/todos.output.ts @@ -0,0 +1,29 @@ +import { commitDocument, systemContext, getAs, listAs } from '@tanstack/cms-core/server' +import type { CmsOpContext } from '@tanstack/cms-core' + +const SERVER = systemContext('orders: server-owned records') + +export async function addItem(cartId: string, ctx: CmsOpContext, n: number) { + // TODO(read-verbs): unless this context is live, get returns the working copy (staged changes overlaid), not the stored row + const cart = (await getAs(SERVER, { collection: 'cart', id: cartId, populate: false }))?.doc ?? null + await commitDocument('cart', cartId, { ...cart, items: [] }) + // TODO(read-verbs): list returns at most 100 items unless `limit` is set (the old verb returned every match); page with nextCursor + // TODO(read-verbs): list items are { id, collection, doc, relations? }, without title or published + const res = await listAs(ctx.access, { + collection: 'order', + where: { cartId }, + populate: false, + }) + // TODO(read-verbs): list rejects a `limit` above 500; page with nextCursor + // TODO(read-verbs): list items are { id, collection, doc, relations? }, without title or published + const recent = await listAs(ctx.access, { + collection: 'order', + limit: n, + populate: false, + }) + const titles = recent.items.map((i) => i.title) + // TODO(read-verbs): unless this context is live, get returns the working copy (staged changes overlaid), not the stored row + // TODO(read-verbs): a locator is the slug (the id only of a document without one); if this can be the id of a slugged document, try get({ id }) first + const product = await getAs(ctx.access, { collection: 'product', locator: decodeURIComponent(cartId), populate: false }) + return { items: res.items, titles, product } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/todos.warnings.json b/scripts/codemods/__fixtures__/read-verbs/todos.warnings.json new file mode 100644 index 00000000..1196760a --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/todos.warnings.json @@ -0,0 +1,9 @@ +[ + "todos.ts:13:22: TODO: unless this context is live, get returns the working copy (staged changes overlaid), not the stored row", + "todos.ts:15:21: TODO: list returns at most 100 items unless `limit` is set (the old verb returned every match); page with nextCursor", + "todos.ts:15:21: TODO: list items are { id, collection, doc, relations? }, without title or published", + "todos.ts:19:24: TODO: list rejects a `limit` above 500; page with nextCursor", + "todos.ts:19:24: TODO: list items are { id, collection, doc, relations? }, without title or published", + "todos.ts:24:25: TODO: unless this context is live, get returns the working copy (staged changes overlaid), not the stored row", + "todos.ts:24:25: TODO: a locator is the slug (the id only of a document without one); if this can be the id of a slugged document, try get({ id }) first" +] diff --git a/scripts/codemods/__fixtures__/read-verbs/untouched.input.ts b/scripts/codemods/__fixtures__/read-verbs/untouched.input.ts new file mode 100644 index 00000000..2f3d3843 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/untouched.input.ts @@ -0,0 +1,31 @@ +import { + findDocumentBySlugAs, + publicContext, + queryDocumentsAs, + readDocumentAs, +} from '@tanstack/cms-core/server' + +export async function search(slug: string, options: { collection: string }) { + const many = await queryDocumentsAs(publicContext(), { + collections: ['post', 'page'], + limit: 10, + }) + const text = await queryDocumentsAs(publicContext(), { + collection: 'post', + query: 'hello', + limit: 10, + }) + const big = await queryDocumentsAs(publicContext(), { + collection: 'post', + limit: 1000, + }) + const byRef = await queryDocumentsAs(publicContext(), options) + const trashed = await readDocumentAs(publicContext(), 'post', 'p1', { + includeDeleted: true, + }) + const pending = readDocumentAs(publicContext(), 'post', 'p1') + const found = await findDocumentBySlugAs(publicContext(), slug, { + preferred: ['page'], + }) + return { many, text, big, byRef, trashed, pending, found } +} diff --git a/scripts/codemods/__fixtures__/read-verbs/untouched.warnings.json b/scripts/codemods/__fixtures__/read-verbs/untouched.warnings.json new file mode 100644 index 00000000..74d33278 --- /dev/null +++ b/scripts/codemods/__fixtures__/read-verbs/untouched.warnings.json @@ -0,0 +1,9 @@ +[ + "untouched.ts:9:22: queryDocumentsAs: `collections` with more than one name has no list equivalent: kept", + "untouched.ts:13:22: queryDocumentsAs: `query` has no list equivalent: kept", + "untouched.ts:18:21: queryDocumentsAs: limit 1000 is above list’s maximum of 500: kept", + "untouched.ts:22:23: queryDocumentsAs: options passed by reference: rewrite by hand", + "untouched.ts:23:25: readDocumentAs: read options (`includeDeleted`) have no get equivalent: kept", + "untouched.ts:26:19: readDocumentAs: read is not awaited: rewrite by hand", + "untouched.ts:27:23: findDocumentBySlugAs: its cross-collection `preferred` lookup has no get equivalent: kept" +] diff --git a/scripts/codemods/index.ts b/scripts/codemods/index.ts index b96a24ea..5a1a1d8f 100644 --- a/scripts/codemods/index.ts +++ b/scripts/codemods/index.ts @@ -3,6 +3,7 @@ import { collectionsArray } from './collections-array' import { createRoutes } from './create-routes' import { definitionSplit } from './definition-split' import { explicitRoles } from './explicit-roles' +import { readVerbsCodemod } from './read-verbs' import type { Codemod } from './lib/harness' /** Every codemod `pnpm codemod ` can run, keyed by name. */ @@ -12,4 +13,5 @@ export const CODEMODS: Record = { [createRoutes.name]: createRoutes, [definitionSplit.name]: definitionSplit, [explicitRoles.name]: explicitRoles, + [readVerbsCodemod.name]: readVerbsCodemod, } diff --git a/scripts/codemods/read-verbs.ts b/scripts/codemods/read-verbs.ts new file mode 100644 index 00000000..6fedd3f4 --- /dev/null +++ b/scripts/codemods/read-verbs.ts @@ -0,0 +1,860 @@ +/** + * The older read verbs → the canonical `get` / `list` (phase 3d): + * + * - `queryDocumentsAs(ctx, bag)` → `listAs(ctx, bag)`; + * - `await readDocumentAs(ctx, c, id)` → + * `(await getAs(ctx, { collection: c, id, populate: false }))?.doc ?? null`; + * - `await readDocumentBySlugAs(ctx, c, slug, { populate })` → + * `(await getAs(ctx, { collection: c, id: slug, populate })) ?? + * (await getAs(ctx, { collection: c, locator: slug, populate }))`, the old + * slug-or-id lookup with the id match first. A locator is the slug, and the + * id only of a document without one; + * - the deprecated forms without a context (`queryDocuments`, …) the same, + * as `publicContext()`; + * - the same three methods on a `cmsAs(cms, ctx)` handle → `.list` / `.get`. + * + * The rewrite keeps each read's result: `populate: false` is written out + * wherever the old call didn't populate, because the new verbs populate by + * default. Where the result or a default still differs, the statement gets + * a `// TODO(read-verbs): …` marker (and a warning): + * + * - a list without `limit` now stops at 100 items, and a non-literal + * `limit` must stay at or under 500; + * - list items are `{ id, collection, doc, relations? }`, without `title` and + * `published`, flagged where the items are used other than through those + * keys; + * - in an edit or preview context, `get` returns the working copy (staged + * changes overlaid), not the stored row. Contexts that are provably `live` + * (`publicContext()`, `{ mode: 'live' }`, `accessContext` without a mode) + * get no marker; + * - a slug read whose key, context or handle can't be evaluated twice (or + * that isn't awaited) becomes a single `locator` read, which no longer + * finds a slugged document by its id. + * + * Left alone, with a warning: options the new bags don't have (`collections` + * with more than one name, `query`, `textQuery`, `relevance`, + * `includeDeleted`), a `limit` literal above 500, options passed by + * reference, reads that aren't awaited, aliased and namespace imports, and + * `findDocumentBySlug(As)` (its cross-collection `preferred` lookup has no + * `get` equivalent). + */ +import { Node, SyntaxKind } from 'ts-morph' +import type { + CallExpression, + Expression, + Identifier, + ObjectLiteralExpression, + SourceFile, +} from 'ts-morph' +import { applyEdits } from './lib/harness' +import type { Codemod, CodemodContext, TextEdit } from './lib/harness' + +type Kind = 'list' | 'read' | 'slug' + +interface Verb { + kind: Kind + /** Takes the access context as its first argument. */ + ctx: boolean +} + +const VERBS: Record = { + queryDocumentsAs: { kind: 'list', ctx: true }, + queryDocuments: { kind: 'list', ctx: false }, + readDocumentAs: { kind: 'read', ctx: true }, + readDocument: { kind: 'read', ctx: false }, + readDocumentBySlugAs: { kind: 'slug', ctx: true }, + readDocumentBySlug: { kind: 'slug', ctx: false }, +} +const METHODS: Record = { + queryDocuments: 'list', + readDocument: 'read', + readDocumentBySlug: 'slug', +} +const NO_EQUIVALENT = new Set(['findDocumentBySlug', 'findDocumentBySlugAs']) +const LIST_KEYS = new Set([ + 'collection', + 'locale', + 'where', + 'sort', + 'limit', + 'offset', + 'cursor', + 'populate', +]) +const RESULT_KEYS = new Set(['id', 'doc', 'collection', 'relations']) +const ITERATORS = new Set(['map', 'forEach', 'some', 'every', 'flatMap']) +const MAX_LIMIT = 500 + +export const TODO = { + overlay: + 'unless this context is live, get returns the working copy (staged changes overlaid), not the stored row', + limit: + 'list returns at most 100 items unless `limit` is set (the old verb returned every match); page with nextCursor', + dynamicLimit: 'list rejects a `limit` above 500; page with nextCursor', + shape: + 'list items are { id, collection, doc, relations? }, without title or published', + locator: + 'a locator is the slug (the id only of a document without one); if this can be the id of a slugged document, try get({ id }) first', +} as const +type Todo = keyof typeof TODO + +const SERVER_SPECIFIER = + /^(@tanstack\/cms-core\/server|\.{1,2}(\/[\w.-]+)*\/server(\/store(\/(read|query|verbs))?)?)$/ + +interface Binding { + /** The import's `{ … }` (or the destructuring pattern) to rewrite. */ + list: Node + names: Array + /** Where the names are in scope: the file, or the destructuring's block. */ + scope: Node +} + +function isServerImportCall(node: Node | undefined): boolean { + if (!node) return false + const call = Node.isAwaitExpression(node) ? node.getExpression() : node + if (!Node.isCallExpression(call)) return false + if (call.getExpression().getKind() !== SyntaxKind.ImportKeyword) return false + const [spec] = call.getArguments() + return ( + spec !== undefined && + Node.isStringLiteral(spec) && + SERVER_SPECIFIER.test(spec.getLiteralValue()) + ) +} + +function findBindings(file: SourceFile, ctx: CodemodContext): Array { + const out: Array = [] + for (const decl of file.getImportDeclarations()) { + if (!SERVER_SPECIFIER.test(decl.getModuleSpecifierValue())) continue + if (decl.isTypeOnly()) continue + const ns = decl.getNamespaceImport() + if (ns) { + ctx.warn( + `namespace import: rewrite \`${ns.getText()}.(…)\` reads by hand`, + ns, + ) + } + const named = decl.getNamedImports() + if (!named.length) continue + for (const spec of named) { + if (VERBS[spec.getName()] && spec.getAliasNode()) { + ctx.warn(`aliased import of ${spec.getName()}: rewrite by hand`, spec) + } + } + out.push({ + list: named[0]!.getParentOrThrow(), + names: named.map((n) => n.getText()), + scope: file, + }) + } + for (const v of file.getDescendantsOfKind(SyntaxKind.VariableDeclaration)) { + const pattern = v.getNameNode() + if (!Node.isObjectBindingPattern(pattern)) continue + if (!isServerImportCall(v.getInitializer())) continue + out.push({ + list: pattern, + names: pattern.getElements().map((e) => e.getText()), + scope: + v.getFirstAncestor((a) => Node.isBlock(a) || Node.isSourceFile(a)) ?? + file, + }) + } + return out +} + +function contains(outer: Node, inner: Node): boolean { + return outer.getPos() <= inner.getPos() && inner.getEnd() <= outer.getEnd() +} + +function bindingAt( + bindings: ReadonlyArray, + name: string, + node: Node, +): Binding | undefined { + return bindings + .filter((b) => b.names.includes(name) && contains(b.scope, node)) + .sort( + (a, b) => + a.scope.getEnd() - + a.scope.getPos() - + (b.scope.getEnd() - b.scope.getPos()), + )[0] +} + +/** `x.name`, `{ name: … }`, a method or member named `name`. */ +function isPropertyName(id: Identifier): boolean { + const parent = id.getParent() + if (Node.isPropertyAccessExpression(parent)) + return parent.getNameNode() === id + return ( + (Node.isPropertyAssignment(parent) || + Node.isMethodDeclaration(parent) || + Node.isPropertySignature(parent) || + Node.isMethodSignature(parent) || + Node.isPropertyDeclaration(parent)) && + parent.getNameNode() === id + ) +} + +function propertyName(prop: Node): string | undefined { + if ( + Node.isPropertyAssignment(prop) || + Node.isShorthandPropertyAssignment(prop) + ) + return prop.getName() + return undefined +} + +function propertyValue(prop: Node): Expression | undefined { + if (Node.isPropertyAssignment(prop)) return prop.getInitializer() + if (Node.isShorthandPropertyAssignment(prop)) return prop.getNameNode() + return undefined +} + +function unwrap(node: Expression): Expression { + let n: Node = node + while (Node.isParenthesizedExpression(n) || Node.isAsExpression(n)) + n = n.getExpression() + return n as Expression +} + +/** Whether `expr` is a context that reads published documents only. */ +function isLiveContext(expr: Expression, file: SourceFile, depth = 0): boolean { + const e = unwrap(expr) + if (Node.isIdentifier(e)) { + if (depth > 3) return false + const decl = file + .getDescendantsOfKind(SyntaxKind.VariableDeclaration) + .find((d) => d.getName() === e.getText()) + const init = decl?.getInitializer() + return init ? isLiveContext(init, file, depth + 1) : false + } + if (!Node.isCallExpression(e)) return false + const callee = e.getExpression().getText() + const args = e.getArguments() + const modeOf = (arg: Node | undefined): string | undefined => { + if (!arg || !Node.isObjectLiteralExpression(arg)) return undefined + const mode = arg.getProperty('mode') + if (!mode) return undefined + return Node.isPropertyAssignment(mode) + ? mode.getInitializer()?.getText() + : 'unknown' + } + const isLive = (text: string | undefined) => + text === `'live'` || text === `"live"` + switch (callee) { + case 'publicContext': + return true + case 'accessContext': { + const arg = args[0] + if (!arg || !Node.isObjectLiteralExpression(arg)) return false + const mode = modeOf(arg) + return mode === undefined || isLive(mode) + } + case 'systemContext': + return isLive(modeOf(args[1])) + case 'withMode': + return isLive(args[1]?.getText()) + default: + return false + } +} + +/** The statement `node` belongs to, directly inside a block or the file. */ +function statementOf(node: Node): Node { + let n = node + for (;;) { + const parent = n.getParent() + if ( + !parent || + Node.isBlock(parent) || + Node.isSourceFile(parent) || + Node.isCaseClause(parent) || + Node.isDefaultClause(parent) || + Node.isModuleBlock(parent) + ) + return n + n = parent + } +} + +function indentAt(file: SourceFile, pos: number): string { + const text = file.getFullText() + const lineStart = text.lastIndexOf('\n', pos - 1) + 1 + return /^[ \t]*/.exec(text.slice(lineStart, pos))![0] +} + +/** Rewrite `node`'s text with edits given as absolute file positions. */ +function rewrite(node: Node, edits: ReadonlyArray): string { + const base = node.getStart() + let text = node.getText() + for (const edit of [...edits].sort((a, b) => b.start - a.start)) { + text = + text.slice(0, edit.start - base) + edit.text + text.slice(edit.end - base) + } + return text +} + +/** References to `name` inside `scope`, other than its declaration `decl`. */ +function referencesOf( + scope: Node, + name: string, + decl: Node, +): Array { + return scope + .getDescendantsOfKind(SyntaxKind.Identifier) + .filter( + (i) => + i.getText() === name && + i !== decl && + i.getStart() > decl.getStart() && + !isPropertyName(i), + ) +} + +function scopeOf(node: Node): Node { + return ( + node.getFirstAncestor( + (a) => + Node.isBlock(a) || + Node.isSourceFile(a) || + Node.isArrowFunction(a) || + Node.isFunctionDeclaration(a), + ) ?? node.getSourceFile() + ) +} + +function bindsOnlyResultKeys(pattern: Node): boolean { + return ( + Node.isObjectBindingPattern(pattern) && + pattern + .getElements() + .every( + (e) => + !e.getDotDotDotToken() && + RESULT_KEYS.has( + (e.getPropertyNameNode() ?? e.getNameNode()).getText(), + ), + ) + ) +} + +/** Every use of one list item `name` reads only `id` / `doc` / `collection` / `relations`. */ +function itemUsesAreSafe(scope: Node, name: Identifier): boolean { + return referencesOf(scope, name.getText(), name).every((ref) => { + const parent = ref.getParent() + return ( + Node.isPropertyAccessExpression(parent) && + parent.getExpression() === ref && + RESULT_KEYS.has(parent.getName()) + ) + }) +} + +/** `items` (an expression for the list's items) is used only item by item, through result keys. */ +function itemsUsesAreSafe(items: Node): boolean { + const parent = items.getParent() + if (!parent) return false + if ( + Node.isPropertyAccessExpression(parent) && + parent.getExpression() === items + ) { + if (parent.getName() === 'length') return true + const call = parent.getParent() + if ( + !ITERATORS.has(parent.getName()) || + !Node.isCallExpression(call) || + call.getExpression() !== parent + ) + return false + const fn = call.getArguments()[0] + if (!Node.isArrowFunction(fn) && !Node.isFunctionExpression(fn)) + return false + const param = fn.getParameters()[0]?.getNameNode() + if (!param) return true + if (Node.isIdentifier(param)) return itemUsesAreSafe(fn, param) + return bindsOnlyResultKeys(param) + } + if ( + Node.isElementAccessExpression(parent) && + parent.getExpression() === items + ) { + const access = parent.getParent() + return ( + Node.isPropertyAccessExpression(access) && + access.getExpression() === parent && + RESULT_KEYS.has(access.getName()) + ) + } + if (Node.isForOfStatement(parent) && parent.getExpression() === items) { + const init = parent.getInitializer() + if (!Node.isVariableDeclarationList(init)) return false + const name = init.getDeclarations()[0]?.getNameNode() + if (!name) return false + if (Node.isIdentifier(name)) return itemUsesAreSafe(parent, name) + return bindsOnlyResultKeys(name) + } + return false +} + +/** + * The top-level keys a list result (`node`, the awaited call) is read + * through, or `null` when it is used in a way the new shape may not match + * (passed or returned whole, or items read through other keys). + */ +function listKeysUsed(node: Node): Set | null { + let n: Node = node + while (Node.isParenthesizedExpression(n.getParent())) n = n.getParentOrThrow() + const parent = n.getParent() + const keys = new Set() + const read = (key: string, items: Node | undefined): boolean => { + keys.add(key) + if (key === 'items') return items !== undefined && itemsUsesAreSafe(items) + return key === 'total' || key === 'nextCursor' + } + if (Node.isPropertyAccessExpression(parent) && parent.getExpression() === n) { + return read(parent.getName(), parent) ? keys : null + } + if (!Node.isVariableDeclaration(parent)) return null + const name = parent.getNameNode() + const scope = scopeOf(parent) + if (Node.isIdentifier(name)) { + const ok = referencesOf(scope, name.getText(), name).every((ref) => { + const access = ref.getParent() + return ( + Node.isPropertyAccessExpression(access) && + access.getExpression() === ref && + read(access.getName(), access) + ) + }) + return ok ? keys : null + } + if (!Node.isObjectBindingPattern(name)) return null + const ok = name.getElements().every((e) => { + if (e.getDotDotDotToken()) return false + const key = (e.getPropertyNameNode() ?? e.getNameNode()).getText() + if (key !== 'items') return read(key, undefined) + keys.add(key) + const local = e.getNameNode() + if (!Node.isIdentifier(local)) return false + return referencesOf(scope, local.getText(), local).every(itemsUsesAreSafe) + }) + return ok ? keys : null +} + +/** Written twice without a second side effect: names, member reads, literals, `publicContext()`. */ +function isRepeatable(expr: Node): boolean { + if ( + Node.isIdentifier(expr) || + Node.isThisExpression(expr) || + Node.isStringLiteral(expr) || + Node.isNoSubstitutionTemplateLiteral(expr) || + Node.isNumericLiteral(expr) + ) + return true + if (Node.isPropertyAccessExpression(expr)) + return isRepeatable(expr.getExpression()) + if (Node.isElementAccessExpression(expr)) { + const arg = expr.getArgumentExpression() + return !!arg && isRepeatable(expr.getExpression()) && isRepeatable(arg) + } + if (Node.isCallExpression(expr)) + return ( + expr.getExpression().getText() === 'publicContext' && + !expr.getArguments().length + ) + return false +} + +/** A parenthesized `await x` for a position where `?? null` would misparse. */ +function needsParens(node: Node): boolean { + const parent = node.getParent() + return !( + Node.isVariableDeclaration(parent) || + Node.isReturnStatement(parent) || + Node.isParenthesizedExpression(parent) || + Node.isExpressionStatement(parent) || + Node.isPropertyAssignment(parent) || + Node.isArrayLiteralExpression(parent) || + Node.isArrowFunction(parent) || + (Node.isCallExpression(parent) && + parent.getArguments().includes(node as Expression)) + ) +} + +interface Rewrite { + edit: TextEdit + todos: Array +} + +/** The new list bag, as edits to `bag`, or a reason to leave the call alone. */ +function listBag( + bag: ObjectLiteralExpression, + todos: Array, +): Array | string { + const edits: Array = [] + let hasLimit = false + let hasPopulate = false + for (const prop of bag.getProperties()) { + const name = propertyName(prop) + if (!name) return 'options spread or computed: rewrite by hand' + if (name === 'collections') { + const value = propertyValue(prop) + if ( + !Node.isArrayLiteralExpression(value) || + value.getElements().length !== 1 || + Node.isSpreadElement(value.getElements()[0]) + ) + return '`collections` with more than one name has no list equivalent: kept' + edits.push({ + start: prop.getStart(), + end: prop.getEnd(), + text: `collection: ${value.getElements()[0]!.getText()}`, + }) + continue + } + if (!LIST_KEYS.has(name)) return `\`${name}\` has no list equivalent: kept` + if (name === 'populate') hasPopulate = true + if (name === 'limit') { + hasLimit = true + const value = propertyValue(prop) + if (Node.isNumericLiteral(value)) { + if (value.getLiteralValue() > MAX_LIMIT) + return `limit ${value.getText()} is above list’s maximum of ${MAX_LIMIT}: kept` + } else { + todos.push('dynamicLimit') + } + } + } + if (!hasLimit) todos.push('limit') + if (!hasPopulate) { + const props = bag.getProperties() + const last = props[props.length - 1] + if (!last) { + edits.push({ + start: bag.getStart(), + end: bag.getEnd(), + text: '{ populate: false }', + }) + } else { + const multiline = bag.getText().includes('\n') + const sep = multiline + ? `\n${indentAt(bag.getSourceFile(), last.getStart())}` + : ' ' + edits.push({ + start: last.getEnd(), + end: last.getEnd(), + text: `,${sep}populate: false`, + }) + } + } + return edits +} + +function getBag( + collection: string, + key: 'id' | 'locator', + value: string, + populate: string | undefined, +): string { + const parts = [ + collection === 'collection' ? 'collection' : `collection: ${collection}`, + value === key ? key : `${key}: ${value}`, + ] + if (populate !== undefined) parts.push(`populate: ${populate}`) + return `{ ${parts.join(', ')} }` +} + +/** `readDocumentBySlug`'s `{ populate }` as get's `populate` text (`undefined`: the default, on). */ +function slugPopulate( + options: Expression | undefined, +): string | null | undefined { + if (!options) return 'false' + if (!Node.isObjectLiteralExpression(options)) return null + let out: string | undefined = 'false' + for (const prop of options.getProperties()) { + if (propertyName(prop) !== 'populate') return null + const value = propertyValue(prop)!.getText() + out = + value === 'true' + ? undefined + : value === 'false' + ? 'false' + : `${value} ?? false` + } + return out +} + +function rewriteCall( + call: CallExpression, + kind: Kind, + form: + | { type: 'verb'; ctx: Expression | undefined; name: string } + | { type: 'method'; handle: Expression; ctx: Expression | undefined }, + ctx: CodemodContext, +): Rewrite | undefined { + const file = call.getSourceFile() + const label = form.type === 'verb' ? form.name : `.${calleeName(call)}` + const warn = (message: string) => ctx.warn(`${label}: ${message}`, call) + const allArgs = call.getArguments() as Array + const args = + form.type === 'verb' && VERBS[form.name]!.ctx ? allArgs.slice(1) : allArgs + const ctxText = form.ctx?.getText() ?? 'publicContext()' + const live = form.ctx ? isLiveContext(form.ctx, file) : true + const todos: Array = [] + const callee = + form.type === 'verb' + ? `${kind === 'list' ? 'listAs' : 'getAs'}(${ctxText}, ` + : `${form.handle.getText()}.${kind === 'list' ? 'list' : 'get'}(` + + if (kind === 'list') { + const [bag, ...extra] = args + if (extra.length) return void warn('unexpected arguments: rewrite by hand') + let bagText = '{ populate: false }' + if (bag) { + if (!Node.isObjectLiteralExpression(bag)) + return void warn('options passed by reference: rewrite by hand') + const edits = listBag(bag, todos) + if (typeof edits === 'string') return void warn(edits) + bagText = rewrite(bag, edits) + } else { + todos.push('limit') + } + let consumer: Node = call + if (Node.isAwaitExpression(call.getParent())) + consumer = call.getParentOrThrow() + const keys = listKeysUsed(consumer) + if (!keys) todos.push('shape') + else if (!keys.has('items') && !keys.has('nextCursor')) { + const at = todos.indexOf('limit') + if (at !== -1) todos.splice(at, 1) + } + return { + edit: { + start: call.getStart(), + end: call.getEnd(), + text: `${callee}${bagText})`, + }, + todos, + } + } + + if (!live) todos.push('overlay') + const [collection, key, options, ...extra] = args + if (!collection || !key || extra.length) + return void warn('unexpected arguments: rewrite by hand') + + if (kind === 'slug') { + const populate = slugPopulate(options) + if (populate === null) + return void warn( + 'options other than a literal `populate`: rewrite by hand', + ) + const bag = (by: 'id' | 'locator') => + `${callee}${getBag(collection.getText(), by, key.getText(), populate)})` + const awaited = call.getParent() + const repeatable = + isRepeatable(key) && + (form.type === 'verb' + ? !form.ctx || isRepeatable(form.ctx) + : isRepeatable(form.handle)) + if (Node.isAwaitExpression(awaited) && repeatable) { + const text = `(await ${bag('id')}) ?? (await ${bag('locator')})` + return { + edit: { + start: awaited.getStart(), + end: awaited.getEnd(), + text: needsParens(awaited) ? `(${text})` : text, + }, + todos, + } + } + todos.push('locator') + return { + edit: { + start: call.getStart(), + end: call.getEnd(), + text: bag('locator'), + }, + todos, + } + } + + if (options) + return void warn( + 'read options (`includeDeleted`) have no get equivalent: kept', + ) + const awaited = call.getParent() + if (!Node.isAwaitExpression(awaited)) + return void warn('read is not awaited: rewrite by hand') + const text = `(await ${callee}${getBag(collection.getText(), 'id', key.getText(), 'false')}))?.doc ?? null` + return { + edit: { + start: awaited.getStart(), + end: awaited.getEnd(), + text: needsParens(awaited) ? `(${text})` : text, + }, + todos, + } +} + +function calleeName(call: CallExpression): string { + const callee = call.getExpression() + return Node.isPropertyAccessExpression(callee) + ? callee.getName() + : callee.getText() +} + +/** The `cmsAs(…)` call `receiver` is, or was assigned from in this file. */ +function cmsAsCall( + receiver: Node, + cmsAsNames: Set, +): CallExpression | undefined { + const e = unwrap(receiver as Expression) + const isCmsAs = (n: Node | undefined): n is CallExpression => + Node.isCallExpression(n) && cmsAsNames.has(n.getExpression().getText()) + if (isCmsAs(e)) return e + if (!Node.isIdentifier(e)) return undefined + const decl = e + .getSourceFile() + .getDescendantsOfKind(SyntaxKind.VariableDeclaration) + .find((d) => d.getName() === e.getText()) + const init = decl?.getInitializer() + return init && isCmsAs(unwrap(init)) + ? (unwrap(init) as CallExpression) + : undefined +} + +function transform(file: SourceFile, ctx: CodemodContext): void { + const bindings = findBindings(file, ctx) + const imported = new Set(bindings.flatMap((b) => b.names)) + const cmsAsNames = new Set(imported.has('cmsAs') ? ['cmsAs'] : []) + const edits: Array = [] + const todosAt = new Map>() + const rewritten = new Map>() + const needed = new Map>() + const callees = new Set() + + for (const call of file.getDescendantsOfKind(SyntaxKind.CallExpression)) { + const callee = call.getExpression() + let result: Rewrite | undefined + if (Node.isIdentifier(callee)) { + const name = callee.getText() + if (NO_EQUIVALENT.has(name) && bindingAt(bindings, name, call)) { + ctx.warn( + `${name}: its cross-collection \`preferred\` lookup has no get equivalent: kept`, + call, + ) + continue + } + const verb = VERBS[name] + if (!verb) continue + const binding = bindingAt(bindings, name, call) + if (!binding) continue + const ctxArg = verb.ctx + ? (call.getArguments()[0] as Expression) + : undefined + if (verb.ctx && !ctxArg) continue + result = rewriteCall( + call, + verb.kind, + { type: 'verb', ctx: ctxArg, name }, + ctx, + ) + if (!result) continue + callees.add(callee) + const done = rewritten.get(binding) ?? new Set() + done.add(name) + rewritten.set(binding, done) + const add = needed.get(binding) ?? new Set() + add.add(verb.kind === 'list' ? 'listAs' : 'getAs') + if (!verb.ctx) add.add('publicContext') + needed.set(binding, add) + } else if (Node.isPropertyAccessExpression(callee)) { + const kind = METHODS[callee.getName()] + if (!kind || !cmsAsNames.size) continue + const handle = cmsAsCall(callee.getExpression(), cmsAsNames) + if (!handle) continue + result = rewriteCall( + call, + kind, + { + type: 'method', + handle: callee.getExpression(), + ctx: handle.getArguments()[1] as Expression | undefined, + }, + ctx, + ) + if (!result) continue + } else { + continue + } + edits.push(result.edit) + if (result.todos.length) { + const stmt = statementOf(call) + const set = todosAt.get(stmt) ?? new Set() + for (const t of result.todos) { + set.add(t) + ctx.warn(`TODO: ${TODO[t]}`, call) + } + todosAt.set(stmt, set) + } + } + if (!edits.length) return + + const nested = edits.filter((e) => + edits.some((o) => o !== e && o.start <= e.start && e.end <= o.end), + ) + if (nested.length) { + ctx.warn('nested read verbs: rewrite by hand') + return + } + + for (const [stmt, todos] of todosAt) { + const pos = stmt.getStart() + const indent = indentAt(file, pos) + const text = [...todos] + .map((t) => `// TODO(read-verbs): ${TODO[t]}\n${indent}`) + .join('') + const same = edits.find((e) => e.start === pos) + if (same) same.text = text + same.text + else edits.push({ start: pos, end: pos, text }) + } + + const stillUsed = new Set() + for (const id of file.getDescendantsOfKind(SyntaxKind.Identifier)) { + if (callees.has(id) || isPropertyName(id)) continue + if ( + id.getFirstAncestorByKind(SyntaxKind.ImportDeclaration) || + id.getFirstAncestorByKind(SyntaxKind.ObjectBindingPattern) + ) + continue + stillUsed.add(id.getText()) + } + for (const b of bindings) { + const done = rewritten.get(b) + if (!done) continue + const names = b.names.filter((n) => !done.has(n) || stillUsed.has(n)) + for (const n of needed.get(b) ?? []) { + const elsewhere = bindings.some((o) => o !== b && o.names.includes(n)) + if (!names.includes(n) && !elsewhere) names.push(n) + } + edits.push({ + start: b.list.getStart(), + end: b.list.getEnd(), + text: `{ ${names.join(', ')} }`, + }) + } + applyEdits(file, edits) +} + +export const readVerbsCodemod: Codemod = { + name: 'read-verbs', + description: + 'Older read verbs (`queryDocuments(As)`, `readDocument(As)`, `readDocumentBySlug(As)`, and the same `cmsAs` methods) → `list` / `get`, with TODO markers where the result or a default differs.', + mightApply: (text) => + [...Object.keys(VERBS), ...NO_EQUIVALENT].some((verb) => + text.includes(`${verb}(`), + ), + transform, +} diff --git a/scripts/dialect-inventory.baseline.json b/scripts/dialect-inventory.baseline.json index 0acb563b..e0ad31ce 100644 --- a/scripts/dialect-inventory.baseline.json +++ b/scripts/dialect-inventory.baseline.json @@ -6,36 +6,36 @@ "test": 9 }, "publicRead": { - "nonTest": 26, + "nonTest": 27, "test": 7 }, "queryDocuments": { - "nonTest": 98, - "test": 20 + "nonTest": 78, + "test": 24 }, "readDocument": { - "nonTest": 24, - "test": 9 + "nonTest": 18, + "test": 12 }, "readDocumentBySlug": { - "nonTest": 13, - "test": 7 + "nonTest": 10, + "test": 13 }, "findDocumentBySlug": { "nonTest": 9, - "test": 1 + "test": 3 }, "getPublicDocument": { - "nonTest": 31, + "nonTest": 23, "test": 13 }, "listPublishedDocuments": { - "nonTest": 46, - "test": 20 + "nonTest": 36, + "test": 22 }, "collectionsRecord": { "nonTest": 0, - "test": 3 + "test": 5 }, "uiReactToolsImport": { "nonTest": 0, @@ -46,12 +46,12 @@ "test": 0 }, "staged": { - "nonTest": 31, - "test": 46 + "nonTest": 42, + "test": 55 }, "pendingId": { - "nonTest": 69, - "test": 76 + "nonTest": 71, + "test": 81 }, "hookBeforeValidate": { "nonTest": 3, diff --git a/starters/documentation-kb/CMS-INTEGRATION.md b/starters/documentation-kb/CMS-INTEGRATION.md index ead4a8dc..1ecbeb1f 100644 --- a/starters/documentation-kb/CMS-INTEGRATION.md +++ b/starters/documentation-kb/CMS-INTEGRATION.md @@ -6,7 +6,7 @@ Catalog row #7 (class) · [README](./README.md) · [`starters/catalog.json`](../ Two product versions of one small docs set. Version, section, and order are fields on a single `docPage` collection. Two public ops build the sidebar tree and run search across versions or within one, and the theme is set to the `docs` variant. -**CMS features it relies on:** select fields as version and section facets, a collection `path` function, `theme.variant: 'docs'`, `queryDocumentsAs` with `where`, `queryDocumentSummariesAs` FTS search, and public `defineOp` ops. +**CMS features it relies on:** select fields as version and section facets, a collection `path` function, `theme.variant: 'docs'`, `listAs` with `where`, `queryDocumentSummariesAs` FTS search, and public `defineOp` ops. ## Files @@ -23,7 +23,7 @@ Two product versions of one small docs set. Version, section, and order are fiel ### Read paths and search -- `getDocsNavTree` runs `queryDocumentsAs(publicContext(), { where: { version }, limit: 200 })`, then groups by `section` and sorts by `order`. `searchVersionedDocs` searches as `publicContext()` too, so drafts never show up in public results. +- `getDocsNavTree` runs `listAs(publicContext(), { where: { version }, limit: 200 })`, then groups by `section` and sorts by `order`. `searchVersionedDocs` searches as `publicContext()` too, so drafts never show up in public results. - `searchVersionedDocs` runs `queryDocumentSummariesAs(ctx, { search, columns })`, which is the built-in SQLite FTS5 trigram index, and filters `version` in memory afterwards. ### Auth, roles, and access @@ -57,7 +57,7 @@ Two product versions of one small docs set. Version, section, and order are fiel ## Docs - [`docs/schema/theming-and-variants.md`](../../docs/schema/theming-and-variants.md): layout variants and how the docs sidebar is built. -- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `queryDocumentsAs`, `queryDocumentSummariesAs`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `listAs`, `queryDocumentSummariesAs`. - [`docs/architecture/storage.md`](../../docs/architecture/storage.md): search and indexes, read-only Markdown storage. - [`docs/mcp/operations-registry.md`](../../docs/mcp/operations-registry.md): adding your own operations. - [`docs/migration/from-astro-starlight.md`](../../docs/migration/from-astro-starlight.md): a fuller docs-variant build. diff --git a/starters/documentation-kb/src/cms.config.ts b/starters/documentation-kb/src/cms.config.ts index bedd724b..b5c1ad44 100644 --- a/starters/documentation-kb/src/cms.config.ts +++ b/starters/documentation-kb/src/cms.config.ts @@ -1,8 +1,8 @@ import { z } from 'zod' import { defineCms, defineOp } from '@tanstack/cms-core' import { + listAs, publicContext, - queryDocumentsAs, queryDocumentSummariesAs, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' @@ -28,7 +28,7 @@ export function registerDocumentationKbCms(options: { dataDir?: string } = {}) { 'Build the hierarchical sidebar navigation tree for a specific product release version.', input: z.object({ version: z.enum(['v1', 'v2']) }), run: async (input) => { - const res = await queryDocumentsAs(publicContext(), { + const res = await listAs(publicContext(), { collection: 'docPage', where: { version: input.version }, limit: 200, diff --git a/starters/ecommerce-storefront/CMS-INTEGRATION.md b/starters/ecommerce-storefront/CMS-INTEGRATION.md index 24ba2b7d..dfb681e3 100644 --- a/starters/ecommerce-storefront/CMS-INTEGRATION.md +++ b/starters/ecommerce-storefront/CMS-INTEGRATION.md @@ -6,7 +6,7 @@ Catalog row #8 (class) · [README](./README.md) · [`starters/catalog.json`](../ Native commerce built on CMS collections: products, variants with prices and inventory, persisted carts, and orders. Two public ops, `addToCart` and `checkoutCart`, run the storefront flow. A pluggable `PaymentAdapter` handles charging. Customers are never CMS staff (S4). -**CMS features it relies on:** collections with a relation, public `defineOp` ops that call `readDocument` and `commitDocument` as trusted server code, `CmsError`, and staff-only `auth.getUser`. +**CMS features it relies on:** collections with a relation, public `defineOp` ops that call `getAs`, `readDocumentAs` and `commitDocument` as trusted server code, `CmsError`, and staff-only `auth.getUser`. ## Files @@ -43,7 +43,7 @@ Native commerce built on CMS collections: products, variants with prices and inv ## Not used, or left to the app - **Customer identity.** Both ops take `customerEmail`/`cartId` as input and check no session or cart ownership. Customer auth is left to the app. -- **Order and cart privacy.** These collections have no `collection.access` rules and are published, so the public `listPublishedDocuments` op returns orders and customer emails to anonymous callers. +- **Order and cart privacy.** These collections have no `collection.access` rules and are published, so the public `list` op (like the older `listPublishedDocuments`) returns orders and customer emails to anonymous callers. - **Inventory.** Inventory is checked in `addToCart` but checkout never decrements it. - No media (product images), search, storefront rendering, typed client, MCP, hooks or events (for example `order.created`), AI, or import/export. @@ -58,5 +58,5 @@ Native commerce built on CMS collections: products, variants with prices and inv - [`docs/architecture/actors.md`](../../docs/architecture/actors.md): customer and staff separation. - [`docs/architecture/authentication.md`](../../docs/architecture/authentication.md): collection access rules, enforcing access in your own server code. - [`docs/mcp/operations-registry.md`](../../docs/mcp/operations-registry.md): adding your own operations. -- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `readDocument`, `commitDocument`, `populateRelations`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `getAs`, `readDocumentAs`, `commitDocument`, `populateRelations`. - [`docs/architecture/events-and-hooks.md`](../../docs/architecture/events-and-hooks.md): for order side effects. diff --git a/starters/ecommerce-storefront/src/cms.config.ts b/starters/ecommerce-storefront/src/cms.config.ts index 365579a3..0f82dbda 100644 --- a/starters/ecommerce-storefront/src/cms.config.ts +++ b/starters/ecommerce-storefront/src/cms.config.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, + getAs, publicContext, readDocumentAs, systemContext, @@ -65,11 +66,13 @@ export function registerEcommerceStorefrontCms( quantity: z.number().int().positive(), }), run: async (input) => { - const variant = await readDocumentAs( - publicContext(), - 'variant', - input.variantId, - ) + const variant = ( + await getAs(publicContext(), { + collection: 'variant', + id: input.variantId, + populate: false, + }) + )?.doc if (!variant || !variant.published) { throw new CmsError('Variant not found.', 'NOT_FOUND') } diff --git a/starters/editorial-publication/CMS-INTEGRATION.md b/starters/editorial-publication/CMS-INTEGRATION.md index 938cb430..1a817bb1 100644 --- a/starters/editorial-publication/CMS-INTEGRATION.md +++ b/starters/editorial-publication/CMS-INTEGRATION.md @@ -6,7 +6,7 @@ Catalog row #6 (class) · [README](./README.md) · [`starters/catalog.json`](../ A multi-author publication with paid tiers. Author submissions are staged for review. Readers are separate from staff: they never get a CMS session (S4). Two custom ops handle the reader-facing paywall and sending the newsletter. -**CMS features it relies on:** staged agent-tool writes with `approve`, staff roles (`author`, `editor`, `admin`), `defineOp` with `public` and `content.publish` access, and `queryDocumentsAs` with `where`. +**CMS features it relies on:** staged agent-tool writes with `approve`, staff roles (`author`, `editor`, `admin`), `defineOp` with `public` and `content.publish` access, and `getAs`/`listAs` with `where`. ## Files @@ -23,8 +23,8 @@ A multi-author publication with paid tiers. Author submissions are staged for re ### Read paths and search -- `readPublicationIssue` loads the issue as `publicContext()`. For paid issues it looks up the reader with `queryDocumentsAs(systemContext('…'), { collection: 'memberSubscription', where: { email }, limit: 1 })`, and returns `body: null, paywalled: true` unless that reader's tier is `paid`. -- `sendNewsletterIssue` reads the issue as the publisher (`ctx.access`) and loads active subscribers with `queryDocumentsAs(systemContext('…', { mode: 'live' }), { limit: 200 })`. +- `readPublicationIssue` loads the issue with `getAs(publicContext(), …)`. For paid issues it looks up the reader with `listAs(systemContext('…'), { collection: 'memberSubscription', where: { email }, limit: 1 })`, and returns `body: null, paywalled: true` unless that reader's tier is `paid`. +- `sendNewsletterIssue` reads the stored issue as the publisher (`readDocumentAs(ctx.access, …)`, because it writes the issue back) and loads active subscribers with `listAs(systemContext('…', { mode: 'live' }), { limit: 200 })`. ### Writes, review, and revisions @@ -43,7 +43,7 @@ A multi-author publication with paid tiers. Author submissions are staged for re ## Not used, or left to the app - **Member identity.** `readPublicationIssue` trusts the `memberEmail` it's given, and no member session exists. Real member auth, through your own provider or a separate `createDbAuth` table, is left to the app. -- **Paywall is per-op only.** `body` has no `field.access` rule, so the public `listPublishedDocuments` op returns paid bodies to anonymous callers. Subscriber emails are exposed the same way, because subscriptions are committed with `published: true`. Add `field.access`/`collection.access`, or keep these documents unpublished. +- **Paywall is per-op only.** `body` has no `field.access` rule, so the public `get` and `list` ops (and the older `listPublishedDocuments`) return paid bodies to anonymous callers. Subscriber emails are exposed the same way, because subscriptions are committed with `published: true`. Add `field.access`/`collection.access`, or keep these documents unpublished. - **Scheduling.** `scheduledAt` is a plain text field. The CMS scheduler (`publishAt`) isn't used. - **No email or payment.** The "email delivery provider" and "payment adapter" in `requires` are an in-memory array and a hand-set `tier`. - No media, search, AI, hooks, import/export, admin UI wiring, or public rendering. @@ -60,4 +60,4 @@ A multi-author publication with paid tiers. Author submissions are staged for re - [`docs/agents/review-queue.md`](../../docs/agents/review-queue.md): staging, approval, scheduling. - [`docs/architecture/authentication.md`](../../docs/architecture/authentication.md): roles, field access rules, optional database auth. - [`docs/mcp/operations-registry.md`](../../docs/mcp/operations-registry.md): adding your own operations. -- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `queryDocumentsAs`, `commitDocument`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `getAs`, `listAs`, `readDocumentAs`, `commitDocument`. diff --git a/starters/editorial-publication/src/cms.config.ts b/starters/editorial-publication/src/cms.config.ts index e514f725..5acfa9f1 100644 --- a/starters/editorial-publication/src/cms.config.ts +++ b/starters/editorial-publication/src/cms.config.ts @@ -2,8 +2,9 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, + getAs, + listAs, publicContext, - queryDocumentsAs, readDocumentAs, systemContext, } from '@tanstack/cms-core/server' @@ -58,11 +59,12 @@ export function registerEditorialPublicationCms( memberEmail: z.string().email().optional(), }), run: async (input) => { - const doc = await readDocumentAs( - publicContext(), - 'issue', - input.issueId, - ) + const doc = ( + await getAs(publicContext(), { + collection: 'issue', + id: input.issueId, + }) + )?.doc if (!doc || !doc.published) { throw new CmsError('Issue not found.', 'NOT_FOUND') } @@ -75,7 +77,7 @@ export function registerEditorialPublicationCms( body: null, } } - const subs = await queryDocumentsAs( + const subs = await listAs( systemContext('paywall: subscriptions are server-owned records'), { collection: 'memberSubscription', @@ -116,7 +118,7 @@ export function registerEditorialPublicationCms( 'BAD_REQUEST', ) } - const subs = await queryDocumentsAs( + const subs = await listAs( systemContext('newsletter: active subscriptions', { mode: 'live' }), { collection: 'memberSubscription', diff --git a/starters/membership-course/CMS-INTEGRATION.md b/starters/membership-course/CMS-INTEGRATION.md index 1327ceff..47beb263 100644 --- a/starters/membership-course/CMS-INTEGRATION.md +++ b/starters/membership-course/CMS-INTEGRATION.md @@ -6,7 +6,7 @@ Catalog row #14 (class) · [README](./README.md) · [`starters/catalog.json`](.. One course with ordered lessons and a per-member progress state machine. A single public op, `completeLessonAndQuiz`, enforces drip unlock, prerequisites, and the quiz answer, then issues a certificate once every lesson is done. Members are never CMS staff (S4). -**CMS features it relies on:** collections as course and progress storage, a public `defineOp` that calls `readDocumentAs`, `queryDocumentsAs`, and `commitDocument`, `CmsError` codes, and staff-only `auth.getUser`. +**CMS features it relies on:** collections as course and progress storage, a public `defineOp` that calls `getAs`, `listAs`, `readDocumentAs`, and `commitDocument`, `CmsError` codes, and staff-only `auth.getUser`. ## Files @@ -23,7 +23,7 @@ One course with ordered lessons and a per-member progress state machine. A singl ### Read paths and search -- The op reads the enrolment as a named `systemContext` (enrolments are server-owned records) and the lesson as `publicContext()`, then lists all published lessons with `queryDocumentsAs(publicContext(), …)` to check prerequisites and completion. +- The op reads the stored enrolment with `readDocumentAs` as a named `systemContext` (enrolments are server-owned records it writes back) and the lesson with `getAs(publicContext(), …)`, then lists all published lessons with `listAs(publicContext(), …)` to check prerequisites and completion. ### Writes, review, and revisions @@ -40,7 +40,7 @@ One course with ordered lessons and a per-member progress state machine. A singl ## Not used, or left to the app - **Member identity.** The op checks no session, so any caller who knows an `enrolmentId` can complete lessons and earn its certificate. Member auth is left to the app. -- **Answer and roster privacy.** `quizAnswer` has no `field.access` rule, and enrolments are published. The public `listPublishedDocuments` op therefore returns quiz answers and member emails to anonymous callers. +- **Answer and roster privacy.** `quizAnswer` has no `field.access` rule, and enrolments are published. The public `list` op (like the older `listPublishedDocuments`) therefore returns quiz answers and member emails to anonymous callers. - **Time.** `daysSinceEnrolment` is a stored number, not computed from an enrolment date. - No lesson rendering, media (video), events (for example a certificate email), search, AI, or import/export. @@ -54,5 +54,5 @@ One course with ordered lessons and a per-member progress state machine. A singl - [`docs/architecture/actors.md`](../../docs/architecture/actors.md): members vs. staff. - [`docs/architecture/authentication.md`](../../docs/architecture/authentication.md): field access rules, enforcing access in your own server code, optional database auth. - [`docs/mcp/operations-registry.md`](../../docs/mcp/operations-registry.md): adding your own operations. -- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `readDocumentAs`, `queryDocumentsAs`, `commitDocument`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `getAs`, `listAs`, `readDocumentAs`, `commitDocument`. - [`docs/architecture/events-and-hooks.md`](../../docs/architecture/events-and-hooks.md). diff --git a/starters/membership-course/src/cms.config.ts b/starters/membership-course/src/cms.config.ts index a8561542..ee7f6a5b 100644 --- a/starters/membership-course/src/cms.config.ts +++ b/starters/membership-course/src/cms.config.ts @@ -2,8 +2,9 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, + getAs, + listAs, publicContext, - queryDocumentsAs, readDocumentAs, systemContext, } from '@tanstack/cms-core/server' @@ -53,11 +54,12 @@ export function registerMembershipCourseCms( if (!enrolment) { throw new CmsError('Enrolment not found.', 'NOT_FOUND') } - const lesson = await readDocumentAs( - publicContext(), - 'lesson', - input.lessonId, - ) + const lesson = ( + await getAs(publicContext(), { + collection: 'lesson', + id: input.lessonId, + }) + )?.doc if (!lesson || !lesson.published) { throw new CmsError('Lesson not found.', 'NOT_FOUND') } @@ -71,7 +73,7 @@ export function registerMembershipCourseCms( ) } - const allLessons = await queryDocumentsAs(publicContext(), { + const allLessons = await listAs(publicContext(), { collection: 'lesson', limit: 100, }) diff --git a/starters/multi-tenant-fleet/CMS-INTEGRATION.md b/starters/multi-tenant-fleet/CMS-INTEGRATION.md index cc90c63d..f518ce40 100644 --- a/starters/multi-tenant-fleet/CMS-INTEGRATION.md +++ b/starters/multi-tenant-fleet/CMS-INTEGRATION.md @@ -6,7 +6,7 @@ Catalog row #9 (class) · [README](./README.md) · [`starters/catalog.json`](../ Many tenant sites run on one instance. Every document carries a `tenantId` field. Custom ops derive the tenant from the authenticated actor, never from client input. That is how pages, search, and assets stay isolated (S8). A super-admin can provision a tenant from a template, and each cross-tenant access is logged. -**CMS features it relies on:** a `tenantId` field on every collection, `defineOp` with `content.read` and `settings.manage` access, `queryDocuments` with `where`, `queryDocumentSummaries` search, and `auth.getUser` mapping tenant actors to built-in roles. +**CMS features it relies on:** a `tenantId` field on every collection, `defineOp` with `content.read` and `settings.manage` access, `listAs` with `where`, `queryDocumentSummaries` search, and `auth.getUser` mapping tenant actors to built-in roles. ## Files @@ -24,7 +24,7 @@ Many tenant sites run on one instance. Every document carries a `tenantId` field ### Read paths and search -- `listTenantPages` and `listTenantAssets` use `queryDocumentsAs(ctx, { where: { tenantId } })`. +- `listTenantPages` and `listTenantAssets` use `listAs(ctx, { where: { tenantId }, populate: false })` and return its items (`{ id, collection, doc }`). - The search path runs `queryDocumentSummariesAs(ctx, { search })`, then drops other tenants' rows in memory. - `readTenantPage` uses `readDocumentAs` and returns `NOT_FOUND` when the `tenantId` doesn't match, even if the id was guessed correctly. @@ -40,7 +40,7 @@ Many tenant sites run on one instance. Every document carries a `tenantId` field ## Not used, or left to the app -- **Isolation covers only the custom ops.** The built-in ops and MCP tools have no tenant filter. A tenant-admin's `read_document` returns another tenant's page, and the public `listPublishedDocuments` returns every tenant's published pages. Add a `collection.access.read` predicate on `tenantId`, or don't expose the built-in ops, before relying on S8. +- **Isolation covers only the custom ops.** The built-in ops and MCP tools have no tenant filter. A tenant-admin's `read_document` returns another tenant's page, and the public `list` op (like the older `listPublishedDocuments`) returns every tenant's published pages. Add a `collection.access.read` predicate on `tenantId`, or don't expose the built-in ops, before relying on S8. - **Media isn't the media library.** `tenantAsset` is a plain collection with a URL field. Uploads and the media adapters aren't used. - `crossTenantAuditLog` is an in-memory array, not the CMS audit log (`listAudit`). - No per-tenant rendering, domain routing, theme application, MCP, admin UI, hooks, AI, or import/export. @@ -55,6 +55,6 @@ Many tenant sites run on one instance. Every document carries a `tenantId` field - [`docs/architecture/authentication.md`](../../docs/architecture/authentication.md): collection access rules (predicates), enforcing access in your own server code. - [`docs/architecture/actors.md`](../../docs/architecture/actors.md). -- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `queryDocuments`, `queryDocumentSummaries`, `listAudit`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `listAs`, `readDocumentAs`, `queryDocumentSummaries`, `listAudit`. - [`docs/mcp/operations-registry.md`](../../docs/mcp/operations-registry.md): built-in agent tools vs. app ops. - [`docs/architecture/storage.md`](../../docs/architecture/storage.md): media adapters. diff --git a/starters/multi-tenant-fleet/src/cms.config.ts b/starters/multi-tenant-fleet/src/cms.config.ts index adb8b651..232c8112 100644 --- a/starters/multi-tenant-fleet/src/cms.config.ts +++ b/starters/multi-tenant-fleet/src/cms.config.ts @@ -2,7 +2,7 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, - queryDocumentsAs, + listAs, queryDocumentSummariesAs, readDocumentAs, } from '@tanstack/cms-core/server' @@ -158,10 +158,11 @@ export function registerMultiTenantFleetCms( ), } } - const res = await queryDocumentsAs(ctx.access, { + const res = await listAs(ctx.access, { collection: 'tenantPage', where: { tenantId }, limit: 100, + populate: false, }) return { items: res.items } }, @@ -200,10 +201,11 @@ export function registerMultiTenantFleetCms( run: async (input, ctx) => { const actor = resolveTenantActor(ctx.request) const tenantId = effectiveTenantId(actor, input.targetTenantId) - const res = await queryDocumentsAs(ctx.access, { + const res = await listAs(ctx.access, { collection: 'tenantAsset', where: { tenantId }, limit: 100, + populate: false, }) return { items: res.items } }, diff --git a/starters/runtime-tables/CMS-INTEGRATION.md b/starters/runtime-tables/CMS-INTEGRATION.md index 9cae0b1a..65350456 100644 --- a/starters/runtime-tables/CMS-INTEGRATION.md +++ b/starters/runtime-tables/CMS-INTEGRATION.md @@ -23,7 +23,7 @@ Tables defined at runtime. A proposed table is stored as a `schemaDefinition` do ### Read paths and search -- `syncRuntimeTablesFromStore()` reads approved definitions with `queryDocumentsAs(systemContext('…', { mode: 'live' }), …)`. +- `syncRuntimeTablesFromStore()` reads approved definitions with `listAs(systemContext('…', { mode: 'live' }), …)`. - Rows in a runtime table are searchable right away through `queryDocumentSummariesAs(ctx, { search })`. ### Writes, review, and revisions diff --git a/starters/runtime-tables/src/cms.config.ts b/starters/runtime-tables/src/cms.config.ts index db02dae1..3b52ef1f 100644 --- a/starters/runtime-tables/src/cms.config.ts +++ b/starters/runtime-tables/src/cms.config.ts @@ -3,7 +3,7 @@ import { approve, stageWrite, systemContext, - queryDocumentsAs, + listAs, } from '@tanstack/cms-core/server' import type { CmsConfig, Collection, Field } from '@tanstack/cms-core' @@ -128,7 +128,7 @@ const APPROVED_DEFINITIONS = systemContext( ) export async function syncRuntimeTablesFromStore() { - const { items } = await queryDocumentsAs(APPROVED_DEFINITIONS, { + const { items } = await listAs(APPROVED_DEFINITIONS, { collection: 'schemaDefinition', limit: 100, })