diff --git a/.changeset/access-fail-closed.md b/.changeset/access-fail-closed.md new file mode 100644 index 00000000..74babf7e --- /dev/null +++ b/.changeset/access-fail-closed.md @@ -0,0 +1,33 @@ +--- +'@tanstack/cms-core': minor +'@tanstack/cms-api': minor +'@tanstack/cms-cli': minor +'@tanstack/search-cms': minor +--- + +**Breaking:** reads fail closed. A read without an access context is a public read, and nothing reads with an ambient session. + +- The plain read functions in `@tanstack/cms-core/server` are deprecated and read as `publicContext()`: published documents only, redacted for an anonymous visitor. They used to read everything, drafts included. The affected functions are `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`. They are removed in a later alpha. Read with `cmsAs(cms, ctx)` or the `…As(ctx, …)` form instead. +- Their `session`, `publishedOnly` and `publicRead` options are removed, along with the `ContextQueryOptions` type. `createCmsSearch` no longer takes `session`, `publishedOnly` or `publicRead`; pass `access`. +- `runWithSession` and `currentSession` are removed. Pass the session, or an access context, to the call that needs it: + - `runOp(name, input, actor, access)` and `cmsMcp.fetch(request, access)` require a context, and throw `UNAUTHORIZED` without one. + - A `cmsTools` call with neither a per-call context (`CMS_ACCESS_KEY`) nor `options.access` fails with `UNAUTHORIZED`. + - `afterChange` and `afterDelete` hooks receive the writer's `session` (new `DeleteHookArgs` type). + - `createApiKey(input, { session })`, `revokeApiKey(id, { session })` and `recordAdminAudit({ …, session })` take the acting session for the audit log. + - `resolveSession()` without a request resolves as a request with no credentials. +- The `search_documents` agent tool takes `mode` (`live`, `preview` or `edit`) instead of `publishedOnly`. A mode wider than the caller's own is ignored. The new `narrowMode(ctx, mode)` does the same for app code. +- `tanstack-cms atproto publish` publishes the published version of a document. + +Leaks fixed: + +- `readDocumentBySlug` and `findDocumentBySlug` check access on the matched document. +- Populated relations follow the reading context, including `publicRead`, so a `publicRead` reader sees published targets the way it sees published sources. A relation into a collection the reader can't read is left out. +- A preview token's document is redacted as for an anonymous visitor. + +Migration: run `pnpm codemod access-context`. It rewrites calls to the `…As` form: + +- a call that passed a `session` becomes `accessContext({ session, mode })`; +- `publishedOnly: true` becomes `publicContext()`; +- an unscoped read becomes `systemContext('access-context codemod: was an unscoped read')`, with a warning. + +Replace each such reason with a real one, or with the visitor's context where the read serves the public. Replace `runWithSession(session, fn)` by hand with an explicit `session` option or context. See "Reads take an access context" in the upgrade guide. diff --git a/.claude/skills/emdash-to-tanstack-cms/SKILL.md b/.claude/skills/emdash-to-tanstack-cms/SKILL.md index 0b9279f9..6a58b9c3 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 `queryDocuments({ where: { tags: 'opinion' } })` and - `readDocument`/`queryDocuments` with `populate: true` resolving `authors`). + then `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` and + `readDocumentAs`/`queryDocuments` with `populate: true` resolving `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 (`queryDocuments({ where })`). + (`/category/`) need an app route (`queryDocumentsAs(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 ca09eaa5..f4dc6ea9 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: `queryDocuments({ 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: `queryDocumentsAs(ctx, { where })` instead | **Field options:** `required` → `required: true`; `unique` → `unique: true`; `index` → `index: true`; `defaultValue` → `defaultValue`; `admin.description` → @@ -176,7 +176,7 @@ 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`/`readDocument` from `@tanstack/cms-core/server`, and attach +`queryDocuments`/`readDocumentAs` 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 @@ -272,7 +272,7 @@ custom nodes and list what isn't converted in the gap report. Self-test: 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` / - `readDocument`, with `populate: true` for relations). `closeStore()` after + `readDocumentAs`, with `populate: true` for relations). `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 488cf0fb..5511af2b 100644 --- a/.claude/skills/voting/SKILL.md +++ b/.claude/skills/voting/SKILL.md @@ -20,8 +20,10 @@ 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 `readDocument`, `queryDocuments`, `commitDocument`, and -`deleteDocument`. +`await` every `readDocumentAs`, `queryDocumentsAs`, `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. ## 0. Prerequisites @@ -124,22 +126,29 @@ import { createServerFn } from '@tanstack/react-start' import { commitDocument, deleteDocument, - queryDocuments, - readDocument, + publicContext, + queryDocumentsAs, + readDocumentAs, requireAuthenticated, + systemContext, } from '@tanstack/cms-core/server' +// Votes and the cached tallies are maintained by the server, not the voter. +const VOTES = systemContext('voting: votes and tallies are server-owned') + export async function castVoteForVoter( postId: string, value: 1 | -1, voterId: string, ) { if (value !== 1 && value !== -1) throw new Error('Invalid vote') - const post = await readDocument('post', postId) - if (!post) throw new Error('Post not found') + // Voters only ever see published posts. + if (!(await readDocumentAs(publicContext(), 'post', postId))) { + throw new Error('Post not found') + } const id = voteId(postId, voterId) - const existing = await readDocument('vote', id) + const existing = await readDocumentAs(VOTES, 'vote', id) if (existing && Number(existing.value) === value) { await deleteDocument('vote', id, { actor: voterId }) // retract } else { @@ -151,12 +160,15 @@ export async function castVoteForVoter( ) } // Recount from source; never trust client-supplied counts. - const votes = await queryDocuments({ + 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 + // Re-read the stored post: a public read may leave out fields the commit + // would then drop. + const post = await readDocumentAs(VOTES, 'post', postId) await commitDocument( 'post', postId, @@ -178,7 +190,7 @@ export const castVote = createServerFn({ method: 'POST' }) }) ``` -The worked example also resolves posts by slug (`readDocumentBySlug`) so +The worked example also resolves posts by slug (`readDocumentBySlugAs`) so links using either form work. **Atomicity gap (report it, don't hide it).** `commitDocument` and @@ -216,9 +228,9 @@ 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 readDocument('post', postId) + const post = await readDocumentAs(publicContext(), 'post', postId) const mine = voterId - ? await readDocument('vote', voteId(postId, voterId)) + ? await readDocumentAs(VOTES, 'vote', voteId(postId, voterId)) : null return { upvotes: Number(post?.upvotes ?? 0), @@ -230,9 +242,8 @@ export async function getVoteState(postId: string, voterId?: string) { // Top posts — score is an indexed number field: export async function getTopPosts(limit = 10) { - return queryDocuments({ + return queryDocumentsAs(publicContext(), { collection: 'post', - publishedOnly: true, sort: { field: 'score', dir: 'desc' }, limit, }) @@ -289,7 +300,7 @@ 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 `queryDocuments({ collection: 'vote' })` (auditability) +- vote docs appear in `queryDocumentsAs(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 diff --git a/.claude/skills/wordpress-to-tanstack-cms/SKILL.md b/.claude/skills/wordpress-to-tanstack-cms/SKILL.md index 5cd2bf42..5dc8ca57 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 - `queryDocuments({ where: { categories: '' } })` and `readDocument`); + `queryDocumentsAs(ctx, { where: { categories: '' } })` and `readDocumentAs`); 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 (`queryDocuments({ where })`). + pages need app routes (`queryDocumentsAs(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/src/collection-runtime.ts b/app/base/src/collection-runtime.ts index 773e7224..34ff7f06 100644 --- a/app/base/src/collection-runtime.ts +++ b/app/base/src/collection-runtime.ts @@ -6,7 +6,8 @@ import type { CmsCollectionRuntime, Collection, CollectionAccess, - Doc, + DeleteHookArgs, + ReadHookArgs, } from '@tanstack/cms-core' /** @@ -18,10 +19,8 @@ import type { function baseHooks(name: string): NonNullable { return { afterChange: createServerOnlyFn( - async ({ id, operation }: ChangeHookArgs) => { - const { currentSession, recordAdminAudit } = - await import('@tanstack/cms-core/server') - const session = currentSession() + async ({ id, operation, session }: ChangeHookArgs) => { + const { recordAdminAudit } = await import('@tanstack/cms-core/server') if (session?.user) await recordAdminAudit({ action: `base.document.${operation}`, @@ -30,24 +29,20 @@ function baseHooks(name: string): NonNullable { }) }, ), - afterDelete: createServerOnlyFn( - async ({ id }: { id: string; actor: string }) => { - const { currentSession, recordAdminAudit } = - await import('@tanstack/cms-core/server') - const session = currentSession() - if (session?.user) - await recordAdminAudit({ - action: 'base.document.delete', - target: `${name}/${id}`, - actor: session.user.id, - }) - }, - ), - postRead: createServerOnlyFn(async ({ doc }: { doc: Doc; id: string }) => { - const { currentSession, assertCollectionAccess } = + afterDelete: createServerOnlyFn(async ({ id, session }: DeleteHookArgs) => { + const { recordAdminAudit } = await import('@tanstack/cms-core/server') + if (session?.user) + await recordAdminAudit({ + action: 'base.document.delete', + target: `${name}/${id}`, + actor: session.user.id, + }) + }), + postRead: createServerOnlyFn(async ({ doc, access }: ReadHookArgs) => { + const { assertCollectionAccess } = await import('@tanstack/cms-core/server') - const session = currentSession() - if (session) assertCollectionAccess(session, name, 'read', doc) + if (access.session) + assertCollectionAccess(access.session, name, 'read', doc) return doc }), } diff --git a/app/base/src/operations.server.ts b/app/base/src/operations.server.ts index c2408d20..57da6e3f 100644 --- a/app/base/src/operations.server.ts +++ b/app/base/src/operations.server.ts @@ -15,13 +15,16 @@ import { assertCollectionAccess, assertQueryableFields, commitDocument, - queryDocuments, - readDocument, redactDoc, protectWrite, stageWrite, recordAdminAudit, listInterfaces, + accessContext, + systemContext, + readDocumentAs, + queryDocumentsAs, + withMode, } from '@tanstack/cms-core/server' import { evacuateWordPress } from '@tanstack/cms-migrate-wp' import { listSkills } from '@tanstack/cms-skills' @@ -35,6 +38,9 @@ import type { } from './operations' import type { CollectionDefinition } from './schema-registry' +/** Reads whose result the op checks itself (`assertCollectionAccess`, `protectWrite`). */ +const CHECKED = systemContext('base op: checked by the op') + function guardSources(ctx: CmsOpContext) { for (const [name, fields] of Object.entries(reportFields)) { assertCollectionAccess(ctx.session, name, 'read') @@ -43,19 +49,17 @@ function guardSources(ctx: CmsOpContext) { } } async function committed(name: string, id: string, ctx: CmsOpContext) { - const doc = await readDocument(name, id) + const doc = await readDocumentAs(CHECKED, name, id) if (!doc) throw new CmsError('Document not found.', 'NOT_FOUND') assertCollectionAccess(ctx.session, name, 'read', doc) return redactDoc(name, doc, ctx.session) } export async function dashboard(ctx: CmsOpContext) { const shop = await committed('shop', 'settings', ctx) - const reports = await queryDocuments({ - collection: 'reports', - session: ctx.session, - publishedOnly: true, - limit: 50, - }) + const reports = await queryDocumentsAs( + accessContext({ session: ctx.session }), + { collection: 'reports', limit: 50 }, + ) return { shop, interfaces: await listInterfaces(ctx), @@ -152,12 +156,10 @@ async function reportData(endDate: string, ctx: CmsOpContext) { const result: Array = [] let cursor: string | undefined do { - const page = await queryDocuments({ - collection: name, - session: ctx.session, - limit: 500, - cursor, - }) + const page = await queryDocumentsAs( + accessContext({ session: ctx.session, mode: 'edit' }), + { collection: name, limit: 500, cursor }, + ) for (const row of page.items) { const parsed = schema.safeParse(redactDoc(name, row.doc, ctx.session)) if (!parsed.success) @@ -210,7 +212,7 @@ export async function submitReport( ctx: CmsOpContext, ) { const id = `coffee-trends-${data.endDate}` - const before = await readDocument('reports', id) + const before = await readDocumentAs(CHECKED, 'reports', id) assertCollectionAccess( ctx.session, 'reports', @@ -313,7 +315,11 @@ export async function evacuateWordPressToBase( let documentsImported = 0 for (const docItem of evacResult.documents) { if (!getCmsConfig().collections[docItem.collection]) continue - const existing = await readDocument(docItem.collection, docItem.id) + const existing = await readDocumentAs( + CHECKED, + docItem.collection, + docItem.id, + ) await commitDocument(docItem.collection, docItem.id, docItem.doc, { session: ctx.session, actor, @@ -330,7 +336,7 @@ export async function evacuateWordPressToBase( const rule = evacResult.redirects[i] if (!rule) continue const redirId = `wp-redirect-${rule.wpId}-${i + 1}` - const existing = await readDocument('redirects', redirId) + const existing = await readDocumentAs(CHECKED, 'redirects', redirId) await commitDocument( 'redirects', redirId, @@ -357,7 +363,8 @@ export async function evacuateWordPressToBase( let stagedReviewCount = 0 for (const seoProposal of evacResult.seoAuditProposals) { if (!getCmsConfig().collections[seoProposal.collection]) continue - const current = await readDocument( + const current = await readDocumentAs( + CHECKED, seoProposal.collection, seoProposal.docId, ) @@ -382,7 +389,11 @@ export async function evacuateWordPressToBase( for (const skillProp of evacResult.skillProposals) { for (const iface of skillProp.interfaceProposals) { if (!getCmsConfig().collections.interfaces) continue - const existingIface = await readDocument('interfaces', iface.id) + const existingIface = await readDocumentAs( + CHECKED, + 'interfaces', + iface.id, + ) await stageWrite({ collection: 'interfaces', docId: iface.id, @@ -416,8 +427,7 @@ export async function evacuateWordPressToBase( const searchFields = cmsSearchFields(colDef) const engine = createCmsSearch({ collection: colDef, - session: ctx.session, - publishedOnly: false, + access: withMode(ctx.access, 'edit'), }) const queryRes = await engine.search({ limit: 50 }) facetedSearchCollections.push({ @@ -429,7 +439,7 @@ export async function evacuateWordPressToBase( // 7. Update shop settings with migrated site title if available if (evacResult.site.title) { - const beforeShop = await readDocument('shop', 'settings') + const beforeShop = await readDocumentAs(CHECKED, 'shop', 'settings') if (beforeShop) { await commitDocument( 'shop', diff --git a/app/base/tests/base.test.ts b/app/base/tests/base.test.ts index a26dcf77..ab65018f 100644 --- a/app/base/tests/base.test.ts +++ b/app/base/tests/base.test.ts @@ -13,14 +13,14 @@ import { getStorage, issueSessionCookie, listAudit, - queryDocuments, - readDocument, reject, requireStorageCapability, resolveSession, - runWithSession, setDbUserDisabled, setUserRole, + systemContext, + queryDocumentsAs, + readDocumentAs, } from '@tanstack/cms-core/server' import type { CmsOpContext, Field } from '@tanstack/cms-core' import { invokeAnyOp } from '@tanstack/cms-api' @@ -334,13 +334,18 @@ describe('coffee shop and reports', () => { receipts: 7, }) expect(report.result.revenueCents).toBe(777000) - expect((await queryDocuments({ collection: 'reports' })).total).toBe(0) + expect( + (await queryDocumentsAs(systemContext('test'), { collection: 'reports' })) + .total, + ).toBe(0) await completeOnboarding( { name: 'New shop', pairingsEnabled: false }, context(), ) await closeStore() - expect((await readDocument('shop', 'settings'))?.name).toBe('New shop') + expect( + (await readDocumentAs(systemContext('test'), 'shop', 'settings'))?.name, + ).toBe('New shop') }) it('accepts preferences idempotently, leaving schemas unchanged', async () => { const ctx = context() @@ -351,10 +356,14 @@ describe('coffee shop and reports', () => { expect(first.reply).toContain('Admins can add collections and fields') await completeOnboarding({ name: 'My shop', pairingsEnabled: true }, ctx) await completeOnboarding({ name: 'My shop', pairingsEnabled: true }, ctx) - expect((await queryDocuments({ collection: 'shop' })).total).toBe(1) - expect((await readDocument('shop', 'settings'))?.onboardingComplete).toBe( - true, - ) + expect( + (await queryDocumentsAs(systemContext('test'), { collection: 'shop' })) + .total, + ).toBe(1) + expect( + (await readDocumentAs(systemContext('test'), 'shop', 'settings')) + ?.onboardingComplete, + ).toBe(true) await expect( completeOnboarding( { name: 'Denied', pairingsEnabled: true }, @@ -365,9 +374,13 @@ describe('coffee shop and reports', () => { it('stages, rejects, approves and versions the same report', async () => { const ctx = context() const first = await submitReport({ endDate: DEMO_END_DATE }, ctx) - expect(await readDocument('reports', first.reportId)).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'reports', first.reportId), + ).toBeNull() await reject(first.pendingId, { rejecter: 'Owner' }) - expect(await readDocument('reports', first.reportId)).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'reports', first.reportId), + ).toBeNull() const second = await submitReport({ endDate: DEMO_END_DATE }, ctx) await approve(second.pendingId, { approver: 'Owner', publish: true }) expect( @@ -377,7 +390,10 @@ describe('coffee shop and reports', () => { ).toBe(40) const third = await submitReport({ endDate: DEMO_END_DATE }, ctx) await approve(third.pendingId, { approver: 'Owner', publish: true }) - expect((await readDocument('reports', third.reportId))?._revision).toBe(2) + expect( + (await readDocumentAs(systemContext('test'), 'reports', third.reportId)) + ?._revision, + ).toBe(2) }) it('denies scoped report reads and operations without credentials', async () => { const scoped = context('viewer') @@ -386,8 +402,12 @@ describe('coffee shop and reports', () => { previewTrends({ endDate: DEMO_END_DATE }, scoped), ).rejects.toThrow() expect( - await runWithSession(scoped.session, () => - invokeAnyOp('listPublishedDocuments', { collection: 'reports' }), + await invokeAnyOp( + 'listPublishedDocuments', + { collection: 'reports' }, + { + access: accessContext({ session: scoped.session, mode: 'edit' }), + }, ), ).toMatchObject({ items: [] }) await expect(invokeAnyOp('baseTrends', {})).rejects.toThrow() @@ -406,13 +426,21 @@ describe('coffee shop and reports', () => { const scoped = context('viewer') scoped.session.scope = { collections: ['reports'] } await expect( - runWithSession(scoped.session, () => - invokeAnyOp('listPublishedDocuments', { collection: 'reports' }), + invokeAnyOp( + 'listPublishedDocuments', + { collection: 'reports' }, + { + access: accessContext({ session: scoped.session, mode: 'edit' }), + }, ), ).rejects.toThrow() await expect( - runWithSession(scoped.session, () => - invokeAnyOp('getPublicDocument', { slugOrId: staged.reportId }), + invokeAnyOp( + 'getPublicDocument', + { slugOrId: staged.reportId }, + { + access: accessContext({ session: scoped.session, mode: 'edit' }), + }, ), ).rejects.toThrow() }) @@ -436,8 +464,9 @@ describe('coffee shop and reports', () => { } }) it('exposes report tools through scoped API keys with review-only writes', async () => { - const { key } = await runWithSession(context().session, () => - createApiKey({ name: 'Report client', role: 'editor' }), + const { key } = await createApiKey( + { name: 'Report client', role: 'editor' }, + { session: context().session }, ) const request = new Request('http://localhost/', { headers: { authorization: `Bearer ${key}` }, @@ -452,11 +481,17 @@ describe('coffee shop and reports', () => { { request }, )) as { reportId: string; staged: boolean } expect(pending.staged).toBe(true) - expect(await readDocument('reports', pending.reportId)).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'reports', pending.reportId), + ).toBeNull() }) it('audits human CRUD and access changes without including credentials', async () => { - await runWithSession(context().session, async () => { - await invokeAnyOp('createDoc', { + const admin = { + access: accessContext({ session: context().session, mode: 'edit' }), + } + await invokeAnyOp( + 'createDoc', + { collection: 'suppliers', id: 'audit-test', doc: { @@ -464,15 +499,24 @@ describe('coffee shop and reports', () => { email: 'audit@example.com', published: true, }, - }) - const user = (await invokeAnyOp('createDbUser', { + }, + admin, + ) + const user = (await invokeAnyOp( + 'createDbUser', + { email: 'audit-user@example.com', name: 'Audit user', role: 'editor', password: 'private-password', - })) as { user: { id: string } } - await invokeAnyOp('setUserRole', { userId: user.user.id, role: 'viewer' }) - }) + }, + admin, + )) as { user: { id: string } } + await invokeAnyOp( + 'setUserRole', + { userId: user.user.id, role: 'viewer' }, + admin, + ) const audit = await listAudit({ limit: 30 }) expect(audit).toEqual( expect.arrayContaining([ diff --git a/app/base/tests/chat.test.ts b/app/base/tests/chat.test.ts index ec5bfdd5..c342a9bf 100644 --- a/app/base/tests/chat.test.ts +++ b/app/base/tests/chat.test.ts @@ -6,8 +6,9 @@ import { chat } from '@tanstack/ai' import { defineCms } from '@tanstack/cms-core' import { closeStore, - readDocument, listPending, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { definition as cmsDefinition } from '../src/cms.definition' @@ -180,7 +181,9 @@ describe('customer chat tools', () => { expect(staged.toolResults[0].result.resultingDocument.ingredients).toEqual( doc.ingredients, ) - expect(await readDocument('recipes', 'cake')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'recipes', 'cake'), + ).toBeNull() await call('approveChange', { id: staged.toolResults[0].result.pendingId, expectedVersion: staged.toolResults[0].result.pendingVersion, diff --git a/app/base/tests/schema-registry.test.ts b/app/base/tests/schema-registry.test.ts index de6636d1..be975897 100644 --- a/app/base/tests/schema-registry.test.ts +++ b/app/base/tests/schema-registry.test.ts @@ -9,10 +9,11 @@ import { closeStore, getStorage, commitDocument, - readDocument, restoreRevision, stageWrite, approve, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { invokeAnyOp, ops } from '@tanstack/cms-api' import { definition as cmsDefinition } from '../src/cms.definition' @@ -372,7 +373,10 @@ describe('persisted runtime collection schemas', () => { await withSchemaRegistry(true, async () => { await approve(pending.id) await restoreRevision('customers', 'ada', 1) - expect((await readDocument('customers', 'ada'))!.loyalty).toBe(10) + expect( + (await readDocumentAs(systemContext('test'), 'customers', 'ada'))! + .loyalty, + ).toBe(10) }) const audit = await storage.listAudit() expect(audit.find((a) => a.action === 'base.schema.published')!.actor).toBe( @@ -667,11 +671,17 @@ describe('CMS nested schemas exposed by Base', () => { }) await closeStore() await withSchemaRegistry(false, async () => { - expect((await readDocument('recipes', 'cake'))!.ingredients).toEqual([ + expect( + (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! + .ingredients, + ).toEqual([ { name: 'Flour', quantity: 250, unit: 'g' }, { name: 'Eggs', quantity: 2, unit: 'each' }, ]) - expect((await readDocument('recipes', 'cake'))!.preparation).toEqual({ + expect( + (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! + .preparation, + ).toEqual({ minutes: 45, }) }) @@ -750,12 +760,14 @@ describe('CMS nested schemas exposed by Base', () => { await withSchemaRegistry(true, async () => { await approve(pending.id) await restoreRevision('recipes', 'cake', 1) - expect((await readDocument('recipes', 'cake'))!.ingredients).toEqual( - after.doc.ingredients, - ) - expect((await readDocument('recipes', 'cake'))!.preparation).toEqual( - after.doc.preparation, - ) + expect( + (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! + .ingredients, + ).toEqual(after.doc.ingredients) + expect( + (await readDocumentAs(systemContext('test'), 'recipes', 'cake'))! + .preparation, + ).toEqual(after.doc.preparation) }) }) it('rejects destructive nested edits and invalid nested relation targets/defaults before migration', async () => { diff --git a/app/base/tests/worker.test.ts b/app/base/tests/worker.test.ts index 6722d5dc..56452b39 100644 --- a/app/base/tests/worker.test.ts +++ b/app/base/tests/worker.test.ts @@ -14,12 +14,13 @@ import { submitInterface, approve, createDbUser, - readDocument, runEventDispatch, getInterfaceScheduleStatus, handleInterfaceScheduleEvent, setDbUserDisabled, setUserRole, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { definition as cmsDefinition } from '../src/cms.definition' import { collectionRuntimes } from '../src/collection-runtime' @@ -124,7 +125,14 @@ describe('Base background interface worker', () => { vi.setSystemTime(new Date('2026-10-11T09:01:00Z')) await expect .poll( - async () => (await readDocument('interfaces', 'scheduled'))?._revision, + async () => + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'scheduled', + ) + )?._revision, { timeout: 5000, interval: 100 }, ) .toBe(2) diff --git a/app/base/tests/wp-evacuation.test.ts b/app/base/tests/wp-evacuation.test.ts index 13d68f98..7c4a5d68 100644 --- a/app/base/tests/wp-evacuation.test.ts +++ b/app/base/tests/wp-evacuation.test.ts @@ -6,7 +6,8 @@ import { defineCms, getCmsConfig } from '@tanstack/cms-core' import { closeStore, listPending, - queryDocuments, + systemContext, + queryDocumentsAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { createCmsSearch } from '@tanstack/search-cms' @@ -236,9 +237,8 @@ describe('SMB Agency 50-Page WordPress Evacuation into app/base', () => { // 4. Verify documents are queryable and de-souped const caseStudies = await withSchemaRegistry(true, () => - queryDocuments({ + queryDocumentsAs(systemContext('test'), { collection: 'case_study', - publishedOnly: false, limit: 50, }), ) @@ -267,8 +267,7 @@ describe('SMB Agency 50-Page WordPress Evacuation into app/base', () => { } const searchEngine = createCmsSearch({ collection: searchableCollection, - publishedOnly: true, - publicRead: true, + access: systemContext('test', { mode: 'live' }), }) const searchResult = await searchEngine.search({ @@ -286,9 +285,8 @@ describe('SMB Agency 50-Page WordPress Evacuation into app/base', () => { // 6. Verify 1:1 SEO 301 Redirects are persisted in the `redirects` collection expect(result.redirectsCreated).toBe(100) const redirects = await withSchemaRegistry(true, () => - queryDocuments({ + queryDocumentsAs(systemContext('test'), { collection: 'redirects', - publishedOnly: false, limit: 100, }), ) @@ -359,36 +357,32 @@ describe('SMB Agency 50-Page WordPress Evacuation into app/base', () => { // Verify coffee_bean, store_location, 10 brewing posts, and menu_item are queryable in app/base const beans = await withSchemaRegistry(true, () => - queryDocuments({ + queryDocumentsAs(systemContext('test'), { collection: 'coffee_bean', - publishedOnly: false, limit: 10, }), ) expect(beans.total).toBe(2) const locations = await withSchemaRegistry(true, () => - queryDocuments({ + queryDocumentsAs(systemContext('test'), { collection: 'store_location', - publishedOnly: false, limit: 10, }), ) expect(locations.total).toBe(2) const posts = await withSchemaRegistry(true, () => - queryDocuments({ + queryDocumentsAs(systemContext('test'), { collection: 'posts', - publishedOnly: false, limit: 20, }), ) expect(posts.total).toBe(10) const menuItems = await withSchemaRegistry(true, () => - queryDocuments({ + queryDocumentsAs(systemContext('test'), { collection: 'menu_item', - publishedOnly: false, limit: 10, }), ) diff --git a/app/prm/bakeoff/README.md b/app/prm/bakeoff/README.md index 2ee1e367..48f2699a 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 98185a40..e1cbee47 100644 --- a/app/prm/bakeoff/latest.json +++ b/app/prm/bakeoff/latest.json @@ -1,5 +1,5 @@ { - "ranAt": "2026-11-06T03:03:19.126Z", + "ranAt": "2026-11-06T03:29:48.979Z", "mode": "fixture", "winner": "exa", "summary": { @@ -20,7 +20,12 @@ "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" @@ -33,7 +38,12 @@ "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" @@ -49,8 +59,15 @@ "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", @@ -59,8 +76,14 @@ "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" + ] } }, { @@ -72,8 +95,14 @@ "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", @@ -82,8 +111,14 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 1, - "matchedFacts": ["stately", "xstate", "state"], - "sampleUrls": ["https://github.com/davidkhourshid"] + "matchedFacts": [ + "stately", + "xstate", + "state" + ], + "sampleUrls": [ + "https://github.com/davidkhourshid" + ] } }, { @@ -95,8 +130,14 @@ "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", @@ -105,8 +146,13 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.6666666666666666, - "matchedFacts": ["nx", "nrwl"], - "sampleUrls": ["https://github.com/victorsavkin"] + "matchedFacts": [ + "nx", + "nrwl" + ], + "sampleUrls": [ + "https://github.com/victorsavkin" + ] } }, { @@ -118,8 +164,14 @@ "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", @@ -128,8 +180,13 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.6666666666666666, - "matchedFacts": ["tanstack", "query"], - "sampleUrls": ["https://github.com/tannerlinsley"] + "matchedFacts": [ + "tanstack", + "query" + ], + "sampleUrls": [ + "https://github.com/tannerlinsley" + ] } }, { @@ -141,8 +198,14 @@ "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", @@ -151,8 +214,13 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.6666666666666666, - "matchedFacts": ["flo", "ai"], - "sampleUrls": ["https://github.com/eugenesergueev"] + "matchedFacts": [ + "flo", + "ai" + ], + "sampleUrls": [ + "https://github.com/eugenesergueev" + ] } }, { @@ -164,8 +232,13 @@ "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", @@ -174,8 +247,12 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": ["developer"], - "sampleUrls": ["https://github.com/dominikkundel"] + "matchedFacts": [ + "developer" + ], + "sampleUrls": [ + "https://github.com/dominikkundel" + ] } }, { @@ -187,8 +264,13 @@ "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", @@ -197,8 +279,12 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": ["frontend"], - "sampleUrls": ["https://github.com/mayashavin"] + "matchedFacts": [ + "frontend" + ], + "sampleUrls": [ + "https://github.com/mayashavin" + ] } }, { @@ -210,8 +296,13 @@ "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", @@ -220,8 +311,12 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": ["runtime"], - "sampleUrls": ["https://github.com/kiritibadam"] + "matchedFacts": [ + "runtime" + ], + "sampleUrls": [ + "https://github.com/kiritibadam" + ] } }, { @@ -233,8 +328,13 @@ "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", @@ -243,8 +343,12 @@ "allowedUrlRate": 1, "primaryIdentityHits": 1, "factRecallRate": 0.5, - "matchedFacts": ["observability"], - "sampleUrls": ["https://github.com/sachinmalhotra"] + "matchedFacts": [ + "observability" + ], + "sampleUrls": [ + "https://github.com/sachinmalhotra" + ] } } ] diff --git a/app/prm/scripts/mine-summit-speakers.ts b/app/prm/scripts/mine-summit-speakers.ts index 2e90e64d..df75b4f4 100644 --- a/app/prm/scripts/mine-summit-speakers.ts +++ b/app/prm/scripts/mine-summit-speakers.ts @@ -34,7 +34,8 @@ import { slugify } from '@tanstack/cms-core' import { closeStore, commitDocument, - readDocument, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createExaSearchProvider } from '../src/enrich/search-provider' import { @@ -545,7 +546,13 @@ async function main() { published: true, } privateSeed.documents.organisation![orgId] = orgDoc - if (!(await readDocument('organisation', orgId))) { + if ( + !(await readDocumentAs( + systemContext('prm script: local maintenance'), + 'organisation', + orgId, + )) + ) { await commitDocument('organisation', orgId, orgDoc, { actor: 'enrichment-agent', summary: `Mined organisation ${mined.orgName} via Exa`, diff --git a/app/prm/scripts/snoop-sunil.ts b/app/prm/scripts/snoop-sunil.ts index d48c4a92..e2f59eb0 100644 --- a/app/prm/scripts/snoop-sunil.ts +++ b/app/prm/scripts/snoop-sunil.ts @@ -4,8 +4,9 @@ import { closeStore, commitDocument, listPending, - readDocument, seedContent, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { runAgent } from '@tanstack/cms-api' @@ -77,7 +78,11 @@ async function main() { } } - const liveDoc = await readDocument('person', 'sunil-pai') + const liveDoc = await readDocumentAs( + systemContext('prm script: local maintenance'), + 'person', + 'sunil-pai', + ) console.log( `\nLive person.enrichmentStatus before /review approval: "${String(liveDoc?.enrichmentStatus)}"`, ) diff --git a/app/prm/src/ops/import-people.ts b/app/prm/src/ops/import-people.ts index 95735b5a..8c618d4f 100644 --- a/app/prm/src/ops/import-people.ts +++ b/app/prm/src/ops/import-people.ts @@ -144,8 +144,10 @@ export const importPeopleOp = defineOp({ .describe('Target event document id for imported talks.'), }), run: async (input) => { - const { readDocument, stageWrite } = + const { stageWrite, systemContext, readDocumentAs } = await import('@tanstack/cms-core/server') + // Whether each record exists decides between staging a create and an update. + const existing = systemContext('import_people: create or update') const parsed = parseSpeakerMapMarkdown(input.markdown) const today = new Date().toISOString().slice(0, 10) const stagedPeople: Array = [] @@ -161,7 +163,11 @@ export const importPeopleOp = defineOp({ if (row.orgName) { orgId = slugify(row.orgName) if (orgId) { - const existingOrg = await readDocument('organisation', orgId) + const existingOrg = await readDocumentAs( + existing, + 'organisation', + orgId, + ) if (!existingOrg && !stagedOrgs.includes(orgId)) { await stageWrite({ collection: 'organisation', @@ -180,7 +186,7 @@ export const importPeopleOp = defineOp({ } } - const existingPerson = await readDocument('person', personId) + const existingPerson = await readDocumentAs(existing, 'person', personId) const existingGroups = Array.isArray(existingPerson?.groups) ? (existingPerson.groups as Array) : [] @@ -214,7 +220,7 @@ export const importPeopleOp = defineOp({ if (row.talkTitle) { const talkId = `talk-${personId}` - const existingTalk = await readDocument('talk', talkId) + const existingTalk = await readDocumentAs(existing, 'talk', talkId) await stageWrite({ collection: 'talk', docId: talkId, @@ -230,7 +236,7 @@ export const importPeopleOp = defineOp({ instruction: `Import talk for ${row.name}`, }) const roleId = `role-${input.eventId}-${personId}` - const existingRole = await readDocument('eventRole', roleId) + const existingRole = await readDocumentAs(existing, 'eventRole', roleId) const priority = row.tier === 'tier-1' ? 'high' @@ -260,7 +266,11 @@ export const importPeopleOp = defineOp({ if (row.sourceUrl) { const sourceId = `src-${personId}-headline` - const existingSource = await readDocument('personSource', sourceId) + const existingSource = await readDocumentAs( + existing, + 'personSource', + sourceId, + ) await stageWrite({ collection: 'personSource', docId: sourceId, diff --git a/app/prm/src/search.functions.ts b/app/prm/src/search.functions.ts index 840a095e..adbe5685 100644 --- a/app/prm/src/search.functions.ts +++ b/app/prm/src/search.functions.ts @@ -6,12 +6,12 @@ export const searchPeople = createServerFn({ method: 'POST' }) .validator((input: SearchRequest) => input) .handler(async ({ data }) => { const { getRequest } = await import('@tanstack/react-start/server') - const { resolveSession } = await import('@tanstack/cms-core/server') + const { accessContext, resolveSession } = + await import('@tanstack/cms-core/server') const { createCmsSearch } = await import('@tanstack/search-cms') const session = await resolveSession(getRequest()) return createCmsSearch({ collection: person, - session, - publicRead: true, + access: accessContext({ session, publicRead: true }), }).search(data) }) diff --git a/app/prm/tests/crm.test.ts b/app/prm/tests/crm.test.ts index b217663e..d7b92034 100644 --- a/app/prm/tests/crm.test.ts +++ b/app/prm/tests/crm.test.ts @@ -37,10 +37,10 @@ import { cmsTools, listAudit, listPending, - readDocument, runOp, - runWithSession, seedContent, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createSqliteStorage } from '@tanstack/cms-core/storage' import { createCmsApiHandler, invokeAnyOp } from '@tanstack/cms-api' @@ -140,7 +140,9 @@ describe('CRM acceptance criteria (§11)', () => { }) await save('by-owner', accessContext({ session: owner, mode: 'edit' })) - expect(await readDocument('person', 'by-owner')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'person', 'by-owner'), + ).toMatchObject({ name: 'by-owner', }) @@ -149,12 +151,16 @@ describe('CRM acceptance criteria (§11)', () => { accessContext({ session: owner, agent: 'enrich', mode: 'edit' }), ) if (approvalRequired) { - expect(await readDocument('person', 'by-agent')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'person', 'by-agent'), + ).toBeNull() expect( (await listPending()).map((p) => [p.docId, p.workflow?.state]), ).toEqual([['by-agent', 'pending_review']]) } else { - expect(await readDocument('person', 'by-agent')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'person', 'by-agent'), + ).toMatchObject({ name: 'by-agent', }) expect(await listPending()).toEqual([]) @@ -272,69 +278,82 @@ describe('CRM acceptance criteria (§11)', () => { user: { id: 'jack', name: 'Jack', role: 'admin', isAdmin: true }, } - await runWithSession(adminSession, async () => { - // Enrichment agent proposes a new person card + personSource rows - await runOp( - 'create_document', - { - collection: 'person', - id: 'new-speaker', - doc: { - name: 'Priya Nair', - headline: - 'Staff Compiler Engineer, Veloce Compute — WASM component sandboxes for tool calls', - org: 'veloce-compute', - role: 'Staff Compiler Engineer', - github: 'priyanair-wasm', - interests: ['agent-harness', 'devtools'], - enrichmentStatus: 'enriched', - enrichedAt: '2026-10-29', - published: true, - }, - instruction: 'Deep-snoop enrichment for Priya Nair', + const agent = accessContext({ + session: normalizeSession(adminSession), + mode: 'edit', + }) + // Enrichment agent proposes a new person card + personSource rows + await runOp( + 'create_document', + { + collection: 'person', + id: 'new-speaker', + doc: { + name: 'Priya Nair', + headline: + 'Staff Compiler Engineer, Veloce Compute — WASM component sandboxes for tool calls', + org: 'veloce-compute', + role: 'Staff Compiler Engineer', + github: 'priyanair-wasm', + interests: ['agent-harness', 'devtools'], + enrichmentStatus: 'enriched', + enrichedAt: '2026-10-29', + published: true, }, - 'enrichment-agent', - ) + instruction: 'Deep-snoop enrichment for Priya Nair', + }, + 'enrichment-agent', + agent, + ) - await runOp( - 'create_document', - { - collection: 'personSource', - id: 'src-priya-headline', - doc: { - person: 'new-speaker', - field: 'headline', - sourceUrl: 'https://veloce.example.dev/team/priya', - fetchedAt: '2026-10-29', - confidence: 'high', - published: true, - }, + await runOp( + 'create_document', + { + collection: 'personSource', + id: 'src-priya-headline', + doc: { + person: 'new-speaker', + field: 'headline', + sourceUrl: 'https://veloce.example.dev/team/priya', + fetchedAt: '2026-10-29', + confidence: 'high', + published: true, }, - 'enrichment-agent', - ) + }, + 'enrichment-agent', + agent, + ) - await runOp( - 'create_document', - { - collection: 'personSource', - id: 'src-priya-interests', - doc: { - person: 'new-speaker', - field: 'interests', - sourceUrl: 'https://veloce.example.dev/team/priya', - fetchedAt: '2026-10-29', - confidence: 'low', - note: 'Inferred from WASM sandbox talk abstract', - published: true, - }, + await runOp( + 'create_document', + { + collection: 'personSource', + id: 'src-priya-interests', + doc: { + person: 'new-speaker', + field: 'interests', + sourceUrl: 'https://veloce.example.dev/team/priya', + fetchedAt: '2026-10-29', + confidence: 'low', + note: 'Inferred from WASM sandbox talk abstract', + published: true, }, - 'enrichment-agent', - ) - }) + }, + 'enrichment-agent', + agent, + ) // Nothing appears in live `documents` before `/review` approval (§11.3) - expect(await readDocument('person', 'new-speaker')).toBeNull() - expect(await readDocument('personSource', 'src-priya-headline')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'person', 'new-speaker'), + ).toBeNull() + expect( + await readDocumentAs( + systemContext('test'), + 'personSource', + 'src-priya-headline', + ), + ).toBeNull() const pending = await listPending() const personPending = pending.find( @@ -351,7 +370,11 @@ describe('CRM acceptance criteria (§11)', () => { await approve(personPending!.id, { approver: 'Jack' }) await approve(interestSourcePending!.id, { approver: 'Jack' }) - const committed = await readDocument('person', 'new-speaker') + const committed = await readDocumentAs( + systemContext('test'), + 'person', + 'new-speaker', + ) expect(committed?.headline).toContain('Staff Compiler Engineer') expect(committed?.enrichmentStatus).toBe('enriched') @@ -372,7 +395,11 @@ describe('CRM acceptance criteria (§11)', () => { await seedContent() // §11.2: Alex Chen is in `needs-disambiguation` with candidate notes - const alex = await readDocument('person', 'alex-chen') + const alex = await readDocumentAs( + systemContext('test'), + 'person', + 'alex-chen', + ) expect(alex?.enrichmentStatus).toBe('needs-disambiguation') expect(String(alex?.notes)).toContain('Disambiguation required') @@ -426,17 +453,23 @@ describe('CRM acceptance criteria (§11)', () => { permissions: [...PERMISSIONS], user: { id: 'jack', name: 'Jack', role: 'admin', isAdmin: true }, } - const result = (await runWithSession(session, () => - invokeAnyOp( - 'import_people', - { markdown, eventId: 'ai-coding-summit-2026' }, - { actor: 'import' }, - ), + const result = (await invokeAnyOp( + 'import_people', + { markdown, eventId: 'ai-coding-summit-2026' }, + { + actor: 'import', + access: accessContext({ + session: normalizeSession(session), + mode: 'edit', + }), + }, )) as { importedCount: number; stagedPeople: Array } expect(result.importedCount).toBe(1) expect(result.stagedPeople).toEqual(['elena-rostova']) - expect(await readDocument('person', 'elena-rostova')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'person', 'elena-rostova'), + ).toBeNull() const pending = await listPending() const stagedPerson = pending.find( diff --git a/docs/agents/review-queue.md b/docs/agents/review-queue.md index 78d1d5cf..119c6b3b 100644 --- a/docs/agents/review-queue.md +++ b/docs/agents/review-queue.md @@ -54,7 +54,7 @@ Agents work through the [agent tools](../mcp/operations-registry#the-agent-tool- Agent tool call (create / update / delete / unpublish / restore / schedule) │ ▼ -runOp(name, input, actor) permission, collection, and field rules +runOp(name, input, actor, access) permission, collection, and field rules │ ▼ stageWrite({ collection, docId, type, doc, actor, instruction }) diff --git a/docs/api/cli.md b/docs/api/cli.md index 001cd2cd..36f0331b 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.queryDocuments({ collection: 'post', publishedOnly: true, limit: 1 }) + const { total } = await core.queryDocumentsAs(core.publicContext(), { collection: 'post', limit: 1 }) console.log(`${total} published posts`) } finally { await core.closeStore() diff --git a/docs/api/cms-core-server.md b/docs/api/cms-core-server.md index 929c37e9..33e155b3 100644 --- a/docs/api/cms-core-server.md +++ b/docs/api/cms-core-server.md @@ -76,7 +76,7 @@ Contexts are frozen and come from the builders. A copied object is not a context function cmsAs(cms: Cms | CmsConfig, ctx: AccessContext): CmsReads ``` -The read verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned): `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the functions below, without the `session`, `publishedOnly` and `publicRead` options. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`. +The read verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned): `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the `…As` functions below, without the context. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`. ```ts validate=type import { defineCms } from '@tanstack/cms-core' @@ -119,30 +119,31 @@ function redactFor(ctx: AccessContext, collect Use these for reads the verbs don't cover. A system context passes every check. -In a host, build one context per request. `@tanstack/cms-api` provides `requestAccessContext(request)` for any host, and `getCmsAccessContext()` in `@tanstack/cms-api/start`. Hooks and event handlers receive the context they run with. The older form, binding a session with `runWithSession` and calling the plain functions, still works but is deprecated for reads. +In a host, build one context per request. `@tanstack/cms-api` provides `requestAccessContext(request)` for any host, and `getCmsAccessContext()` in `@tanstack/cms-api/start`. Hooks and event handlers receive the context they run with. Nothing reads with an ambient session: a read without a context is a public read. + +The plain read functions below (`queryDocuments`, `readDocument`, …) are deprecated. They take no context and read as `publicContext()`: published documents only, redacted for an anonymous visitor. `pnpm codemod access-context` rewrites calls to the `…As(ctx, …)` form, and they are removed in a later alpha. --- ## Documents and queries -### `queryDocuments(options?)` +### `queryDocumentsAs(ctx, options?)` ```ts -function queryDocuments(options?: QueryDocumentsOptions): Promise +function queryDocumentsAs(ctx: AccessContext, options?: QueryDocumentsOptions): Promise +function queryDocuments(options?: QueryDocumentsOptions): Promise // deprecated: reads as publicContext() interface QueryDocumentsOptions { collection?: string collections?: Array // restrict a cross-collection query query?: string // full-text search over title and content locale?: string - publishedOnly?: boolean populate?: boolean // attach `relations` to each item where?: Record | ReadonlyArray // see "Filters" below sort?: { field: string; dir?: 'asc' | 'desc' } // a system column or a field path (`seo.score`) limit?: number offset?: number cursor?: string // `nextCursor` from the previous page (replaces `offset`) - session?: CmsSession // redact results and reject queries on unreadable fields } interface QueryDocumentsResult { @@ -159,24 +160,18 @@ interface QueryDocumentsResult { } ``` -The general-purpose query over committed documents. Unrestricted queries filter, -sort, and page in the storage adapter. When `session` is supplied, documents, -titles, and populated relations are redacted after read hooks; collection access -and visible search matches are applied before paging and counting. Document-dependent -access rules may require scanning matching rows. Omit `session` only for trusted -server code that needs complete documents. +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 +matches are applied before paging and counting, and filtering or sorting on a +field `ctx` can't read is `FORBIDDEN`. Document-dependent access rules may require +scanning matching rows. Trusted server code that needs complete documents reads +with a named `systemContext(reason)`. ```ts validate=type -import { queryDocuments } from '@tanstack/cms-core/server' +import { publicContext, queryDocumentsAs } from '@tanstack/cms-core/server' -const { items, total, nextCursor } = await queryDocuments({ - collection: 'post', - publishedOnly: true, - where: { category: 'engineering', rank: { gte: 3 } }, - sort: { field: 'updatedAt', dir: 'desc' }, - limit: 20, - populate: true, -}) +const { items, total, nextCursor } = await queryDocumentsAs(publicContext(), { collection: 'post', where: { category: 'engineering', rank: { gte: 3 } }, sort: { field: 'updatedAt', dir: 'desc' }, limit: 20, populate: true }) ``` #### Filters @@ -210,20 +205,21 @@ 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 { queryDocuments } from '@tanstack/cms-core/server' +import { systemContext, queryDocumentsAs } from '@tanstack/cms-core/server' let cursor: string | undefined do { - const page = await queryDocuments({ collection: 'post', limit: 100, cursor }) + const page = await queryDocumentsAs(systemContext('export every post'), { collection: 'post', limit: 100, cursor }) // ... cursor = page.nextCursor } while (cursor) ``` -### `queryDocumentSummaries(query)` +### `queryDocumentSummariesAs(ctx, query)` ```ts -function queryDocumentSummaries(q: DocumentSummaryQuery): Promise<{ items: Array; total: number }> +function queryDocumentSummariesAs(ctx: AccessContext, q: DocumentSummaryQuery): Promise<{ items: Array; total: number }> +function queryDocumentSummaries(q: DocumentSummaryQuery): Promise<{ items: Array; total: number }> // deprecated: reads as publicContext() interface DocumentSummaryQuery { collection: string @@ -253,20 +249,21 @@ interface DocSummary { } ``` -Paginated summaries for one collection: the admin list view. Pending creates (staged, not yet approved) are listed first on page 1. +Paginated summaries for one collection, as `ctx` sees them: the admin list view. Pending creates (staged, not yet approved) are listed first on page 1 for an `edit` context. -### `readDocument(collection, id)` +### `readDocumentAs(ctx, collection, id)` ```ts -function readDocument(collectionName: string, id: string): Promise +function readDocumentAs(ctx: AccessContext, collectionName: string, id: string): Promise +function readDocument(collectionName: string, id: string): Promise // deprecated: reads as publicContext() ``` -The committed document, after `postRead` hooks. +The committed document, after `postRead` hooks, redacted for `ctx`. `null` when it doesn't exist or `ctx` can't read it. -### `readDocumentWithPending(collection, id)` +### `readDocumentWithPendingAs(ctx, collection, id)` ```ts -function readDocumentWithPending(collectionName: string, id: string): Promise<{ +function readDocumentWithPendingAs(ctx: AccessContext, collectionName: string, id: string): Promise<{ doc: Doc | null isPending: boolean pendingId?: string @@ -275,61 +272,62 @@ function readDocumentWithPending(collectionName: string, id: string): Promise<{ }> ``` -The latest version including any staged change or draft, as the editor and agents see it. +The latest version including any staged change or draft, as the editor and agents see it. A `live` context gets the published version only. The deprecated `readDocumentWithPending(collection, id)` reads as `publicContext()`. -### `readDocumentBySlug(collection, slugOrId, options?)` +### `readDocumentBySlugAs(ctx, collection, slugOrId, options?)` ```ts -function readDocumentBySlug( +function readDocumentBySlugAs( + ctx: AccessContext, collectionName: string, slugOrId: string, - options?: { publishedOnly?: boolean; populate?: boolean }, + options?: { populate?: boolean }, ): 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. +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()`. -### `findDocumentBySlug(slugOrId, options?)` +### `findDocumentBySlugAs(ctx, slugOrId, options?)` ```ts -function findDocumentBySlug( +function findDocumentBySlugAs( + ctx: AccessContext, slugOrId: string, - options?: { preferred?: Array; publishedOnly?: boolean }, + options?: { preferred?: Array; populate?: boolean }, ): Promise<{ collection: string; id: string; doc: Doc } | null> ``` -`readDocumentBySlug` across every collection, trying `preferred` collections first. The public `/p/$id` and `/post/$id` routes use it. +`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()`. -### `readSingleton(collection, options?)` +### `readSingletonAs(ctx, collection)` ```ts -function readSingleton(collectionName: string, options?: { publishedOnly?: boolean }): Promise<{ id: string; doc: Doc } | null> +function readSingletonAs(ctx: AccessContext, collectionName: string): Promise<{ id: string; doc: Doc } | null> +function readSingleton(collectionName: string): Promise<{ id: string; doc: Doc } | null> // deprecated: reads as publicContext() ``` The single document of an `isSingleton` collection. -### `populateRelations(collection, doc, options?)` +### `populateRelationsAs(ctx, collection, doc)` ```ts -function populateRelations( - collectionName: string, - doc: Doc, - options?: { publishedOnly?: boolean }, -): Promise | null>> +function populateRelationsAs(ctx: AccessContext, collectionName: string, doc: Doc): Promise | null>> +function populateRelations(collectionName: string, doc: Doc): Promise | null>> // deprecated: reads as publicContext() ``` -Resolves every `relation` field of `doc` to its target document(s), keyed by field name. +Resolves every `relation` field of `doc` to the target document(s) `ctx` can read, keyed by field name. A `publicRead` context sees published targets the way it sees published sources. Fields whose target collection `ctx` can't read are left out. -### `listDocuments(collection?, options?)` +### `listDocumentsAs(ctx, collection?, options?)` ```ts -function listDocuments( +function listDocumentsAs( + ctx: AccessContext, collectionName?: string, options?: { locale?: string; limit?: number; offset?: number; collections?: Array }, ): Promise> ``` -Summaries across one or all collections, including pending creates. +Summaries across one or all collections `ctx` can read, including pending creates for an `edit` context. The deprecated `listDocuments(collection?, options?)` reads as `publicContext()`. ### `listPublicDocuments(collection?)` @@ -339,10 +337,11 @@ function listPublicDocuments(collectionName?: string): Promise> +function findReferencesAs(ctx: AccessContext, collectionName: string, id: string): Promise> +function findReferences(collectionName: string, id: string): Promise> // deprecated: reads as publicContext() interface DocumentReference { collection: string @@ -352,12 +351,13 @@ interface DocumentReference { } ``` -Documents whose `relation` fields point at `collection/id`. +Documents `ctx` can read whose `relation` fields point at `collection/id`. -### `listTranslations(collection, id)` +### `listTranslationsAs(ctx, collection, id)` ```ts -function listTranslations(collectionName: string, docId: string): Promise> +function listTranslationsAs(ctx: AccessContext, collectionName: string, docId: string): Promise> +function listTranslations(collectionName: string, docId: string): Promise> // deprecated: reads as publicContext() interface TranslationSummary { locale: string @@ -416,9 +416,9 @@ interface CommitOptions { Validates, runs hooks, and commits directly, bypassing the review queue. A pending draft of the document is folded in, so committing is how a draft gets published. Returns the committed document with its new `_revision`. ```ts validate=type -import { commitDocument, readDocument } from '@tanstack/cms-core/server' +import { commitDocument, systemContext, readDocumentAs } from '@tanstack/cms-core/server' -const current = await readDocument('post', 'hello-world') +const current = await readDocumentAs(systemContext('import script'), 'post', 'hello-world') await commitDocument( 'post', 'hello-world', @@ -584,7 +584,8 @@ Sets `published: false` and clears `publishAt`, immediately or staged. ### `listRevisions(collection, id)` and `restoreRevision(collection, id, revision, options?)` ```ts -function listRevisions(collectionName: string, docId: string): Promise> // newest first +function listRevisionsAs(ctx: AccessContext, collectionName: string, docId: string): Promise> // newest first +function listRevisions(collectionName: string, docId: string): Promise> // deprecated: reads as publicContext() function restoreRevision( collectionName: string, @@ -712,13 +713,13 @@ Drains the outbox once — the cron tick, then claims and delivers due events in ## Agent operations -### `runOp(name, input, actor, access?)` +### `runOp(name, input, actor, access)` ```ts -function runOp(name: string, input: any, actor: string, access?: AccessContext): Promise +function runOp(name: string, input: any, actor: string, access: AccessContext): Promise ``` -Runs one of the agent tools from `opSchemas` (`list_documents`, `create_document`, …) as `access`, usually the agent's context: `accessContext({ session, agent: 'content-agent', mode: 'edit' })`. Every agent surface funnels through it: the content agent, the MCP server, and the WebMCP endpoint. Write tools always stage their changes for review, recorded with `actor`. With a session-bearing context, the tool's permission and collection access are enforced and field access rules apply. A system context bypasses them, and a preview context is refused. Without `access`, the session bound by `runWithSession` is used. That fallback is deprecated. +Runs one of the agent tools from `opSchemas` (`list_documents`, `create_document`, …) as `access`, usually the agent's context: `accessContext({ session, agent: 'content-agent', mode: 'edit' })`. Every agent surface funnels through it: the content agent, the MCP server, and the WebMCP endpoint. Write tools always stage their changes for review, recorded with `actor`. With a session-bearing context, the tool's permission and collection access are enforced and field access rules apply. A system context bypasses them, and a preview context is refused. A call without an access context throws `UNAUTHORIZED`. ### `cmsTools(actor)` @@ -726,7 +727,7 @@ Runs one of the agent tools from `opSchemas` (`list_documents`, `create_document function cmsTools(actor: string, options?: { access?: AccessContext; authorizedOnly?: boolean; readOnly?: boolean; include?: (op: CmsOpDefinition) => boolean; onResult?: (result: CmsToolResult) => void }): Promise> // @tanstack/ai server tools, one per agent op ``` -The agent tools as `@tanstack/ai` server tools, for your own `chat()` loops. `@tanstack/cms-api` uses them for content chat and MCP. Every call runs `runOp` as the agent's context. A host that serves one tool set to many callers passes each call's context in the tool's runtime context, under `CMS_ACCESS_KEY`; the MCP server does this with `handle(request, { context: { [CMS_ACCESS_KEY]: access } })`. Otherwise `options.access` applies, then the session bound by `runWithSession`. `authorizedOnly` filters advertised tools against that context's session; execution always rechecks access. `onResult` receives JSON-compatible receipts (`name`, `kind`, `status`, `result`). With an observer, tool errors become structured results so the model can correct its request. Observer failures cannot break a committed tool write. Without these options, the existing MCP catalog and error behavior stay intact. +The agent tools as `@tanstack/ai` server tools, for your own `chat()` loops. `@tanstack/cms-api` uses them for content chat and MCP. Every call runs `runOp` as the agent's context. A host that serves one tool set to many callers passes each call's context in the tool's runtime context, under `CMS_ACCESS_KEY`; the MCP server does this with `handle(request, { context: { [CMS_ACCESS_KEY]: access } })`. Otherwise `options.access` applies. A call with neither fails with `UNAUTHORIZED`. `authorizedOnly` filters advertised tools against that context's session; execution always rechecks access. `onResult` receives JSON-compatible receipts (`name`, `kind`, `status`, `result`). With an observer, tool errors become structured results so the model can correct its request. Observer failures cannot break a committed tool write. Without these options, the existing MCP catalog and error behavior stay intact. --- @@ -1029,12 +1030,10 @@ A request is authenticated, in order, by: a CMS API key (`Authorization: Bearer ```ts function resolveSession(request?: Request, options?: { fresh?: boolean }): Promise // memoized per Request -function runWithSession(session: CmsSession, fn: () => T): T // deprecated for reads: pass an access context -function currentSession(): CmsSession | undefined function isDevAuth(): boolean // whether an app without `auth` runs as a local admin ``` -`resolveSession()` without a request returns the session bound by `runWithSession`, if any. +`resolveSession()` without a request resolves as a request with no credentials: the local admin under dev auth, otherwise nobody. There is no ambient session; pass the session, or an access context, to the call that needs it. Pass `{ fresh: true }` to bypass request memoization when rechecking a long-lived connection. ### Guards @@ -1086,9 +1085,9 @@ function accessibleCollections(session: CmsSession, action?: CollectionAction): ### API keys ```ts -function createApiKey(input: CreateApiKeyInput): Promise<{ key: string; record: ApiKeySummary }> +function createApiKey(input: CreateApiKeyInput, options?: { session?: CmsSession }): Promise<{ key: string; record: ApiKeySummary }> function listApiKeys(): Promise> -function revokeApiKey(id: string): Promise +function revokeApiKey(id: string, options?: { session?: CmsSession }): Promise interface CreateApiKeyInput { name: string @@ -1101,7 +1100,7 @@ type ApiKeySummary = Omit const API_KEY_PREFIX: 'tscms_' ``` -Keys are prefixed `tscms_`, stored as SHA-256 hashes, and the plaintext `key` is returned once. A key acts with its role and optional collection scope on the HTTP API, the client, and MCP. Admins usually create keys on the admin Settings page; `createApiKey` does the same from a script. +Keys are prefixed `tscms_`, stored as SHA-256 hashes, and the plaintext `key` is returned once. A key acts with its role and optional collection scope on the HTTP API, the client, and MCP. Admins usually create keys on the admin Settings page; `createApiKey` does the same from a script. `options.session` is the admin recorded in the audit log. ```ts validate=type import { createApiKey } from '@tanstack/cms-core/server' diff --git a/docs/architecture/data-layer.md b/docs/architecture/data-layer.md index 93cbeba3..5e95c358 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 `queryDocuments()` 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 `queryDocumentsAs(ctx, …)` inside a Start server function (`examples/db-markdown`): ```ts // src/cms.config.ts @@ -172,11 +172,11 @@ export const cms = defineCms({ ```ts // src/docs.functions.ts import { createServerFn } from '@tanstack/react-start' -import { queryDocuments } from '@tanstack/cms-core/server' +import { publicContext, queryDocumentsAs } from '@tanstack/cms-core/server' import './cms.config' export const listMarkdownDocs = createServerFn({ method: 'GET' }).handler(async () => { - const { items } = await queryDocuments({ + const { items } = await queryDocumentsAs(publicContext(), { collection: 'post', sort: { field: 'date', dir: 'desc' }, }) diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md index 060f5a7f..fb2d375e 100644 --- a/docs/architecture/terminology.md +++ b/docs/architecture/terminology.md @@ -32,7 +32,7 @@ The core API is being refactored before 1.0. This page fixes the words used in t Jack's term for an inconsistency that spreads across the API: one concept with several spellings, several verbs, or several layers that each solve it differently. Each copy looks harmless; together they make the API hard to learn and easy to misuse. -Examples today: five read verbs (`getPublicDocument`, `readDocument`, `readDocumentBySlug`, `queryDocuments`, `collection().published()`), a camelCase HTTP registry next to a snake_case agent registry, and a `publishedOnly` boolean every caller must remember. The refactor treats each as one thing to fix everywhere, not per call site. +Examples (before the refactor): five read verbs (`getPublicDocument`, `readDocument`, `readDocumentBySlug`, `queryDocuments`, `collection().published()`), a camelCase HTTP registry next to a snake_case agent registry, and a `publishedOnly` boolean every caller must remember. The refactor treats each as one thing to fix everywhere, not per call site. ## Locator @@ -101,7 +101,7 @@ Rules core enforces on every decision, whatever the strategy: ## Access context -**Planned.** 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 = cms.as(ctx)`, then `db.list({ collection: 'post' })`. Forgetting the context is a type error, not a silent public read. Hooks, event handlers and strategies 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.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. Its **mode** decides which version a read returns: @@ -111,9 +111,9 @@ Its **mode** decides which version a read returns: | `preview` | The working copy, read-only, for a preview link or token | | `edit` | The working copy, for editing | -Planned builders: `publicContext()`, `accessContext({ session })`, `systemContext(reason)` (the reason is required so privileged use stays greppable), and preview-token contexts. +Builders: `publicContext()`, `accessContext({ session })`, `systemContext(reason)` (the reason is required so privileged use stays greppable), and preview-token contexts (`previewContext`, `previewTokenContext`). -**Today:** an optional session passed to some reads, a `publishedOnly` boolean the caller must remember, and an ambient session fallback (`runWithSession`/`currentSession()`). +**Today:** every read takes a context, and there is no ambient session. Writes still take an optional `session`. ## Actor diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md index 55f445d8..7782a20a 100644 --- a/docs/deployment/upgrading.md +++ b/docs/deployment/upgrading.md @@ -114,15 +114,16 @@ Codes come from `CMS_ERROR_CODES` (`BAD_REQUEST`, `VALIDATION_FAILED`, ### 5. Store reads are async and paginated `getStore()` and `listDocs()` are gone, because they loaded the whole store -into memory. Use the query functions from `@tanstack/cms-core/server`: +into memory. Use the query functions from `@tanstack/cms-core/server`, with +the access context to read as (see [step 25](#25-reads-take-an-access-context)): | 0.x | 1.0 | | --- | --- | -| `getStore().documents.post` | `queryDocuments({ collection: 'post', where, sort, limit, offset })` | -| `listDocs('post')` | `queryDocumentSummaries({ collection: 'post', status, search, limit, offset })` | -| `getStore().documents.post[id]` | `readDocument('post', id)` | -| find by slug in one collection | `readDocumentBySlug('post', slug, { publishedOnly: true })` | -| find by slug across collections | `findDocumentBySlug(slug, { preferred: ['page', 'post'] })` | +| `getStore().documents.post` | `queryDocumentsAs(ctx, { collection: 'post', where, sort, limit, offset })` | +| `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)` | +| 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`. @@ -379,6 +380,48 @@ The admin routes use the module named in `createRoutes(definition, { renderers } - **Scheduling a published document** schedules its open draft or proposal and keeps the live version up, instead of unpublishing it until `publishAt`. With nothing pending it fails with `BAD_REQUEST`. - **Storage.** Migrations add change-set workflow and schedule columns and audit transition columns (SQLite/libsql v16, Postgres v8); run `tanstack-cms migrate`. Custom `StorageAdapter`s should persist the new `PendingRecord` (`workflow`, `publishAt`) and `AuditRecord` (`changeSet`, `from`, `to`, `effects`, `reason`) fields and may implement `findDuePendingPublish`. +### 25. Reads take an access context + +Every read says who is reading: `publicContext()` for a visitor, +`getCmsAccessContext()` (TanStack Start) or `accessContext({ session })` for +the request's user, and `systemContext(reason)` for trusted jobs. Read with +`cmsAs(cms, ctx)` or the `…As(ctx, …)` functions. See +[Access contexts](../api/cms-core-server#access-contexts). + +- **The plain read functions fail closed.** `queryDocuments`, `readDocument`, + `readDocumentBySlug`, `findDocumentBySlug`, `readSingleton`, + `populateRelations`, `listDocuments`, `queryDocumentSummaries`, + `groupDocuments`, `findReferences`, `listTranslations`, `listRevisions` and + `readDocumentWithPending` are deprecated and read as `publicContext()`: + published documents only, redacted for an anonymous visitor. They used to + read everything, drafts included. +- **Their `session`, `publishedOnly` and `publicRead` options are gone**, as + are the same options on `createCmsSearch` (pass `access`). +- **No ambient session.** `runWithSession` and `currentSession` are removed. + `runOp(name, input, actor, access)` and `cmsMcp.fetch(request, access)` + require a context, and `cmsTools` refuses a call without one. `afterChange` + and `afterDelete` hooks receive the writer's `session`; `postRead` hooks + receive `access`. `createApiKey`, `revokeApiKey` and `recordAdminAudit` + take the acting `session` as an option. +- **`search_documents`** takes `mode` (`live`, `preview`, `edit`) instead of + `publishedOnly`. A mode wider than the caller's is ignored. +- **Fixed leaks.** Slug reads check access on the matched document, populated + relations follow the reading context (including `publicRead`), and a + preview token's document is redacted as for an anonymous visitor. + +Run the codemod, then review each `systemContext` it adds: + +```bash +pnpm codemod access-context +``` + +It rewrites the calls to the `…As` form. A call that passed a `session` +becomes `accessContext({ session, mode })`, `publishedOnly: true` becomes +`publicContext()`, and an unscoped read becomes +`systemContext('access-context codemod: was an unscoped read')` with a +warning. Replace that reason with a real one, or with the visitor's context +where the read serves the public. + ## Versioning policy From 1.0, TanStack CMS follows [semantic versioning](https://semver.org). The diff --git a/docs/mcp/http-mcp-server.md b/docs/mcp/http-mcp-server.md index c6e93e13..fba246bb 100644 --- a/docs/mcp/http-mcp-server.md +++ b/docs/mcp/http-mcp-server.md @@ -31,7 +31,7 @@ export const cmsMcp = createMCPServer({ }) ``` -`handleMcpApi(request)` from `@tanstack/cms-api/http` authorizes the request, applies the `mcp` rate limit, binds the caller's session, and forwards to `cmsMcp.fetch`. In a TanStack Start app, the CMS route `/api/mcp` calls it for you; in any other server, `createCmsApiHandler()` serves `/api/mcp` along with the rest of the API. +`handleMcpApi(request)` from `@tanstack/cms-api/http` authorizes the request, applies the `mcp` rate limit, builds the caller's access context, and forwards to `cmsMcp.fetch(request, access)`. In a TanStack Start app, the CMS route `/api/mcp` calls it for you; in any other server, `createCmsApiHandler()` serves `/api/mcp` along with the rest of the API. - `POST /api/mcp` handles JSON-RPC messages (`initialize`, `tools/list`, `tools/call`). - `GET /api/mcp` opens the server-to-client stream. diff --git a/docs/mcp/operations-registry.md b/docs/mcp/operations-registry.md index 2f1b0843..eeabefbb 100644 --- a/docs/mcp/operations-registry.md +++ b/docs/mcp/operations-registry.md @@ -166,7 +166,7 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/ | `list_collections` | read | Collections and their fields | | `list_documents` | read | Document summaries, filtered by collection and locale, paginated (`limit`, `offset`, `cursor`) | | `read_document` | read | One document, including staged creates and updates | -| `search_documents` | read | Full-text search and structured `where` / `sort` queries with collection, locale, published filters, and pagination (`limit`, `offset`, `cursor`) | +| `search_documents` | read | Full-text search and structured `where` / `sort` queries with collection, locale, a read `mode` (`live` for published only; never wider than the caller's), and pagination (`limit`, `offset`, `cursor`) | | `list_revisions` | read | Revision history, newest first | | `list_translations` | read | A document's locale variants | | `create_document` | write | Stage a new document | @@ -178,33 +178,35 @@ Agents get a smaller, task-shaped set of tools. `opSchemas` (`packages/core/src/ Two server-side pieces in `@tanstack/cms-core/server` attach behavior: -- **`runOp(name, input, actor)`** executes a tool. When a session is bound (every transport binds one), it requires `content.read` for read tools and `content.write` for write tools (`content.delete` for `delete_document` and `content.publish` for `unpublish_document`, matching the human operations), checks the collection's `access` rules and API key scope, hides collections the session cannot read, redacts unreadable fields, and preserves fields the session cannot write. Write tools never commit: they call `stageWrite()`, so the change waits in the [review queue](../agents/review-queue) with `actor` recorded. -- **`cmsTools(actor)`** wraps every agent tool (`agentOpSchemas()`: `opSchemas` plus your ops marked `agent`) as a `@tanstack/ai` server tool bound to an actor. +- **`runOp(name, input, actor, access)`** executes a tool as an access context (every transport builds one per request; a call without one throws `UNAUTHORIZED`). With a session-bearing context, it requires `content.read` for read tools and `content.write` for write tools (`content.delete` for `delete_document` and `content.publish` for `unpublish_document`, matching the human operations), checks the collection's `access` rules and API key scope, hides collections the session cannot read, redacts unreadable fields, and preserves fields the session cannot write. Write tools never commit: they call `stageWrite()`, so the change waits in the [review queue](../agents/review-queue) with `actor` recorded. +- **`cmsTools(actor, { access })`** wraps every agent tool (`agentOpSchemas()`: `opSchemas` plus your ops marked `agent`) as a `@tanstack/ai` server tool bound to an actor and a context. A host serving many callers from one tool set passes each call's context under `CMS_ACCESS_KEY` instead. | Surface | How it uses the tools | Actor | | --- | --- | --- | | Content agent (`/agent`) | `chat({ tools: await cmsTools('content-agent') })` | `content-agent` | | HTTP MCP server (`/api/mcp`) | `createMCPServer({ tools: await cmsTools('mcp') })` | `mcp` | -| WebMCP (`unstable_WebMcpBadge`) | Registers each `agentOpSchemas()` entry in the browser; calls `POST /api/cms`, which runs `runOp(name, input, 'webmcp')` | `webmcp` | +| WebMCP (`unstable_WebMcpBadge`) | Registers each `agentOpSchemas()` entry in the browser; calls `POST /api/cms`, which runs `runOp(name, input, 'webmcp', access)` | `webmcp` | You can hand the same tools to your own agent: ```ts import { chat } from '@tanstack/ai' -import { cmsTools, resolveSession, runWithSession } from '@tanstack/cms-core/server' - -const session = await resolveSession(request) -const reply = await runWithSession(session, () => - chat({ - adapter, - tools: await cmsTools('my-agent'), - messages, - stream: false, - }), -) +import { accessContext, cmsTools, resolveSession } from '@tanstack/cms-core/server' + +const access = accessContext({ + session: await resolveSession(request), + agent: 'my-agent', + mode: 'edit', +}) +const reply = await chat({ + adapter, + tools: await cmsTools('my-agent', { access }), + messages, + stream: false, +}) ``` -Bind a session with `runWithSession` so the tools enforce that user's permissions. Without a bound session, `runOp` skips the permission and redaction checks (writes are still staged). +The tools enforce that user's permissions, collection access and field rules. A `systemContext(reason)` skips those checks (writes are still staged); use it only for trusted server code. ## Adding Your Own Operations diff --git a/docs/mcp/webmcp.md b/docs/mcp/webmcp.md index bf274319..1559c107 100644 --- a/docs/mcp/webmcp.md +++ b/docs/mcp/webmcp.md @@ -84,7 +84,7 @@ Accepts `{ op: string, input?: unknown }` and: 3. Checks the request origin (CSRF), since the call rides on the user's cookies. 4. Resolves the session and requires **`agent.use`** for every tool, read or write (`UNAUTHORIZED` or `FORBIDDEN` otherwise). 5. Applies the `mcp` rate limit. -6. Runs `runOp(op, input, 'webmcp')` with the session bound, so collection rules and field redaction apply exactly as they do for that user elsewhere. +6. Runs `runOp(op, input, 'webmcp', access)` with the caller's agent context, so collection rules and field redaction apply exactly as they do for that user elsewhere. Success returns `{ result }`; failures return `{ error: { code, message, details? } }` with the matching HTTP status. Write tools return `{ staged: true, pendingId, status }`. diff --git a/docs/migration/from-emdash.md b/docs/migration/from-emdash.md index f8817066..5ebeb683 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 `queryDocuments({ 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 `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` finds 4 posts; and that `populate: true` resolves `authors` to 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 4cd79278..5e2d05b1 100644 --- a/docs/migration/from-payload.md +++ b/docs/migration/from-payload.md @@ -66,7 +66,7 @@ Payload v3 and TanStack CMS are both **code-first TypeScript CMSs** with schema | `schedulePublish` | `publishAt` / `unpublishAt` | System fields on every document | | `upload: true` collection | Media library + `image` fields | Not a content collection | | `auth: true` collection | `defineCms({ auth: { getUser } })` + roles | Users live in your identity provider | -| globals | `isSingleton: true` collection (`readSingleton()`) or `theme` | | +| globals | `isSingleton: true` collection (`readSingletonAs(ctx, name)`) or `theme` | | | (public URL) | `path: (doc, id) => string` | Feeds the sitemap and "View" links | | `plugin-seo` / `plugin-redirects` / `plugin-search` | `seoField()` / `redirectsCollection()` / built-in full-text search | | | `storage-s3` / `db-sqlite` | `createS3Media()` / `createSqliteStorage()` or `createLibsqlStorage()` | | @@ -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 `queryDocuments({ where })` call | +| `join`, `ui` | — | `join` becomes a `queryDocumentsAs(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 `queryDocuments()` or `readDocument()`. 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 `queryDocumentsAs(ctx, …)` or `readDocumentAs(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 8fd94164..ddba6396 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`/`readDocument` 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` | `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` | | **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 `queryDocuments({ where })` for reverse lookups. +- **No GROQ projections or reverse references.** Use `relation` fields with `populate: true`, and `queryDocumentsAs(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. @@ -53,7 +53,7 @@ Both define schemas in TypeScript. They differ in who hosts the data, how it's q | Sanity | Core `type` | Notes | |---|---|---| | `defineType({ type: 'document' })` | A collection | `page` (with `blocks`) and `post` match the built-in routes | -| singleton documents | `isSingleton: true` | Read with `readSingleton()` | +| singleton documents | `isSingleton: true` | Read with `readSingletonAs(ctx, name)` | | `string`, `text`, `number`, `boolean` | `text`, `textarea`, `number`, `boolean` | `validation: Rule.required()` → `required: true` | | `string` with `options.list` | `select` | | | `array` of `string` with `options.list` | `multiselect` | | diff --git a/docs/migration/from-wordpress.md b/docs/migration/from-wordpress.md index 8565c132..f4cff954 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 `queryDocuments({ 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 `queryDocumentsAs(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 fb641c44..a666479f 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 `queryDocuments()` and `readDocument()` 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 `queryDocumentsAs(ctx, …)` and `readDocumentAs(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 5b1a68b7..a20dece0 100644 --- a/docs/schema/building-pages.md +++ b/docs/schema/building-pages.md @@ -108,9 +108,9 @@ 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. -The store's plain read functions (`queryDocuments({ publishedOnly: true })`, `readDocumentBySlug(…, { publishedOnly: true })`, and so on) still work, but they don't know who is asking. Without a `session` they read like a system context, so you must pass `publishedOnly: true` yourself. Prefer `cmsAs`. Each verb also exists in argument form (`queryDocumentsAs(ctx, …)`, `readDocumentAs(ctx, …)`) for code that passes the context along. +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()`. -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. `populateRelations(collection, doc)` does the same for a document you already have. +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. ### 3. The HTTP client diff --git a/docs/schema/collections-and-fields.md b/docs/schema/collections-and-fields.md index 8feba8b7..b43828d7 100644 --- a/docs/schema/collections-and-fields.md +++ b/docs/schema/collections-and-fields.md @@ -127,7 +127,7 @@ export const cms = defineCms({ | `titleField` | `string` | Field used as the document title in lists, search, and `cmsHead`. | | `fields` | `Array` | Ordered field descriptors. | | `path?` | `(doc, id) => string \| null` | Public URL of a document. Used by `/sitemap.xml` and "View" links; collections without it are left out of the sitemap. Return `null` for documents with no page. | -| `isSingleton?` | `boolean` | Only one document may exist (site settings, navigation). The admin opens it directly; a second create fails with `CONFLICT`. Read it with `readSingleton(name)`. | +| `isSingleton?` | `boolean` | Only one document may exist (site settings, navigation). The admin opens it directly; a second create fails with `CONFLICT`. Read it with `readSingletonAs(ctx, name)`. | | `readOnly?` | `boolean` | Disallow creating, updating, staging, or deleting documents in this collection (`FORBIDDEN`). Automatically `true` when `storage` is a read-only adapter such as `createMarkdownStorage()`. | | `storage?` | `StorageAdapter` | Per-collection storage adapter (for example `createMarkdownStorage({ dir: 'content/posts' })`), overriding the global `defineCms({ storage })` for this collection's documents. | | `slugField?` | `string` | Field used for slug lookups. Defaults to a field named `slug` (`getSlugField()`). | diff --git a/examples/astro-starlight-after/src/migration.test.ts b/examples/astro-starlight-after/src/migration.test.ts index dee27db7..8c07a1e2 100644 --- a/examples/astro-starlight-after/src/migration.test.ts +++ b/examples/astro-starlight-after/src/migration.test.ts @@ -20,10 +20,12 @@ import { closeStore, importContent, parseCmsExport, - queryDocuments, - readDocument, resolveRedirect, seedContent, + publicContext, + systemContext, + queryDocumentsAs, + readDocumentAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -139,11 +141,16 @@ describe('astro starlight → tanstack cms parity', () => { useTempStore({ seed: true }) const { seeded } = await seedContent({ force: true }) expect(seeded).toBe(EXPECTED.page.total + EXPECTED.redirect.total) - expect((await queryDocuments({ collection: 'page' })).total).toBe(6) expect( - (await queryDocuments({ collection: 'page', publishedOnly: true })).total, + (await queryDocumentsAs(systemContext('test'), { collection: 'page' })) + .total, + ).toBe(6) + expect( + (await queryDocumentsAs(publicContext(), { collection: 'page' })).total, ).toBe(5) - expect(await readDocument('page', 'start-installation')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'page', 'start-installation'), + ).toMatchObject({ title: 'Installation', slug: '/start/installation', }) @@ -154,7 +161,10 @@ describe('astro starlight → tanstack cms parity', () => { const data = parseCmsExport(JSON.parse(JSON.stringify(asCmsExport()))) const result = await importContent(data) expect(result.created).toBe(EXPECTED.page.total + EXPECTED.redirect.total) - expect((await queryDocuments({ collection: 'page' })).total).toBe(6) + expect( + (await queryDocumentsAs(systemContext('test'), { collection: 'page' })) + .total, + ).toBe(6) expect(await resolveRedirect('/start/installation/')).toEqual({ to: '/p/start-installation', status: 301, diff --git a/examples/blog-voting/src/voting/votes.ts b/examples/blog-voting/src/voting/votes.ts index 3a2e2f84..516a7fdd 100644 --- a/examples/blog-voting/src/voting/votes.ts +++ b/examples/blog-voting/src/voting/votes.ts @@ -18,10 +18,12 @@ import { createServerFn } from '@tanstack/react-start' import { commitDocument, deleteDocument, - queryDocuments, - readDocument, - readDocumentBySlug, requireAuthenticated, + publicContext, + systemContext, + readDocumentAs, + readDocumentBySlugAs, + queryDocumentsAs, } from '@tanstack/cms-core/server' import type { Doc } from '@tanstack/cms-core' @@ -53,16 +55,20 @@ export function voteId(postId: string, voterId: string): string { return `vote:${postId}:${voterId}` } +/** Votes and the cached tallies are maintained by the server, not the voter. */ +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 readDocument('post', postId) + const direct = await readDocumentAs(publicContext(), 'post', postId) if (direct) return { id: postId, doc: direct } - const bySlug = await readDocumentBySlug('post', postId) + const bySlug = await readDocumentBySlugAs(publicContext(), 'post', postId) if (bySlug) return { id: bySlug.id, doc: bySlug.doc } throw new Error(`Post not found: ${postId}`) } async function tallyVotes(postId: string): Promise { - const votes = await queryDocuments({ + const votes = await queryDocumentsAs(VOTES, { collection: 'vote', where: { post: postId }, }) @@ -90,9 +96,9 @@ export async function castVoteForVoter( if (value !== 1 && value !== -1) { throw new Error(`Invalid vote value: ${JSON.stringify(value)}`) } - const { id: resolvedId, doc: post } = await resolvePost(postId) + const { id: resolvedId } = await resolvePost(postId) const id = voteId(resolvedId, voterId) - const existing = await readDocument('vote', id) + const existing = await readDocumentAs(VOTES, 'vote', id) if ( existing && @@ -110,10 +116,11 @@ export async function castVoteForVoter( // Recount from source — never trust client-supplied counts. const tally = await tallyVotes(resolvedId) + const stored = await readDocumentAs(VOTES, 'post', resolvedId) await commitDocument( 'post', resolvedId, - { ...(post as Record), ...tally }, + { ...(stored as Record), ...tally }, { actor: voterId, summary: 'Vote tally update' }, ) return tally @@ -128,7 +135,7 @@ export async function getVoteState( const rec = post as Record const mine = voterId != null && voterId !== '' - ? await readDocument('vote', voteId(resolvedId, voterId)) + ? await readDocumentAs(VOTES, 'vote', voteId(resolvedId, voterId)) : null return { upvotes: Number(rec.upvotes ?? 0), @@ -151,9 +158,8 @@ export async function getTopPosts(limit = 10): Promise< downvotes: number }> > { - const { items } = await queryDocuments({ + const { items } = await queryDocumentsAs(publicContext(), { collection: 'post', - publishedOnly: true, sort: { field: 'score', dir: 'desc' }, limit, }) diff --git a/examples/blog-voting/src/voting/voting.test.ts b/examples/blog-voting/src/voting/voting.test.ts index e8dfde35..bca4c65a 100644 --- a/examples/blog-voting/src/voting/voting.test.ts +++ b/examples/blog-voting/src/voting/voting.test.ts @@ -12,8 +12,9 @@ import { afterEach, describe, expect, it } from 'vitest' import { defineCms } from '@tanstack/cms-core' import { closeStore, - queryDocuments, - readDocument, + systemContext, + readDocumentAs, + queryDocumentsAs, } from '@tanstack/cms-core/server' import { castVoteForVoter, getTopPosts, getVoteState, voteId } from './votes' @@ -79,9 +80,21 @@ describe('voting', () => { const tally = await castVoteForVoter('p1', 1, 'alice') expect(tally).toEqual({ upvotes: 1, downvotes: 0, score: 1 }) // The vote document exists (audit trail)… - expect((await readDocument('vote', voteId('p1', 'alice')))?.value).toBe(1) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'vote', + voteId('p1', 'alice'), + ) + )?.value, + ).toBe(1) // …and the post carries the cached counts. - const post = (await readDocument('post', 'p1')) as Record + const post = (await readDocumentAs( + systemContext('test'), + 'post', + 'p1', + )) as Record expect(post.upvotes).toBe(1) expect(post.score).toBe(1) }) @@ -91,7 +104,13 @@ describe('voting', () => { await castVoteForVoter('p1', 1, 'alice') const tally = await castVoteForVoter('p1', 1, 'alice') expect(tally).toEqual({ upvotes: 0, downvotes: 0, score: 0 }) - expect(await readDocument('vote', voteId('p1', 'alice'))).toBeNull() + expect( + await readDocumentAs( + systemContext('test'), + 'vote', + voteId('p1', 'alice'), + ), + ).toBeNull() }) it('flips when the opposite vote is cast', async () => { @@ -99,7 +118,15 @@ describe('voting', () => { await castVoteForVoter('p1', 1, 'alice') const tally = await castVoteForVoter('p1', -1, 'alice') expect(tally).toEqual({ upvotes: 0, downvotes: 1, score: -1 }) - expect((await readDocument('vote', voteId('p1', 'alice')))?.value).toBe(-1) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'vote', + voteId('p1', 'alice'), + ) + )?.value, + ).toBe(-1) }) it('accumulates across voters but never double-counts one voter', async () => { @@ -110,7 +137,9 @@ describe('voting', () => { const tally = await castVoteForVoter('p1', 1, 'alice') // retract alice expect(tally).toEqual({ upvotes: 1, downvotes: 1, score: 0 }) // Deterministic ids: exactly one doc per (post, voter), ever. - const votes = await queryDocuments({ collection: 'vote' }) + const votes = await queryDocumentsAs(systemContext('test'), { + collection: 'vote', + }) expect(votes.total).toBe(2) }) diff --git a/examples/db-markdown/README.md b/examples/db-markdown/README.md index c5493f92..e4214af7 100644 --- a/examples/db-markdown/README.md +++ b/examples/db-markdown/README.md @@ -13,8 +13,9 @@ 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 `queryDocuments({ collection: 'post' })` from - `@tanstack/cms-core/server`; the client never touches `node:fs`. + collection on the server with `queryDocumentsAs(publicContext(), { collection: 'post' })` + from `@tanstack/cms-core/server`, 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 to `published` posts and sorts by date, and the detail page looks a post up @@ -28,6 +29,6 @@ pnpm --filter db-markdown dev # http://localhost:3020 ``` Add or edit a file in `content/posts/` and reload. `draft-post.md` has -`published: false`, so it stays off the index. +`published: false`, so the public read never returns it. See [Data Layer with TanStack DB](../../docs/architecture/data-layer.md). diff --git a/examples/db-markdown/content/posts/draft-post.md b/examples/db-markdown/content/posts/draft-post.md index bc657da9..cce9349e 100644 --- a/examples/db-markdown/content/posts/draft-post.md +++ b/examples/db-markdown/content/posts/draft-post.md @@ -5,5 +5,5 @@ tags: [draft] published: false --- -You should not see this post in the list. The home page filters on -`published` — in the query, not in a template. +You should not see this post in the list. The server reads posts as a +public visitor, so drafts never reach the client. diff --git a/examples/db-markdown/src/docs.functions.ts b/examples/db-markdown/src/docs.functions.ts index f86d2a53..f9779f12 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 { queryDocuments } from '@tanstack/cms-core/server' +import { publicContext, queryDocumentsAs } from '@tanstack/cms-core/server' import './cms.config' type Json = @@ -19,7 +19,9 @@ export const listMarkdownDocs = createServerFn({ method: 'GET' }).handler( async (): Promise< Array & { id: string; body: string }> > => { - const { items } = await queryDocuments({ collection: 'post' }) + const { items } = await queryDocumentsAs(publicContext(), { + collection: 'post', + }) return items.map((item) => ({ ...(item.doc as Record), id: item.id, diff --git a/examples/emdash-after/MIGRATION.md b/examples/emdash-after/MIGRATION.md index bf569520..3d2e52c8 100644 --- a/examples/emdash-after/MIGRATION.md +++ b/examples/emdash-after/MIGRATION.md @@ -100,7 +100,7 @@ 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; - `queryDocuments({ where: { tags: 'opinion' } })` finds 4 posts; and + `queryDocumentsAs(ctx, { where: { tags: 'opinion' } })` finds 4 posts; and `populate: true` resolves `building-for-the-long-term`'s `authors` to "EmDash Editorial" and "Guest Contributor". diff --git a/examples/emdash-after/src/migration.test.ts b/examples/emdash-after/src/migration.test.ts index 002bc9b1..76461d5a 100644 --- a/examples/emdash-after/src/migration.test.ts +++ b/examples/emdash-after/src/migration.test.ts @@ -18,10 +18,12 @@ import { closeStore, importContent, parseCmsExport, - queryDocuments, - readDocument, - readDocumentBySlug, seedContent, + publicContext, + systemContext, + queryDocumentsAs, + readDocumentAs, + readDocumentBySlugAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -135,15 +137,24 @@ describe('emdash → tanstack cms parity', () => { useTempStore({ seed: true }) const { seeded } = await seedContent({ force: true }) expect(seeded).toBe(TOTAL) - expect((await queryDocuments({ collection: 'post' })).total).toBe(8) expect( - (await queryDocuments({ collection: 'post', publishedOnly: true })).total, + (await queryDocumentsAs(systemContext('test'), { collection: 'post' })) + .total, + ).toBe(8) + expect( + (await queryDocumentsAs(publicContext(), { collection: 'post' })).total, ).toBe(7) expect( - (await queryDocuments({ collection: 'post', where: { tags: 'opinion' } })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + where: { tags: 'opinion' }, + }) + ).total, ).toBe(4) - expect(await readDocument('page', 'about')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'page', 'about'), + ).toMatchObject({ title: 'About', }) }) @@ -153,7 +164,8 @@ 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 readDocumentBySlug( + const found = await readDocumentBySlugAs( + systemContext('test'), 'post', 'building-for-the-long-term', { populate: true }, diff --git a/examples/payload-after/src/migration.test.ts b/examples/payload-after/src/migration.test.ts index aa1af0bc..466aa598 100644 --- a/examples/payload-after/src/migration.test.ts +++ b/examples/payload-after/src/migration.test.ts @@ -18,9 +18,11 @@ import { closeStore, importContent, parseCmsExport, - queryDocuments, - readDocument, seedContent, + publicContext, + systemContext, + queryDocumentsAs, + readDocumentAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -118,14 +120,17 @@ describe('payload → tanstack cms parity', () => { const { seeded } = await seedContent({ force: true }) expect(seeded).toBe(4) for (const [name, expected] of Object.entries(EXPECTED)) { - expect((await queryDocuments({ collection: name })).total).toBe( - expected.total, - ) expect( - (await queryDocuments({ collection: name, publishedOnly: true })).total, + (await queryDocumentsAs(systemContext('test'), { collection: name })) + .total, + ).toBe(expected.total) + expect( + (await queryDocumentsAs(publicContext(), { collection: name })).total, ).toBe(expected.published) } - expect(await readDocument('page', 'home')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'page', 'home'), + ).toMatchObject({ title: 'Welcome', }) }) @@ -135,9 +140,17 @@ describe('payload → tanstack cms parity', () => { const data = parseCmsExport(JSON.parse(JSON.stringify(asCmsExport()))) const result = await importContent(data) expect(result.created).toBe(4) - expect((await queryDocuments({ collection: 'page' })).total).toBe(2) - expect((await queryDocuments({ collection: 'post' })).total).toBe(2) - expect(await readDocument('post', 'hello-world')).toMatchObject({ + expect( + (await queryDocumentsAs(systemContext('test'), { collection: 'page' })) + .total, + ).toBe(2) + expect( + (await queryDocumentsAs(systemContext('test'), { collection: 'post' })) + .total, + ).toBe(2) + expect( + await readDocumentAs(systemContext('test'), 'post', 'hello-world'), + ).toMatchObject({ title: 'Hello world', body: 'There is not much here yet.', }) diff --git a/examples/payload-after/src/routeTree.gen.ts b/examples/payload-after/src/routeTree.gen.ts index b6f4a185..38df3fe4 100644 --- a/examples/payload-after/src/routeTree.gen.ts +++ b/examples/payload-after/src/routeTree.gen.ts @@ -13,10 +13,10 @@ import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesIndexRouteImpo import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRouteImport } from './../../../packages/ui-react/src/routes/$' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRouteImport } from './../../../packages/ui-react/src/routes/robots.txt' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRouteImport } from './../../../packages/ui-react/src/routes/sitemap.xml' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/agent' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/content' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/review' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/settings' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/agent' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/content' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/review' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/settings' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRouteImport } from './../../../packages/ui-react/src/routes/api.cms' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRouteImport } from './../../../packages/ui-react/src/routes/api.mcp' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRouteImport } from './../../../packages/ui-react/src/routes/api.media' @@ -24,7 +24,7 @@ import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPDotidRouteImp import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRouteImport } from './../../../packages/ui-react/src/routes/post.$id' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRouteImport } from './../../../packages/ui-react/src/routes/api.media.$name' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRouteImport } from './../../../packages/ui-react/src/routes/preview.$collection.$id' -import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRouteImport } from './../../../packages/ui-react/.generated/204af191d4b3/edit.$collection.$id' +import { Route as DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRouteImport } from './../../../packages/ui-react/.generated/3b63267ad9fd/edit.$collection.$id' import { Route as DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRouteImport } from './../../../packages/ui-react/src/routes/api.cms.v1.$' const DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesIndexRoute = @@ -55,32 +55,32 @@ const DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute = getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRouteImport.update( { id: '/admin/agent', path: '/admin/agent', getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRouteImport.update( { id: '/admin/content', path: '/admin/content', getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRouteImport.update( { id: '/admin/review', path: '/admin/review', getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRouteImport.update( { id: '/admin/settings', path: '/admin/settings', @@ -135,8 +135,8 @@ const DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidR getParentRoute: () => rootRouteImport, } as any, ) -const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute = - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRouteImport.update( +const DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute = + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRouteImport.update( { id: '/admin/edit/$collection/$id', path: '/admin/edit/$collection/$id', @@ -157,10 +157,10 @@ export interface FileRoutesByFullPath { '/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute '/robots.txt': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute '/sitemap.xml': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute - '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute - '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute - '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute + '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute + '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute + '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute + '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute '/api/cms': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute '/api/mcp': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute '/api/media': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -168,7 +168,7 @@ export interface FileRoutesByFullPath { '/post/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute '/api/media/$name': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute '/preview/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute + '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute '/api/cms/v1/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } export interface FileRoutesByTo { @@ -176,10 +176,10 @@ export interface FileRoutesByTo { '/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute '/robots.txt': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute '/sitemap.xml': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute - '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute - '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute - '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute + '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute + '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute + '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute + '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute '/api/cms': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute '/api/mcp': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute '/api/media': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -187,7 +187,7 @@ export interface FileRoutesByTo { '/post/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute '/api/media/$name': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute '/preview/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute + '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute '/api/cms/v1/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } export interface FileRoutesById { @@ -196,10 +196,10 @@ export interface FileRoutesById { '/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute '/robots.txt': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute '/sitemap.xml': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute - '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute - '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute - '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute + '/admin/agent': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute + '/admin/content': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute + '/admin/review': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute + '/admin/settings': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute '/api/cms': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute '/api/mcp': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute '/api/media': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -207,7 +207,7 @@ export interface FileRoutesById { '/post/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute '/api/media/$name': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute '/preview/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute + '/admin/edit/$collection/$id': typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute '/api/cms/v1/$': typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } export interface FileRouteTypes { @@ -275,10 +275,10 @@ export interface RootRouteChildren { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSplatRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaRoute @@ -286,7 +286,7 @@ export interface RootRouteChildren { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPostDotidRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute } @@ -324,28 +324,28 @@ declare module '@tanstack/react-router' { id: '/admin/agent' path: '/admin/agent' fullPath: '/admin/agent' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRouteImport parentRoute: typeof rootRouteImport } '/admin/content': { id: '/admin/content' path: '/admin/content' fullPath: '/admin/content' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRouteImport parentRoute: typeof rootRouteImport } '/admin/review': { id: '/admin/review' path: '/admin/review' fullPath: '/admin/review' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRouteImport parentRoute: typeof rootRouteImport } '/admin/settings': { id: '/admin/settings' path: '/admin/settings' fullPath: '/admin/settings' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRouteImport parentRoute: typeof rootRouteImport } '/api/cms': { @@ -401,7 +401,7 @@ declare module '@tanstack/react-router' { id: '/admin/edit/$collection/$id' path: '/admin/edit/$collection/$id' fullPath: '/admin/edit/$collection/$id' - preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRouteImport + preLoaderRoute: typeof DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRouteImport parentRoute: typeof rootRouteImport } '/api/cms/v1/$': { @@ -423,14 +423,14 @@ const rootRouteChildren: RootRouteChildren = { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesRobotsDottxtRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesSitemapDotxmlRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3AgentRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ContentRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3ReviewRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3SettingsRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdAgentRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdContentRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdReviewRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdSettingsRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmcpRoute: @@ -445,8 +445,8 @@ const rootRouteChildren: RootRouteChildren = { DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotmediaDotnameRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesPreviewDotcollectionDotidRoute, - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute: - DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated204af191d4b3EditDotcollectionDotidRoute, + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute: + DotDotDotDotDotDotDotDotPackagesUiReactDotgenerated3b63267ad9fdEditDotcollectionDotidRoute, DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute: DotDotDotDotDotDotDotDotPackagesUiReactSrcRoutesApiDotcmsDotv1DotsplatRoute, } diff --git a/examples/picks/src/search.functions.ts b/examples/picks/src/search.functions.ts index 97b909af..814b6608 100644 --- a/examples/picks/src/search.functions.ts +++ b/examples/picks/src/search.functions.ts @@ -33,11 +33,11 @@ export const searchPicks = createServerFn({ method: 'POST' }) .validator((input: SearchRequest) => input) .handler(async ({ data }) => { const { createCmsSearch } = await import('@tanstack/search-cms') + const { accessContext } = await import('@tanstack/cms-core/server') const { session } = await features() return createCmsSearch({ collection: picks, - session, - publicRead: true, + access: accessContext({ session, publicRead: true }), }).search(data) }) export const translatePicks = createServerFn({ method: 'POST' }) diff --git a/examples/wordpress-after/MIGRATION.md b/examples/wordpress-after/MIGRATION.md index 8fba08c8..d313dae5 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; - `queryDocuments({ where: { categories: 'growing' } })` finds 3 posts; and + `queryDocumentsAs(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 d898b94b..6f426b80 100644 --- a/examples/wordpress-after/src/migration.test.ts +++ b/examples/wordpress-after/src/migration.test.ts @@ -20,10 +20,12 @@ import { closeStore, importContent, parseCmsExport, - queryDocuments, - readDocument, resolveRedirect, seedContent, + publicContext, + systemContext, + queryDocumentsAs, + readDocumentAs, } from '@tanstack/cms-core/server' import { cms } from './cms.config' import { seedDocuments } from './seed-data' @@ -141,19 +143,24 @@ describe('wordpress → tanstack cms parity', () => { useTempStore({ seed: true }) const { seeded } = await seedContent({ force: true }) expect(seeded).toBe(TOTAL) - expect((await queryDocuments({ collection: 'post' })).total).toBe(5) expect( - (await queryDocuments({ collection: 'post', publishedOnly: true })).total, + (await queryDocumentsAs(systemContext('test'), { collection: 'post' })) + .total, + ).toBe(5) + expect( + (await queryDocumentsAs(publicContext(), { collection: 'post' })).total, ).toBe(4) expect( ( - await queryDocuments({ + await queryDocumentsAs(systemContext('test'), { collection: 'post', where: { categories: 'growing' }, }) ).total, ).toBe(3) - expect(await readDocument('page', 'about')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'page', 'about'), + ).toMatchObject({ title: 'About The Garden Path', }) }) diff --git a/packages/api/src/http.ts b/packages/api/src/http.ts index 80d2eb5c..822b2c25 100644 --- a/packages/api/src/http.ts +++ b/packages/api/src/http.ts @@ -64,7 +64,6 @@ import { requirePermission, resolveSession, runOp, - runWithSession, saveMedia, snapWidth, snapHeight, @@ -270,9 +269,7 @@ async function dispatchCmsApi(request: Request): Promise { }) // `runOp` validates the input through the op's Standard Schema once; no // separate pre-validation here. - const result = await runWithSession(session, () => - runOp(op.name, body.input ?? {}, 'webmcp', access), - ) + const result = await runOp(op.name, body.input ?? {}, 'webmcp', access) return json({ result }) } catch (e) { return opError(e, request) @@ -311,15 +308,15 @@ export async function handleMcpApi(request: Request): Promise { )) as BodyInit) : undefined, }) - if (!session) return await cmsMcp.fetch(boundedRequest) + if (!session) { + return errorJson('UNAUTHORIZED', 'Unauthorized MCP request') + } const agent = accessContext({ session, mode: 'edit', agent: agentActorName('mcp', session), }) - return await runWithSession(session, () => - cmsMcp.fetch(boundedRequest, agent), - ) + return await cmsMcp.fetch(boundedRequest, agent) } catch (e) { return opError(e, request) } diff --git a/packages/api/src/mcp.ts b/packages/api/src/mcp.ts index 3952187c..ec32c614 100644 --- a/packages/api/src/mcp.ts +++ b/packages/api/src/mcp.ts @@ -16,7 +16,6 @@ import { getCmsConfig, hasPermission } from '@tanstack/cms-core' import { CMS_ACCESS_KEY, cmsTools, - currentSession, isMissingModule, missingPeer, } from '@tanstack/cms-core/server' @@ -83,13 +82,9 @@ export const cmsMcp = { /** * Serve one MCP request. Tools are listed for, and every call reads and * writes as, `access` (e.g. `accessContext({ session, agent: 'mcp', - * mode: 'edit' })`). Without it the session bound by `runWithSession` is - * used; that fallback is deprecated. + * mode: 'edit' })`). */ - fetch: async (request: Request, access?: AccessContext) => { - if (!access) { - return (await serverFor(getCmsConfig(), currentSession())).fetch(request) - } + fetch: async (request: Request, access: AccessContext) => { const server = await serverFor(getCmsConfig(), access.session) return server.handle(request, { context: { [CMS_ACCESS_KEY]: access } }) }, diff --git a/packages/api/src/media-ops.ts b/packages/api/src/media-ops.ts index 6e5206c7..f9fc01a9 100644 --- a/packages/api/src/media-ops.ts +++ b/packages/api/src/media-ops.ts @@ -21,11 +21,12 @@ import { loadTanstackAi, rateLimit, readMedia, - readDocumentWithPending, - readDocument, + readDocumentWithPendingAs, + readDocumentAs, redactFor, requirePermission, saveMedia, + systemContext, updateMediaItem, } from '@tanstack/cms-core/server' import { requireImageAdapter } from './ai' @@ -39,6 +40,9 @@ import { import type { CmsOpContext } from '@tanstack/cms-core' import type { AccessContext } from '@tanstack/cms-core/server' +/** Usage rows, checked against the caller's context below. */ +const USAGE_READ = systemContext('media usage: checked by the op') + async function readableMediaUsage( urlOrId: string, access: AccessContext, @@ -52,8 +56,13 @@ async function readableMediaUsage( usage .filter((item) => canReadCollection(access, item.collection)) .map(async (item) => { - const live = await readDocument(item.collection, item.id) - const pending = await readDocumentWithPending( + const live = await readDocumentAs( + USAGE_READ, + item.collection, + item.id, + ) + const pending = await readDocumentWithPendingAs( + USAGE_READ, item.collection, item.id, ) @@ -252,7 +261,12 @@ export const mediaOps = { const [, mime, b64] = match const item = await saveMedia( new Uint8Array(Buffer.from(b64 ?? '', 'base64')), - { hintMime: mime, filename: input.filename, alt: input.alt }, + { + hintMime: mime, + filename: input.filename, + alt: input.alt, + session: ctx.session, + }, ) return { url: item.url, item } }, diff --git a/packages/api/src/ops.ts b/packages/api/src/ops.ts index 7e43548b..50528055 100644 --- a/packages/api/src/ops.ts +++ b/packages/api/src/ops.ts @@ -55,10 +55,8 @@ import { restoreDocument, listAudit, listPending, - listRevisions, - listTranslations, - readDocument, - readDocumentWithPending, + listTranslationsAs, + readDocumentAs, readDocumentWithPendingAs, findDocumentBySlugAs, findReferencesAs, @@ -66,6 +64,7 @@ import { queryDocumentsAs, queryDocumentSummariesAs, accessContext, + systemContext, assertReadable, canReadCollection, canReadDocument, @@ -99,8 +98,6 @@ import { recordAdminAudit, resolveSession, restoreRevision, - runWithSession, - currentSession, } from '@tanstack/cms-core/server' import { aiCapabilities, requireTextAdapter } from './ai' import { mediaOps } from './media-ops' @@ -146,6 +143,12 @@ export interface CmsContext { access?: AccessContext } +/** + * Reads an op makes before deciding access: the op checks the caller's + * context against the result itself. + */ +const OP_READ = systemContext('admin op: checked by the op') + /** The header an HTTP caller narrows its read mode with. */ export const READ_MODE_HEADER = 'x-cms-read-mode' @@ -452,14 +455,18 @@ async function saveAsHuman( }, ) { const { session } = ctx - const existing = opts.create ? null : await readDocument(collection, id) + const existing = opts.create + ? null + : await readDocumentAs(OP_READ, collection, id) assertCollectionAccess( session, collection, existing ? 'update' : 'create', existing ?? doc, ) - const open = existing ? await readDocumentWithPending(collection, id) : null + const open = existing + ? await readDocumentWithPendingAs(OP_READ, collection, id) + : null // A re-save merges onto this door's own open change set; another door's is // refused by the strategy executor until it's resolved. const ownSource = canPublish(session, collection, existing ?? (doc as Doc)) @@ -585,8 +592,12 @@ const _ops = { run: async (input: z.infer, ctx: CmsOpContext) => { const access = editing(ctx) assertReadable(access, input.collection) - const result = await readDocumentWithPending(input.collection, input.id) - const live = await readDocument(input.collection, input.id) + const result = await readDocumentWithPendingAs( + OP_READ, + input.collection, + input.id, + ) + const live = await readDocumentAs(OP_READ, input.collection, input.id) if (live ?? result.doc) assertReadable(access, input.collection, { id: input.id, @@ -683,8 +694,12 @@ const _ops = { run: async (input: z.infer, ctx: CmsOpContext) => { const access = editing(ctx) assertReadable(access, input.collection) - const current = await readDocumentWithPending(input.collection, input.id) - const live = await readDocument(input.collection, input.id) + const current = await readDocumentWithPendingAs( + OP_READ, + input.collection, + input.id, + ) + const live = await readDocumentAs(OP_READ, input.collection, input.id) if (live ?? current.doc) assertReadable(access, input.collection, { id: input.id, @@ -692,7 +707,7 @@ const _ops = { }) const [revisions, translations, references] = await Promise.all([ listRevisionsAs(access, input.collection, input.id), - listTranslations(input.collection, input.id), + listTranslationsAs(OP_READ, input.collection, input.id), findReferencesAs(access, input.collection, input.id), ]) return { @@ -700,7 +715,11 @@ const _ops = { translations: ( await Promise.all( translations.map(async (translation) => { - const doc = await readDocument(input.collection, translation.id) + const doc = await readDocumentAs( + OP_READ, + input.collection, + translation.id, + ) if ( !doc || !canReadDocument(access, input.collection, { @@ -728,7 +747,8 @@ const _ops = { references .filter((r) => canReadCollection(access, r.collection)) .map(async (reference) => { - const doc = await readDocument( + const doc = await readDocumentAs( + OP_READ, reference.collection, reference.id, ) @@ -767,14 +787,18 @@ const _ops = { input: z.infer, ctx: CmsOpContext, ) => { - const current = await readDocumentWithPending(input.collection, input.id) - const live = await readDocument(input.collection, input.id) + const current = await readDocumentWithPendingAs( + OP_READ, + input.collection, + input.id, + ) + const live = await readDocumentAs(OP_READ, input.collection, input.id) const numericRevision = /^v?\d+$/.test(input.revisionId) ? Number(input.revisionId.replace(/^v/, '')) : null const historical = !live && !current.doc - ? (await listRevisions(input.collection, input.id)).find( + ? (await listRevisionsAs(OP_READ, input.collection, input.id)).find( (revision) => revision.id === input.revisionId || revision.revision === numericRevision, @@ -832,7 +856,7 @@ const _ops = { input: docRef, output: okOutput, run: async (input: z.infer, ctx: CmsOpContext) => { - const live = await readDocument(input.collection, input.id) + const live = await readDocumentAs(OP_READ, input.collection, input.id) assertCollectionAccess(ctx.session, input.collection, 'update', live) if (!canPublish(ctx.session, input.collection, live)) { throw new CmsError('Only publishers can discard drafts.', 'FORBIDDEN') @@ -860,7 +884,7 @@ const _ops = { ) } const existing = ( - await readDocumentWithPending(input.collection, input.id) + await readDocumentWithPendingAs(OP_READ, input.collection, input.id) ).doc if (existing) { throw new CmsError( @@ -886,8 +910,12 @@ const _ops = { input: deleteDocInput, output: okOutput, run: async (input: z.infer, ctx: CmsOpContext) => { - const current = await readDocumentWithPending(input.collection, input.id) - const live = await readDocument(input.collection, input.id) + const current = await readDocumentWithPendingAs( + OP_READ, + input.collection, + input.id, + ) + const live = await readDocumentAs(OP_READ, input.collection, input.id) assertCollectionAccess( ctx.session, input.collection, @@ -912,7 +940,7 @@ const _ops = { input: docRef, output: okOutput, run: async (input: z.infer, ctx: CmsOpContext) => { - const live = await readDocument(input.collection, input.id) + const live = await readDocumentAs(OP_READ, input.collection, input.id) assertCollectionAccess(ctx.session, input.collection, 'delete', live) await restoreDocument(input.collection, input.id, { session: ctx.session, @@ -931,8 +959,12 @@ const _ops = { input: purgeDocInput, output: okOutput, run: async (input: z.infer, ctx: CmsOpContext) => { - const current = await readDocumentWithPending(input.collection, input.id) - const live = await readDocument(input.collection, input.id) + const current = await readDocumentWithPendingAs( + OP_READ, + input.collection, + input.id, + ) + const live = await readDocumentAs(OP_READ, input.collection, input.id) assertCollectionAccess( ctx.session, input.collection, @@ -973,7 +1005,7 @@ const _ops = { for (const id of [...new Set(input.ids)]) { try { if (action === 'delete' || action === 'purge') { - const live = await readDocument(collection, id) + const live = await readDocumentAs(OP_READ, collection, id) assertCollectionAccess(ctx.session, collection, 'delete', live) await deleteDocument(collection, id, { session: ctx.session, @@ -982,7 +1014,7 @@ const _ops = { purge: action === 'purge', }) } else if (action === 'restore') { - const live = await readDocument(collection, id) + const live = await readDocumentAs(OP_READ, collection, id) assertCollectionAccess(ctx.session, collection, 'delete', live) await restoreDocument(collection, id, { session: ctx.session, @@ -993,12 +1025,12 @@ const _ops = { // Publishing takes the latest draft; unpublishing keeps the live content. const current = action === 'publish' - ? (await readDocumentWithPending(collection, id)).doc - : await readDocument(collection, id) + ? (await readDocumentWithPendingAs(OP_READ, collection, id)).doc + : await readDocumentAs(OP_READ, collection, id) if (!current) { throw new CmsError(`Document not found: ${id}`, 'NOT_FOUND') } - const live = await readDocument(collection, id) + const live = await readDocumentAs(OP_READ, collection, id) assertCollectionAccess( ctx.session, collection, @@ -1041,7 +1073,7 @@ const _ops = { description: 'Propose an AI field edit (returns, does not save).', input: proposeEditInput, run: async (input: z.infer, ctx: CmsOpContext) => { - const live = await readDocument(input.collection, input.id) + const live = await readDocumentAs(OP_READ, input.collection, input.id) assertCollectionAccess( ctx.session, input.collection, @@ -1136,9 +1168,18 @@ const _ops = { ) .map(async (entry) => { const doc = - (await readDocument(entry.collection, entry.docId)) ?? - (await listRevisions(entry.collection, entry.docId))[0] - ?.doc ?? + (await readDocumentAs( + OP_READ, + entry.collection, + entry.docId, + )) ?? + ( + await listRevisionsAs( + OP_READ, + entry.collection, + entry.docId, + ) + )[0]?.doc ?? null return canReadDocument(access, entry.collection, { id: entry.docId, @@ -1166,7 +1207,11 @@ const _ops = { const pending = await getPending(input.id) if (!pending) throw new CmsError(`Unknown pending change: ${input.id}`, 'NOT_FOUND') - const live = await readDocument(pending.collection, pending.docId) + const live = await readDocumentAs( + OP_READ, + pending.collection, + pending.docId, + ) if (!hasPermission(ctx.session, 'content.publish')) { // The strategy decides what a non-publishing reviewer's approval // does; core re-checks access if it writes live content. @@ -1221,7 +1266,7 @@ const _ops = { assertReadable(access, pending.collection, { id: pending.docId, doc: - (await readDocument(pending.collection, pending.docId)) ?? + (await readDocumentAs(OP_READ, pending.collection, pending.docId)) ?? pending.before ?? pending.after, }) @@ -1260,7 +1305,7 @@ const _ops = { assertReadable(access, pending.collection, { id: pending.docId, doc: - (await readDocument(pending.collection, pending.docId)) ?? + (await readDocumentAs(OP_READ, pending.collection, pending.docId)) ?? pending.before ?? pending.after, }) @@ -1330,11 +1375,15 @@ const _ops = { ctx: CmsOpContext, ) => { const colName = input.collection ?? 'page' - const live = await readDocument(colName, input.id) + const live = await readDocumentAs(OP_READ, colName, input.id) assertCollectionAccess(ctx.session, colName, 'update', live) const adapter = await requireTextAdapter('The on-page agent') const blocksFieldName = resolveBlocksField(colName, input.blocksField) - const { doc } = await readDocumentWithPending(colName, input.id) + const { doc } = await readDocumentWithPendingAs( + OP_READ, + colName, + input.id, + ) if (!doc) throw new CmsError(`No ${colName} with id "${input.id}".`, 'NOT_FOUND') const readable = redactFor(ctx.access, colName, doc) @@ -1478,7 +1527,11 @@ const _ops = { ) => { const colName = input.collection ?? 'page' const blocksFieldName = resolveBlocksField(colName, input.blocksField) - const { doc } = await readDocumentWithPending(colName, input.id) + const { doc } = await readDocumentWithPendingAs( + OP_READ, + colName, + input.id, + ) if (!doc) throw new CmsError(`No ${colName} with id "${input.id}".`, 'NOT_FOUND') const saved = await saveAsHuman( @@ -1506,8 +1559,8 @@ const _ops = { description: 'Create an API key for an agent or integration, optionally limited to collections. The key is shown once.', input: createApiKeyInput, - run: async (input: z.infer) => - createApiKey(input), + run: async (input: z.infer, ctx: CmsOpContext) => + createApiKey(input, { session: ctx.session }), }, revokeApiKey: { @@ -1516,8 +1569,11 @@ const _ops = { description: 'Revoke an API key.', input: revokeApiKeyInput, output: okOutput, - run: async (input: z.infer) => ({ - ok: await revokeApiKey(input.id), + run: async ( + input: z.infer, + ctx: CmsOpContext, + ) => ({ + ok: await revokeApiKey(input.id, { session: ctx.session }), }), }, @@ -1533,9 +1589,11 @@ const _ops = { ) => { // Minting a preview link requires the right to read the document (and, as // the editor affordance, to write it). Scope the check to this document. - const live = await readDocument(input.collection, input.id) + const live = await readDocumentAs(OP_READ, input.collection, input.id) const current = - live ?? (await readDocumentWithPending(input.collection, input.id)).doc + live ?? + (await readDocumentWithPendingAs(OP_READ, input.collection, input.id)) + .doc if (!current) { throw new CmsError( `No ${input.collection} with id "${input.id}".`, @@ -1623,9 +1681,13 @@ const _ops = { description: 'Map an external user (by id and/or email) to a CMS role, optionally scoped to collections. Creates or updates the mapping.', input: setUserRoleInput, - run: async (input: z.infer) => { + run: async (input: z.infer, ctx: CmsOpContext) => { const result = await setUserRole(input) - await recordAdminAudit({ action: 'auth.role.set', target: result.id }) + await recordAdminAudit({ + action: 'auth.role.set', + target: result.id, + session: ctx.session, + }) return result }, }, @@ -1636,12 +1698,16 @@ const _ops = { description: 'Remove a user→role mapping by id.', input: removeUserRoleInput, output: okOutput, - run: async (input: z.infer) => { + run: async ( + input: z.infer, + ctx: CmsOpContext, + ) => { const ok = await removeUserRole(input.id) if (ok) await recordAdminAudit({ action: 'auth.role.removed', target: input.id, + session: ctx.session, }) return { ok } }, @@ -1662,11 +1728,12 @@ const _ops = { description: 'Create or invite a DB-auth user. With a password the account is active; without one an invite token is returned once.', input: createUserInput, - run: async (input: z.infer) => { + run: async (input: z.infer, ctx: CmsOpContext) => { const result = await createDbUser(input) await recordAdminAudit({ action: result.inviteToken ? 'auth.user.invited' : 'auth.user.created', target: result.user.id, + session: ctx.session, }) return result }, @@ -1678,12 +1745,16 @@ const _ops = { description: 'Enable or disable a DB-auth user.', input: setUserDisabledInput, output: okOutput, - run: async (input: z.infer) => { + run: async ( + input: z.infer, + ctx: CmsOpContext, + ) => { const ok = await setDbUserDisabled(input.id, input.disabled) if (ok) await recordAdminAudit({ action: input.disabled ? 'auth.user.disabled' : 'auth.user.enabled', target: input.id, + session: ctx.session, }) return { ok } }, @@ -1817,12 +1888,9 @@ async function runResolved( if (op.access !== 'public') await requirePermission(op.access, session) if (op.access === 'agent.use') await rateLimit('ai', ctx.request, session) const actor = ctx.actor ?? 'human' - // The session stays bound for code that still reads `currentSession()`. - return runWithSession(session, () => - op.agent - ? runOp(op.name, input, actor, access) - : op.run(input, { request: ctx.request, session, actor, access }), - ) + return op.agent + ? runOp(op.name, input, actor, access) + : op.run(input, { request: ctx.request, session, actor, access }) } /** @@ -2058,9 +2126,8 @@ async function executeAgentChat( * Run a named agent (`defineCms({ ai: { agents } })`) or the default content * agent (`name` undefined) from server code (e.g. an event handler) without an * HTTP hop. The agent acts as `options.access` (an `accessContext`, or a - * `systemContext` for a trusted job), else `options.session`, else the - * session bound by `runWithSession`, else a local admin session; its tools - * enforce that context's access and stage writes. + * `systemContext` for a trusted job), else `options.session`, else a local + * admin session; its tools enforce that context's access and stage writes. */ export async function runAgent( name: string | undefined, @@ -2072,24 +2139,19 @@ export async function runAgent( }, ): Promise<{ reply: string; toolResults?: Array }> { const session = - options?.access?.session ?? - options?.session ?? - currentSession() ?? - DEFAULT_UNCONFIGURED_SESSION + options?.access?.session ?? options?.session ?? DEFAULT_UNCONFIGURED_SESSION const access = options?.access ?? accessContext({ session, mode: 'edit' }) const actor = (name ? getCmsConfig().ai?.agents?.[name]?.actor : undefined) ?? name ?? 'content-agent' - return runWithSession(session, () => - executeAgentChat( - { - ...(name ? { agent: name } : {}), - messages, - includeToolResults: options?.includeToolResults, - }, - { session, actor, access }, - ), + return executeAgentChat( + { + ...(name ? { agent: name } : {}), + messages, + includeToolResults: options?.includeToolResults, + }, + { session, actor, access }, ) } diff --git a/packages/api/tests/access.test.ts b/packages/api/tests/access.test.ts index 0e6a589d..d5b6278c 100644 --- a/packages/api/tests/access.test.ts +++ b/packages/api/tests/access.test.ts @@ -2,7 +2,11 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { PERMISSIONS } from '@tanstack/cms-core' -import { commitDocument, readDocument } from '@tanstack/cms-core/server' +import { + commitDocument, + systemContext, + readDocumentAs, +} from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { ops } from '../src/ops' import { cleanup, cookieAuth, req, setupCms } from './helpers' @@ -222,7 +226,9 @@ describe('roles', () => { ) expect(authored.status).toBe(200) expect((authored.result as { staged: boolean }).staged).toBe(true) - expect((await readDocument('post', 'hello'))?.title).toBe('Hello') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'hello'))?.title, + ).toBe('Hello') expect( ( await call( @@ -244,7 +250,9 @@ describe('roles', () => { { role: 'editor' }, ) expect((edited.result as { staged: boolean }).staged).toBe(false) - expect((await readDocument('post', 'hello'))?.title).toBe('By editor') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'hello'))?.title, + ).toBe('By editor') }) it('customers (no CMS role) get nothing beyond public content', async () => { @@ -318,7 +326,7 @@ describe('collection and field access', () => { }, { role: 'editor' }, ) - const stored = await readDocument('post', 'hello') + const stored = await readDocumentAs(systemContext('test'), 'post', 'hello') expect(stored?.title).toBe('Edited') expect(stored?.internalNotes).toBe('secret') @@ -399,7 +407,9 @@ describe('collection and field access', () => { ) expect(restored.status).toBe(200) expect(JSON.stringify(restored.result)).not.toContain('secret-v') - expect((await readDocument('post', 'p1'))?.adminOnly).toBe('secret-v2') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.adminOnly, + ).toBe('secret-v2') }) it('filters inbound references in getDocEditorMeta, media usage in getMediaUsage, and blocks sorting on hidden fields in listDocumentSummaries', async () => { @@ -566,7 +576,11 @@ describe('collection and field access', () => { { role: 'editor' }, ) expect(savedBlocks.status).toBe(200) - const afterSave = await readDocument('page', 'home') + const afterSave = await readDocumentAs( + systemContext('test'), + 'page', + 'home', + ) expect(afterSave?.title).toBe('Draft Title') }) }) @@ -720,7 +734,7 @@ describe('MCP', () => { arguments: { collection: 'post', id: 'x', doc: { title: 'X' } }, }) expect(write.text).toMatch(/content\.write|Forbidden|not found/) - expect(await readDocument('post', 'x')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'x')).toBeNull() }) it('proposing a delete or unpublish needs delete / publish rights', async () => { diff --git a/packages/api/tests/act-on-change.test.ts b/packages/api/tests/act-on-change.test.ts index c507e62c..e76348bf 100644 --- a/packages/api/tests/act-on-change.test.ts +++ b/packages/api/tests/act-on-change.test.ts @@ -1,6 +1,10 @@ import { afterEach, describe, expect, it } from 'vitest' import { commit, defineCms, discard, publish, stage } from '@tanstack/cms-core' -import { closeStore, readDocument } from '@tanstack/cms-core/server' +import { + closeStore, + readDocumentAs, + systemContext, +} from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { cleanup, cookieAuth, req, setupCms } from './helpers' import type { DocumentStateStrategy } from '@tanstack/cms-core' @@ -111,7 +115,9 @@ describe('the review queue and actOnChange', () => { 'reviewer', ), ).toMatchObject({ status: 200 }) - expect(await readDocument('post', 'pitch')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'pitch'), + ).toBeNull() const [approved] = (await call('reviewSnapshot', {}, 'editor')).result .pending expect(approved.review).toMatchObject({ @@ -133,7 +139,9 @@ describe('the review queue and actOnChange', () => { expect( await call('actOnChange', { id: pitch.id, action: 'publish' }, 'editor'), ).toMatchObject({ status: 200, result: { label: 'Published' } }) - expect(await readDocument('post', 'pitch')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'pitch'), + ).toMatchObject({ title: 'Pitch', published: true, }) @@ -164,7 +172,9 @@ describe('the review queue and actOnChange', () => { ) ).code, ).toBe('CONFLICT') - expect(await readDocument('post', 'pitch')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'pitch'), + ).toBeNull() const signed = await call( 'actOnChange', @@ -175,7 +185,9 @@ describe('the review queue and actOnChange', () => { status: 200, result: { ok: true, effects: ['commit', 'publish'], label: 'Live' }, }) - expect(await readDocument('post', 'pitch')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'pitch'), + ).toMatchObject({ title: 'Pitch', published: true, }) diff --git a/packages/api/tests/bulk.test.ts b/packages/api/tests/bulk.test.ts index 46daeb47..62f08dd0 100644 --- a/packages/api/tests/bulk.test.ts +++ b/packages/api/tests/bulk.test.ts @@ -1,5 +1,9 @@ import { afterEach, describe, expect, it } from 'vitest' -import { commitDocument, readDocument } from '@tanstack/cms-core/server' +import { + commitDocument, + systemContext, + readDocumentAs, +} from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { cleanup, req, setupCms } from './helpers' @@ -47,8 +51,12 @@ describe('bulkDocuments', () => { error: expect.objectContaining({ code: 'NOT_FOUND' }), }, ]) - expect((await readDocument('post', 'a'))?.published).toBe(true) - expect((await readDocument('post', 'b'))?.published).toBe(true) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.published, + ).toBe(true) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'b'))?.published, + ).toBe(true) }) it('publishing takes the pending draft of a live document', async () => { @@ -58,13 +66,17 @@ describe('bulkDocuments', () => { id: 'c', doc: { title: 'C draft', published: true }, }) - expect((await readDocument('post', 'c'))?.title).toBe('C') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'c'))?.title, + ).toBe('C') await call('bulkDocuments', { collection: 'post', ids: ['c'], action: 'publish', }) - expect((await readDocument('post', 'c'))?.title).toBe('C draft') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'c'))?.title, + ).toBe('C draft') }) it('unpublishes and deletes', async () => { @@ -74,15 +86,17 @@ describe('bulkDocuments', () => { ids: ['c'], action: 'unpublish', }) - expect((await readDocument('post', 'c'))?.published).toBe(false) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'c'))?.published, + ).toBe(false) const del = await call( 'bulkDocuments', { collection: 'post', ids: ['a', 'b'], action: 'delete' }, 'admin', ) expect(del.result.ok).toBe(true) - expect(await readDocument('post', 'a')).toBeNull() - expect(await readDocument('post', 'b')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'a')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'b')).toBeNull() }) it('requires publish rights for publish and delete rights for delete', async () => { @@ -99,7 +113,9 @@ describe('bulkDocuments', () => { 'viewer', ) expect(asViewer.status).toBe(403) - expect((await readDocument('post', 'a'))?.published).toBe(false) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.published, + ).toBe(false) }) }) diff --git a/packages/api/tests/characterization/save-paths.test.ts b/packages/api/tests/characterization/save-paths.test.ts index 362a4e06..9e7124b1 100644 --- a/packages/api/tests/characterization/save-paths.test.ts +++ b/packages/api/tests/characterization/save-paths.test.ts @@ -27,9 +27,11 @@ import { commitDocument, listAudit, listPending, - listRevisions, - readDocument, - readDocumentBySlug, + publicContext, + systemContext, + readDocumentBySlugAs, + listRevisionsAs, + readDocumentAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../../src/http' import { writeOutput } from '../../src/outputs' @@ -83,7 +85,7 @@ async function seed(extra: Partial = {}) { } const liveTitle = async (id: string) => - (await readDocumentBySlug('post', id, { publishedOnly: true }))?.doc.title + (await readDocumentBySlugAs(publicContext(), 'post', id))?.doc.title describe('saveAsHuman: publisher (editor holds content.publish)', () => { it('createDoc commits: { ok, staged: false, doc } with no pendingId; revision "Created document"', async () => { @@ -96,7 +98,9 @@ describe('saveAsHuman: publisher (editor holds content.publish)', () => { expect(Object.keys(out).sort()).toEqual(['doc', 'ok', 'staged']) expect(out).toMatchObject({ ok: true, staged: false }) expect(out.doc).toMatchObject({ title: 'New', _revision: 1 }) - expect((await listRevisions('post', 'new'))[0]).toMatchObject({ + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'new'))[0], + ).toMatchObject({ actor: 'human', summary: 'Created document', }) @@ -179,7 +183,9 @@ describe('saveAsHuman: publisher (editor holds content.publish)', () => { expect(Object.keys(out).sort()).toEqual(['doc', 'ok', 'staged']) expect(await listPending()).toEqual([]) expect(await liveTitle('live')).toBe('Final') - expect((await readDocument('post', 'live'))?._revision).toBe(2) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'live'))?._revision, + ).toBe(2) }) it('saveDoc with published: false on a published doc commits the unpublish immediately', async () => { @@ -215,7 +221,9 @@ describe('saveAsHuman: publisher (editor holds content.publish)', () => { 'editor', ) expect(out).toMatchObject({ staged: true, pendingId: expect.any(String) }) - expect(await readDocument('post', 'new')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'new'), + ).toBeNull() }) it('bulkDocuments publish commits the latest draft; unpublish keeps the live content', async () => { @@ -243,15 +251,17 @@ describe('saveAsHuman: publisher (editor holds content.publish)', () => { expect(await liveTitle('live')).toBe('Drafted') expect(await liveTitle('wip')).toBe('WIP') expect(await listPending()).toEqual([]) - expect((await listRevisions('post', 'wip'))[0]?.summary).toBe( - 'Bulk publish', - ) + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'wip'))[0]?.summary, + ).toBe('Bulk publish') await call( 'bulkDocuments', { collection: 'post', ids: ['live'], action: 'unpublish' }, 'editor', ) - expect(await readDocument('post', 'live')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'live'), + ).toMatchObject({ title: 'Drafted', published: false, }) @@ -292,7 +302,9 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => { instruction: 'Created document', }), ]) - expect(await readDocument('post', 'new')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'new'), + ).toBeNull() }) it('saveDoc on a published doc stages (not a draft); live unchanged; the review queue shows it', async () => { @@ -319,7 +331,9 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => { 'author', ) expect(out.staged).toBe(true) - expect((await readDocument('post', 'wip'))?.title).toBe('WIP') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'wip'))?.title, + ).toBe('WIP') }) it('a second author save coalesces into the same pendingId, merged onto the open proposal', async () => { @@ -383,7 +397,9 @@ describe('saveAsHuman: author (no content.publish) stages for review', () => { }) expect(out.pendingId).toBeUndefined() expect(await listPending()).toEqual([]) - expect((await readDocument('post', 'wip'))?.title).toBe('Auto') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'wip'))?.title, + ).toBe('Auto') expect((await listAudit())[0]).toMatchObject({ actor: 'human (approved by auto-approve)', decision: 'approved', @@ -494,7 +510,9 @@ describe('review decisions over HTTP', () => { { id: proposal.pendingId, publish: false }, 'editor', ) - expect(await readDocument('post', 'live')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'live'), + ).toMatchObject({ title: 'Author edit', published: false, }) diff --git a/packages/api/tests/contract/s2-propagation.test.ts b/packages/api/tests/contract/s2-propagation.test.ts index 0d6b94d7..24ce2741 100644 --- a/packages/api/tests/contract/s2-propagation.test.ts +++ b/packages/api/tests/contract/s2-propagation.test.ts @@ -13,7 +13,8 @@ import { import { closeStore, commitDocument, - queryDocumentSummaries, + systemContext, + queryDocumentSummariesAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../../src/http' import { buildOpenApiDocument } from '../../src/openapi' @@ -134,7 +135,7 @@ describe('Seam S2 — One schema definition propagates to all five downstream su expect(JSON.stringify(openApi)).toContain('post') // Surface 5: Search index (FTS query matches the new field value) - const searchResult = await queryDocumentSummaries({ + const searchResult = await queryDocumentSummariesAs(systemContext('test'), { collection: 'post', search: 'ReykjavikAurora', columns: ['title', 'locationTag'], diff --git a/packages/api/tests/contract/s3-s5-contract.test.ts b/packages/api/tests/contract/s3-s5-contract.test.ts index 21de1d3f..27c40fef 100644 --- a/packages/api/tests/contract/s3-s5-contract.test.ts +++ b/packages/api/tests/contract/s3-s5-contract.test.ts @@ -6,7 +6,8 @@ import { importContent, listAudit, listPending, - readDocument, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../../src/http' import { invokeAnyOp } from '../../src/ops' @@ -203,13 +204,19 @@ describe('Seam S3 — Every write passes Governance (four-way staging & attribut expect(entry.after.title).toBe('Proposed Title') expect(entry.after.views).toBe(10) // None is visible to readers before approval - expect(await readDocument('article', id)).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'article', id), + ).toBeNull() } // Approve one change and verify it becomes visible and audited const approvedId = byDocId.get('via-mcp-tool')!.id await approve(approvedId, { approver: 'reviewer-1' }) - const committed = await readDocument('article', 'via-mcp-tool') + const committed = await readDocumentAs( + systemContext('test'), + 'article', + 'via-mcp-tool', + ) expect(committed?.title).toBe('Proposed Title') const audit = await listAudit() expect( @@ -318,7 +325,13 @@ describe.each(['in-process', 'http-client', 'mcp'])( expect(pending).toHaveLength(1) expect(pending[0]?.docId).toBe(`doc-${transport}`) expect(pending[0]?.after.title).toBe(`Hello from ${transport}`) - expect(await readDocument('article', `doc-${transport}`)).toBeNull() + expect( + await readDocumentAs( + systemContext('test'), + 'article', + `doc-${transport}`, + ), + ).toBeNull() }) it('rejects validation errors (wrong field type) and stages nothing', async () => { diff --git a/packages/api/tests/ops.test.ts b/packages/api/tests/ops.test.ts index 59d60ff5..33e044af 100644 --- a/packages/api/tests/ops.test.ts +++ b/packages/api/tests/ops.test.ts @@ -1,5 +1,9 @@ import { afterEach, describe, expect, it } from 'vitest' -import { commitDocument, readDocument } from '@tanstack/cms-core/server' +import { + commitDocument, + systemContext, + readDocumentAs, +} from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { cleanup, req, setupCms } from './helpers' @@ -218,7 +222,9 @@ describe('writing', () => { 'author', ) expect(res.result).toMatchObject({ ok: true, staged: true }) - expect(await readDocument('post', 'pitch')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'pitch'), + ).toBeNull() }) it('restores an earlier revision', async () => { @@ -269,7 +275,9 @@ describe('writing', () => { 'admin', ) expect(forced.status).toBe(200) - expect(await readDocument('author', 'ada')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'author', 'ada'), + ).toBeNull() expect( (await call('deleteDoc', { collection: 'post', id: 'live' }, 'author')) .code, @@ -284,9 +292,9 @@ describe('writing', () => { 'editor', ) expect(res.result).toEqual({ ok: true, staged: false }) - expect((await readDocument('page', 'home'))?.blocks).toEqual([ - { _type: 'hero', heading: 'Hello' }, - ]) + expect( + (await readDocumentAs(systemContext('test'), 'page', 'home'))?.blocks, + ).toEqual([{ _type: 'hero', heading: 'Hello' }]) expect( (await call('savePageBlocks', { id: 'missing', blocks: [] }, 'editor')) .code, @@ -323,11 +331,15 @@ describe('review queue', () => { expect( (await call('approveChange', { id: edit.id }, 'editor')).status, ).toBe(200) - expect((await readDocument('post', 'draft'))?.title).toBe('Author edit') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'draft'))?.title, + ).toBe('Author edit') expect( (await call('rejectChange', { id: create.id }, 'editor')).status, ).toBe(200) - expect(await readDocument('post', 'pitch')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'pitch'), + ).toBeNull() expect((await call('rejectChange', { id: 'nope' }, 'editor')).code).toBe( 'NOT_FOUND', ) diff --git a/packages/api/tests/readiness.test.ts b/packages/api/tests/readiness.test.ts index d1addce3..919adbf4 100644 --- a/packages/api/tests/readiness.test.ts +++ b/packages/api/tests/readiness.test.ts @@ -5,10 +5,11 @@ import { createSqliteStorage } from '@tanstack/cms-core/storage' import { closeStore, commitDocument, - readDocument, stageWrite, - listRevisions, saveMedia, + systemContext, + readDocumentAs, + listRevisionsAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { invokeAnyOp } from '../src/ops' @@ -444,7 +445,9 @@ describe('1.0 request invariants', () => { }, context, ) - expect(await readDocument('post', 'one')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'one'), + ).toMatchObject({ title: 'Partial', owner: 'Draft owner', published: true, @@ -488,7 +491,9 @@ describe('1.0 request invariants', () => { { id: staged.pendingId, force: true, publish: true }, { request: req('/', { role: 'editor' }) }, ) - expect(await readDocument('post', 'one')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'one'), + ).toMatchObject({ title: 'Author proposal', secret: 'second', }) @@ -509,7 +514,9 @@ describe('1.0 request invariants', () => { { collection: 'post', id: 'mine', revisionId: history.revisions[0]!.id }, context, ) - expect(await readDocument('post', 'mine')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'mine'), + ).toMatchObject({ title: 'Mine', owner: 'u-editor', }) @@ -521,7 +528,9 @@ describe('1.0 request invariants', () => { title: 'Other owner private', owner: 'other', }) - const older = (await listRevisions('post', 'one'))[0]! + const older = ( + await listRevisionsAs(systemContext('test'), 'post', 'one') + )[0]! await commitDocument('post', 'one', { title: 'Now mine', owner: 'u-editor', @@ -533,7 +542,9 @@ describe('1.0 request invariants', () => { { request: req('/', { role: 'editor' }) }, ), ).rejects.toMatchObject({ code: 'FORBIDDEN' }) - expect((await readDocument('post', 'one'))?.title).toBe('Now mine') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'one'))?.title, + ).toBe('Now mine') }) it('rejects non-ASCII JSON over the byte limit', async () => { diff --git a/packages/api/tests/soft-delete.test.ts b/packages/api/tests/soft-delete.test.ts index 16f45866..c58336d8 100644 --- a/packages/api/tests/soft-delete.test.ts +++ b/packages/api/tests/soft-delete.test.ts @@ -1,8 +1,9 @@ import { afterEach, describe, expect, it } from 'vitest' import { commitDocument, - readDocument, readTrashedDocument, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { cleanup, req, setupCms } from './helpers' @@ -50,7 +51,7 @@ describe('soft delete / trash / restore / purge', () => { (await call('deleteDoc', { collection: 'post', id: 'a' })).status, ).toBe(200) // Gone from normal reads, retained in the trash. - expect(await readDocument('post', 'a')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'a')).toBeNull() expect(await readTrashedDocument('post', 'a')).not.toBeNull() const live = await callGet('listDocumentSummaries', { collection: 'post' }) @@ -70,7 +71,9 @@ describe('soft delete / trash / restore / purge', () => { expect( (await call('restoreDoc', { collection: 'post', id: 'a' })).status, ).toBe(200) - expect(await readDocument('post', 'a')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'a'), + ).not.toBeNull() expect(await readTrashedDocument('post', 'a')).toBeNull() }) @@ -106,7 +109,9 @@ describe('soft delete / trash / restore / purge', () => { action: 'restore', }) expect(restored.result.ok).toBe(true) - expect(await readDocument('post', 'a')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'a'), + ).not.toBeNull() expect(await readTrashedDocument('post', 'b')).not.toBeNull() const purged = await call('bulkDocuments', { diff --git a/packages/api/tests/workflow.test.ts b/packages/api/tests/workflow.test.ts index 46521ab2..16388f0f 100644 --- a/packages/api/tests/workflow.test.ts +++ b/packages/api/tests/workflow.test.ts @@ -3,8 +3,9 @@ import { commitDocument, onCmsEvent, runScheduledPublishing, - readDocument, stageWrite, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '../src/http' import { cleanup, moveLiveUnder, req, setupCms } from './helpers' @@ -46,7 +47,9 @@ describe('drafts of published documents', () => { }) expect(saved.status).toBe(200) expect(saved.result).toMatchObject({ draft: true, staged: false }) - expect((await readDocument('post', 'live'))?.title).toBe('Live') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'live'))?.title, + ).toBe('Live') const editing = await call('getDocument', { collection: 'post', @@ -76,7 +79,9 @@ describe('drafts of published documents', () => { publish: true, }) expect(published.result).toMatchObject({ staged: false }) - expect((await readDocument('post', 'live'))?.title).toBe('Final title') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'live'))?.title, + ).toBe('Final title') const editing = await call('getDocument', { collection: 'post', id: 'live', @@ -91,7 +96,9 @@ describe('drafts of published documents', () => { id: 'live', doc: { title: 'Live', published: false }, }) - expect((await readDocument('post', 'live'))?.published).toBe(false) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'live'))?.published, + ).toBe(false) }) it('unpublished documents commit directly', async () => { @@ -102,7 +109,9 @@ describe('drafts of published documents', () => { doc: { title: 'WIP 2', published: false }, }) expect(saved.result.draft).toBeUndefined() - expect((await readDocument('post', 'wip'))?.title).toBe('WIP 2') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'wip'))?.title, + ).toBe('WIP 2') }) it('discardDraft restores the live version for editing', async () => { @@ -131,7 +140,8 @@ describe('drafts of published documents', () => { it('stale drafts are rejected by optimistic concurrency', async () => { await seed() - const rev = (await readDocument('post', 'live'))?._revision as number + const rev = (await readDocumentAs(systemContext('test'), 'post', 'live')) + ?._revision as number await commitDocument('post', 'live', { title: 'Someone else', published: true, @@ -162,11 +172,15 @@ describe('approving stale proposals', () => { const stale = await call('approveChange', { id: pending.id }) expect(stale.status).toBe(409) expect(stale.code).toBe('CONFLICT') - expect((await readDocument('post', 'wip'))?.title).toBe('Human') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'wip'))?.title, + ).toBe('Human') const forced = await call('approveChange', { id: pending.id, force: true }) expect(forced.status).toBe(200) - expect((await readDocument('post', 'wip'))?.title).toBe('Agent') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'wip'))?.title, + ).toBe('Agent') }) }) @@ -189,10 +203,16 @@ describe('scheduled unpublish', () => { }) await runScheduledPublishing() off() - const expired = await readDocument('post', 'expiring') + const expired = await readDocumentAs( + systemContext('test'), + 'post', + 'expiring', + ) expect(expired?.published).toBe(false) expect(expired?.unpublishAt).toBeUndefined() - expect((await readDocument('post', 'later'))?.published).toBe(true) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'later'))?.published, + ).toBe(true) expect(events).toEqual(['expiring']) }) }) diff --git a/packages/cli/src/commands/atproto.ts b/packages/cli/src/commands/atproto.ts index 7394e458..86cf1622 100644 --- a/packages/cli/src/commands/atproto.ts +++ b/packages/cli/src/commands/atproto.ts @@ -129,9 +129,13 @@ export async function atprotoCommand( return 1 } try { - const doc = await core.readDocument(collection, id) + const doc = await core.readDocumentAs( + core.publicContext(), + collection, + id, + ) if (!doc) { - io.error(`Document not found: ${collection}/${id}`) + io.error(`No published document: ${collection}/${id}`) return 1 } const client = await makeClient() diff --git a/packages/cli/tests/cli.test.ts b/packages/cli/tests/cli.test.ts index daea87d3..7221e670 100644 --- a/packages/cli/tests/cli.test.ts +++ b/packages/cli/tests/cli.test.ts @@ -551,7 +551,7 @@ describe('tanstack-cms atproto command', () => { missing, ), ).toBe(1) - expect(missing.err).toEqual(['Document not found: post/nope']) + expect(missing.err).toEqual(['No published document: post/nope']) const badConfig = capture() expect( diff --git a/packages/client/tests/db.test.ts b/packages/client/tests/db.test.ts index c8b1a24c..71ad1ad4 100644 --- a/packages/client/tests/db.test.ts +++ b/packages/client/tests/db.test.ts @@ -17,7 +17,8 @@ import { defineCms } from '@tanstack/cms-core' import { closeStore, commitDocument, - readDocument, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '@tanstack/cms-api' import { createCmsClient } from '../src/index' @@ -240,7 +241,9 @@ describe('createCmsCollectionOptions', () => { doc.title = 'Stale edit' }).isPersisted.promise, ).rejects.toMatchObject({ code: 'CONFLICT' }) - expect((await readDocument('post', 'a'))?.title).toBe('Other editor') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.title, + ).toBe('Other editor') }) it('streams SSE events from /api/cms/v1/events and invalidates queryClient in live mode', async () => { diff --git a/packages/core/bench/store.ts b/packages/core/bench/store.ts index d0eec658..845ec7a7 100644 --- a/packages/core/bench/store.ts +++ b/packages/core/bench/store.ts @@ -18,11 +18,13 @@ import { closeStore, commitDocument, exportContent, - findDocumentBySlug, importContent, - queryDocumentSummaries, - queryDocuments, - readDocument, + publicContext, + systemContext, + readDocumentAs, + queryDocumentSummariesAs, + queryDocumentsAs, + findDocumentBySlugAs, } from '../src/server' import type { CmsExportDocument } from '../src/server' @@ -156,12 +158,14 @@ async function run(size: number): Promise> { ) record( 'read by id', - await time(1000, (i) => readDocument('post', `post-${pick(i)}`)), + await time(1000, (i) => + readDocumentAs(systemContext('test'), 'post', `post-${pick(i)}`), + ), ) record( 'list page 1 (updatedAt desc)', await time(50, () => - queryDocumentSummaries({ + queryDocumentSummariesAs(systemContext('test'), { collection: 'post', sort: { field: 'updatedAt', dir: 'desc' }, limit: 25, @@ -172,7 +176,7 @@ async function run(size: number): Promise> { record( 'list page 1 (title asc)', await time(50, () => - queryDocumentSummaries({ + queryDocumentSummariesAs(systemContext('test'), { collection: 'post', sort: { field: 'title', dir: 'asc' }, limit: 25, @@ -183,7 +187,7 @@ async function run(size: number): Promise> { record( 'list search', await time(20, (i) => - queryDocumentSummaries({ + queryDocumentSummariesAs(systemContext('test'), { collection: 'post', search: WORDS[i % WORDS.length], limit: 25, @@ -194,7 +198,7 @@ async function run(size: number): Promise> { record( 'list published filter', await time(50, () => - queryDocumentSummaries({ + queryDocumentSummariesAs(systemContext('test'), { collection: 'post', status: 'published', limit: 25, @@ -205,7 +209,7 @@ async function run(size: number): Promise> { record( 'list deep page', await time(20, () => - queryDocumentSummaries({ + queryDocumentSummariesAs(systemContext('test'), { collection: 'post', limit: 25, offset: Math.max(0, size - 50), @@ -215,9 +219,8 @@ async function run(size: number): Promise> { record( 'public query (published)', await time(50, () => - queryDocuments({ + queryDocumentsAs(publicContext(), { collection: 'post', - publishedOnly: true, limit: 20, offset: 0, }), @@ -226,7 +229,9 @@ async function run(size: number): Promise> { record( 'find by slug', await time(500, (i) => - findDocumentBySlug(`post-${pick(i)}`, { preferred: ['post'] }), + findDocumentBySlugAs(systemContext('test'), `post-${pick(i)}`, { + preferred: ['post'], + }), ), ) record( diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 04c4cca9..d5a59c77 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -163,6 +163,7 @@ export type { CollectionRoles, CollectionHooks, ChangeHookArgs, + DeleteHookArgs, ReadHookArgs, ContentMigration, SystemMetadata, diff --git a/packages/core/src/ops.ts b/packages/core/src/ops.ts index 315beb0c..522ea8fd 100644 --- a/packages/core/src/ops.ts +++ b/packages/core/src/ops.ts @@ -434,7 +434,12 @@ export const opSchemas: Array = [ where: whereInput.optional(), sort: sortInput.optional(), locale: z.string().optional(), - publishedOnly: z.boolean().optional(), + mode: z + .enum(['live', 'preview', 'edit']) + .optional() + .describe( + '`live` searches published documents only. A mode wider than the caller’s own is ignored.', + ), limit: z.number().int().min(1).max(500).optional(), offset: z.number().int().min(0).optional(), cursor: z diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index 0389c2b5..9234f8c4 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -19,6 +19,7 @@ import { z } from 'zod' import { contentLocales, getCmsConfig } from './config' import type { CollectionAccess, FieldAccess } from './lib/access' import type { AccessContext } from './lib/access-context' +import type { CmsSession } from './lib/auth' import type { StorageAdapter } from './storage/types' import type { AnyDocumentStateStrategy } from './document-state' import { isBuiltInFieldType } from './lib/authoring' @@ -348,6 +349,16 @@ export interface ChangeHookArgs { id: string operation: 'create' | 'update' actor: string + /** `afterChange` only: the writer's session, when the write carried one. */ + session?: CmsSession +} + +/** What a delete hook receives. */ +export interface DeleteHookArgs { + id: string + actor: string + /** `afterDelete` only: the writer's session, when the delete carried one. */ + session?: CmsSession } /** What a `postRead` hook receives. */ @@ -396,7 +407,7 @@ export interface CollectionHooks { */ postRead?: (args: ReadHookArgs) => MaybePromise /** Before a delete transaction; throw to veto. */ - preDelete?: (args: { id: string; actor: string }) => MaybePromise + preDelete?: (args: DeleteHookArgs) => MaybePromise /** * Runs synchronously after a delete commits. * @@ -404,7 +415,7 @@ export interface CollectionHooks { * handler on `document.deleted`: `defineEventHandler` in * `defineCms({ eventHandlers })`. Removed before 1.0. */ - afterDelete?: (args: { id: string; actor: string }) => MaybePromise + afterDelete?: (args: DeleteHookArgs) => MaybePromise } /** One step in a collection's data migrations (`Collection.migrations`). */ diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 53c0432b..2054fee9 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -264,6 +264,7 @@ export { previewContext, previewTokenContext, withMode, + narrowMode, isAccessContext, parseReadMode, canReadCollection, @@ -295,11 +296,7 @@ export { listTranslationsAs, listRevisionsAs, } from './server/store' -export type { - ContextQueryOptions, - DocumentWithPending, - ListDocumentsOptions, -} from './server/store' +export type { DocumentWithPending, ListDocumentsOptions } from './server/store' export { agentOps, runOp } from './server/cms-ops' export { cmsTools, @@ -311,8 +308,6 @@ export type { CoreSkillSummary, CmsToolsOptions } from './server/cms-tools' export { isMissingModule, loadTanstackAi, missingPeer } from './server/optional' export { resolveSession, - runWithSession, - currentSession, requirePermission, assertCollectionAccess, requireAuthenticated, diff --git a/packages/core/src/server/access-context.ts b/packages/core/src/server/access-context.ts index 8c62e60f..66c37bb0 100644 --- a/packages/core/src/server/access-context.ts +++ b/packages/core/src/server/access-context.ts @@ -5,9 +5,8 @@ * field redaction from a context, here and nowhere else. * * Builders never read the request; the host builds the context, usually from - * `resolveSession(request)`. The legacy read signatures (`session` / - * `publishedOnly` / `publicRead`) are mapped onto a context by - * `legacyReadContext`, so they behave exactly as before. + * `resolveSession(request)`. The deprecated read verbs that take no context + * read as `publicContext()`, so a forgotten context fails closed. * * Server-only. */ @@ -193,13 +192,14 @@ export function agentContext(args: { /** * The holder of a verified preview token: the token's one document, drafts - * and staged changes included, returned as stored. + * and staged changes included, redacted as for an anonymous visitor. */ export function previewContext(record: PreviewTokenRecord): AccessContext { return frozen({ actor: { kind: 'preview', tokenId: record.id }, permissions: [], mode: 'preview', + session: UNAUTHENTICATED_SESSION, publicRead: false, scope: Object.freeze({ collection: record.collection, @@ -230,34 +230,19 @@ export function withMode(ctx: AccessContext, mode: ReadMode): AccessContext { return frozen({ ...ctx, mode: assertMode(mode) }) } +const MODE_RANK: Record = { live: 0, preview: 1, edit: 2 } + /** - * The context today's read signatures describe. With no session the store - * skips access entirely, which is a system read. - * - * @internal + * `ctx` narrowed to `mode` when that's narrower than its own (`live` < + * `preview` < `edit`); a wider `mode` is ignored. Untrusted callers (tool + * inputs, headers) choose a mode through this. */ -export function legacyReadContext(args: { - session?: CmsSession - publishedOnly?: boolean - publicRead?: boolean -}): AccessContext { - const mode: ReadMode = args.publishedOnly ? 'live' : 'edit' - if (!args.session) { - return systemContext('legacy read without a session', { mode }) - } - return accessContext({ - session: args.session, - mode, - publicRead: args.publicRead, - }) -} - -/** `ctx` with its access bypassed but the same read mode. @internal */ -export function bypassingContext( +export function narrowMode( ctx: AccessContext, - reason: string, + mode: ReadMode | undefined, ): AccessContext { - return systemContext(reason, { mode: ctx.mode }) + if (!mode || MODE_RANK[assertMode(mode)] >= MODE_RANK[ctx.mode]) return ctx + return withMode(ctx, mode) } /** `ctx` without `publicRead`. @internal */ @@ -354,7 +339,7 @@ export function assertReadable( }) : canReadCollection(ctx, collectionName) if (ok) return - if (ctx.session && !ctx.session.isAuthenticated) { + if (!ctx.scope && ctx.session && !ctx.session.isAuthenticated) { throw new CmsError('Unauthorized: authentication required.', 'UNAUTHORIZED') } throw new CmsError(`Forbidden: cannot read ${collectionName}.`, 'FORBIDDEN') diff --git a/packages/core/src/server/assets.ts b/packages/core/src/server/assets.ts index 421667a4..1a7c40e0 100644 --- a/packages/core/src/server/assets.ts +++ b/packages/core/src/server/assets.ts @@ -16,7 +16,8 @@ import { assetCollectionName } from '../assets' import { canAccessCollection } from '../lib/access' import { getCmsConfig } from '../config' import { getStorage } from './storage' -import { readDocument, readDocumentWithPending } from './store/read' +import { systemContext } from './access-context' +import { readDocumentAs, readDocumentWithPendingAs } from './store/read' import { commitDocument } from './store/write' import { stageWrite } from './store/review' import type { AssetDoc } from '../assets' @@ -25,6 +26,11 @@ import type { CmsSession } from '../lib/auth' import type { MediaKind } from '../media/sniff' import type { MediaRecord } from '../storage/types' +/** Asset visibility is decided here, by uploader and publish rights. */ +const ASSET_READ = systemContext( + 'assets: governed by uploader and publish rights', +) + /** `actor` string for a session: the user id/name, else `human`. */ export function assetActor(session: CmsSession | undefined): string { return session?.user?.id ?? session?.user?.name ?? 'human' @@ -183,8 +189,9 @@ export async function updateAssetDocument( session: CmsSession | undefined, ): Promise { const collection = assetCollectionName() - const current = await readDocument(collection, id) - const base = current ?? (await readDocumentWithPending(collection, id)).doc + const current = await readDocumentAs(ASSET_READ, collection, id) + const base = + current ?? (await readDocumentWithPendingAs(ASSET_READ, collection, id)).doc if (!base) throw new Error(`No asset document with id "${id}".`) const next: Doc = { ...base, ...toDoc(patch) } const actor = assetActor(session) @@ -234,11 +241,11 @@ export async function resolveAssetForServing( session: CmsSession | undefined, ): Promise { const collection = assetCollectionName() - const live = await readDocument(collection, id) + const live = await readDocumentAs(ASSET_READ, collection, id) if (live && !live.deletedAt) return live // No committed asset: fall back to the pending overlay, but only for the // authenticated uploader (so others can't see an unapproved asset). - const pending = await readDocumentWithPending(collection, id) + const pending = await readDocumentWithPendingAs(ASSET_READ, collection, id) if ( pending.isPending && pending.doc && diff --git a/packages/core/src/server/auth.ts b/packages/core/src/server/auth.ts index 275a76ea..51a3d9d5 100644 --- a/packages/core/src/server/auth.ts +++ b/packages/core/src/server/auth.ts @@ -8,10 +8,9 @@ * 3. with no provider: a local admin when `NODE_ENV` is `development` or * `test` (or with `defineCms({ dev: true })`), otherwise nobody. * - * Every transport resolves the session once and enforces the operation's - * declared permission. The session is also bound to the async context - * (`runWithSession`), so `runOp` (agents, MCP, WebMCP) enforces the same - * rules without threading it through every call. + * Every transport resolves the session once, enforces the operation's + * declared permission, and passes the session (or an access context built + * from it) explicitly to whatever it calls. Nothing reads it ambiently. * * Server-only. */ @@ -46,14 +45,15 @@ export { API_KEY_PREFIX } * changes, …) in the audit trail. These entries carry `action`/`target` * instead of the doc-centric `collection`/`docId`/`decision`. Never pass a * secret as `target` — log an identifier or prefix only. The actor defaults - * to the current session's user. + * to `session`'s user. */ export async function recordAdminAudit(args: { action: string target?: string actor?: string + session?: CmsSession }): Promise { - const session = currentSession() + const session = args.session const actor = args.actor ?? session?.user?.name ?? session?.user?.id ?? 'human' await ( @@ -83,7 +83,6 @@ export function runInConfigScope(config: ResolvedCmsConfig, fn: () => T): T { return configContext.run(config, fn) } -const sessionContext = new AsyncLocalStorage() const sessionCache = new WeakMap< Request, WeakMap> @@ -220,20 +219,17 @@ async function computeSession( } /** - * Resolve the `CmsSession` for a request. Memoized per Request object; with - * no request, the session bound by `runWithSession` (if any) is used. - * `fresh` bypasses memoization for long-lived event streams. + * Resolve the `CmsSession` for a request. Memoized per Request object. + * Without a request, the auth provider sees an empty request, or (with no + * provider) the dev/test local admin applies. `fresh` bypasses memoization + * for long-lived event streams. */ export function resolveSession( request?: Request, options?: { fresh?: boolean }, ): Promise { if (request && options?.fresh) return computeSession(request) - if (!request) { - const bound = sessionContext.getStore() - if (bound) return Promise.resolve(bound) - return computeSession(undefined) - } + if (!request) return computeSession(undefined) const config = getCmsConfig() let sessions = sessionCache.get(request) if (!sessions) { @@ -248,16 +244,6 @@ export function resolveSession( return cached } -/** Run `fn` with `session` bound for `runOp` and other context-aware checks. */ -export function runWithSession(session: CmsSession, fn: () => T): T { - return sessionContext.run(session, fn) -} - -/** The session bound by `runWithSession`, if any. */ -export function currentSession(): CmsSession | undefined { - return sessionContext.getStore() -} - function deny(session: CmsSession, what: string): never { if (!session.isAuthenticated) { throw new CmsError('Unauthorized: authentication required.', 'UNAUTHORIZED') @@ -336,9 +322,13 @@ function summarize({ hash: _hash, ...rest }: ApiKeyRecord): ApiKeySummary { return rest } -/** Create a key. The plaintext `key` is returned once and never stored. */ +/** + * Create a key. The plaintext `key` is returned once and never stored. + * `session` is recorded as the audit actor. + */ export async function createApiKey( input: CreateApiKeyInput, + options?: { session?: CmsSession }, ): Promise<{ key: string; record: ApiKeySummary }> { const name = input.name.trim() if (!name) @@ -372,6 +362,7 @@ export async function createApiKey( await recordAdminAudit({ action: 'apikey.create', target: `${record.name} (${record.prefix}…)`, + session: options?.session, }) return { key, record: summarize(record) } } @@ -381,7 +372,11 @@ export async function listApiKeys(): Promise> { return (await storage.listApiKeys()).map(summarize) } -export async function revokeApiKey(id: string): Promise { +/** Revoke a key; `session` is recorded as the audit actor. */ +export async function revokeApiKey( + id: string, + options?: { session?: CmsSession }, +): Promise { const storage = requireStorageCapability(await getStorage(), 'apiKeys') const record = (await storage.listApiKeys()).find((k) => k.id === id) if (!record) return false @@ -390,6 +385,7 @@ export async function revokeApiKey(id: string): Promise { await recordAdminAudit({ action: 'apikey.revoke', target: `${record.name} (${record.prefix}…)`, + session: options?.session, }) } return true diff --git a/packages/core/src/server/cms-ops.ts b/packages/core/src/server/cms-ops.ts index b49727eb..9d2bd4c0 100644 --- a/packages/core/src/server/cms-ops.ts +++ b/packages/core/src/server/cms-ops.ts @@ -5,7 +5,8 @@ * funnels through — the content agent, the HTTP MCP server, and the * `/api/cms` RPC (WebMCP). `actor` is recorded on staged writes so the review * queue and audit trail show who proposed each change; `access` is the - * agent's context, which every read derives its visibility from. + * agent's context, which every read derives its visibility from. There is + * no default: a call without a context is refused. * * Server-only. */ @@ -14,16 +15,15 @@ import { configuredOps, opSchemas, validateWithStandardSchema } from '../ops' import { getCmsConfig } from '../config' import { protectWrite } from './access' import { - accessContext, bypassesRules, canReadCollection, + isAccessContext, + narrowMode, redactFor, systemContext, - withMode, } from './access-context' import { assertCollectionAccess, - currentSession, requirePermission, resolveSession, } from './auth' @@ -33,8 +33,12 @@ import type { CollectionAction, Permission } from '../lib/access' import type { CmsOpDefinition } from '../ops' import type { Doc } from '../schema' +/** Tool targets; each tool checks the agent's access itself. */ +const TOOL_READ = systemContext('agent tool target') + async function readOrPending(collection: string, id: string) { - const doc = (await store.readDocumentWithPending(collection, id)).doc + const doc = (await store.readDocumentWithPendingAs(TOOL_READ, collection, id)) + .doc if (!doc) { throw new CmsError( `No ${collection} document with id "${id}".`, @@ -319,7 +323,11 @@ export async function proposeSkillInstallOp( input.formSlug ?? input.collectionName?.replace(/_/g, '-') ?? 'contact-us' const instruction = `Add formEmbed (${formSlug}) block to /${input.targetPageId} page draft` if (collectionsConfig.page) { - const existing = await store.readDocument('page', input.targetPageId) + const existing = await store.readDocumentAs( + TOOL_READ, + 'page', + input.targetPageId, + ) const pending = await store.stageWrite({ collection: 'page', docId: input.targetPageId, @@ -383,34 +391,28 @@ export function agentOps(): Array { return [...builtInAgentOps, ...configuredOps().filter((op) => op.agent)] } -/** - * The context a `runOp` call without one reads with: the session bound by - * `runWithSession` in edit mode, or a system context. - */ -function ambientOpContext(): AccessContext { - const session = currentSession() - return session - ? accessContext({ session, mode: 'edit' }) - : systemContext('runOp without a session or context') -} - /** * Run an agent operation as `access` (an agent's context, usually * `accessContext({ session, agent, mode: 'edit' })`). With a session-bearing * context the op's permission and collection access are enforced, * unwritable fields are preserved, and unreadable fields are redacted; a - * system context bypasses the rules. Without `access`, the session bound by - * `runWithSession` is used (deprecated: pass the context). + * system context bypasses the rules. */ export async function runOp( name: string, input: unknown, actor: string, - access?: AccessContext, + access: AccessContext, ): Promise { const op = agentOps().find((o) => o.name === name) if (!op) throw new CmsError(`Unknown operation: ${name}`, 'NOT_FOUND') - const ctx = access ?? ambientOpContext() + if (!isAccessContext(access)) { + throw new CmsError( + 'runOp needs an access context (accessContext, systemContext, …).', + 'UNAUTHORIZED', + ) + } + const ctx = access if (ctx.scope) { throw new CmsError( 'Forbidden: a preview context cannot run operations.', @@ -426,8 +428,14 @@ export async function runOp( if (typeof data?.collection === 'string') { const ref = data as { collection: string; id?: string; doc?: Doc } const existing = ref.id - ? ((await store.readDocument(ref.collection, ref.id)) ?? - (await store.readDocumentWithPending(ref.collection, ref.id)).doc) + ? ((await store.readDocumentAs(TOOL_READ, ref.collection, ref.id)) ?? + ( + await store.readDocumentWithPendingAs( + TOOL_READ, + ref.collection, + ref.id, + ) + ).doc) : undefined assertCollectionAccess( session, @@ -566,20 +574,17 @@ async function dispatch( } case 'search_documents': - return store.queryDocumentsAs( - input?.publishedOnly ? withMode(ctx, 'live') : ctx, - { - collection: input?.collection, - collections: readableCollections(ctx), - query: input?.query, - locale: input?.locale, - where: input?.where, - sort: input?.sort, - limit: input?.limit, - offset: input?.offset, - cursor: input?.cursor, - }, - ) + return store.queryDocumentsAs(narrowMode(ctx, input?.mode), { + collection: input?.collection, + collections: readableCollections(ctx), + query: input?.query, + locale: input?.locale, + where: input?.where, + sort: input?.sort, + limit: input?.limit, + offset: input?.offset, + cursor: input?.cursor, + }) case 'list_revisions': return store.listRevisionsAs(ctx, input.collection, input.id) diff --git a/packages/core/src/server/cms-tools.ts b/packages/core/src/server/cms-tools.ts index d4c2577b..8d651e5b 100644 --- a/packages/core/src/server/cms-tools.ts +++ b/packages/core/src/server/cms-tools.ts @@ -19,7 +19,6 @@ import { } from './cms-ops' import type { CoreSkillSummary } from './cms-ops' import { loadTanstackAi } from './optional' -import { currentSession } from './auth' import { isAccessContext } from './access-context' import type { AccessContext } from './access-context' import { hasPermission } from '../lib/access' @@ -43,8 +42,8 @@ export interface CmsToolsOptions { * `accessContext({ session, agent: 'content-agent', mode: 'edit' })`. It * decides `authorizedOnly`, and every tool call reads and writes as it. A * call's own runtime context (`ctx.context[CMS_ACCESS_KEY]`, which the MCP - * server sets per request) takes precedence. Without either, the session - * bound by `runWithSession` is used; that fallback is deprecated. + * server sets per request) takes precedence. A call with neither is + * refused with `UNAUTHORIZED`. */ access?: AccessContext } @@ -64,9 +63,7 @@ function callAccess(toolCtx: unknown): AccessContext | undefined { export async function cmsTools(actor: string, options?: CmsToolsOptions) { const { toolDefinition } = await loadTanstackAi() - const buildSession = options?.access - ? options.access.session - : currentSession() + const buildSession = options?.access?.session const observe = ( result: Omit & { result: unknown }, ) => { @@ -101,13 +98,16 @@ export async function cmsTools(actor: string, options?: CmsToolsOptions) { inputSchema: op.input, }).server(async (input, toolCtx?: unknown) => { const access = callAccess(toolCtx) ?? options?.access - const execSession = access - ? access.session - : (currentSession() ?? buildSession) - const resolvedActor = execSession?.agent - ? `${actor}:${execSession.agent}` + const resolvedActor = access?.session?.agent + ? `${actor}:${access.session.agent}` : actor try { + if (!access) { + throw new CmsError( + 'Unauthorized: the tool call has no access context.', + 'UNAUTHORIZED', + ) + } const result = await runOp(op.name, input, resolvedActor, access) observe({ name: op.name, diff --git a/packages/core/src/server/interface-schedules.ts b/packages/core/src/server/interface-schedules.ts index 1bfee774..7326d4de 100644 --- a/packages/core/src/server/interface-schedules.ts +++ b/packages/core/src/server/interface-schedules.ts @@ -10,16 +10,16 @@ import { CmsError } from '../errors' import { nextCronRun } from '../lib/cron' import { interfaceCollectionName, executeInterface } from './interfaces' import { getStorage } from './storage' -import { commitDocument, readDocument, queryDocuments } from './store' -import { - assertCollectionAccess, - recordAdminAudit, - runWithSession, -} from './auth' +import { commitDocument, readDocumentAs, queryDocumentsAs } from './store' +import { systemContext, withMode } from './access-context' +import { assertCollectionAccess, recordAdminAudit } from './auth' /** Interface runs need the caller's session, not a read context. */ type InterfaceOpContext = Omit +/** Reads whose access the caller checks against the session itself. */ +const SCHEDULE_READ = systemContext('interface schedules') + const statusSchema = z.object({ generation: z.string(), nextRunAt: z.string(), @@ -105,7 +105,7 @@ export async function getInterfaceScheduleStatus( ctx: InterfaceOpContext, ) { admin(ctx) - const doc = await readDocument(interfaceCollectionName(), id) + const doc = await readDocumentAs(SCHEDULE_READ, interfaceCollectionName(), id) if (!doc) throw new CmsError('Interface not found.', 'NOT_FOUND') assertCollectionAccess(ctx.session, interfaceCollectionName(), 'read', doc) return { @@ -119,7 +119,11 @@ export async function setInterfaceSchedulePaused( ctx: InterfaceOpContext, ) { admin(ctx) - const doc = await readDocument(interfaceCollectionName(), input.id) + const doc = await readDocumentAs( + SCHEDULE_READ, + interfaceCollectionName(), + input.id, + ) if (!scheduled(doc)) throw new CmsError('This report has no published schedule.', 'BAD_REQUEST') assertCollectionAccess(ctx.session, interfaceCollectionName(), 'update', doc) @@ -162,9 +166,7 @@ async function capture( 'Report edits are awaiting review. Scheduled refresh is waiting.', 'CONFLICT', ) - const rendered = await runWithSession(ctx.session, () => - executeInterface(doc.definition, {}, ctx), - ) + const rendered = await executeInterface(doc.definition, {}, ctx) if ( rendered.evidence.collections.some( (name) => @@ -179,19 +181,17 @@ async function capture( await (await getStorage()).setMeta(snapshotRef, JSON.stringify(rendered)) // The run receipt commits with the revision. A retry after a crash sees it // even when the status metadata could not be updated, avoiding duplicate revisions. - return runWithSession(ctx.session, () => - commitDocument( - collection, - id, - { ...doc, snapshotRef, snapshotRunKey: runKey }, - { - session: ctx.session, - actor: ctx.actor, - summary: 'Refreshed approved report snapshot', - expectedRevision: Number(doc._revision), - expectedPendingVersion: 0, - }, - ), + return commitDocument( + collection, + id, + { ...doc, snapshotRef, snapshotRunKey: runKey }, + { + session: ctx.session, + actor: ctx.actor, + summary: 'Refreshed approved report snapshot', + expectedRevision: Number(doc._revision), + expectedPendingVersion: 0, + }, ) } export async function refreshInterfaceSnapshot( @@ -199,7 +199,7 @@ export async function refreshInterfaceSnapshot( ctx: InterfaceOpContext, ) { admin(ctx) - const doc = await readDocument(interfaceCollectionName(), id) + const doc = await readDocumentAs(SCHEDULE_READ, interfaceCollectionName(), id) if ( !doc || !doc.published || @@ -235,9 +235,8 @@ export async function runInterfaceSchedules(options?: { now?: string }) { const resolver = getCmsConfig().interfaces?.scheduleSession const result = { refreshed: 0, waiting: 0, failed: 0 } for (let offset = 0; ; offset += 200) { - const page = await queryDocuments({ + const page = await queryDocumentsAs(withMode(SCHEDULE_READ, 'live'), { collection, - publishedOnly: true, limit: 200, offset, sort: { field: 'id' }, @@ -323,7 +322,11 @@ export async function handleInterfaceScheduleEvent({ return await sync( event.documentId, - await readDocument(interfaceCollectionName(), event.documentId), + await readDocumentAs( + SCHEDULE_READ, + interfaceCollectionName(), + event.documentId, + ), clock(), ) } diff --git a/packages/core/src/server/interfaces.ts b/packages/core/src/server/interfaces.ts index e643fbe2..769df0ee 100644 --- a/packages/core/src/server/interfaces.ts +++ b/packages/core/src/server/interfaces.ts @@ -17,10 +17,11 @@ import type { Doc, JsonValue } from '../schema' import { CmsError } from '../errors' import { assertCollectionAccess } from './auth' import { assertQueryableFields, redactDoc, protectWrite } from './access' +import { accessContext, systemContext } from './access-context' import { - queryDocuments, - readDocument, - readDocumentWithPending, + queryDocumentsAs, + readDocumentAs, + readDocumentWithPendingAs, stageWrite, listPending, } from './store' @@ -31,6 +32,13 @@ import { nextCronRun } from '../lib/cron' /** Interface runs need the caller's session, not a read context. */ type InterfaceOpContext = Omit +/** Reads whose access the caller checks against the session itself. */ +const INTERFACE_READ = systemContext('interfaces: checked against the session') + +function sessionRead(ctx: InterfaceOpContext, live = false) { + return accessContext({ session: ctx.session, mode: live ? 'live' : 'edit' }) +} + const queryInput = z .object({ collection: z.string().min(1).max(64), @@ -92,7 +100,7 @@ export function createInterfaceQuery( throw new CmsError('Interface query limit exceeded.', 'VALIDATION_FAILED') const q = queryInput.parse(input) dataCollection(q.collection, ctx) - const result = await queryDocuments({ ...q, session: ctx.session }) + const result = await queryDocumentsAs(sessionRead(ctx), q) rows += result.items.length if (rows > 2000) throw new CmsError('Interface row limit exceeded.', 'VALIDATION_FAILED') @@ -243,7 +251,11 @@ async function executeCode( 'Content write access is required.', 'FORBIDDEN', ) - const before = await readDocument(input.collection, input.id) + const before = await readDocumentAs( + INTERFACE_READ, + input.collection, + input.id, + ) if (!before) throw new CmsError('Document not found.', 'NOT_FOUND') assertCollectionAccess( @@ -310,11 +322,9 @@ async function executeCode( export async function listInterfaces(ctx: InterfaceOpContext) { const collection = interfaceCollectionName() assertCollectionAccess(ctx.session, collection, 'read') - const docs = await queryDocuments({ + const docs = await queryDocumentsAs(sessionRead(ctx, !ctx.session.isAdmin), { collection, - session: ctx.session, limit: 500, - publishedOnly: !ctx.session.isAdmin, }) const items = docs.items.map(({ id, doc }) => ({ id, @@ -349,7 +359,7 @@ export async function getInterfaceEditor(id: string, ctx: InterfaceOpContext) { author(ctx) const collection = interfaceCollectionName() assertCollectionAccess(ctx.session, collection, 'read') - const found = await readDocumentWithPending(collection, id) + const found = await readDocumentWithPendingAs(INTERFACE_READ, collection, id) if (!found.doc) throw new CmsError('Interface not found.', 'NOT_FOUND') return { id, @@ -357,7 +367,9 @@ export async function getInterfaceEditor(id: string, ctx: InterfaceOpContext) { kind: z.enum(['page', 'report']).parse(found.doc.kind), mode: z.enum(['live', 'snapshot']).parse(found.doc.mode), definition: interfaceDefinitionSchema.parse(found.doc.definition), - revision: Number((await readDocument(collection, id))?._revision ?? 0), + revision: Number( + (await readDocumentAs(INTERFACE_READ, collection, id))?._revision ?? 0, + ), pendingVersion: found.pendingVersion ?? 0, schedule: found.doc.schedule ?? null, } @@ -371,7 +383,7 @@ export async function getInterfaceMetadata( const collection = interfaceCollectionName() const config = getCmsConfig().collections[collection] if (!canAccessCollection(ctx.session, config, 'read')) return null - const doc = await readDocument(collection, id) + const doc = await readDocumentAs(INTERFACE_READ, collection, id) if ( !doc || !doc.published || @@ -402,7 +414,7 @@ export async function submitInterface( ) nextCronRun(parsed.schedule.cron, new Date()) } - const before = await readDocument(collection, parsed.id) + const before = await readDocumentAs(INTERFACE_READ, collection, parsed.id) assertCollectionAccess( ctx.session, collection, @@ -418,7 +430,7 @@ export async function submitInterface( const legacy = parsed.kind === 'page' ? 'page' : 'reports' if ( getCmsConfig().collections[legacy] && - (await readDocument(legacy, parsed.id)) + (await readDocumentAs(INTERFACE_READ, legacy, parsed.id)) ) throw new CmsError( 'That URL is already used by existing content.', @@ -507,7 +519,7 @@ export async function refreshInterfaceComponents( async function published(id: string, kind: string, ctx: InterfaceOpContext) { const collection = interfaceCollectionName() assertCollectionAccess(ctx.session, collection, 'read') - const doc = await readDocument(collection, id) + const doc = await readDocumentAs(INTERFACE_READ, collection, id) if (!doc || doc.published !== true || doc.kind !== kind) throw new CmsError('Interface not found.', 'NOT_FOUND') assertCollectionAccess(ctx.session, collection, 'read', doc) @@ -524,10 +536,14 @@ async function snapshotEvidence(evidence: Evidence, ctx: InterfaceOpContext) { } for (const q of evidence.queries) { // Revalidate filtering/sorting with today's field rules, even for empty snapshots. - await queryDocuments({ ...q, limit: 1, session: ctx.session }) + await queryDocumentsAs(sessionRead(ctx), { ...q, limit: 1 }) } for (const source of evidence.sources) { - const current = await readDocument(source.collection, source.id) + const current = await readDocumentAs( + INTERFACE_READ, + source.collection, + source.id, + ) if (!current) throw new CmsError( 'A snapshot source is no longer accessible.', diff --git a/packages/core/src/server/media.ts b/packages/core/src/server/media.ts index b9edfd20..091b1643 100644 --- a/packages/core/src/server/media.ts +++ b/packages/core/src/server/media.ts @@ -21,6 +21,7 @@ import { sniffMedia, } from '../media/sniff' import { nodeImport } from '../storage/node-import' +import { accessContext, systemContext } from './access-context' import { resolveSession } from './auth' import { getStorage } from './storage' import { sanitizeSvg } from './svg' @@ -35,7 +36,7 @@ import { updateAssetDocument, } from './assets' import { commitDocument, deleteDocument } from './store/write' -import { findReferences, queryDocumentSummaries } from './store/read' +import { findReferencesAs, queryDocumentSummariesAs } from './store/read' import type { AssetDoc } from '../assets' import type { CmsSession } from '../lib/auth' import type { MediaAdapter } from '../media/types' @@ -209,8 +210,8 @@ export interface SaveMediaOptions { tags?: Array /** * The uploader's session, so the asset document is governed like content - * (publishers commit, authors stage for review). Defaults to the ambient - * session (`resolveSession()`), or a local admin in dev/test. + * (publishers commit, authors stage for review). Defaults to + * `resolveSession()` without a request: a local admin in dev/test. */ session?: CmsSession } @@ -384,12 +385,14 @@ export async function listMediaItems( // `media`→`asset` migration + loose-blob adoption keep it complete, so there // is no `media`-table read here. const byId = new Map() - const summaries = await queryDocumentSummaries({ - collection: assetCollectionName(), - search, - sort: { field: 'updatedAt', dir: 'desc' }, - session, - }) + const summaries = await queryDocumentSummariesAs( + accessContext({ session, mode: 'edit' }), + { + collection: assetCollectionName(), + search, + sort: { field: 'updatedAt', dir: 'desc' }, + }, + ) for (const summary of summaries.items) { const doc = await resolveAssetForServing(summary.id, session) if (doc) byId.set(summary.id, assetDocToRecord(summary.id, doc)) @@ -495,7 +498,11 @@ export async function findMediaUsage( } // Structural `asset` references (committed + pending), access-unaware here; // the readable projection is computed by the op layer. - for (const ref of await findReferences(assetCollectionName(), mediaId)) { + for (const ref of await findReferencesAs( + systemContext('media usage: every structural reference'), + assetCollectionName(), + mediaId, + )) { add(ref.collection, ref.id) } // `image` fields (and markdown bodies) store the `/api/media/` URL string. @@ -689,7 +696,7 @@ export interface ReadMediaOptions { /** * The requesting session. A pending (staged) asset resolves only for its * authenticated uploader; everyone else gets the committed version or 404. - * Defaults to the ambient session (`resolveSession()`). + * Defaults to `resolveSession()` without a request. */ session?: CmsSession } diff --git a/packages/core/src/server/seo.ts b/packages/core/src/server/seo.ts index 1bf635b0..91aeba74 100644 --- a/packages/core/src/server/seo.ts +++ b/packages/core/src/server/seo.ts @@ -4,9 +4,12 @@ import { adminBasePath, getCmsConfig } from '../config' import { collections } from '../schema' import { isSafeRedirectTarget, seoOverrides } from '../lib/seo' -import { queryDocuments } from './store' +import { publicContext, systemContext } from './access-context' +import { queryDocumentsAs } from './store' const PAGE = 500 +/** Redirects apply whether or not the redirect document is published. */ +const REDIRECT_READ = systemContext('redirect lookup') function escapeXml(s: string): string { return s @@ -40,9 +43,8 @@ export async function listSitemapEntries( for (const collection of Object.values(collections())) { if (!collection.path) continue for (let offset = 0; ; offset += PAGE) { - const page = await queryDocuments({ + const page = await queryDocumentsAs(publicContext(), { collection: collection.name, - publishedOnly: true, limit: PAGE, offset, }) @@ -121,7 +123,7 @@ export async function resolveRedirect( candidates.push(pathname.replace(/\/+$/, '')) } for (const from of candidates) { - const { items } = await queryDocuments({ + const { items } = await queryDocumentsAs(REDIRECT_READ, { collection: name, where: { from }, limit: 1, diff --git a/packages/core/src/server/store.ts b/packages/core/src/server/store.ts index 1bb51150..14a5c82c 100644 --- a/packages/core/src/server/store.ts +++ b/packages/core/src/server/store.ts @@ -73,7 +73,6 @@ export { } from './store/query' export type { QueryDocumentsOptions, - ContextQueryOptions, WhereInput, QueryDocumentsResult, } from './store/query' diff --git a/packages/core/src/server/store/collaboration.ts b/packages/core/src/server/store/collaboration.ts index 31df8b5d..f0817fa5 100644 --- a/packages/core/src/server/store/collaboration.ts +++ b/packages/core/src/server/store/collaboration.ts @@ -13,23 +13,31 @@ * - delete: the comment's author, or a session with `review.decide`. * - assign / unassign: `content.write` on the collection (same rule as an edit). * + * The checks apply to the `session` passed in; without one the caller is + * trusted (server-internal code), as with the write path. + * * Server-only. */ import { randomUUID } from 'node:crypto' import { CmsError } from '../../errors' import { hasPermission } from '../../lib/access' -import { assertCollectionAccess, currentSession } from '../auth' +import { systemContext } from '../access-context' +import { assertCollectionAccess } from '../auth' import { getStorage } from '../storage' import { enqueueEvent } from '../outbox' import { queueNotification } from '../notifications' import { commitDocument } from './write' -import { readDocument, readDocumentWithPending } from './read' +import { readDocumentAs, readDocumentWithPendingAs } from './read' import type { CmsSession } from '../../lib/auth' import type { CommentRecord, StorageOps } from '../../storage/types' import type { Doc } from '../../schema' export type { CommentRecord } from '../../storage/types' +const COLLABORATION = systemContext( + 'collaboration: the document a comment or assignment targets', +) + function actorName(session: CmsSession | undefined): string { return session?.user?.id ?? session?.user?.name ?? 'human' } @@ -54,8 +62,8 @@ async function assertCanReadDoc( ): Promise { if (!session) return const live = - (await readDocument(collection, docId)) ?? - (await readDocumentWithPending(collection, docId)).doc + (await readDocumentAs(COLLABORATION, collection, docId)) ?? + (await readDocumentWithPendingAs(COLLABORATION, collection, docId)).doc assertCollectionAccess(session, collection, 'read', live ?? undefined) } @@ -76,7 +84,7 @@ export interface AddCommentArgs { export async function addComment(args: AddCommentArgs): Promise { const storage = await getStorage() requireComments(storage) - const session = args.session ?? currentSession() + const session = args.session await assertCanReadDoc(args.collection, args.docId, session) const body = args.body.trim() @@ -137,7 +145,7 @@ export async function listComments( ): Promise> { const storage = await getStorage() requireComments(storage) - await assertCanReadDoc(collection, docId, session ?? currentSession()) + await assertCanReadDoc(collection, docId, session) return (await storage.listComments?.(collection, docId)) ?? [] } @@ -159,7 +167,7 @@ export async function resolveComment( requireComments(storage) const comment = await storage.getComment?.(id) if (!comment) throw new CmsError(`Unknown comment: ${id}`, 'NOT_FOUND') - const session = options?.session ?? currentSession() + const session = options?.session await assertCanReadDoc(comment.collection, comment.docId, session) if (!canDecide(comment, session)) { throw new CmsError( @@ -183,7 +191,7 @@ export async function deleteComment( requireComments(storage) const comment = await storage.getComment?.(id) if (!comment) return false - const session = options?.session ?? currentSession() + const session = options?.session await assertCanReadDoc(comment.collection, comment.docId, session) if (!canDecide(comment, session)) { throw new CmsError( @@ -220,8 +228,12 @@ export interface AssignArgs { * Requires `content.write` on the collection (the same rule as editing it). */ export async function assignDocument(args: AssignArgs): Promise { - const session = args.session ?? currentSession() - const existing = await readDocument(args.collection, args.docId) + const session = args.session + const existing = await readDocumentAs( + COLLABORATION, + args.collection, + args.docId, + ) if (!existing) { throw new CmsError( `No ${args.collection} document with id "${args.docId}".`, diff --git a/packages/core/src/server/store/document-state.ts b/packages/core/src/server/store/document-state.ts index 2b85c6b3..9a525927 100644 --- a/packages/core/src/server/store/document-state.ts +++ b/packages/core/src/server/store/document-state.ts @@ -1378,6 +1378,7 @@ export async function executeStrategyWrite( id: write.docId, operation, actor: author, + ...(write.session ? { session: write.session } : {}), }) emitCommit( write.collection, @@ -1388,7 +1389,11 @@ export async function executeStrategyWrite( ) } if (deleted !== undefined) { - await runAfterDelete(collection, { id: write.docId, actor: author }) + await runAfterDelete(collection, { + id: write.docId, + actor: author, + ...(write.session ? { session: write.session } : {}), + }) emitCmsEvent('document.deleted', { collection: write.collection, id: write.docId, diff --git a/packages/core/src/server/store/internal.ts b/packages/core/src/server/store/internal.ts index 1e053482..e296878b 100644 --- a/packages/core/src/server/store/internal.ts +++ b/packages/core/src/server/store/internal.ts @@ -21,8 +21,10 @@ import { denormalize } from '../indexing' import { commitEvents, emitCmsEvent, stayedLive } from '../events' import { collectRelations } from './relations' import type { + ChangeHookArgs, Collection, CollectionHooks, + DeleteHookArgs, Doc, Field, FieldValidator, @@ -173,12 +175,7 @@ export async function runPreDelete( /** The deprecated post-commit `afterChange` hook. */ export async function runAfterChange( collection: Collection | undefined, - args: { - doc: Doc - id: string - operation: 'create' | 'update' - actor: string - }, + args: ChangeHookArgs, ): Promise { const hook = collection?.hooks?.afterChange if (!collection || !hook) return @@ -188,7 +185,7 @@ export async function runAfterChange( /** The deprecated post-commit `afterDelete` hook. */ export async function runAfterDelete( collection: Collection | undefined, - args: { id: string; actor: string }, + args: DeleteHookArgs, ): Promise { const hook = collection?.hooks?.afterDelete if (!collection || !hook) return diff --git a/packages/core/src/server/store/query.ts b/packages/core/src/server/store/query.ts index fdcfc068..308528bc 100644 --- a/packages/core/src/server/store/query.ts +++ b/packages/core/src/server/store/query.ts @@ -17,18 +17,16 @@ import { bypassesRules, canReadCollection, isLiveRead, - legacyReadContext, + publicContext, queryReadableDocuments, redactFor, storageVisibility, - withoutPublicRead, } from '../access-context' import { denormalize } from '../indexing' import { getStorage } from '../storage' import { applyPostRead, collections, isScalarField } from './internal' import { populateRelationsAs } from './read' import type { AccessContext } from '../access-context' -import type { CmsSession } from '../../lib/auth' import type { Doc } from '../../schema' import type { StorageGroup, @@ -45,7 +43,6 @@ export interface QueryDocumentsOptions { query?: string textQuery?: { fields: ReadonlyArray; terms: ReadonlyArray } locale?: string - publishedOnly?: boolean populate?: boolean /** * Filters. An object maps field paths to a value (`eq`), an array (`in`), @@ -60,20 +57,8 @@ export interface QueryDocumentsOptions { offset?: number /** Continue from a previous result's `nextCursor` (replaces `offset`). */ cursor?: string - /** When set, results are redacted and querying unreadable fields is `FORBIDDEN`. */ - session?: CmsSession - publicRead?: boolean } -/** - * `QueryDocumentsOptions` without the visibility options, which a context - * replaces. - */ -export type ContextQueryOptions = Omit< - QueryDocumentsOptions, - 'session' | 'publishedOnly' | 'publicRead' -> - /** The `where` forms `queryDocuments` accepts. */ export type WhereInput = Record | ReadonlyArray @@ -210,19 +195,26 @@ function decodeCursor(cursor: string, fingerprint: string): number { ) } -/** Query, filter, search, sort, and paginate documents across one or all collections. */ +/** + * `queryDocumentsAs` as `publicContext()`: published documents, redacted as + * for an anonymous visitor. + * + * @deprecated Use `queryDocumentsAs(ctx, options)`. + */ export function queryDocuments( options?: QueryDocumentsOptions, ): Promise { - return queryDocumentsAs(legacyReadContext(options ?? {}), options) + return queryDocumentsAs(publicContext(), options) } /** - * `queryDocuments` as `ctx`: visibility and redaction come from the context. + * Query, filter, search, sort, and paginate the documents `ctx` may read + * across one or all collections. Results are redacted for `ctx`, and + * filtering or sorting on a field it may not read is `FORBIDDEN`. */ export async function queryDocumentsAs( ctx: AccessContext, - options?: ContextQueryOptions, + options?: QueryDocumentsOptions, ): Promise { const storage = await getStorage() const names = ( @@ -287,8 +279,6 @@ export async function queryDocumentsAs( ctx, ) - // Populated relations don't get `publicRead` visibility. - const relationsCtx = withoutPublicRead(ctx) const page: QueryDocumentsResult['items'] = [] for (const row of result.items) { const doc = await applyPostRead(row.collection, row.id, row.doc, ctx) @@ -306,11 +296,7 @@ export async function queryDocumentsAs( published: row.published, ...(options?.populate ? { - relations: await populateRelationsAs( - relationsCtx, - row.collection, - doc, - ), + relations: await populateRelationsAs(ctx, row.collection, doc), } : {}), }) @@ -349,21 +335,26 @@ export async function reindexDocuments(): Promise { return count } -/** Aggregate persisted values with the same read constraints as document queries. */ +/** + * `groupDocumentsAs` as `publicContext()`. + * + * @deprecated Use `groupDocumentsAs(ctx, field, options)`. + */ export function groupDocuments( field: string, options: QueryDocumentsOptions, ): Promise> { - return groupDocumentsAs(legacyReadContext(options), field, options) + return groupDocumentsAs(publicContext(), field, options) } /** - * `groupDocuments` as `ctx`. + * Aggregate persisted values of the documents `ctx` may read, with the same + * constraints as `queryDocumentsAs`. */ export async function groupDocumentsAs( ctx: AccessContext, field: string, - options: ContextQueryOptions, + options: QueryDocumentsOptions, ): Promise> { const names = ( options.collection diff --git a/packages/core/src/server/store/read.ts b/packages/core/src/server/store/read.ts index 45bc575f..a59abefc 100644 --- a/packages/core/src/server/store/read.ts +++ b/packages/core/src/server/store/read.ts @@ -14,11 +14,10 @@ import { fieldPath } from '../../storage/where' import { assertQueryableFields } from '../access' import { bypassesRules, - bypassingContext, canReadCollection, canReadDocument, isLiveRead, - legacyReadContext, + publicContext, queryReadableDocuments, redactFor, systemContext, @@ -28,7 +27,6 @@ import { getStorage } from '../storage' import { applyPostRead, collections, requireCollection } from './internal' import { collectRelations, nestedRelationTargets } from './relations' import type { AccessContext } from '../access-context' -import type { CmsSession } from '../../lib/auth' import type { Collection, Doc, Field, JsonValue } from '../../schema' import type { IndexedDocumentRecord, @@ -161,27 +159,29 @@ export interface DocumentSummaryQuery { columns?: Array /** Only documents assigned to this user id ("assigned to me" filter). */ assignedTo?: string - /** When set, sorting on fields `session` may not read is `FORBIDDEN`. */ - session?: CmsSession } /** - * Paginated document summaries for one collection — the admin list view. - * Pending creates (agent drafts not yet approved) are listed first on page 1. + * Paginated document summaries for one collection, read as + * `publicContext()`. + * + * @deprecated Use `queryDocumentSummariesAs(ctx, q)`. */ export function queryDocumentSummaries( q: DocumentSummaryQuery, ): Promise<{ items: Array; total: number }> { - return queryDocumentSummariesAs(legacyReadContext({ session: q.session }), q) + return queryDocumentSummariesAs(publicContext(), q) } /** - * `queryDocumentSummaries` as `ctx`. A `live` context lists published - * documents only, without pending creates. + * Paginated document summaries for one collection as `ctx`: the admin list + * view. Pending creates (agent drafts not yet approved) are listed first on + * page 1; a `live` context lists published documents only, without them. + * Sorting on a field `ctx` may not read is `FORBIDDEN`. */ export async function queryDocumentSummariesAs( ctx: AccessContext, - q: Omit, + q: DocumentSummaryQuery, ): Promise<{ items: Array; total: number }> { const collection = requireCollection(q.collection) const sortField = q.sort?.field @@ -321,16 +321,17 @@ async function pendingCreateSummaries( ) } -/** All document summaries (optionally one collection / locale), including pending creates. */ +/** + * All document summaries (optionally one collection / locale), read as + * `publicContext()`. + * + * @deprecated Use `listDocumentsAs(ctx, collectionName, options)`. + */ export function listDocuments( collectionName?: string, - options?: ListDocumentsOptions & { session?: CmsSession }, + options?: ListDocumentsOptions, ): Promise> { - return listDocumentsAs( - legacyReadContext({ session: options?.session }), - collectionName, - options, - ) + return listDocumentsAs(publicContext(), collectionName, options) } /** Options for `listDocuments`. */ @@ -343,7 +344,8 @@ export interface ListDocumentsOptions { } /** - * `listDocuments` as `ctx`. + * All document summaries (optionally one collection / locale) `ctx` may + * read, including pending creates outside `live` mode. */ export async function listDocumentsAs( ctx: AccessContext, @@ -371,15 +373,20 @@ export async function listDocumentsAs( return out } -const UNSCOPED_READ = systemContext('store read by id without a session') const TRASH_READ = systemContext('trash read') +const TRANSLATION_LINKS = systemContext('translation links') +/** + * One published document, read as `publicContext()`. + * + * @deprecated Use `readDocumentAs(ctx, collectionName, id, options)`. + */ export function readDocument( collectionName: string, id: string, options?: { includeDeleted?: boolean }, ): Promise { - return readDocumentAs(UNSCOPED_READ, collectionName, id, options) + return readDocumentAs(publicContext(), collectionName, id, options) } /** @@ -432,20 +439,23 @@ export interface DocumentWithPending { } /** - * Read a document, overlaying any staged create/update so agents, drafts, and - * previews see the latest uncommitted version. + * `readDocumentWithPendingAs` as `publicContext()`, which reads the published + * version only. + * + * @deprecated Use `readDocumentWithPendingAs(ctx, collectionName, id)`. */ export function readDocumentWithPending( collectionName: string, id: string, ): Promise { - return readDocumentWithPendingAs(UNSCOPED_READ, collectionName, id) + return readDocumentWithPendingAs(publicContext(), collectionName, id) } /** - * `readDocumentWithPending` as `ctx`. The staged overlay applies in `preview` - * and `edit` modes; a `live` context reads the published version only. A - * document `ctx` can't see reads as missing. + * Read a document as `ctx`, overlaying any staged create/update so agents, + * drafts, and previews see the latest uncommitted version. The overlay + * applies in `preview` and `edit` modes; a `live` context reads the + * published version only. A document `ctx` can't see reads as missing. */ export async function readDocumentWithPendingAs( ctx: AccessContext, @@ -509,34 +519,30 @@ function isRecord(v: unknown): v is Record { } /** - * Resolve every `relation` field on a document (including inside `group`, - * `array`, and `blocks`) into its target `Doc` (or `Array` for - * `many: true`), keyed by field name or dotted path. + * `populateRelationsAs` as `publicContext()`. + * + * @deprecated Use `populateRelationsAs(ctx, collectionName, doc)`. */ export function populateRelations( collectionName: string, doc: Doc, - options?: { publishedOnly?: boolean; session?: CmsSession } | CmsSession, ): Promise | null>> { - const opts: { publishedOnly?: boolean; session?: CmsSession } = - options && 'isAuthenticated' in options - ? { session: options } - : (options ?? {}) - return populateRelationsAs(legacyReadContext(opts), collectionName, doc) + return populateRelationsAs(publicContext(), collectionName, doc) } /** - * `populateRelations` as `ctx`. Related documents don't get `publicRead` - * visibility: each target is read under the target collection's own rule. + * Resolve every `relation` field on a document (including inside `group`, + * `array`, and `blocks`) into the target `Doc`s `ctx` may read (an + * `Array` for `many: true`), keyed by field name or dotted path. A + * `publicRead` context sees published targets the way it sees the source. */ export async function populateRelationsAs( - context: AccessContext, + ctx: AccessContext, collectionName: string, doc: Doc, ): Promise | null>> { const collection = collections()[collectionName] if (!collection) return {} - const ctx = withoutPublicRead(context) const live = isLiveRead(ctx) const sourceDoc = redactFor(ctx, collectionName, doc) const storage = await getStorage() @@ -613,20 +619,19 @@ export async function populateRelationsAs( return resolved } -/** The single document of an `isSingleton` collection. */ +/** + * The published document of an `isSingleton` collection, read as + * `publicContext()`. + * + * @deprecated Use `readSingletonAs(ctx, collectionName)`. + */ export function readSingleton( collectionName: string, - options?: { publishedOnly?: boolean }, ): Promise<{ id: string; doc: Doc } | null> { - return readSingletonAs( - legacyReadContext({ publishedOnly: options?.publishedOnly }), - collectionName, - ) + return readSingletonAs(publicContext(), collectionName) } -/** - * `readSingleton` as `ctx`. - */ +/** The single document of an `isSingleton` collection, as `ctx` reads it. */ export async function readSingletonAs( ctx: AccessContext, collectionName: string, @@ -654,23 +659,28 @@ export async function readSingletonAs( type Relations = Record | null> -/** Read by id, or by the collection's slug field (leading slashes ignored). */ +/** + * `readDocumentBySlugAs` as `publicContext()`. + * + * @deprecated Use `readDocumentBySlugAs(ctx, collectionName, slugOrId, options)`. + */ export function readDocumentBySlug( collectionName: string, slugOrId: string, - options?: { - publishedOnly?: boolean - populate?: boolean - session?: CmsSession - }, + options?: { populate?: boolean }, ): Promise<{ id: string; doc: Doc; relations?: Relations } | null> { - const [doc, relations] = legacySlugContexts(options) - return readBySlug(doc, relations, collectionName, slugOrId, options?.populate) + return readDocumentBySlugAs( + publicContext(), + collectionName, + slugOrId, + options, + ) } /** - * `readDocumentBySlug` as `ctx`: a match `ctx` can't see is skipped, and the - * returned document is redacted. + * Read by id, or by the collection's slug field (leading slashes ignored), + * as `ctx`: a match `ctx` can't see is skipped, and the returned document + * is redacted. */ export function readDocumentBySlugAs( ctx: AccessContext, @@ -678,27 +688,11 @@ export function readDocumentBySlugAs( slugOrId: string, options?: { populate?: boolean }, ): Promise<{ id: string; doc: Doc; relations?: Relations } | null> { - return readBySlug(ctx, ctx, collectionName, slugOrId, options?.populate) -} - -/** - * The legacy slug reads check no access on the matched document: the session - * only scopes populated relations. - */ -function legacySlugContexts(options?: { - publishedOnly?: boolean - session?: CmsSession -}): [AccessContext, AccessContext] { - const relations = legacyReadContext(options ?? {}) - return [ - bypassingContext(relations, 'slug read: the session scopes relations only'), - relations, - ] + return readBySlug(ctx, collectionName, slugOrId, options?.populate) } async function readBySlug( ctx: AccessContext, - relationsCtx: AccessContext, collectionName: string, slugOrId: string, populate: boolean | undefined, @@ -711,11 +705,7 @@ async function readBySlug( doc: redactFor(ctx, collectionName, doc), ...(populate ? { - relations: await populateRelationsAs( - relationsCtx, - collectionName, - doc, - ), + relations: await populateRelationsAs(ctx, collectionName, doc), } : {}), }) @@ -745,46 +735,29 @@ async function readBySlug( } /** - * Find a document by id/slug across collections, trying `preferred` - * collections first. Used by the public `/p/:id` and `/post/:id` routes. + * `findDocumentBySlugAs` as `publicContext()`. + * + * @deprecated Use `findDocumentBySlugAs(ctx, slugOrId, options)`. */ export function findDocumentBySlug( slugOrId: string, - options?: { - preferred?: Array - publishedOnly?: boolean - populate?: boolean - session?: CmsSession - }, + options?: { preferred?: Array; populate?: boolean }, ): Promise<{ collection: string id: string doc: Doc relations?: Relations } | null> { - const [doc, relations] = legacySlugContexts(options) - return findBySlug(doc, relations, slugOrId, options) + return findDocumentBySlugAs(publicContext(), slugOrId, options) } /** - * `findDocumentBySlug` as `ctx`. + * Find a document `ctx` can see by id/slug across collections, trying + * `preferred` collections first. Used by the public `/p/:id` and + * `/post/:id` routes. */ -export function findDocumentBySlugAs( - ctx: AccessContext, - slugOrId: string, - options?: { preferred?: Array; populate?: boolean }, -): Promise<{ - collection: string - id: string - doc: Doc - relations?: Relations -} | null> { - return findBySlug(ctx, ctx, slugOrId, options) -} - -async function findBySlug( +export async function findDocumentBySlugAs( ctx: AccessContext, - relationsCtx: AccessContext, slugOrId: string, options?: { preferred?: Array; populate?: boolean }, ): Promise<{ @@ -799,24 +772,21 @@ async function findBySlug( ...Object.keys(collections()).filter((c) => !preferred.includes(c)), ] for (const collection of order) { - const found = await readBySlug( - ctx, - relationsCtx, - collection, - slugOrId, - options?.populate, - ) + const found = await readBySlug(ctx, collection, slugOrId, options?.populate) if (found) return { collection, ...found } } return null } -/** Published documents grouped by collection and id. Prefer `queryDocuments` for large sites. */ +/** + * Published documents grouped by collection and id, as an anonymous visitor + * sees them. Prefer `queryDocumentsAs` for large sites. + */ export async function listPublicDocuments( collectionName?: string, ): Promise>> { const storage = await getStorage() - const ctx = systemContext('listPublicDocuments', { mode: 'live' }) + const ctx = publicContext() const names = collectionName ? [collectionName] : Object.keys(collections()) const out: Record> = {} for (const col of names) { @@ -863,27 +833,24 @@ async function scanCollection( } /** - * Documents whose `relation` fields point at `collection/id`, including - * relations inside groups, arrays, and blocks. `field` is the dotted path. + * `findReferencesAs` as `publicContext()`. + * + * @deprecated Use `findReferencesAs(ctx, collectionName, id, adapter)`. */ export function findReferences( collectionName: string, id: string, adapter?: StorageOps, - session?: CmsSession, ): Promise> { - return findReferencesAs( - legacyReadContext({ session }), - collectionName, - id, - adapter, - ) + return findReferencesAs(publicContext(), collectionName, id, adapter) } /** - * `findReferences` as `ctx`: only references from documents `ctx` can see, - * through fields it can read. The read mode doesn't apply: references from - * drafts and staged changes count. + * Documents whose `relation` fields point at `collection/id`, including + * relations inside groups, arrays, and blocks; `field` is the dotted path. + * Only references from documents `ctx` can see, through fields it can read. + * The read mode doesn't apply: references from drafts and staged changes + * count. */ export async function findReferencesAs( ctx: AccessContext, @@ -1022,21 +989,21 @@ export async function findReferencesAs( return visibleReferences() } -/** All locale variants linked to a document (canonical source + translations). */ +/** + * `listTranslationsAs` as `publicContext()`. + * + * @deprecated Use `listTranslationsAs(ctx, collectionName, docId)`. + */ export function listTranslations( collectionName: string, docId: string, - session?: CmsSession, ): Promise> { - return listTranslationsAs( - legacyReadContext({ session }), - collectionName, - docId, - ) + return listTranslationsAs(publicContext(), collectionName, docId) } /** - * `listTranslations` as `ctx`: only the variants `ctx` can see. + * All locale variants linked to a document (canonical source + + * translations) that `ctx` can see. */ export async function listTranslationsAs( ctx: AccessContext, @@ -1045,13 +1012,17 @@ export async function listTranslationsAs( ): Promise> { const collection = requireCollection(collectionName) const storage = await getStorage() - const current = await readDocument(collectionName, docId) + const current = await readDocumentAs(TRANSLATION_LINKS, collectionName, docId) if (!current) return [] const canonicalId = typeof current.translationOf === 'string' && current.translationOf ? current.translationOf : docId - const canonical = await readDocument(collectionName, canonicalId) + const canonical = await readDocumentAs( + TRANSLATION_LINKS, + collectionName, + canonicalId, + ) const summarizeVariant = ( id: string, @@ -1095,7 +1066,11 @@ export async function listTranslationsAs( if (bypassesRules(ctx) && !ctx.scope && !live) return Array.from(out.values()) const visible: Array = [] for (const variant of out.values()) { - const doc = await readDocument(collectionName, variant.id) + const doc = await readDocumentAs( + TRANSLATION_LINKS, + collectionName, + variant.id, + ) if (!doc || (live && !variant.published)) continue if ( !canReadDocument(ctx, collectionName, { diff --git a/packages/core/src/server/store/review.ts b/packages/core/src/server/store/review.ts index 0dfc01a6..2fbd6f10 100644 --- a/packages/core/src/server/store/review.ts +++ b/packages/core/src/server/store/review.ts @@ -15,7 +15,7 @@ import { checkFieldRules, requireWritableCollection, } from './internal' -import { readDocument } from './read' +import { readDocumentAs } from './read' import { executeStrategyWrite, prepareStagedChange } from './document-state' import type { CmsSession } from '../../lib/auth' import type { PendingSource, StorageOps, WriteType } from '../../storage/types' @@ -23,6 +23,8 @@ import type { AccessContext } from '../../lib/access-context' import type { IncomingChange, StrategyOutcome } from './document-state' import type { AuditEntry, Pending } from './internal' +const STAGE_BEFORE_READ = systemContext('saveDraft: the committed document') + export interface StageWriteArgs { collection: string docId: string @@ -286,7 +288,7 @@ export async function saveDraft( ctx?: AccessContext }, ): Promise { - const live = await readDocument(collectionName, id) + const live = await readDocumentAs(STAGE_BEFORE_READ, collectionName, id) assertExpectedRevision(live, options?.expectedRevision) return stageWrite({ collection: collectionName, diff --git a/packages/core/src/server/store/revisions.ts b/packages/core/src/server/store/revisions.ts index 6ccdf670..9d7bf1ff 100644 --- a/packages/core/src/server/store/revisions.ts +++ b/packages/core/src/server/store/revisions.ts @@ -8,13 +8,15 @@ import { protectWrite } from '../access' import { bypassesRules, canReadDocument, + publicContext, redactFor, + systemContext, withoutPublicRead, } from '../access-context' import { assertCollectionAccess } from '../auth' import { upgradeStoredDoc } from '../content-migrations' import { getStorage } from '../storage' -import { readDocumentWithPending } from './read' +import { readDocumentWithPendingAs } from './read' import { stageWrite } from './review' import { commitDocument } from './write' import type { AccessContext } from '../access-context' @@ -22,25 +24,32 @@ import type { CmsSession } from '../../lib/auth' import type { Doc } from '../../schema' import type { Pending, Revision } from './internal' -/** Revision history, newest first. */ -export async function listRevisions( +const RESTORE = systemContext('revision restore') + +/** + * `listRevisionsAs` as `publicContext()`. + * + * @deprecated Use `listRevisionsAs(ctx, collectionName, docId)`. + */ +export function listRevisions( collectionName: string, docId: string, ): Promise> { - const storage = await getStorage() - return storage.listRevisions(collectionName, docId) + return listRevisionsAs(publicContext(), collectionName, docId) } /** - * `listRevisions` as `ctx`: the revisions `ctx` may read, redacted. The read - * mode doesn't apply; history includes unpublished versions. + * Revision history, newest first: the revisions `ctx` may read, redacted. + * The read mode doesn't apply; history includes unpublished versions. */ export async function listRevisionsAs( ctx: AccessContext, collectionName: string, docId: string, ): Promise> { - const revisions = await listRevisions(collectionName, docId) + const revisions = await ( + await getStorage() + ).listRevisions(collectionName, docId) if (bypassesRules(ctx) && !ctx.scope) return revisions const scoped = withoutPublicRead(ctx) return revisions @@ -61,7 +70,7 @@ export async function restoreRevision( revisionIdOrNumber: string | number, options?: { actor?: string; stage?: boolean; session?: CmsSession }, ): Promise { - const revisions = await listRevisions(collectionName, docId) + const revisions = await listRevisionsAs(RESTORE, collectionName, docId) const numeric = typeof revisionIdOrNumber === 'number' ? revisionIdOrNumber @@ -91,7 +100,9 @@ export async function restoreRevision( // path upgrade an older revision to the current shape. let doc: Doc = { ...rest, _contentVersion: rest._contentVersion ?? 0 } if (options?.session) { - const existing = (await readDocumentWithPending(collectionName, docId)).doc + const existing = ( + await readDocumentWithPendingAs(RESTORE, collectionName, docId) + ).doc doc = protectWrite(collectionName, doc, existing, options.session) } const summary = `Restored from revision #${target.revision}` diff --git a/packages/core/src/server/store/scheduling.ts b/packages/core/src/server/store/scheduling.ts index 12eae696..8a631796 100644 --- a/packages/core/src/server/store/scheduling.ts +++ b/packages/core/src/server/store/scheduling.ts @@ -12,7 +12,7 @@ import { registerScheduledSweep, } from '../storage' import { executeStrategyWrite } from './document-state' -import { readDocument } from './read' +import { readDocumentAs } from './read' import { stageWrite } from './review' import { commitDocument } from './write' import type { Doc } from '../../schema' @@ -21,6 +21,7 @@ import type { AccessContext } from '../../lib/access-context' import type { Pending } from './internal' const SCHEDULER = systemContext('scheduled publishing', { actor: 'scheduler' }) +const SCHEDULE_READ = systemContext('scheduleDocument: the committed document') /** * Fire the strategy's `publish` / `unpublish` action as the scheduler. Skips @@ -185,7 +186,7 @@ export async function scheduleDocument( publishAt: string | null, options?: { actor?: string; stage?: boolean; ctx?: AccessContext }, ): Promise { - const existing = await readDocument(collectionName, docId) + const existing = await readDocumentAs(SCHEDULE_READ, collectionName, docId) if (!existing) { throw new CmsError( `No ${collectionName} document with id "${docId}".`, diff --git a/packages/core/src/server/store/write.ts b/packages/core/src/server/store/write.ts index c0ff7eb9..da518a4e 100644 --- a/packages/core/src/server/store/write.ts +++ b/packages/core/src/server/store/write.ts @@ -24,10 +24,14 @@ import { validate, writeDocument, } from './internal' -import { findReferences, readDocument, readDocumentWithPending } from './read' +import { accessContext, systemContext } from '../access-context' +import { + findReferencesAs, + readDocumentAs, + readDocumentWithPendingAs, +} from './read' import { stageWrite } from './review' import { assertCollectionAccess } from '../auth' -import { accessContext, systemContext } from '../access-context' import { executeStrategyWrite } from './document-state' import type { AccessContext } from '../access-context' import type { CmsSession } from '../../lib/auth' @@ -35,6 +39,8 @@ import type { Doc } from '../../schema' import type { Pending } from './internal' import type { AuditRecord, StorageOps } from '../../storage/types' +const WRITE_READ = systemContext('write path') + export interface CommitOptions { actor?: string summary?: string @@ -165,7 +171,7 @@ export async function deleteDocument( ): Promise { const collection = requireWritableCollection(collectionName) if (options?.stage) { - const existing = await readDocument(collectionName, id) + const existing = await readDocumentAs(WRITE_READ, collectionName, id) return stageWrite({ collection: collectionName, docId: id, @@ -200,7 +206,11 @@ export async function deleteDocument( ) }) notifyStorageCommit() - await runAfterDelete(collection, { id, actor }) + await runAfterDelete(collection, { + id, + actor, + ...(options?.session ? { session: options.session } : {}), + }) emitCmsEvent('document.deleted', { collection: collectionName, id, @@ -289,10 +299,15 @@ export async function commitDeletion( existingRow?.doc ?? pendingRow?.after ?? null, ) if (existingRow && !options.force) { - const refs = await findReferences(collectionName, id, tx) + const refs = await findReferencesAs(WRITE_READ, collectionName, id, tx) if (refs.length) { const readable = options.session - ? await findReferences(collectionName, id, tx, options.session) + ? await findReferencesAs( + accessContext({ session: options.session, mode: 'edit' }), + collectionName, + id, + tx, + ) : refs throw new CmsError( `Cannot delete ${collectionName}/${id}: referenced by ${ @@ -472,8 +487,8 @@ export async function unpublishDocument( options?: { actor?: string; stage?: boolean; instruction?: string }, ): Promise { const existing = - (await readDocument(collectionName, id)) ?? - (await readDocumentWithPending(collectionName, id)).doc + (await readDocumentAs(WRITE_READ, collectionName, id)) ?? + (await readDocumentWithPendingAs(WRITE_READ, collectionName, id)).doc if (!existing) { throw new CmsError( `No ${collectionName} document with id "${id}".`, diff --git a/packages/core/tests/access-context.test.ts b/packages/core/tests/access-context.test.ts index 845917b1..2ee94504 100644 --- a/packages/core/tests/access-context.test.ts +++ b/packages/core/tests/access-context.test.ts @@ -15,8 +15,13 @@ import { cmsTools, commitDocument, createPreviewToken, + findDocumentBySlug, + listRevisions, + populateRelations, queryDocuments, + readDocument, readDocumentBySlug, + readDocumentWithPending, runOp, stageWrite, } from '../src/server' @@ -25,7 +30,6 @@ import { assertReadable, canReadCollection, canReadDocument, - legacyReadContext, previewContext, previewTokenContext, publicContext, @@ -34,6 +38,7 @@ import { parseReadMode, storageVisibility, systemContext, + narrowMode, withMode, } from '../src/server/access-context' import { cmsAs } from '../src/server/cms-as' @@ -249,19 +254,14 @@ describe('builders', () => { }) }) - it('legacyReadContext maps today’s read arguments', () => { - const none = legacyReadContext({}) - expect(none.actor.kind).toBe('system') - expect(none.mode).toBe('edit') - expect(legacyReadContext({ publishedOnly: true }).mode).toBe('live') - const staff = legacyReadContext({ - session: as('viewer'), - publishedOnly: false, - publicRead: true, - }) - expect(staff.actor.kind).toBe('user') - expect(staff.mode).toBe('edit') - expect(staff.publicRead).toBe(true) + it('narrowMode only ever narrows', () => { + const edit = systemContext('x') + expect(narrowMode(edit, 'live').mode).toBe('live') + expect(narrowMode(edit, undefined)).toBe(edit) + const live = publicContext() + expect(narrowMode(live, 'edit')).toBe(live) + expect(narrowMode(live, 'preview')).toBe(live) + expect(() => narrowMode(edit, 'all' as never)).toThrow(/Unknown read mode/) }) }) @@ -314,14 +314,26 @@ describe('derivation', () => { expect(await ids(editor, 'memo')).toEqual(['m-draft', 'm-live']) }) - it('redacts fields by session and populates relations under their own rule', async () => { + it('redacts fields by session; populated relations keep publicRead', async () => { const cms = await seeded() const viewerRelations = await cmsAs( cms, accessContext({ session: as('viewer'), publicRead: true }), ).queryDocuments({ collection: 'post', populate: true }) expect(viewerRelations.items[0]?.doc).not.toHaveProperty('secret') - expect(viewerRelations.items[0]?.relations).toEqual({}) + expect(viewerRelations.items[0]?.relations?.author).toMatchObject({ + title: 'Published memo', + }) + const bySlug = await cmsAs( + cms, + accessContext({ session: as('viewer'), publicRead: true }), + ).readDocumentBySlug('post', 'live', { populate: true }) + expect(bySlug?.relations?.author).toMatchObject({ title: 'Published memo' }) + const ruled = await cmsAs( + cms, + accessContext({ session: as('viewer') }), + ).populateRelations('post', { title: 'x', author: 'm-live' }) + expect(ruled).toEqual({}) const admin = cmsAs(cms, accessContext({ session: as('admin') })) const [live] = ( @@ -361,37 +373,80 @@ describe('derivation', () => { expect((await live.readDocumentWithPending('post', 'draft')).doc).toBeNull() }) - it('a preview context reads its one document, unredacted, overlay included', async () => { + it('a preview context reads its one document, redacted, overlay included', async () => { const cms = await seeded() - const ctx = previewContext({ - id: 't1', - collection: 'post', - docId: 'live', - expiresAt: new Date(Date.now() + 60_000).toISOString(), - createdAt: new Date().toISOString(), - createdBy: 'ada', - }) - const db = cmsAs(cms, ctx) + const token = (docId: string) => + previewContext({ + id: 't1', + collection: 'post', + docId, + expiresAt: new Date(Date.now() + 60_000).toISOString(), + createdAt: new Date().toISOString(), + createdBy: 'ada', + }) + const db = cmsAs(cms, token('live')) const read = await db.readDocumentWithPending('post', 'live') expect(read.doc?.title).toBe('Staged title') expect((await db.readDocumentWithPending('post', 'draft')).doc).toBeNull() expect(await ids(db, 'post')).toEqual(['live']) expect(await ids(db, 'memo')).toEqual([]) + + const draft = cmsAs(cms, token('draft')) + const drafted = await draft.readDocumentWithPending('post', 'draft') + expect(drafted.doc?.title).toBe('Draft post') + expect(drafted.doc).not.toHaveProperty('secret') + expect(await draft.readDocument('post', 'draft')).not.toHaveProperty( + 'secret', + ) + expect(() => cms.run(() => assertReadable(token('draft'), 'memo'))).toThrow( + /Forbidden/, + ) }) - it('legacy slug reads keep skipping the session for the matched document', async () => { + it('slug reads check access on the matched document', async () => { const cms = await seeded() + const viewer = cmsAs( + cms, + accessContext({ session: as('viewer'), mode: 'edit' }), + ) + expect(await viewer.readDocumentBySlug('memo', 'm-live')).toBeNull() + expect(await viewer.readDocumentBySlug('memo', 'm-draft')).toBeNull() + expect( + await viewer.findDocumentBySlug('m-draft', { preferred: ['memo'] }), + ).toBeNull() await cms.run(async () => { - const viewer = as('viewer') + expect(await readDocumentBySlug('memo', 'm-draft')).toBeNull() + expect(await readDocumentBySlug('post', 'draft')).toBeNull() + expect(await findDocumentBySlug('m-draft')).toBeNull() expect( - (await readDocumentBySlug('memo', 'm-live', { session: viewer }))?.id, - ).toBe('m-live') + (await readDocumentBySlug('post', 'live'))?.doc, + ).not.toHaveProperty('secret') + }) + const editor = cmsAs( + cms, + accessContext({ session: as('editor'), mode: 'edit' }), + ) + expect((await editor.readDocumentBySlug('memo', 'm-draft'))?.id).toBe( + 'm-draft', + ) + }) + + it('the deprecated verbs without a context read as public', async () => { + const cms = await seeded() + await cms.run(async () => { + const { items } = await queryDocuments({ collection: 'post' }) + expect(items.map((i) => i.id)).toEqual(['live']) + expect(items[0]?.doc).not.toHaveProperty('secret') + expect(await readDocument('post', 'draft')).toBeNull() + expect(await readDocument('post', 'live')).not.toHaveProperty('secret') + const working = await readDocumentWithPending('post', 'live') + expect(working).toMatchObject({ isPending: false }) + expect(working.doc?.title).toBe('Live post') + expect(await listRevisions('post', 'draft')).toEqual([]) expect( - (await queryDocuments({ collection: 'memo', session: viewer })).total, - ).toBe(0) + await populateRelations('post', { title: 'x', author: 'm-draft' }), + ).toEqual({ author: null }) }) - const handle = cmsAs(cms, accessContext({ session: as('viewer') })) - expect(await handle.readDocumentBySlug('memo', 'm-live')).toBeNull() }) it('postRead receives the reading context', async () => { @@ -476,6 +531,59 @@ describe('derivation', () => { }) }) + it('runOp and cmsTools refuse a call without a context', async () => { + const cms = await seeded() + await cms.run(async () => { + const list = { collection: 'post' } + await expect( + runOp('list_documents', list, 'agent', undefined as never), + ).rejects.toThrow(/needs an access context/) + await expect( + runOp('list_documents', list, 'agent', { ...publicContext() }), + ).rejects.toThrow(/needs an access context/) + const [tool] = (await cmsTools('mcp')).filter( + (t) => t.name === 'list_documents', + ) + await expect(tool!.execute!(list, {} as never)).rejects.toThrow( + /no access context/, + ) + const viaCall = (await tool!.execute!(list, { + context: { + [CMS_ACCESS_KEY]: accessContext({ + session: as('editor'), + mode: 'live', + }), + }, + } as never)) as Array<{ id: string }> + expect(viaCall.map((d) => d.id)).toEqual(['live']) + }) + }) + + it('search_documents narrows to live, never widens', async () => { + const cms = await seeded() + await cms.run(async () => { + const search = (mode: string, ctx = systemContext('test')) => + runOp( + 'search_documents', + { collection: 'post', mode }, + 'agent', + ctx, + ) as Promise<{ items: Array<{ id: string }> }> + expect((await search('live')).items.map((i) => i.id)).toEqual(['live']) + expect((await search('edit')).items.map((i) => i.id).sort()).toEqual([ + 'draft', + 'live', + ]) + const anon = accessContext({ + session: as('admin'), + mode: 'live', + }) + expect((await search('edit', anon)).items.map((i) => i.id)).toEqual([ + 'live', + ]) + }) + }) + it('scopes reads to the bound instance', async () => { const cms = await seeded() const other = createCms(config('other')) diff --git a/packages/core/tests/assets.test.ts b/packages/core/tests/assets.test.ts index 5be020ca..8dae0e9e 100644 --- a/packages/core/tests/assets.test.ts +++ b/packages/core/tests/assets.test.ts @@ -19,22 +19,22 @@ import type { CmsSessionInput, InferDoc } from '../src/index' import { closeStore, commitDocument, - findReferences, getMediaItem, getStorage, - readDocument, readMedia, resolveMediaAdapter, - runWithSession, saveMedia, updateMediaItem, deleteMediaItem, reject, listPending, - readDocumentWithPending, focalCropWindow, sweepAssetOrphans, deleteDocument, + systemContext, + readDocumentAs, + readDocumentWithPendingAs, + findReferencesAs, } from '../src/server' import { createLocalMedia } from '../src/media' import type { MediaAdapter } from '../src/media' @@ -131,7 +131,7 @@ describe('asset collection (built-in)', () => { }, { actor: 'edie' }, ) - const doc = await readDocument(name, 'a1') + const doc = await readDocumentAs(systemContext('test'), name, 'a1') expect(doc?.filename).toBe('a1.png') expect(doc?._revision).toBe(1) }) @@ -184,12 +184,18 @@ describe('asset field type', () => { describe('/api/media/ resolution', () => { it('serves an uploaded asset and preserves the transform pipeline', async () => { setup() - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'cat.png', alt: 'A cat' }), - ) + const item = await saveMedia(PNG, { + filename: 'cat.png', + alt: 'A cat', + session: editor, + }) expect(item.url).toBe(`/api/media/${item.id}`) // The asset exists as a published document. - const doc = await readDocument(assetCollectionName(), item.id) + const doc = await readDocumentAs( + systemContext('test'), + assetCollectionName(), + item.id, + ) expect(doc?.blobKey).toBe(`${item.id}.png`) const read = await readMedia(item.url) @@ -200,21 +206,28 @@ describe('/api/media/ resolution', () => { it('shows a non-publisher their own pending upload but hides it from others', async () => { setup() // An author (no publish rights) uploads: the asset doc is staged. - const item = await runWithSession(author, () => - saveMedia(PNG, { filename: 'draft.png' }), - ) + const item = await saveMedia(PNG, { + filename: 'draft.png', + session: author, + }) // Not committed yet. - expect(await readDocument(assetCollectionName(), item.id)).toBeNull() + expect( + await readDocumentAs( + systemContext('test'), + assetCollectionName(), + item.id, + ), + ).toBeNull() expect((await listPending()).some((p) => p.docId === item.id)).toBe(true) // The uploader resolves their own pending asset via the overlay. - const mine = await runWithSession(author, () => getMediaItem(item.url)) + const mine = await getMediaItem(item.url, author) expect(mine?.id).toBe(item.id) // Another author does NOT see the unapproved asset. - const theirs = await runWithSession(other, () => getMediaItem(item.url)) + const theirs = await getMediaItem(item.url, other) expect(theirs).toBeNull() // Neither does an anonymous visitor. - const nobody = await runWithSession(anon, () => getMediaItem(item.url)) + const nobody = await getMediaItem(item.url, anon) expect(nobody).toBeNull() }) @@ -225,9 +238,7 @@ describe('/api/media/ resolution', () => { publicUrl: (key) => `https://cdn.test/${key}`, } setup({ media: cdn }) - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'cdn.png' }), - ) + const item = await saveMedia(PNG, { filename: 'cdn.png', session: editor }) const read = await readMedia(item.url) expect(read?.redirect).toBe(`https://cdn.test/${item.id}.png`) }) @@ -236,29 +247,43 @@ describe('/api/media/ resolution', () => { describe('governed upload (review for non-publishers)', () => { it('stages an author upload and commits an editor upload', async () => { setup() - const authored = await runWithSession(author, () => - saveMedia(PNG, { filename: 'by-author.png' }), - ) - expect(await readDocument(assetCollectionName(), authored.id)).toBeNull() - - const published = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'by-editor.png' }), + const authored = await saveMedia(PNG, { + filename: 'by-author.png', + session: author, + }) + expect( + await readDocumentAs( + systemContext('test'), + assetCollectionName(), + authored.id, + ), + ).toBeNull() + + const published = await saveMedia(PNG, { + filename: 'by-editor.png', + session: editor, + }) + const doc = await readDocumentAs( + systemContext('test'), + assetCollectionName(), + published.id, ) - const doc = await readDocument(assetCollectionName(), published.id) expect(doc?.published).toBe(true) }) it('deletes the orphaned blob when a staged asset-create is rejected', async () => { setup() - const item = await runWithSession(author, () => - saveMedia(PNG, { filename: 'rejected.png' }), - ) + const item = await saveMedia(PNG, { + filename: 'rejected.png', + session: author, + }) const adapter = resolveMediaAdapter() expect(await adapter.get(`${item.id}.png`)).not.toBeNull() const pending = (await listPending()).find((p) => p.docId === item.id)! await reject(pending.id, { rejecter: 'edie' }) // The staged document is gone and its blob was cleaned up. - const overlay = await readDocumentWithPending( + const overlay = await readDocumentWithPendingAs( + systemContext('test'), assetCollectionName(), item.id, ) @@ -270,16 +295,18 @@ describe('governed upload (review for non-publishers)', () => { describe('where-used via findReferences', () => { it('finds documents that reference an asset through an asset field', async () => { setup() - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'used.png' }), - ) + const item = await saveMedia(PNG, { filename: 'used.png', session: editor }) await commitDocument( 'post', 'p1', { title: 'Uses it', hero: item.id, attachments: [] }, { actor: 'edie' }, ) - const refs = await findReferences(assetCollectionName(), item.id) + const refs = await findReferencesAs( + systemContext('test'), + assetCollectionName(), + item.id, + ) expect(refs.map((r) => `${r.collection}/${r.id}`)).toContain('post/p1') }) }) @@ -287,9 +314,10 @@ describe('where-used via findReferences', () => { describe('image field back-compat', () => { it('keeps serving a legacy /api/media URL stored in an image field', async () => { setup() - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'legacy.png' }), - ) + const item = await saveMedia(PNG, { + filename: 'legacy.png', + session: editor, + }) // Stored as a bare URL string in the `image` field — still resolves. await commitDocument( 'post', @@ -297,7 +325,7 @@ describe('image field back-compat', () => { { title: 'Legacy', cover: item.url, attachments: [] }, { actor: 'edie' }, ) - const doc = await readDocument('post', 'p1') + const doc = await readDocumentAs(systemContext('test'), 'post', 'p1') expect(doc?.cover).toBe(item.url) const read = await readMedia(String(doc?.cover)) expect(read?.record.id).toBe(item.id) @@ -307,16 +335,17 @@ describe('image field back-compat', () => { describe('metadata edits through the asset document', () => { it('updates and clears asset metadata', async () => { setup() - const item = await runWithSession(editor, () => - saveMedia(PNG, { - filename: 'edit.png', - caption: 'Original', - credit: 'Jane', - tags: ['a', 'b'], - }), - ) - const updated = await runWithSession(editor, () => - updateMediaItem(item.url, { caption: 'Changed', credit: '', tags: [] }), + const item = await saveMedia(PNG, { + filename: 'edit.png', + caption: 'Original', + credit: 'Jane', + tags: ['a', 'b'], + session: editor, + }) + const updated = await updateMediaItem( + item.url, + { caption: 'Changed', credit: '', tags: [] }, + editor, ) expect(updated.caption).toBe('Changed') expect(updated.credit).toBeUndefined() @@ -325,9 +354,10 @@ describe('metadata edits through the asset document', () => { it('refuses to delete an asset still referenced by a document', async () => { setup() - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'inuse.png' }), - ) + const item = await saveMedia(PNG, { + filename: 'inuse.png', + session: editor, + }) await commitDocument( 'post', 'p1', @@ -335,7 +365,7 @@ describe('metadata edits through the asset document', () => { { actor: 'edie' }, ) await expect( - runWithSession(editor, () => deleteMediaItem(item.url)), + deleteMediaItem(item.url, { session: editor }), ).rejects.toMatchObject({ code: 'CONFLICT' }) }) }) @@ -353,7 +383,11 @@ describe('no dual-read: loose-blob adoption + data migration', () => { expect(item?.id).toBe('loose1') expect(item?.filename).toBe('loose1.png') // Adoption created a governed asset document (the only read path now). - const doc = await readDocument(assetCollectionName(), 'loose1') + const doc = await readDocumentAs( + systemContext('test'), + assetCollectionName(), + 'loose1', + ) expect(doc?.blobKey).toBe('loose1.png') expect(doc?.published).toBe(true) }) @@ -462,9 +496,10 @@ describe('focal-point crop math (focalCropWindow)', () => { it('honors an asset focalPoint end-to-end through readMedia', async () => { setup() - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'focal.png' }), - ) + const item = await saveMedia(PNG, { + filename: 'focal.png', + session: editor, + }) // Give the asset dimensions + an off-center focal point. await commitDocument( assetCollectionName(), @@ -485,8 +520,10 @@ describe('focal-point crop math (focalCropWindow)', () => { // An aspect-changing transform should resolve (sharp may be absent in CI, // in which case the original is returned — either way it must not throw and // the focal point is read into the transform path). - const read = await runWithSession(editor, () => - readMedia(item.url, { width: 64, height: 64 }), + const read = await readMedia( + item.url, + { width: 64, height: 64 }, + { session: editor }, ) expect(read?.record.id).toBe(item.id) expect(read?.record.focalPoint).toEqual({ x: 0.9, y: 0.5 }) @@ -505,9 +542,7 @@ describe('orphan sweep (sweepAssetOrphans)', () => { // An orphan: a blob with no asset document. await adapter.put('orphan.png', PNG, { contentType: 'image/png' }) // An in-use blob: a committed asset document references it. - const used = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'kept.png' }), - ) + const used = await saveMedia(PNG, { filename: 'kept.png', session: editor }) const result = await sweepAssetOrphans({ now: now(), graceMs: 0 }) expect(result.deleted).toContain('orphan.png') expect(result.deleted).not.toContain(`${used.id}.png`) @@ -530,9 +565,10 @@ describe('orphan sweep (sweepAssetOrphans)', () => { it("keeps a trashed asset's blob (restore must work)", async () => { setup() const adapter = resolveMediaAdapter() - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'trashed.png' }), - ) + const item = await saveMedia(PNG, { + filename: 'trashed.png', + session: editor, + }) // Soft-delete (trash, not purge): the document is in trash; bytes remain. await deleteDocument(assetCollectionName(), item.id, { actor: 'edie' }) const result = await sweepAssetOrphans({ now: now(), graceMs: 0 }) @@ -544,10 +580,17 @@ describe('orphan sweep (sweepAssetOrphans)', () => { setup() const adapter = resolveMediaAdapter() // An author upload stages (no committed document) but writes the blob. - const item = await runWithSession(author, () => - saveMedia(PNG, { filename: 'staged.png' }), - ) - expect(await readDocument(assetCollectionName(), item.id)).toBeNull() + const item = await saveMedia(PNG, { + filename: 'staged.png', + session: author, + }) + expect( + await readDocumentAs( + systemContext('test'), + assetCollectionName(), + item.id, + ), + ).toBeNull() const result = await sweepAssetOrphans({ now: now(), graceMs: 0 }) expect(result.deleted).not.toContain(`${item.id}.png`) expect(await adapter.get(`${item.id}.png`)).not.toBeNull() @@ -556,9 +599,10 @@ describe('orphan sweep (sweepAssetOrphans)', () => { it('removes a blob left behind after a document purge (crash recovery)', async () => { setup() const adapter = resolveMediaAdapter() - const item = await runWithSession(editor, () => - saveMedia(PNG, { filename: 'lingering.png' }), - ) + const item = await saveMedia(PNG, { + filename: 'lingering.png', + session: editor, + }) // Simulate a crash between doc-purge and blob-delete: purge the document // but re-write the blob so it lingers with no backing document. await deleteDocument(assetCollectionName(), item.id, { diff --git a/packages/core/tests/characterization/workflow-suite.ts b/packages/core/tests/characterization/workflow-suite.ts index 7fbcf42c..47eba26d 100644 --- a/packages/core/tests/characterization/workflow-suite.ts +++ b/packages/core/tests/characterization/workflow-suite.ts @@ -60,20 +60,22 @@ import { listAudit, listPending, listPublicDocuments, - listRevisions, onCmsEvent, - readDocument, - readDocumentBySlug, - readDocumentWithPending, reject, runEventDispatch, runOp, runScheduledPublishing, - runWithSession, saveDraft, scheduleDocument, stageWrite, unpublishDocument, + publicContext, + systemContext, + accessContext, + readDocumentBySlugAs, + readDocumentAs, + listRevisionsAs, + readDocumentWithPendingAs, } from '../../src/server' import type { CmsReviewConfig } from '../../src/index' import type { CmsExport, StorageAdapter } from '../../src/server' @@ -213,9 +215,7 @@ export function runWorkflowCharacterization( }) async function publicTitle(): Promise { - const found = await readDocumentBySlug('post', 'p1', { - publishedOnly: true, - }) + const found = await readDocumentBySlugAs(publicContext(), 'post', 'p1') return found?.doc.title } @@ -243,9 +243,13 @@ export function runWorkflowCharacterization( expect(pending.baseRevision).toBeUndefined() expect(pending.after.title).toBe('Draft') expect(await listPending()).toHaveLength(1) - expect(await readDocument('post', 'p1')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toBeNull() expect(await publicTitle()).toBeUndefined() - expect(await listRevisions('post', 'p1')).toEqual([]) + expect( + await listRevisionsAs(systemContext('test'), 'post', 'p1'), + ).toEqual([]) // decided in phase 4 (2026-11-06): stage decisions are audited. expect(await auditFor('p1')).toEqual([ stageAudit('agent', 'submit', { @@ -273,12 +277,20 @@ export function runWorkflowCharacterization( source: 'agent', }) expect(pending.before?.title).toBe('Hello') - expect((await readDocument('post', 'p1'))?.title).toBe('Hello') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Hello') expect(await publicTitle()).toBe('Hello') expect((await listPublicDocuments('post')).post?.p1?.title).toBe( 'Hello', ) - expect(await readDocumentWithPending('post', 'p1')).toMatchObject({ + expect( + await readDocumentWithPendingAs( + systemContext('test'), + 'post', + 'p1', + ), + ).toMatchObject({ doc: { title: 'Hello, world' }, isPending: true, pendingId: pending.id, @@ -286,7 +298,9 @@ export function runWorkflowCharacterization( pendingVersion: 1, livePublished: true, }) - expect(await listRevisions('post', 'p1')).toHaveLength(1) + expect( + await listRevisionsAs(systemContext('test'), 'post', 'p1'), + ).toHaveLength(1) expect(await drainDurable()).toEqual(['review.submitted by agent']) expect(takeBus()).toEqual([]) }) @@ -396,7 +410,13 @@ export function runWorkflowCharacterization( expect(pending.after.title).toBe('Hello') expect(await publicTitle()).toBe('Hello') // A staged delete does not overlay the working copy. - expect(await readDocumentWithPending('post', 'p1')).toMatchObject({ + expect( + await readDocumentWithPendingAs( + systemContext('test'), + 'post', + 'p1', + ), + ).toMatchObject({ doc: { title: 'Hello' }, isPending: false, }) @@ -433,13 +453,19 @@ export function runWorkflowCharacterization( }) expect(await getPending(pending.id)).toBeNull() expect(await listPending()).toEqual([]) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Hello, world', published: true, _revision: 2, }) expect(await publicTitle()).toBe('Hello, world') - const [latest] = await listRevisions('post', 'p1') + const [latest] = await listRevisionsAs( + systemContext('test'), + 'post', + 'p1', + ) expect(latest).toMatchObject({ revision: 2, actor: 'agent', @@ -486,8 +512,13 @@ export function runWorkflowCharacterization( }) await drainDurable() await approve(pending.id) - expect((await readDocument('post', 'p1'))?._revision).toBe(1) - expect((await listRevisions('post', 'p1'))[0]).toMatchObject({ + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1')) + ?._revision, + ).toBe(1) + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'p1'))[0], + ).toMatchObject({ revision: 1, actor: 'agent', summary: 'Approved create from agent', @@ -521,7 +552,10 @@ export function runWorkflowCharacterization( actor: 'agent', }) await approve(pending.id, { publish: true }) - expect((await readDocument('post', 'p1'))?.published).toBe(true) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1')) + ?.published, + ).toBe(true) expect(await publicTitle()).toBe('New') }) @@ -547,7 +581,9 @@ export function runWorkflowCharacterization( code: 'NOT_FOUND', }) expect(await listPending()).toEqual([]) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Human', _revision: 2, }) @@ -596,10 +632,14 @@ export function runWorkflowCharacterization( }) await drainDurable() await approve(pending.id, { approver: 'reviewer' }) - expect(await readDocument('post', 'p1')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toBeNull() expect(await publicTitle()).toBeUndefined() expect( - await readDocument('post', 'p1', { includeDeleted: true }), + await readDocumentAs(systemContext('test'), 'post', 'p1', { + includeDeleted: true, + }), ).toMatchObject({ _revision: 2, deletedAt: expect.any(String) }) // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is // audited too. @@ -644,11 +684,15 @@ export function runWorkflowCharacterization( const decided = await reject(pending.id, { rejecter: 'reviewer' }) expect(decided.id).toBe(pending.id) expect(await listPending()).toEqual([]) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Hello', _revision: 1, }) - expect(await listRevisions('post', 'p1')).toHaveLength(1) + expect( + await listRevisionsAs(systemContext('test'), 'post', 'p1'), + ).toHaveLength(1) // fixed in phase 4a (#1: direct commit audit) — seedLive's commit is // audited too. // decided in phase 4 (2026-11-06): stage decisions are audited. @@ -750,7 +794,9 @@ export function runWorkflowCharacterization( true, ) expect(await listPending()).toEqual([]) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Hello', _revision: 1, }) @@ -874,7 +920,9 @@ export function runWorkflowCharacterization( after: { title: 'Agent', slug: 'p1-moved' }, }) await approve(proposal.id) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Agent', slug: 'p1-moved', _revision: 3, @@ -888,14 +936,21 @@ export function runWorkflowCharacterization( await commitDocument('post', 'p1', { title: 'v1', slug: 'p1' }) await commitDocument('post', 'p1', { title: 'v2', slug: 'p1' }) await commitDocument('post', 'p2', { title: 'other' }) - const revisions = await listRevisions('post', 'p1') + const revisions = await listRevisionsAs( + systemContext('test'), + 'post', + 'p1', + ) expect( revisions.map((r) => [r.revision, r.actor, r.summary]), ).toEqual([ [2, 'human', 'Edited document'], [1, 'human', 'Created document'], ]) - expect((await readDocument('post', 'p2'))?._revision).toBe(1) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p2')) + ?._revision, + ).toBe(1) }) it('create unpublished: document.created only, on the outbox and the bus; edit: document.updated', async () => { @@ -952,9 +1007,10 @@ export function runWorkflowCharacterization( const doc = await unpublishDocument('post', 'p1') expect(doc).toMatchObject({ published: false, _revision: 2 }) expect(await publicTitle()).toBeUndefined() - expect((await listRevisions('post', 'p1'))[0]?.summary).toBe( - 'Unpublish document', - ) + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'p1'))[0] + ?.summary, + ).toBe('Unpublish document') expect(await drainDurable()).toEqual([ 'document.unpublished by human', 'document.updated by human', @@ -981,15 +1037,21 @@ export function runWorkflowCharacterization( code: 'CONFLICT', details: { expectedRevision: 5, actualRevision: 1 }, }) - expect(await listRevisions('post', 'p1')).toHaveLength(1) + expect( + await listRevisionsAs(systemContext('test'), 'post', 'p1'), + ).toHaveLength(1) }) it('deleteDocument (direct): soft delete, revision +1, audit approved type delete under the human actor', async () => { setup() await seedLive() await deleteDocument('post', 'p1') - expect(await readDocument('post', 'p1')).toBeNull() - expect((await listRevisions('post', 'p1'))[0]).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toBeNull() + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'p1'))[0], + ).toMatchObject({ revision: 2, summary: 'Deleted document', }) @@ -1022,7 +1084,9 @@ export function runWorkflowCharacterization( published: false, _revision: 2, }) - expect((await listRevisions('post', 'p1'))[0]).toMatchObject({ + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'p1'))[0], + ).toMatchObject({ actor: 'human', summary: `Schedule publish for ${LATER}`, }) @@ -1031,13 +1095,17 @@ export function runWorkflowCharacterization( expect(await runScheduledPublishing(AFTER_LATER)).toEqual([ { collection: 'post', id: 'p1', publishedAt: AFTER_LATER }, ]) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ published: true, publishAt: LATER, _revision: 3, }) expect(await publicTitle()).toBe('Soon') - expect((await listRevisions('post', 'p1'))[0]).toMatchObject({ + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'p1'))[0], + ).toMatchObject({ revision: 3, actor: 'scheduler', summary: `Auto-published on schedule (${LATER})`, @@ -1089,10 +1157,12 @@ export function runWorkflowCharacterization( takeBus() // Unpublishes are not part of the returned list. expect(await runScheduledPublishing(AFTER_LATER)).toEqual([]) - const doc = await readDocument('post', 'p1') + const doc = await readDocumentAs(systemContext('test'), 'post', 'p1') expect(doc).toMatchObject({ published: false, _revision: 2 }) expect(doc?.unpublishAt).toBeUndefined() - expect((await listRevisions('post', 'p1'))[0]).toMatchObject({ + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'p1'))[0], + ).toMatchObject({ actor: 'scheduler', summary: `Auto-unpublished on schedule (${LATER})`, }) @@ -1133,7 +1203,9 @@ export function runWorkflowCharacterization( version: 2, publishAt: LATER, }) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Hello', published: true, _revision: 1, @@ -1146,7 +1218,9 @@ export function runWorkflowCharacterization( expect.objectContaining({ collection: 'post', id: 'p1' }), ]) expect(await listPending()).toEqual([]) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Next', published: true, _revision: 2, @@ -1173,7 +1247,10 @@ export function runWorkflowCharacterization( instruction: `Schedule publish for ${LATER}`, after: { publishAt: LATER, published: false }, }) - expect((await readDocument('post', 'p1'))?.publishAt).toBeUndefined() + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1')) + ?.publishAt, + ).toBeUndefined() }) }) @@ -1259,7 +1336,9 @@ export function runWorkflowCharacterization( actor: 'trusted', source: 'review', }) - expect((await readDocument('post', 'p1'))?.title).toBe('Trusted') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Trusted') expect((await listPending()).map((p) => p.docId).sort()).toEqual([ 'boom', 'p2', @@ -1287,7 +1366,9 @@ export function runWorkflowCharacterization( expect(result).toMatchObject({ created: 1, updated: 0 }) expect(await listPending()).toEqual([]) expect(await publicTitle()).toBe('Imported') - expect(await listRevisions('post', 'p1')).toEqual([ + expect( + await listRevisionsAs(systemContext('test'), 'post', 'p1'), + ).toEqual([ expect.objectContaining({ revision: 1, actor: 'import', @@ -1342,18 +1423,19 @@ export function runWorkflowCharacterization( role: 'admin', user: { id: 'ada', name: 'Ada' }, }) - await runWithSession(admin, async () => { - await runOp( - 'create_document', - { collection: 'post', id: 'p2', doc: { title: 'New' } }, - 'mcp', - ) - await runOp( - 'update_document', - { collection: 'post', id: 'p1', doc: { title: 'Edited' } }, - 'mcp', - ) - }) + const agent = accessContext({ session: admin, mode: 'edit' }) + await runOp( + 'create_document', + { collection: 'post', id: 'p2', doc: { title: 'New' } }, + 'mcp', + agent, + ) + await runOp( + 'update_document', + { collection: 'post', id: 'p1', doc: { title: 'Edited' } }, + 'mcp', + agent, + ) const pending = await listPending() expect( pending @@ -1364,7 +1446,9 @@ export function runWorkflowCharacterization( ['p2', 'create', 'mcp', 'agent'], ]) expect(await publicTitle()).toBe('Hello') - expect(await readDocument('post', 'p2')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'p2'), + ).toBeNull() }) it('unpublish_document, schedule_document and delete_document stage too (instruction defaults name the action)', async () => { @@ -1374,6 +1458,7 @@ export function runWorkflowCharacterization( 'unpublish_document', { collection: 'post', id: 'p1' }, 'mcp', + systemContext('test'), ) const [unpublish] = await listPending() expect(unpublish).toMatchObject({ @@ -1386,6 +1471,7 @@ export function runWorkflowCharacterization( 'schedule_document', { collection: 'post', id: 'p1', publishAt: LATER }, 'mcp', + systemContext('test'), ) const [schedule] = await listPending() expect(schedule).toMatchObject({ @@ -1397,6 +1483,7 @@ export function runWorkflowCharacterization( 'delete_document', { collection: 'post', id: 'p1' }, 'mcp', + systemContext('test'), ) expect(await listPending()).toEqual([ expect.objectContaining({ diff --git a/packages/core/tests/collaboration.test.ts b/packages/core/tests/collaboration.test.ts index c32768ac..d966d692 100644 --- a/packages/core/tests/collaboration.test.ts +++ b/packages/core/tests/collaboration.test.ts @@ -12,10 +12,10 @@ import { deleteComment, flushNotifications, listComments, - queryDocumentSummaries, - readDocument, resolveComment, - runWithSession, + systemContext, + readDocumentAs, + queryDocumentSummariesAs, } from '../src/server' import { normalizeSession } from '../src/index' import type { CmsSessionInput } from '../src/index' @@ -94,39 +94,40 @@ describe('editorial collaboration: comments, assignment, notifications', () => { setup() await commitDocument('post', 'p1', { title: 'Hello' }) - const root = await runWithSession(author, () => - addComment({ collection: 'post', docId: 'p1', body: 'Fix the intro' }), - ) + const root = await addComment({ + collection: 'post', + docId: 'p1', + body: 'Fix the intro', + session: author, + }) expect(root.author).toBe('ada') expect(root.parentId).toBeNull() expect(root.resolved).toBe(false) - const reply = await runWithSession(other, () => - addComment({ - collection: 'post', - docId: 'p1', - body: 'On it', - parentId: root.id, - }), - ) + const reply = await addComment({ + collection: 'post', + docId: 'p1', + body: 'On it', + parentId: root.id, + session: other, + }) expect(reply.parentId).toBe(root.id) // A reply to a reply collapses onto the thread root (one level deep). - const nested = await runWithSession(other, () => - addComment({ - collection: 'post', - docId: 'p1', - body: 'me too', - parentId: reply.id, - }), - ) + const nested = await addComment({ + collection: 'post', + docId: 'p1', + body: 'me too', + parentId: reply.id, + session: other, + }) expect(nested.parentId).toBe(root.id) - const list = await runWithSession(author, () => listComments('post', 'p1')) + const list = await listComments('post', 'p1', author) expect(list).toHaveLength(3) expect(list.map((c) => c.id)).toEqual([root.id, reply.id, nested.id]) - const resolved = await runWithSession(author, () => resolveComment(root.id)) + const resolved = await resolveComment(root.id, { session: author }) expect(resolved.resolved).toBe(true) expect(resolved.resolvedBy).toBe('ada') }) @@ -134,14 +135,13 @@ describe('editorial collaboration: comments, assignment, notifications', () => { it('a field-pinned comment records its field path', async () => { setup() await commitDocument('post', 'p1', { title: 'Hello' }) - const c = await runWithSession(author, () => - addComment({ - collection: 'post', - docId: 'p1', - body: 'typo', - fieldPath: 'title', - }), - ) + const c = await addComment({ + collection: 'post', + docId: 'p1', + body: 'typo', + fieldPath: 'title', + session: author, + }) expect(c.fieldPath).toBe('title') }) @@ -149,9 +149,12 @@ describe('editorial collaboration: comments, assignment, notifications', () => { setup() await commitDocument('post', 'p1', { title: 'Hello' }) await expect( - runWithSession(author, () => - addComment({ collection: 'post', docId: 'p1', body: ' ' }), - ), + addComment({ + collection: 'post', + docId: 'p1', + body: ' ', + session: author, + }), ).rejects.toThrow() }) @@ -168,56 +171,58 @@ describe('editorial collaboration: comments, assignment, notifications', () => { }) // The author role cannot read the `secret` collection → cannot comment. await expect( - runWithSession(author, () => - addComment({ collection: 'secret', docId: 's1', body: 'hi' }), - ), + addComment({ + collection: 'secret', + docId: 's1', + body: 'hi', + session: author, + }), ).rejects.toThrow() // The owner can. - const c = await runWithSession(owner, () => - addComment({ collection: 'secret', docId: 's1', body: 'hi' }), - ) + const c = await addComment({ + collection: 'secret', + docId: 's1', + body: 'hi', + session: owner, + }) expect(c.id).toBeTruthy() }) it('only the author or a reviewer may resolve or delete a comment', async () => { setup() await commitDocument('post', 'p1', { title: 'Hello' }) - const c = await runWithSession(author, () => - addComment({ collection: 'post', docId: 'p1', body: 'note' }), - ) + const c = await addComment({ + collection: 'post', + docId: 'p1', + body: 'note', + session: author, + }) // A different author cannot resolve or delete it. - await expect( - runWithSession(other, () => resolveComment(c.id)), - ).rejects.toThrow() - await expect( - runWithSession(other, () => deleteComment(c.id)), - ).rejects.toThrow() + await expect(resolveComment(c.id, { session: other })).rejects.toThrow() + await expect(deleteComment(c.id, { session: other })).rejects.toThrow() // A reviewer (editor, review.decide) can. - const resolved = await runWithSession(editor, () => resolveComment(c.id)) + const resolved = await resolveComment(c.id, { session: editor }) expect(resolved.resolved).toBe(true) - expect(await runWithSession(editor, () => deleteComment(c.id))).toBe(true) - expect( - await runWithSession(author, () => listComments('post', 'p1')), - ).toEqual([]) + expect(await deleteComment(c.id, { session: editor })).toBe(true) + expect(await listComments('post', 'p1', author)).toEqual([]) }) it('retains comments on soft delete and removes them on purge', async () => { setup() await commitDocument('post', 'p1', { title: 'Hello' }) - await runWithSession(author, () => - addComment({ collection: 'post', docId: 'p1', body: 'note' }), - ) + await addComment({ + collection: 'post', + docId: 'p1', + body: 'note', + session: author, + }) const { deleteDocument } = await import('../src/server') // Soft delete (trash) keeps the comments so a restore brings them back. await deleteDocument('post', 'p1', { actor: 'edie' }) - expect( - await runWithSession(author, () => listComments('post', 'p1')), - ).toHaveLength(1) + expect(await listComments('post', 'p1', author)).toHaveLength(1) // Purge (hard delete) cascades the comments away with the document. await deleteDocument('post', 'p1', { actor: 'edie', purge: true }) - expect( - await runWithSession(author, () => listComments('post', 'p1')), - ).toEqual([]) + expect(await listComments('post', 'p1', author)).toEqual([]) }) // --- Assignment ---------------------------------------------------------- @@ -227,14 +232,19 @@ describe('editorial collaboration: comments, assignment, notifications', () => { await commitDocument('post', 'p1', { title: 'One' }) await commitDocument('post', 'p2', { title: 'Two' }) - const assigned = await runWithSession(editor, () => - assignDocument({ collection: 'post', docId: 'p1', assignee: 'ada' }), - ) + const assigned = await assignDocument({ + collection: 'post', + docId: 'p1', + assignee: 'ada', + session: editor, + }) expect(assigned._assignee).toBe('ada') // Persisted on the document (and revisioned via the commit path). - expect((await readDocument('post', 'p1'))?._assignee).toBe('ada') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?._assignee, + ).toBe('ada') - const mine = await queryDocumentSummaries({ + const mine = await queryDocumentSummariesAs(systemContext('test'), { collection: 'post', assignedTo: 'ada', }) @@ -242,11 +252,14 @@ describe('editorial collaboration: comments, assignment, notifications', () => { expect(mine.items[0]?.assignee).toBe('ada') // Unassign with an empty string. - const cleared = await runWithSession(editor, () => - assignDocument({ collection: 'post', docId: 'p1', assignee: '' }), - ) + const cleared = await assignDocument({ + collection: 'post', + docId: 'p1', + assignee: '', + session: editor, + }) expect(cleared._assignee).toBeFalsy() - const none = await queryDocumentSummaries({ + const none = await queryDocumentSummariesAs(systemContext('test'), { collection: 'post', assignedTo: 'ada', }) @@ -256,11 +269,16 @@ describe('editorial collaboration: comments, assignment, notifications', () => { it('a plain edit preserves the assignee', async () => { setup() await commitDocument('post', 'p1', { title: 'One' }) - await runWithSession(editor, () => - assignDocument({ collection: 'post', docId: 'p1', assignee: 'ada' }), - ) + await assignDocument({ + collection: 'post', + docId: 'p1', + assignee: 'ada', + session: editor, + }) await commitDocument('post', 'p1', { title: 'One edited' }) - expect((await readDocument('post', 'p1'))?._assignee).toBe('ada') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?._assignee, + ).toBe('ada') }) // --- Notifications ------------------------------------------------------- @@ -275,9 +293,12 @@ describe('editorial collaboration: comments, assignment, notifications', () => { }, }) await commitDocument('post', 'p1', { title: 'One' }) - await runWithSession(editor, () => - assignDocument({ collection: 'post', docId: 'p1', assignee: 'ada' }), - ) + await assignDocument({ + collection: 'post', + docId: 'p1', + assignee: 'ada', + session: editor, + }) await flushNotifications() expect(seen).toHaveLength(1) expect(seen[0]?.type).toBe('document.assigned') @@ -336,9 +357,12 @@ describe('editorial collaboration: comments, assignment, notifications', () => { logger: { info, warn: () => {}, error: () => {} }, }) await commitDocument('post', 'p1', { title: 'One' }) - await runWithSession(editor, () => - assignDocument({ collection: 'post', docId: 'p1', assignee: 'ada' }), - ) + await assignDocument({ + collection: 'post', + docId: 'p1', + assignee: 'ada', + session: editor, + }) await flushNotifications() expect(info).toHaveBeenCalled() }) diff --git a/packages/core/tests/content-migrations.test.ts b/packages/core/tests/content-migrations.test.ts index bdbffbcd..0d21d7bf 100644 --- a/packages/core/tests/content-migrations.test.ts +++ b/packages/core/tests/content-migrations.test.ts @@ -9,11 +9,12 @@ import { commitDocument, contentMigrationStatus, listPending, - listRevisions, migrateContent, - readDocument, restoreRevision, saveDraft, + systemContext, + readDocumentAs, + listRevisionsAs, } from '../src/server' import { getStorage } from '../src/server/storage' import type { Collection, ContentMigration } from '../src/index' @@ -79,7 +80,7 @@ async function rawDoc(id: string) { describe('content migrations', () => { it('upgrades older documents on read without writing', async () => { await seedThenUpgrade(v1([addTags, renameHeadline])) - const doc = await readDocument('note', 'n1') + const doc = await readDocumentAs(systemContext('test'), 'note', 'n1') expect(doc).toMatchObject({ title: 'Note n1', tags: [], @@ -151,9 +152,11 @@ describe('content migrations', () => { it('upgrades an old revision when it is restored', async () => { await seedThenUpgrade(v1([renameHeadline])) await commitDocument('note', 'n1', { title: 'Edited' }) - const [first] = await listRevisions('note', 'n1').then((r) => - r.sort((a, b) => a.revision - b.revision), - ) + const [first] = await listRevisionsAs( + systemContext('test'), + 'note', + 'n1', + ).then((r) => r.sort((a, b) => a.revision - b.revision)) expect(first?.doc).toHaveProperty('headline') await restoreRevision('note', 'n1', first!.revision) expect(await rawDoc('n1')).toMatchObject({ diff --git a/packages/core/tests/document-state.test.ts b/packages/core/tests/document-state.test.ts index a16852f6..1571ba8d 100644 --- a/packages/core/tests/document-state.test.ts +++ b/packages/core/tests/document-state.test.ts @@ -34,9 +34,9 @@ import { importContent, listAudit, listPending, - listRevisions, + listRevisionsAs, listStrandedChangeSets, - readDocument, + readDocumentAs, runEventDispatch, saveDraft, stageWrite, @@ -172,7 +172,9 @@ describe('direct strategy', () => { }) expect(result.after).toMatchObject({ title: 'Now', _revision: 1 }) expect(await listPending()).toEqual([]) - expect(await readDocument('post', 'p1')).toMatchObject({ title: 'Now' }) + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Now' }) expect((await listAudit())[0]).toMatchObject({ docId: 'p1', actor: 'agent', @@ -186,7 +188,9 @@ describe('direct strategy', () => { await setup({ postState: directStrategy() }) await commitDocument('post', 'p1', { title: 'Live', published: true }) await saveDraft('post', 'p1', { title: 'Draft', published: true }) - expect((await readDocument('post', 'p1'))?.title).toBe('Live') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Live') expect(await listPending()).toEqual([ expect.objectContaining({ source: 'draft' }), ]) @@ -218,7 +222,7 @@ describe('review strategy', () => { actor: 'agent', instruction: 'Draft it', }) - expect(await readDocument('post', 'p1')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'p1')).toBeNull() expect(await drain()).toEqual([ { type: 'review.submitted', @@ -317,7 +321,9 @@ describe('review strategy', () => { }) expect(approval.committed).toBeNull() expect(await documentStateLabel('post', 'p1')).toBe('Approved') - expect((await readDocument('post', 'p1'))?.title).toBe('Live') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Live') expect((await listAudit())[0]).toMatchObject({ action: 'approve', decision: 'transitioned', @@ -386,7 +392,7 @@ describe('review strategy', () => { expect(await documentStateLabel('post', 'p1')).toBe('Approved') await submit('Second') expect(await documentStateLabel('post', 'p1')).toBe('Pending Review') - expect(await readDocument('post', 'p1')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'p1')).toBeNull() }) it('an approved deletion is applied only by someone who may delete', async () => { @@ -437,7 +443,7 @@ describe('review strategy', () => { ), ).toMatchObject({ label: 'Delete', tone: 'danger' }) await act('editor', 'publish') - expect(await readDocument('post', 'p1')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'p1')).toBeNull() }) it('a publisher who approves publishes in the same decision', async () => { @@ -471,7 +477,7 @@ describe('core rules', () => { message: 'Not today.', details: { action: 'edit', rule: 'strategy' }, }) - expect(await readDocument('post', 'p1')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'p1')).toBeNull() expect(await listAudit()).toEqual([ expect.objectContaining({ docId: 'p1', @@ -505,7 +511,7 @@ describe('core rules', () => { await expect( commitDocument('post', 'p1', { title: 'Forged' }), ).rejects.toMatchObject({ details: { rule: 'core-event' } }) - expect(await readDocument('post', 'p1')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'p1')).toBeNull() expect(await drain()).toEqual([]) }) @@ -517,7 +523,9 @@ describe('core rules', () => { await expect( commitDocument('post', 'p1', { title: 'Sneaky', published: true }), ).rejects.toMatchObject({ details: { rule: 'live-content' } }) - expect((await readDocument('post', 'p1'))?.title).toBe('Live') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Live') }) it('the agent floor: an agent causes publish only when the strategy grants it', async () => { @@ -540,7 +548,9 @@ describe('core rules', () => { postState: fixed(effects, { grants: { publish: ['agent'] } }), }) await write() - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Agent', published: true, }) @@ -611,14 +621,18 @@ describe('core rules', () => { action: { type: 'restore', input: { revision: 1 } }, }) expect(outcome.committed).toMatchObject({ title: 'One', _revision: 3 }) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'One', published: true, _revision: 3, }) - expect((await listRevisions('post', 'p1')).map((r) => r.revision)).toEqual([ - 3, 2, 1, - ]) + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'p1')).map( + (r) => r.revision, + ), + ).toEqual([3, 2, 1]) }) it('a refusal in the middle of an import writes none of it', async () => { @@ -641,7 +655,9 @@ describe('core rules', () => { ], }), ).rejects.toMatchObject({ code: 'FORBIDDEN' }) - expect(await readDocument('post', 'good')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'good'), + ).toBeNull() expect(await listAudit()).toEqual([ expect.objectContaining({ docId: 'bad', @@ -749,7 +765,9 @@ describe('change-set state', () => { id: 'p1', action: { type: 'approve' }, }) - expect(await readDocument('post', 'p1')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'p1'), + ).toMatchObject({ title: 'Proposal', _revision: 2, }) @@ -790,7 +808,9 @@ describe('change-set state', () => { id: 'p1', action: { type: 'approve' }, }) - expect((await readDocument('post', 'p1'))?.title).toBe('Proposal') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Proposal') expect( (await listAudit()).find((a) => a.decision === 'approved'), ).toMatchObject({ id, from: { legal: true, migrated: true } }) @@ -832,7 +852,9 @@ describe('change-set state', () => { }) expect(await listPending()).toEqual([]) expect(await listStrandedChangeSets()).toEqual([]) - expect((await readDocument('post', 'p1'))?.title).toBe('Live') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Live') }) }) diff --git a/packages/core/tests/events.test.ts b/packages/core/tests/events.test.ts index e0c3af45..734239f4 100644 --- a/packages/core/tests/events.test.ts +++ b/packages/core/tests/events.test.ts @@ -11,8 +11,9 @@ import { getStorage, listDeadLetterEvents, listEventSchedules, - readDocument, runEventDispatch, + systemContext, + readDocumentAs, } from '../src/server' import { defineCms } from '../src/config' @@ -78,7 +79,7 @@ describe('async events: outbox, dispatcher, hooks', () => { }, }) await commitDocument('post', 'p1', { title: 'Hello There World' }) - const doc = await readDocument('post', 'p1') + const doc = await readDocumentAs(systemContext('test'), 'post', 'p1') expect(doc?.slug).toBe('hello-there-world') }) @@ -98,7 +99,7 @@ describe('async events: outbox, dispatcher, hooks', () => { await expect(commitDocument('post', 'p1', { title: 'Hi' })).rejects.toThrow( 'nope', ) - expect(await readDocument('post', 'p1')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'p1')).toBeNull() const result = await runEventDispatch() // Nothing was ever enqueued. expect(result.claimed).toBe(0) @@ -238,7 +239,9 @@ describe('async events: outbox, dispatcher, hooks', () => { // `spawn` ran once (for root). The child it created did not refire it. expect(created).toEqual(['root']) - expect(await readDocument('post', 'child')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'child'), + ).not.toBeNull() // `observe` saw both the root (depth 0) and the child (depth 1), and the // child event's causationId chains back to the root event. @@ -415,8 +418,12 @@ describe('async events: outbox, dispatcher, hooks', () => { await commitDocument('post', 'p1', { title: 'Hi' }) await runEventDispatch() await runEventDispatch() - expect(await readDocument('log', 'l1')).not.toBeNull() - expect(await readDocument('post', 'nope')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'log', 'l1'), + ).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'nope'), + ).toBeNull() expect( failures.some((f) => String(f.error).includes('may not write')), ).toBe(true) diff --git a/packages/core/tests/field-access.test.ts b/packages/core/tests/field-access.test.ts index 0370ca22..f81b14cb 100644 --- a/packages/core/tests/field-access.test.ts +++ b/packages/core/tests/field-access.test.ts @@ -6,15 +6,16 @@ import { defineCms, normalizeSession } from '../src/index' import { closeStore, commitDocument, - listRevisions, - populateRelations, protectWrite, - queryDocumentSummaries, - queryDocuments, redactDoc, restoreRevision, runOp, - runWithSession, + accessContext, + systemContext, + queryDocumentsAs, + listRevisionsAs, + populateRelationsAs, + queryDocumentSummariesAs, } from '../src/server' import type { BlockType, Collection } from '../src/index' @@ -210,24 +211,21 @@ describe('nested and document-aware field access', () => { it('rejects filters and sorts on hidden nested fields', async () => { setup() await expect( - queryDocuments({ + queryDocumentsAs(accessContext({ session: as('editor'), mode: 'edit' }), { collection: 'product', where: [{ field: 'pricing.cost', op: 'gt', value: 1 }], - session: as('editor'), }), ).rejects.toMatchObject({ code: 'FORBIDDEN' }) await expect( - queryDocuments({ + queryDocumentsAs(accessContext({ session: as('editor'), mode: 'edit' }), { collection: 'product', sort: { field: 'variants.supplier' }, - session: as('editor'), }), ).rejects.toMatchObject({ code: 'FORBIDDEN' }) await expect( - queryDocuments({ + queryDocumentsAs(accessContext({ session: as('editor'), mode: 'edit' }), { collection: 'product', where: [{ field: 'pricing.list', op: 'gt', value: 1 }], - session: as('editor'), }), ).resolves.toMatchObject({ total: 0 }) }) @@ -245,33 +243,30 @@ describe('nested and document-aware field access', () => { // `supplier` is admin-only. A value that lives only in a restricted field // must not reveal the document to an editor — otherwise match/no-match // leaks the hidden content. - const secret = (await runWithSession(editor, () => - runOp( - 'search_documents', - { collection: 'product', query: 'ZontarSupplier' }, - 'agent', - ), + const secret = (await runOp( + 'search_documents', + { collection: 'product', query: 'ZontarSupplier' }, + 'agent', + accessContext({ session: editor, mode: 'edit' }), )) as { items: Array<{ id: string }>; total: number } expect(secret.items).toHaveLength(0) expect(secret.total).toBe(0) // A value in a readable field still matches for the same editor. - const readable = (await runWithSession(editor, () => - runOp( - 'search_documents', - { collection: 'product', query: 'PublicWidget' }, - 'agent', - ), + const readable = (await runOp( + 'search_documents', + { collection: 'product', query: 'PublicWidget' }, + 'agent', + accessContext({ session: editor, mode: 'edit' }), )) as { items: Array<{ id: string }> } expect(readable.items.map((i) => i.id)).toEqual(['p1']) // An admin (who can read `supplier`) still finds it by the restricted value. - const admin = (await runWithSession(as('admin'), () => - runOp( - 'search_documents', - { collection: 'product', query: 'ZontarSupplier' }, - 'agent', - ), + const admin = (await runOp( + 'search_documents', + { collection: 'product', query: 'ZontarSupplier' }, + 'agent', + accessContext({ session: as('admin'), mode: 'edit' }), )) as { items: Array<{ id: string }> } expect(admin.items.map((i) => i.id)).toEqual(['p1']) }) @@ -386,7 +381,7 @@ describe('nested and document-aware field access', () => { pricing: { list: 20, cost: 9 }, published: true, }) - const revs = await listRevisions('product', 'w1') + const revs = await listRevisionsAs(systemContext('test'), 'product', 'w1') const rev1 = revs.find((r) => r.revision === 1)! // Editor cannot write pricing.cost, so restoring rev 1 keeps current cost=9 @@ -401,52 +396,49 @@ describe('nested and document-aware field access', () => { // Agent tools (create_document, update_document, restore_revision) redact resultingDocument const editorSession = as('editor') - const created = (await runWithSession(editorSession, () => - runOp( - 'create_document', - { - collection: 'product', - id: 'w2', - doc: { - name: 'W2', - owner: 'u-admin', - notes: 'forged', - }, + const created = (await runOp( + 'create_document', + { + collection: 'product', + id: 'w2', + doc: { + name: 'W2', + owner: 'u-admin', + notes: 'forged', }, - 'agent', - ), + }, + 'agent', + accessContext({ session: editorSession, mode: 'edit' }), )) as { resultingDocument: Record } expect(created.resultingDocument.notes).toBeUndefined() expect(created.resultingDocument.pricing).toEqual({ list: 0 }) - const updated = (await runWithSession(editorSession, () => - runOp( - 'update_document', - { - collection: 'product', - id: 'w1', - doc: { - name: 'V3', - owner: 'u-admin', - pricing: { list: 30, cost: 999 }, - }, + const updated = (await runOp( + 'update_document', + { + collection: 'product', + id: 'w1', + doc: { + name: 'V3', + owner: 'u-admin', + pricing: { list: 30, cost: 999 }, }, - 'agent', - ), + }, + 'agent', + accessContext({ session: editorSession, mode: 'edit' }), )) as { resultingDocument: Record } expect(updated.resultingDocument.pricing).toEqual({ list: 30 }) expect(updated.resultingDocument.notes).toBeUndefined() - const restoredViaOp = (await runWithSession(editorSession, () => - runOp( - 'restore_revision', - { - collection: 'product', - id: 'w1', - revision: '1', - }, - 'agent', - ), + const restoredViaOp = (await runOp( + 'restore_revision', + { + collection: 'product', + id: 'w1', + revision: '1', + }, + 'agent', + accessContext({ session: editorSession, mode: 'edit' }), )) as { resultingDocument: Record } expect(restoredViaOp.resultingDocument.pricing).toEqual({ list: 10 }) expect(restoredViaOp.resultingDocument.notes).toBeUndefined() @@ -554,9 +546,11 @@ describe('nested and document-aware field access', () => { published: true, }) - const viewerRels = await populateRelations('article', articleDoc, { - session: as('viewer'), - }) + const viewerRels = await populateRelationsAs( + accessContext({ session: as('viewer'), mode: 'edit' }), + 'article', + articleDoc, + ) // secretCol is not readable by viewer expect(viewerRels.secretRef).toBeUndefined() // nested relations in group, array, and blocks are populated and redacted @@ -573,9 +567,11 @@ describe('nested and document-aware field access', () => { name: 'Alice', }) - const adminRels = await populateRelations('article', articleDoc, { - session: as('admin'), - }) + const adminRels = await populateRelationsAs( + accessContext({ session: as('admin'), mode: 'edit' }), + 'article', + articleDoc, + ) expect(adminRels.secretRef).toMatchObject({ code: 'TOP-SECRET', }) @@ -619,28 +615,25 @@ describe('nested and document-aware field access', () => { published: true, }) - const summaries = await queryDocumentSummaries({ - collection: 'post', - columns: ['title'], - session: as('editor'), - }) + const summaries = await queryDocumentSummariesAs( + accessContext({ session: as('editor'), mode: 'edit' }), + { collection: 'post', columns: ['title'] }, + ) expect(summaries.items[0]?.title).toBe('Original [postRead]') expect(summaries.items[0]?.values?.title).toBe('Original [postRead]') await expect( - queryDocumentSummaries({ - collection: 'post', - sort: { field: 'secretScore' }, - session: as('editor'), - }), + queryDocumentSummariesAs( + accessContext({ session: as('editor'), mode: 'edit' }), + { collection: 'post', sort: { field: 'secretScore' } }, + ), ).rejects.toMatchObject({ code: 'FORBIDDEN' }) await expect( - queryDocumentSummaries({ - collection: 'post', - sort: { field: 'bad;drop' }, - session: as('admin'), - }), + queryDocumentSummariesAs( + accessContext({ session: as('admin'), mode: 'edit' }), + { collection: 'post', sort: { field: 'bad;drop' } }, + ), ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) }) }) diff --git a/packages/core/tests/field-i18n.test.ts b/packages/core/tests/field-i18n.test.ts index 5bfd875d..751fe36d 100644 --- a/packages/core/tests/field-i18n.test.ts +++ b/packages/core/tests/field-i18n.test.ts @@ -14,8 +14,9 @@ import { import { closeStore, commitDocument, - queryDocuments, - readDocument, + systemContext, + readDocumentAs, + queryDocumentsAs, } from '../src/server' import type { Field, InferDoc } from '../src/index' @@ -286,7 +287,11 @@ describe('field-level localization', () => { }, { actor: 'test' }, ) - const stored = await readDocument('article', 'post-1') + const stored = await readDocumentAs( + systemContext('test'), + 'article', + 'post-1', + ) expect(stored).toBeTruthy() // The raw stored shape is the tagged map (editor reads this to edit all // locales); public read paths resolve it per locale. @@ -321,7 +326,9 @@ describe('field-level localization', () => { }, { actor: 'test' }, ) - const { items } = await queryDocuments({ collection: 'article' }) + const { items } = await queryDocumentsAs(systemContext('test'), { + collection: 'article', + }) const row = items.find((i) => i.id === 'post-2') expect(row?.title).toBe('English Title') }) diff --git a/packages/core/tests/fields.test.ts b/packages/core/tests/fields.test.ts index 5f94dde1..62ec6f28 100644 --- a/packages/core/tests/fields.test.ts +++ b/packages/core/tests/fields.test.ts @@ -17,9 +17,10 @@ import { closeStore, commitDocument, dbFile, - queryDocuments, - readDocument, stageWrite, + systemContext, + queryDocumentsAs, + readDocumentAs, } from '../src/server' import type { Collection, InferDoc } from '../src/index' @@ -264,7 +265,7 @@ describe('server-side field rules', () => { expect((rejected as PromiseRejectedResult).reason).toMatchObject({ code: 'VALIDATION_FAILED', }) - const { items } = await queryDocuments({ + const { items } = await queryDocumentsAs(systemContext('test'), { collection: 'product', where: { sku: 'RACE' }, }) @@ -275,7 +276,7 @@ describe('server-side field rules', () => { setup() await commitDocument('product', 'p1', base) await commitDocument('product', 'p2', { ...base, name: 'B', sku: 'L-2' }) - const { items } = await queryDocuments({ + const { items } = await queryDocumentsAs(systemContext('test'), { collection: 'product', where: { sku: 'L-2' }, }) @@ -311,7 +312,7 @@ describe('server-side field rules', () => { }, }) await commitDocument('product', 'p1', { ...base, name: ' Spaced ' }) - const doc = await readDocument('product', 'p1') + const doc = await readDocumentAs(systemContext('test'), 'product', 'p1') expect(doc?.name).toBe('Spaced') expect(doc?.readAt).toBe('now') }) diff --git a/packages/core/tests/interface-schedules.test.ts b/packages/core/tests/interface-schedules.test.ts index 2578cf1c..c6143bec 100644 --- a/packages/core/tests/interface-schedules.test.ts +++ b/packages/core/tests/interface-schedules.test.ts @@ -18,7 +18,6 @@ import { getStorage, getInterfaceScheduleStatus, handleInterfaceScheduleEvent, - readDocument, readInterface, refreshInterfaceComponents, refreshInterfaceSnapshot, @@ -28,6 +27,8 @@ import { setInterfaceSchedulePaused, submitInterface, accessContext, + systemContext, + readDocumentAs, } from '../src/server' let dir: string @@ -152,9 +153,15 @@ describe('scheduled persistent snapshots and component subscriptions', () => { .status await runEventDispatch({ now: time('2026-10-11T09:01:00Z') }) expect(await value()).toBe(2) - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 2, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(2) // Simulate a crash after the atomic revision/run receipt, before status advanced. await ( await getStorage() @@ -163,14 +170,26 @@ describe('scheduled persistent snapshots and component subscriptions', () => { JSON.stringify(before), ) await runInterfaceSchedules({ now: '2026-10-11T09:01:00Z' }) - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 2, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(2) await closeStore() await runEventDispatch({ now: time('2026-10-11T12:00:00Z') }) - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 3, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(3) expect( (await getInterfaceScheduleStatus('recipe-count', ctx())).status ?.nextRunAt, @@ -184,9 +203,15 @@ describe('scheduled persistent snapshots and component subscriptions', () => { ) await closeStore() await runEventDispatch({ now: time('2026-10-11T09:01:00Z') }) - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 1, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(1) expect( (await getInterfaceScheduleStatus('recipe-count', ctx())).status?.paused, ).toBe(true) @@ -207,17 +232,29 @@ describe('scheduled persistent snapshots and component subscriptions', () => { ctx(), ) await runInterfaceSchedules() - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 2, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(2) }) it('rechecks the owner and waits for pending edits without publishing them or overwriting the live report', async () => { await publish() enabled = false await runEventDispatch({ now: time('2026-10-11T09:01:00Z') }) - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 1, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(1) expect( (await getInterfaceScheduleStatus('recipe-count', ctx())).status ?.lastError, @@ -237,9 +274,15 @@ describe('scheduled persistent snapshots and component subscriptions', () => { ctx(), ) await runEventDispatch({ now: time('2026-10-11T09:02:00Z') }) - expect((await readDocument('interfaces', 'recipe-count'))?.title).toBe( - 'Recipe count', - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?.title, + ).toBe('Recipe count') expect( (await getInterfaceScheduleStatus('recipe-count', ctx())).status ?.lastError, @@ -249,9 +292,15 @@ describe('scheduled persistent snapshots and component subscriptions', () => { ).rejects.toThrow('review') await reject(pending.pendingId) await runEventDispatch({ now: time('2026-10-11T09:03:00Z') }) - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 2, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(2) }) it('retains the last good snapshot, backs off failures, and pauses a repeatedly failing report', async () => { await publish() @@ -270,9 +319,15 @@ describe('scheduled persistent snapshots and component subscriptions', () => { (await getInterfaceScheduleStatus('recipe-count', ctx())).status ?.pausedBy, ).toBe('failure') - expect((await readDocument('interfaces', 'recipe-count'))?._revision).toBe( - 1, - ) + expect( + ( + await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-count', + ) + )?._revision, + ).toBe(1) }) it('refreshes only affected components and detects published definition changes', async () => { const next = definition() diff --git a/packages/core/tests/interfaces.test.ts b/packages/core/tests/interfaces.test.ts index bbed6409..1e804e37 100644 --- a/packages/core/tests/interfaces.test.ts +++ b/packages/core/tests/interfaces.test.ts @@ -22,11 +22,12 @@ import { getInterfaceMetadata, readInterface, submitInterface, - readDocument, restoreRevision, listPending, redactDoc, accessContext, + systemContext, + readDocumentAs, } from '../src/server' let dir: string @@ -300,7 +301,9 @@ describe('persistent CMS interfaces', () => { await expect( dispatchInterfaceEvent(args, context('editor')), ).rejects.toThrow('pending document changed') - expect((await readDocument('recipes', 'eggs'))?.minutes).toBe(5) + expect( + (await readDocumentAs(systemContext('test'), 'recipes', 'eggs'))?.minutes, + ).toBe(5) expect( (await listPending()).filter((p) => p.collection === 'recipes'), ).toHaveLength(1) @@ -320,7 +323,11 @@ describe('persistent CMS interfaces', () => { expect(saved.result.nodes.find((n) => n.id === 'total')?.props.value).toBe( 2, ) - const doc = await readDocument('interfaces', 'recipe-book') + const doc = await readDocumentAs( + systemContext('test'), + 'interfaces', + 'recipe-book', + ) expect( JSON.stringify(redactDoc('interfaces', doc, context().session)), ).not.toContain('private') @@ -451,6 +458,8 @@ describe('persistent CMS interfaces', () => { ) broken.nodes[1].dataSource = 'while(true) {}' await expect(executeInterface(broken, {}, context())).rejects.toThrow() - expect(await readDocument('interfaces', 'recipe-book')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'interfaces', 'recipe-book'), + ).toBeNull() }, 10000) }) diff --git a/packages/core/tests/plugins.test.ts b/packages/core/tests/plugins.test.ts index d45017b7..2cbac562 100644 --- a/packages/core/tests/plugins.test.ts +++ b/packages/core/tests/plugins.test.ts @@ -20,7 +20,8 @@ import { closeStore, commitDocument, onCmsEvent, - readDocument, + readDocumentAs, + systemContext, } from '../src/server' import type { CmsEventName } from '../src/server' import type { BlockType, CmsEvent, Collection } from '../src/index' @@ -176,7 +177,9 @@ describe('defineCms({ plugins })', () => { plugins: [analytics], }) await commitDocument('pageview', 'p1', { path: '/', published: true }) - expect(await readDocument('pageview', 'p1')).toMatchObject({ path: '/' }) + expect( + await readDocumentAs(systemContext('test'), 'pageview', 'p1'), + ).toMatchObject({ path: '/' }) expect(events.map((e) => [e.event, e.collection, e.id])).toEqual([ ['document.created', 'pageview', 'p1'], ['document.published', 'pageview', 'p1'], diff --git a/packages/core/tests/preview-tokens.test.ts b/packages/core/tests/preview-tokens.test.ts index ffe70cf4..da00d4ff 100644 --- a/packages/core/tests/preview-tokens.test.ts +++ b/packages/core/tests/preview-tokens.test.ts @@ -8,10 +8,11 @@ import { closeStore, commitDocument, createPreviewToken, - readDocumentWithPending, revokePreviewToken, saveDraft, verifyPreviewToken, + systemContext, + readDocumentWithPendingAs, } from '../src/server' const tempDirs: Array = [] @@ -152,7 +153,11 @@ describe('preview tokens', () => { const verified = await verifyPreviewToken(token, 'post', 'hello') expect(verified.ok).toBe(true) - const pending = await readDocumentWithPending('post', 'hello') + const pending = await readDocumentWithPendingAs( + systemContext('test'), + 'post', + 'hello', + ) expect(pending.isPending).toBe(true) expect(pending.doc?.title).toBe('Draft title') expect(pending.livePublished).toBe(true) diff --git a/packages/core/tests/readiness.test.ts b/packages/core/tests/readiness.test.ts index 2eecb4ec..6e75c25e 100644 --- a/packages/core/tests/readiness.test.ts +++ b/packages/core/tests/readiness.test.ts @@ -11,13 +11,14 @@ import { listAudit, listPending, onCmsEvent, - queryDocuments, - readDocument, reject, runScheduledPublishing, stageWrite, saveDraft, runOp, + systemContext, + readDocumentAs, + queryDocumentsAs, } from '../src/server' const post: CmsConfig['collections'][number] = { @@ -159,7 +160,9 @@ describe('1.0 workflow invariants', () => { await reject(pending.id) release.resolve() await failed - expect(await readDocument('post', 'one')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'one'), + ).toBeNull() expect((await listAudit()).map((entry) => entry.action)).toEqual([ 'reject', 'submit', @@ -228,7 +231,9 @@ describe('1.0 workflow invariants', () => { reject(first.id, { expectedVersion: first.version }), ).rejects.toMatchObject({ code: 'CONFLICT' }) await approve(second.id, { expectedVersion: second.version }) - expect((await readDocument('post', 'one'))?.title).toBe('Second') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'one'))?.title, + ).toBe('Second') }) it('detects simultaneous edits to the same unpublished draft', async () => { @@ -253,7 +258,9 @@ describe('1.0 workflow invariants', () => { expect( results.filter((result) => result.status === 'fulfilled'), ).toHaveLength(1) - expect((await readDocument('post', 'one'))?.title).toBe('Live') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'one'))?.title, + ).toBe('Live') }) it('lets agents read the latest draft but not edit over it while it is open', async () => { @@ -279,13 +286,19 @@ describe('1.0 workflow invariants', () => { published: true, }) expect( - await runOp('read_document', { collection: 'post', id: 'one' }, 'agent'), + await runOp( + 'read_document', + { collection: 'post', id: 'one' }, + 'agent', + systemContext('test'), + ), ).toMatchObject({ title: 'Human draft' }) await expect( runOp( 'update_document', { collection: 'post', id: 'one', doc: { body: 'Agent body' } }, 'agent', + systemContext('test'), ), ).rejects.toMatchObject({ code: 'CONFLICT', @@ -298,7 +311,9 @@ describe('1.0 workflow invariants', () => { after: expect.objectContaining({ body: 'Draft body' }), }), ]) - expect((await readDocument('post', 'one'))?.body).toBe('Live body') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'one'))?.body, + ).toBe('Live body') }) it('rechecks ownership when forced approval commits after an ownership change', async () => { @@ -353,7 +368,9 @@ describe('1.0 workflow invariants', () => { }) release.resolve() await failed - expect((await readDocument('post', 'one'))?.owner).toBe('bob') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'one'))?.owner, + ).toBe('bob') }) it('refuses referenced deletes on approval unless explicitly forced', async () => { @@ -381,9 +398,13 @@ describe('1.0 workflow invariants', () => { await expect(approve(pending.id, { force: true })).rejects.toMatchObject({ code: 'CONFLICT', }) - expect(await readDocument('author', 'ann')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'author', 'ann'), + ).not.toBeNull() await approve(pending.id, { forceDelete: true }) - expect(await readDocument('author', 'ann')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'author', 'ann'), + ).toBeNull() }) it('soft-deletes (trashes) a document when an approved proposal deletes one', async () => { @@ -402,8 +423,10 @@ describe('1.0 workflow invariants', () => { await approve(pending.id) // The trashed translation leaves normal reads but is retained; its link on // the canonical is kept intact so a restore brings it back. - expect(await readDocument('post', 'fr')).toBeNull() - expect((await readDocument('post', 'en'))?.translations).toEqual({ + expect(await readDocumentAs(systemContext('test'), 'post', 'fr')).toBeNull() + expect( + (await readDocumentAs(systemContext('test'), 'post', 'en'))?.translations, + ).toEqual({ fr: 'fr', }) }) @@ -439,7 +462,9 @@ describe('1.0 workflow invariants', () => { await expect(approve(deletion.id)).rejects.toMatchObject({ code: 'CONFLICT', }) - expect(await readDocument('author', 'ann')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'author', 'ann'), + ).not.toBeNull() }) it('allows only one concurrent singleton create', async () => { @@ -450,7 +475,10 @@ describe('1.0 workflow invariants', () => { expect( results.filter((result) => result.status === 'fulfilled'), ).toHaveLength(1) - expect((await queryDocuments({ collection: 'post' })).total).toBe(1) + expect( + (await queryDocumentsAs(systemContext('test'), { collection: 'post' })) + .total, + ).toBe(1) }) it('publishes once when two schedule sweeps race', async () => { @@ -485,7 +513,9 @@ describe('1.0 workflow invariants', () => { runScheduledPublishing('2099-01-01T00:00:00.000Z'), ]) expect(results.flat()).toHaveLength(1) - expect((await readDocument('post', 'one'))?._revision).toBe(2) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'one'))?._revision, + ).toBe(2) expect(events).toEqual(['document.updated', 'document.published']) } finally { stop() @@ -522,7 +552,9 @@ describe('1.0 workflow invariants', () => { }) release.resolve() expect(await sweep).toEqual([]) - expect((await readDocument('post', 'one'))?.title).toBe('Newer edit') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'one'))?.title, + ).toBe('Newer edit') }) it('validates the final document returned by postValidate', async () => { @@ -544,6 +576,8 @@ describe('1.0 workflow invariants', () => { await expect(approve(pending.id)).rejects.toMatchObject({ code: 'VALIDATION_FAILED', }) - expect(await readDocument('post', 'one')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'one'), + ).toBeNull() }) }) diff --git a/packages/core/tests/references.test.ts b/packages/core/tests/references.test.ts index f7c55aab..e90be035 100644 --- a/packages/core/tests/references.test.ts +++ b/packages/core/tests/references.test.ts @@ -7,12 +7,13 @@ import { closeStore, commitDocument, deleteDocument, - findReferences, importContent, parseCmsExport, - queryDocumentSummaries, - readDocument, stageWrite, + systemContext, + findReferencesAs, + readDocumentAs, + queryDocumentSummariesAs, } from '../src/server' const dirs: Array = [] @@ -112,7 +113,9 @@ describe('referential integrity', () => { }) const fields = async (id: string) => - (await findReferences('author', id)).map((r) => r.field).sort() + (await findReferencesAs(systemContext('test'), 'author', id)) + .map((r) => r.field) + .sort() expect(await fields('ann')).toEqual(['author', 'credits.1.people']) expect(await fields('bob')).toEqual(['meta.editor']) expect(await fields('cy')).toEqual(['credits.0.people', 'credits.1.people']) @@ -123,7 +126,9 @@ describe('referential integrity', () => { code: 'CONFLICT', }) } - expect(await readDocument('author', 'dee')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'author', 'dee'), + ).not.toBeNull() }) it('ignores text that merely contains the id', async () => { @@ -133,7 +138,9 @@ describe('referential integrity', () => { title: 'ann', body: [{ _type: 'quote', text: 'ann' }], }) - expect(await findReferences('author', 'ann')).toEqual([]) + expect( + await findReferencesAs(systemContext('test'), 'author', 'ann'), + ).toEqual([]) expect(await deleteDocument('author', 'ann')).toBe(true) }) @@ -155,9 +162,11 @@ describe('referential integrity', () => { ], }), ) - expect((await findReferences('author', 'ann')).map((r) => r.id)).toEqual([ - 'zz', - ]) + expect( + (await findReferencesAs(systemContext('test'), 'author', 'ann')).map( + (r) => r.id, + ), + ).toEqual(['zz']) await expect(deleteDocument('author', 'ann')).rejects.toMatchObject({ code: 'CONFLICT', }) @@ -227,14 +236,14 @@ describe('relation targets in large collections', () => { actor: 'mcp', }) - const hit = await queryDocumentSummaries({ + const hit = await queryDocumentSummariesAs(systemContext('test'), { collection: 'author', search: 'Writer 247', limit: 20, }) expect(hit.items.map((i) => i.id)).toContain('a247') - const byId = await queryDocumentSummaries({ + const byId = await queryDocumentSummariesAs(systemContext('test'), { collection: 'author', ids: ['a3', 'a249', 'pending-one', 'missing'], limit: 500, diff --git a/packages/core/tests/slow-hooks.test.ts b/packages/core/tests/slow-hooks.test.ts index b1641f6c..88624dca 100644 --- a/packages/core/tests/slow-hooks.test.ts +++ b/packages/core/tests/slow-hooks.test.ts @@ -2,7 +2,12 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { closeStore, commitDocument, readDocument } from '../src/server' +import { + closeStore, + commitDocument, + systemContext, + readDocumentAs, +} from '../src/server' import { defineCms } from '../src/config' import { SLOW_HOOK_MS, @@ -74,8 +79,8 @@ describe('dev-mode slow-hook warning', () => { }, }) await commitDocument('post', 'a', { title: 'A' }) - await readDocument('post', 'a') - await readDocument('post', 'a') + await readDocumentAs(systemContext('test'), 'post', 'a') + await readDocumentAs(systemContext('test'), 'post', 'a') const stages = hookWarnings().map((w) => /Hook (\S+) took/.exec(w)?.[1]) expect(stages.sort()).toEqual(['post.afterChange', 'post.postRead']) }) @@ -86,7 +91,9 @@ describe('dev-mode slow-hook warning', () => { postRead: ({ doc }) => doc, }) await commitDocument('post', 'a', { title: ' A ' }) - expect((await readDocument('post', 'a'))?.title).toBe('A') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.title, + ).toBe('A') expect(hookWarnings()).toEqual([]) }) diff --git a/packages/core/tests/storage-conformance.test.ts b/packages/core/tests/storage-conformance.test.ts index 4798dd82..e368c5d4 100644 --- a/packages/core/tests/storage-conformance.test.ts +++ b/packages/core/tests/storage-conformance.test.ts @@ -23,10 +23,12 @@ import { commitDocument, deleteDocument, listCollectionsMeta, - queryDocuments, - readDocument, - readDocumentBySlug, stageWrite, + publicContext, + systemContext, + readDocumentAs, + readDocumentBySlugAs, + queryDocumentsAs, } from '../src/server' import { createD1Driver, @@ -203,30 +205,33 @@ describe('createMarkdownStorage & read-only collections', () => { ).toBe(false) expect(listCollectionsMeta()[0]?.readOnly).toBe(true) - const alpha = await readDocument('post', 'alpha') + const alpha = await readDocumentAs(systemContext('test'), 'post', 'alpha') expect(alpha).toMatchObject({ title: 'Alpha Post', body: 'Alpha body content', published: true, }) - const bySlug = await readDocumentBySlug('post', 'alpha-slug') + const bySlug = await readDocumentBySlugAs( + systemContext('test'), + 'post', + 'alpha-slug', + ) expect(bySlug?.id).toBe('alpha') - const published = await queryDocuments({ + const published = await queryDocumentsAs(publicContext(), { collection: 'post', - publishedOnly: true, }) expect(published.total).toBe(1) expect(published.items.map((i) => i.id)).toEqual(['alpha']) - const sorted = await queryDocuments({ + const sorted = await queryDocumentsAs(systemContext('test'), { collection: 'post', sort: { field: 'rank', dir: 'asc' }, }) expect(sorted.items.map((i) => i.id)).toEqual(['beta', 'alpha']) - const searched = await queryDocuments({ + const searched = await queryDocumentsAs(systemContext('test'), { collection: 'post', query: 'Alpha body', }) @@ -286,18 +291,23 @@ describe('createMarkdownStorage & read-only collections', () => { name: 'Acme Anvil', published: true, }) - expect((await readDocument('product', 'anvil'))?.name).toBe('Acme Anvil') + expect( + (await readDocumentAs(systemContext('test'), 'product', 'anvil'))?.name, + ).toBe('Acme Anvil') // Read-only markdown collection works and rejects writes - expect((await readDocument('docs', 'getting-started'))?.title).toBe( - 'Getting Started', - ) + expect( + (await readDocumentAs(systemContext('test'), 'docs', 'getting-started')) + ?.title, + ).toBe('Getting Started') await expect( commitDocument('docs', 'new-doc', { title: 'No', body: 'No' }), ).rejects.toThrow(/read-only/i) // Cross-collection query merges results across both storage backends - const all = await queryDocuments({ collections: ['docs', 'product'] }) + const all = await queryDocumentsAs(systemContext('test'), { + collections: ['docs', 'product'], + }) expect(all.total).toBe(2) expect(all.items.map((i) => `${i.collection}/${i.id}`)).toEqual([ 'docs/getting-started', @@ -341,7 +351,7 @@ describe('createMarkdownStorage & read-only collections', () => { }) return { site: getCmsConfig().theme?.name, - doc: await readDocument('post', '1'), + doc: await readDocumentAs(systemContext('test'), 'post', '1'), } }), runWithCmsConfig(cfgB, async () => { @@ -351,7 +361,7 @@ describe('createMarkdownStorage & read-only collections', () => { }) return { site: getCmsConfig().theme?.name, - doc: await readDocument('post', '1'), + doc: await readDocumentAs(systemContext('test'), 'post', '1'), } }), ]) @@ -433,7 +443,9 @@ describe('createMarkdownStorage & read-only collections', () => { await approve(pCustom.id) await reject(pBase.id) expect(await listPending()).toEqual([]) - expect((await readDocument('auditCol', 'c1'))?.title).toBe('Custom Doc') + expect( + (await readDocumentAs(systemContext('test'), 'auditCol', 'c1'))?.title, + ).toBe('Custom Doc') const audits = await listAudit() expect( audits.map((a) => `${a.collection} ${a.action} ${a.decision}`).sort(), @@ -487,13 +499,13 @@ describe('createMarkdownStorage & read-only collections', () => { ], }) - const desc = await queryDocuments({ + const desc = await queryDocumentsAs(systemContext('test'), { collection: 'post', sort: { field: '_updatedAt', dir: 'desc' }, }) expect(desc.items.map((i) => i.id)).toEqual(['newer', 'older']) - const asc = await queryDocuments({ + const asc = await queryDocumentsAs(systemContext('test'), { collection: 'post', sort: { field: '_updatedAt', dir: 'asc' }, }) @@ -562,8 +574,8 @@ describe('createMarkdownStorage & read-only collections', () => { await expect(importContent(file)).rejects.toMatchObject({ code: 'VALIDATION_FAILED', }) - expect(await readDocument('post', 'a')).toBeNull() - expect(await readDocument('post', 'b')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'a')).toBeNull() + expect(await readDocumentAs(systemContext('test'), 'post', 'b')).toBeNull() }) it('rolls back every statement in a D1 batch when a later one fails', async () => { diff --git a/packages/core/tests/store-index.test.ts b/packages/core/tests/store-index.test.ts index dea822bf..11053bfe 100644 --- a/packages/core/tests/store-index.test.ts +++ b/packages/core/tests/store-index.test.ts @@ -9,12 +9,14 @@ import { closeStore, commitDocument, deleteDocument, - listDocuments, listPublicDocuments, - listTranslations, - queryDocuments, - readDocumentBySlug, stageWrite, + publicContext, + systemContext, + queryDocumentsAs, + readDocumentBySlugAs, + listDocumentsAs, + listTranslationsAs, } from '../src/server' /** @@ -97,21 +99,23 @@ describe('indexed read path', () => { const dir = makeTempDir() await seed(dir) expect( - (await queryDocuments({ collection: 'post', publishedOnly: true })).total, + (await queryDocumentsAs(publicContext(), { collection: 'post' })).total, ).toBe(2) expect( ( - await queryDocuments({ + await queryDocumentsAs(publicContext(), { collection: 'post', - publishedOnly: true, locale: 'en', }) ).items.map((i) => i.id), ).toEqual(['a']) expect( - (await queryDocuments({ collection: 'post', locale: 'de' })).items.map( - (i) => i.id, - ), + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + locale: 'de', + }) + ).items.map((i) => i.id), ).toEqual(['c']) }) @@ -120,7 +124,7 @@ describe('indexed read path', () => { await seed(dir) expect( ( - await queryDocuments({ + await queryDocumentsAs(systemContext('test'), { collection: 'post', where: { title: 'Hello world' }, }) @@ -128,24 +132,43 @@ describe('indexed read path', () => { ).toEqual(['a']) // multiselect array-contains, mirroring the old JS includes() check expect( - (await queryDocuments({ collection: 'post', where: { tags: 'news' } })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + where: { tags: 'news' }, + }) + ).total, ).toBe(2) expect( - (await queryDocuments({ collection: 'post', where: { tags: 'release' } })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + where: { tags: 'release' }, + }) + ).total, ).toBe(2) expect( - (await queryDocuments({ collection: 'post', where: { tags: 'nope' } })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + where: { tags: 'nope' }, + }) + ).total, ).toBe(0) expect( - (await queryDocuments({ collection: 'post', where: { published: true } })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + where: { published: true }, + }) + ).total, ).toBe(2) expect( ( - await queryDocuments({ collection: 'post', where: { slug: '/hello' } }) + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + where: { slug: '/hello' }, + }) ).items.map((i) => i.id), ).toEqual(['a']) }) @@ -155,22 +178,40 @@ describe('indexed read path', () => { await seed(dir) // token match expect( - (await queryDocuments({ collection: 'post', query: 'Hello' })).total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'Hello', + }) + ).total, ).toBe(1) // substring match, like the old haystack.includes(q) expect( - (await queryDocuments({ collection: 'post', query: 'ello' })).total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'ello', + }) + ).total, ).toBe(1) expect( - (await queryDocuments({ collection: 'post', query: 'zzz-no-match' })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'zzz-no-match', + }) + ).total, ).toBe(0) // FTS5 special characters are phrase-quoted: no syntax error, and they // match literally — just like the old haystack.includes(q) semantics. // No seeded doc contains literal parens, so this matches nothing… expect( - (await queryDocuments({ collection: 'post', query: 'hello (world)' })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'hello (world)', + }) + ).total, ).toBe(0) // …but a doc containing them matches. await commitDocument('post', 'paren', { @@ -181,8 +222,12 @@ describe('indexed read path', () => { locale: 'en', }) expect( - (await queryDocuments({ collection: 'post', query: 'hello (world)' })) - .total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'hello (world)', + }) + ).total, ).toBe(1) }) @@ -197,21 +242,36 @@ describe('indexed read path', () => { locale: 'en', }) expect( - (await queryDocuments({ collection: 'post', query: 'Hello' })).total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'Hello', + }) + ).total, ).toBe(0) expect( - (await queryDocuments({ collection: 'post', query: 'Completely' })).total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'Completely', + }) + ).total, ).toBe(1) await deleteDocument('post', 'a') expect( - (await queryDocuments({ collection: 'post', query: 'Completely' })).total, + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'Completely', + }) + ).total, ).toBe(0) }) it('sorts and paginates like before', async () => { const dir = makeTempDir() await seed(dir) - const asc = await queryDocuments({ + const asc = await queryDocumentsAs(systemContext('test'), { collection: 'post', sort: { field: 'title', dir: 'asc' }, }) @@ -220,7 +280,7 @@ describe('indexed read path', () => { 'Hello world', 'Second post', ]) - const page = await queryDocuments({ + const page = await queryDocumentsAs(systemContext('test'), { collection: 'post', sort: { field: 'title', dir: 'asc' }, limit: 1, @@ -233,30 +293,43 @@ describe('indexed read path', () => { it('resolves slugs with and without leading slashes', async () => { const dir = makeTempDir() await seed(dir) - expect((await readDocumentBySlug('post', 'a'))?.id).toBe('a') - expect((await readDocumentBySlug('post', '/hello'))?.id).toBe('a') - expect((await readDocumentBySlug('post', 'hello'))?.id).toBe('a') - expect((await readDocumentBySlug('post', 'second'))?.id).toBe('b') - expect((await readDocumentBySlug('post', '/second'))?.id).toBe('b') - expect(await readDocumentBySlug('post', 'missing')).toBeNull() expect( - await readDocumentBySlug('post', 'b', { publishedOnly: true }), - ).toBeNull() + (await readDocumentBySlugAs(systemContext('test'), 'post', 'a'))?.id, + ).toBe('a') + expect( + (await readDocumentBySlugAs(systemContext('test'), 'post', '/hello'))?.id, + ).toBe('a') expect( - (await readDocumentBySlug('post', 'a', { publishedOnly: true }))?.id, + (await readDocumentBySlugAs(systemContext('test'), 'post', 'hello'))?.id, ).toBe('a') + expect( + (await readDocumentBySlugAs(systemContext('test'), 'post', 'second'))?.id, + ).toBe('b') + expect( + (await readDocumentBySlugAs(systemContext('test'), 'post', '/second')) + ?.id, + ).toBe('b') + expect( + await readDocumentBySlugAs(systemContext('test'), 'post', 'missing'), + ).toBeNull() + expect(await readDocumentBySlugAs(publicContext(), 'post', 'b')).toBeNull() + expect((await readDocumentBySlugAs(publicContext(), 'post', 'a'))?.id).toBe( + 'a', + ) }) it('lists documents and public documents from the index', async () => { const dir = makeTempDir() await seed(dir) - const all = await listDocuments('post') + const all = await listDocumentsAs(systemContext('test'), 'post') expect(all).toHaveLength(3) const a = all.find((d) => d.id === 'a')! expect(a.title).toBe('Hello world') expect(a.published).toBe(true) expect(a.locale).toBe('en') - const de = await listDocuments('post', { locale: 'de' }) + const de = await listDocumentsAs(systemContext('test'), 'post', { + locale: 'de', + }) expect(de.map((d) => d.id)).toEqual(['c']) const pub = await listPublicDocuments('post') expect(Object.keys(pub.post).sort()).toEqual(['a', 'c']) @@ -272,7 +345,7 @@ describe('indexed read path', () => { doc: { title: 'Staged draft', published: false }, actor: 'agent', }) - const all = await listDocuments('post') + const all = await listDocumentsAs(systemContext('test'), 'post') const staged = all.find((d) => d.id === 'draft-1') expect(staged?.pending).toBe(true) expect(staged?.title).toBe('Staged draft') @@ -312,15 +385,23 @@ describe('indexed read path', () => { // Opening the store migrates: columns added, backfilled, FTS rebuilt. expect( - (await queryDocuments({ collection: 'post', publishedOnly: true })).total, + (await queryDocumentsAs(publicContext(), { collection: 'post' })).total, ).toBe(1) - expect((await readDocumentBySlug('post', '/legacy'))?.id).toBe('legacy-1') expect( - (await queryDocuments({ collection: 'post', query: 'Legacy' })).total, + (await readDocumentBySlugAs(systemContext('test'), 'post', '/legacy')) + ?.id, + ).toBe('legacy-1') + expect( + ( + await queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'Legacy', + }) + ).total, ).toBe(1) expect( ( - await queryDocuments({ + await queryDocumentsAs(systemContext('test'), { collection: 'post', where: { title: 'Legacy post' }, }) @@ -336,7 +417,9 @@ describe('indexed read path', () => { }, }) await commitDocument('post', 'a', { title: 'Hello', published: true }) - const { items } = await queryDocuments({ collection: 'post' }) + const { items } = await queryDocumentsAs(systemContext('test'), { + collection: 'post', + }) expect(items[0]?.doc.title).toBe('Hello!') expect(items[0]?.title).toBe('Hello') expect((await listPublicDocuments('post')).post['a']?.title).toBe('Hello!') @@ -356,7 +439,11 @@ describe('indexed read path', () => { locale: 'de', translationOf: 'orig', }) - const summaries = await listTranslations('post', 'trans') + const summaries = await listTranslationsAs( + systemContext('test'), + 'post', + 'trans', + ) expect(summaries.map((s) => s.id).sort()).toEqual(['orig', 'trans']) expect(summaries.find((s) => s.isCanonical)?.id).toBe('orig') }) @@ -373,7 +460,7 @@ describe('indexed read path', () => { }) await approve(pending.id) expect( - (await queryDocuments({ collection: 'post', publishedOnly: true })).total, + (await queryDocumentsAs(publicContext(), { collection: 'post' })).total, ).toBe(3) }) }) diff --git a/packages/core/tests/store.test.ts b/packages/core/tests/store.test.ts index 8841a796..68a64b95 100644 --- a/packages/core/tests/store.test.ts +++ b/packages/core/tests/store.test.ts @@ -18,18 +18,8 @@ import { deleteDocument, getPending, listAudit, - listDocuments, listPending, listPublicDocuments, - listRevisions, - listTranslations, - populateRelations, - queryDocuments, - queryDocumentSummaries, - readDocument, - readDocumentBySlug, - readDocumentWithPending, - readSingleton, readTrashedDocument, reject, restoreDocument, @@ -44,6 +34,18 @@ import { stageWrite, unpublishDocument, verifyMcpAccess, + publicContext, + systemContext, + readDocumentAs, + listRevisionsAs, + listDocumentsAs, + listTranslationsAs, + readDocumentWithPendingAs, + queryDocumentsAs, + queryDocumentSummariesAs, + readDocumentBySlugAs, + readSingletonAs, + populateRelationsAs, } from '../src/server' describe('SQLite store, revisions, scheduling, and i18n', () => { @@ -107,7 +109,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }, }) - const initial = await readDocument('post', 'hello') + const initial = await readDocumentAs(systemContext('test'), 'post', 'hello') expect(existsSync(dbFile())).toBe(true) expect(initial?.title).toBe('Hello v1') expect(initial?._revision).toBe(1) @@ -120,7 +122,11 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) expect(v2._revision).toBe(2) - const revisions = await listRevisions('post', 'hello') + const revisions = await listRevisionsAs( + systemContext('test'), + 'post', + 'hello', + ) expect(revisions).toHaveLength(2) expect(revisions[0]?.revision).toBe(2) expect(revisions[0]?.doc.title).toBe('Hello v2') @@ -131,7 +137,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { const restored = await restoreRevision('post', 'hello', 1) expect((restored as any).title).toBe('Hello v1') expect((restored as any)._revision).toBe(3) - expect(await listRevisions('post', 'hello')).toHaveLength(3) + expect( + await listRevisionsAs(systemContext('test'), 'post', 'hello'), + ).toHaveLength(3) }) it('automatically imports legacy cms.json on first SQLite initialization', async () => { @@ -155,7 +163,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { ) setupTestCms(dir) - const doc = await readDocument('post', 'from-json') + const doc = await readDocumentAs(systemContext('test'), 'post', 'from-json') expect(doc?.title).toBe('Migrated from JSON') expect(doc?._revision).toBe(1) }) @@ -174,11 +182,17 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) expect(await listPending()).toHaveLength(1) - expect(await readDocument('post', 'agent-post')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'agent-post'), + ).toBeNull() await approve(staged.id) expect(await listPending()).toHaveLength(0) - const committed = await readDocument('post', 'agent-post') + const committed = await readDocumentAs( + systemContext('test'), + 'post', + 'agent-post', + ) expect(committed?.title).toBe('Draft by Agent') expect(committed?._revision).toBe(1) expect((await listAudit())[0]?.decision).toBe('approved') @@ -192,9 +206,10 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { actor: 'webmcp', }) await reject(stagedUpdate.id) - expect((await readDocument('post', 'agent-post'))?.title).toBe( - 'Draft by Agent', - ) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'agent-post')) + ?.title, + ).toBe('Draft by Agent') expect((await listAudit())[0]?.decision).toBe('rejected') }) @@ -219,7 +234,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { await expect(approve(staged.id)).rejects.toMatchObject({ code: 'NOT_FOUND', }) - expect((await readDocument('post', 'hello'))?.title).toBe('Human edit') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'hello'))?.title, + ).toBe('Human edit') expect( (await listAudit()).find((a) => a.decision === 'discarded'), ).toMatchObject({ @@ -257,7 +274,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { after: { title: 'Agent edit', tags: ['news'] }, }) await approve(staged.id) - expect(await readDocument('post', 'hello')).toMatchObject({ + expect( + await readDocumentAs(systemContext('test'), 'post', 'hello'), + ).toMatchObject({ title: 'Agent edit', tags: ['news'], _revision: 3, @@ -277,7 +296,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) await commitDocument('post', 'hello', { title: 'v2', published: true }) await expect(approve(del.id)).rejects.toMatchObject({ code: 'NOT_FOUND' }) - expect(await readDocument('post', 'hello')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'hello'), + ).not.toBeNull() const create = await stageWrite({ collection: 'post', @@ -290,7 +311,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { await expect(approve(create.id)).rejects.toMatchObject({ code: 'NOT_FOUND', }) - expect((await readDocument('post', 'fresh'))?.title).toBe('Human') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'fresh'))?.title, + ).toBe('Human') }) it('supports scheduled publishing and auto-publishes when publishAt is reached', async () => { @@ -303,9 +326,9 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { // Schedule in the future await scheduleDocument('post', 'launch', '2099-01-01T00:00:00.000Z') - const summaryBefore = (await listDocuments('post')).find( - (d) => d.id === 'launch', - ) + const summaryBefore = ( + await listDocumentsAs(systemContext('test'), 'post') + ).find((d) => d.id === 'launch') expect(summaryBefore?.published).toBe(false) expect(summaryBefore?.scheduled).toBe(true) expect(summaryBefore?.publishAt).toBe('2099-01-01T00:00:00.000Z') @@ -317,7 +340,11 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect(autoPublished).toHaveLength(1) expect(autoPublished[0]?.id).toBe('launch') - const afterDoc = await readDocument('post', 'launch') + const afterDoc = await readDocumentAs( + systemContext('test'), + 'post', + 'launch', + ) expect(afterDoc?.published).toBe(true) }) @@ -347,15 +374,21 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) await deleteDocument('post', 'welcome-es', { purge: true }) - const canonical = await readDocument('post', 'welcome') + const canonical = await readDocumentAs( + systemContext('test'), + 'post', + 'welcome', + ) expect(canonical?.translations).toEqual({ fr: 'welcome-fr' }) expect(canonical?._revision).toBe(2) await deleteDocument('post', 'welcome', { purge: true }) - const fr = await readDocument('post', 'welcome-fr') + const fr = await readDocumentAs(systemContext('test'), 'post', 'welcome-fr') expect(fr?.translationOf).toBeUndefined() expect(fr?.title).toBe('Bienvenue') - expect(await listTranslations('post', 'welcome-fr')).toHaveLength(1) + expect( + await listTranslationsAs(systemContext('test'), 'post', 'welcome-fr'), + ).toHaveLength(1) }) it('tracks multi-locale document variants and exposes new ops via runOp', async () => { @@ -378,11 +411,17 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }, }) - const esDocs = await listDocuments('post', { locale: 'es' }) + const esDocs = await listDocumentsAs(systemContext('test'), 'post', { + locale: 'es', + }) expect(esDocs).toHaveLength(1) expect(esDocs[0]?.id).toBe('welcome-es') - const translations = await listTranslations('post', 'welcome') + const translations = await listTranslationsAs( + systemContext('test'), + 'post', + 'welcome', + ) expect(translations).toHaveLength(2) expect(translations.map((t) => t.locale).sort()).toEqual(['en', 'es']) @@ -391,6 +430,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { 'list_revisions', { collection: 'post', id: 'welcome' }, 'mcp', + systemContext('test'), )) as Array expect(revsViaOp).toHaveLength(1) @@ -398,6 +438,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { 'list_translations', { collection: 'post', id: 'welcome-es' }, 'mcp', + systemContext('test'), )) as Array expect(translationsViaOp).toHaveLength(2) @@ -409,6 +450,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { publishAt: '2099-05-01T12:00:00.000Z', }, 'content-agent', + systemContext('test'), )) as { staged: boolean } expect(scheduleViaOp.staged).toBe(true) @@ -416,6 +458,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { 'restore_revision', { collection: 'post', id: 'welcome', revision: '1' }, 'content-agent', + systemContext('test'), )) as { staged: boolean } expect(restoreViaOp.staged).toBe(true) }) @@ -434,12 +477,17 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { instruction: 'Create draft', }, 'content-agent', + systemContext('test'), )) as { staged: boolean; pendingId: string } expect(created.staged).toBe(true) expect(await listPending()).toHaveLength(1) // Agent reads the document it just staged - const withPending = await readDocumentWithPending('post', 'staged-draft') + const withPending = await readDocumentWithPendingAs( + systemContext('test'), + 'post', + 'staged-draft', + ) expect(withPending.isPending).toBe(true) expect(withPending.pendingId).toBe(created.pendingId) expect(withPending.doc?.title).toBe('Initial Draft') @@ -448,6 +496,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { 'read_document', { collection: 'post', id: 'staged-draft' }, 'content-agent', + systemContext('test'), )) as any expect(viaReadOp.title).toBe('Initial Draft') @@ -461,6 +510,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { instruction: 'Refine draft', }, 'content-agent', + systemContext('test'), )) as { staged: boolean; pendingId: string; resultingDocument: any } expect(updated.staged).toBe(true) expect(updated.pendingId).toBe(created.pendingId) @@ -486,35 +536,48 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { const unpublished = (await unpublishDocument('post', 'first')) as any expect(unpublished.published).toBe(false) expect(unpublished.publishAt).toBeUndefined() - expect((await readDocument('post', 'first'))?.published).toBe(false) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'first'))?.published, + ).toBe(false) // Stage unpublish via runOp const stagedUnpub = (await runOp( 'unpublish_document', { collection: 'post', id: 'second', instruction: 'Take offline' }, 'mcp', + systemContext('test'), )) as { staged: boolean; pendingId: string } expect(stagedUnpub.staged).toBe(true) await approve(stagedUnpub.pendingId) - expect((await readDocument('post', 'second'))?.published).toBe(false) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'second')) + ?.published, + ).toBe(false) // Stage deletion via runOp and approve it const stagedDel = (await runOp( 'delete_document', { collection: 'post', id: 'first', instruction: 'Remove obsolete post' }, 'mcp', + systemContext('test'), )) as { staged: boolean; pendingId: string } expect(stagedDel.staged).toBe(true) - expect(await readDocument('post', 'first')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'first'), + ).not.toBeNull() await approve(stagedDel.pendingId) - expect(await readDocument('post', 'first')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'first'), + ).toBeNull() expect((await listAudit())[0]?.type).toBe('delete') expect((await listAudit())[0]?.decision).toBe('approved') // Direct deletion by human const deletedDirect = await deleteDocument('post', 'second') expect(deletedDirect).toBe(true) - expect(await readDocument('post', 'second')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'second'), + ).toBeNull() }) it('soft-deletes to trash, restores, and purges', async () => { @@ -528,19 +591,23 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { // Soft delete leaves the document in the trash, not gone. expect(await deleteDocument('post', 'first')).toBe(true) - expect(await readDocument('post', 'first')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'first'), + ).toBeNull() const trashed = await readTrashedDocument('post', 'first') expect(trashed).not.toBeNull() expect(typeof trashed?.deletedAt).toBe('string') // It is excluded from normal queries and listings... - const live = await queryDocuments({ collection: 'post' }) + const live = await queryDocumentsAs(systemContext('test'), { + collection: 'post', + }) expect(live.items.map((i) => i.id).sort()).toEqual(['second']) - const listed = await listDocuments('post') + const listed = await listDocumentsAs(systemContext('test'), 'post') expect(listed.map((i) => i.id).sort()).toEqual(['second']) // ...but shows up in the trash listing with a deletedAt stamp. - const trash = await queryDocumentSummaries({ + const trash = await queryDocumentSummariesAs(systemContext('test'), { collection: 'post', status: 'trash', }) @@ -552,11 +619,17 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { // Restore brings it back out of the trash. const restored = (await restoreDocument('post', 'first')) as any expect(restored.deletedAt).toBeUndefined() - expect(await readDocument('post', 'first')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'first'), + ).not.toBeNull() expect(await readTrashedDocument('post', 'first')).toBeNull() expect( - (await queryDocumentSummaries({ collection: 'post', status: 'trash' })) - .items.length, + ( + await queryDocumentSummariesAs(systemContext('test'), { + collection: 'post', + status: 'trash', + }) + ).items.length, ).toBe(0) // Restoring something that isn't trashed is a NOT_FOUND. @@ -569,9 +642,11 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect(await readTrashedDocument('post', 'first')).not.toBeNull() expect(await deleteDocument('post', 'first', { purge: true })).toBe(true) expect(await readTrashedDocument('post', 'first')).toBeNull() - expect(await readDocument('post', 'first', { includeDeleted: true })).toBe( - null, - ) + expect( + await readDocumentAs(systemContext('test'), 'post', 'first', { + includeDeleted: true, + }), + ).toBe(null) }) it('stages and approves a soft delete, then stages a restore', async () => { @@ -584,20 +659,26 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { 'delete_document', { collection: 'post', id: 'first', instruction: 'trash it' }, 'mcp', + systemContext('test'), )) as { staged: boolean; pendingId: string } expect(del.staged).toBe(true) await approve(del.pendingId) - expect(await readDocument('post', 'first')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'first'), + ).toBeNull() expect(await readTrashedDocument('post', 'first')).not.toBeNull() const restore = (await runOp( 'restore_document', { collection: 'post', id: 'first', instruction: 'bring it back' }, 'mcp', + systemContext('test'), )) as { staged: boolean; pendingId: string } expect(restore.staged).toBe(true) await approve(restore.pendingId) - expect(await readDocument('post', 'first')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'first'), + ).not.toBeNull() expect(await readTrashedDocument('post', 'first')).toBeNull() }) @@ -608,11 +689,15 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { hello: { title: 'Hello', slug: 'hello', published: true }, }, }) - expect((await readDocumentBySlug('post', 'hello'))?.id).toBe('hello') + expect( + (await readDocumentBySlugAs(systemContext('test'), 'post', 'hello'))?.id, + ).toBe('hello') await deleteDocument('post', 'hello') - expect(await readDocumentBySlug('post', 'hello')).toBeNull() expect( - await readDocumentBySlug('post', 'hello', { publishedOnly: true }), + await readDocumentBySlugAs(systemContext('test'), 'post', 'hello'), + ).toBeNull() + expect( + await readDocumentBySlugAs(publicContext(), 'post', 'hello'), ).toBeNull() }) @@ -642,11 +727,20 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) // readDocumentBySlug (with and without leading slash, and publishedOnly filter) - expect((await readDocumentBySlug('post', 'blog/alpha'))?.id).toBe('alpha') - expect((await readDocumentBySlug('post', '/blog/alpha'))?.id).toBe('alpha') - expect((await readDocumentBySlug('post', 'blog/beta'))?.id).toBe('beta') expect( - await readDocumentBySlug('post', 'blog/beta', { publishedOnly: true }), + (await readDocumentBySlugAs(systemContext('test'), 'post', 'blog/alpha')) + ?.id, + ).toBe('alpha') + expect( + (await readDocumentBySlugAs(systemContext('test'), 'post', '/blog/alpha')) + ?.id, + ).toBe('alpha') + expect( + (await readDocumentBySlugAs(systemContext('test'), 'post', 'blog/beta')) + ?.id, + ).toBe('beta') + expect( + await readDocumentBySlugAs(publicContext(), 'post', 'blog/beta'), ).toBeNull() // listPublicDocuments excludes unpublished drafts @@ -654,7 +748,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect(Object.keys(pub.post ?? {}).sort()).toEqual(['alpha', 'gamma']) // queryDocuments with search query, publishedOnly, where, sort, limit/offset - const searchAi = await queryDocuments({ + const searchAi = await queryDocumentsAs(systemContext('test'), { collection: 'post', query: 'deep dive', }) @@ -664,21 +758,26 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { // A double-quote in the term is a valid FTS5 phrase, not a syntax error: // it must not crash the query (regression for JSON.stringify escaping). await expect( - queryDocuments({ collection: 'post', query: 'a"b' }), + queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'a"b', + }), ).resolves.toMatchObject({ total: expect.any(Number) }) await expect( - queryDocuments({ collection: 'post', query: 'he said "hi"' }), + queryDocumentsAs(systemContext('test'), { + collection: 'post', + query: 'he said "hi"', + }), ).resolves.toBeDefined() - const pubOnly = await queryDocuments({ + const pubOnly = await queryDocumentsAs(publicContext(), { collection: 'post', - publishedOnly: true, sort: { field: 'title', dir: 'desc' }, }) expect(pubOnly.total).toBe(2) expect(pubOnly.items.map((i) => i.id)).toEqual(['gamma', 'alpha']) - const byTag = await queryDocuments({ + const byTag = await queryDocumentsAs(systemContext('test'), { collection: 'post', where: { tags: 'release' }, sort: { field: 'id', dir: 'asc' }, @@ -723,7 +822,11 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) expect(committed.slug).toBe('/auto/hooked') - const loaded = (await readDocument('post', 'hooked')) as any + const loaded = (await readDocumentAs( + systemContext('test'), + 'post', + 'hooked', + )) as any expect(loaded.readHookTag).toBe('enriched') await deleteDocument('post', 'hooked', { actor: 'editor' }) @@ -821,7 +924,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) // Singleton reading and single-document constraint - const singleton = await readSingleton('settings') + const singleton = await readSingletonAs(systemContext('test'), 'settings') expect(singleton?.id).toBe('settings') expect(singleton?.doc.siteTitle).toBe('Acme Blog') @@ -855,13 +958,11 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { ) // Custom slugField resolution + relation population - const foundByCustomSlug = await readDocumentBySlug( + const foundByCustomSlug = await readDocumentBySlugAs( + publicContext(), 'post', 'articles/intro', - { - publishedOnly: true, - populate: true, - }, + { populate: true }, ) expect(foundByCustomSlug?.id).toBe('intro') expect((foundByCustomSlug?.relations?.author as any)?.name).toBe('Jane Doe') @@ -873,16 +974,19 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { ).toEqual(['Deep Dive']) // Direct populateRelations without publishedOnly includes draft relations - const allRels = await populateRelations('post', foundByCustomSlug!.doc) + const allRels = await populateRelationsAs( + systemContext('test'), + 'post', + foundByCustomSlug!.doc, + ) expect((allRels.relatedPosts as Array).map((d) => d.title)).toEqual([ 'Deep Dive', 'Draft Post', ]) // queryDocuments with populate: true - const queried = await queryDocuments({ + const queried = await queryDocumentsAs(publicContext(), { collection: 'post', - publishedOnly: true, populate: true, }) expect(queried.items).toHaveLength(2) @@ -904,7 +1008,10 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) const approvedPublished = await approve(stagedDraft.id, { publish: true }) expect(approvedPublished.after.published).toBe(true) - expect((await readDocument('post', 'agent-created'))?.published).toBe(true) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'agent-created')) + ?.published, + ).toBe(true) }) it('enforces authentication, role guards, and MCP API keys when configured', async () => { @@ -1081,8 +1188,14 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { { hook: 'postValidate', id: 'unsched-1', published: false }, { hook: 'afterChange', id: 'unsched-1', published: false }, ]) - expect((await readDocument('post', 'sched-1'))?.hookStamped).toBe(true) - expect((await readDocument('post', 'unsched-1'))?.published).toBe(false) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'sched-1')) + ?.hookStamped, + ).toBe(true) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'unsched-1')) + ?.published, + ).toBe(false) expect(emitted.every((e) => e.hasDoc)).toBe(true) expect(emitted.map((e) => `${e.event}:${e.id}`)).toEqual([ 'document.updated:sched-1', @@ -1091,7 +1204,8 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { 'document.unpublished:unsched-1', ]) expect( - (await readDocument('post', 'unsched-1'))?.unpublishAt, + (await readDocumentAs(systemContext('test'), 'post', 'unsched-1')) + ?.unpublishAt, ).toBeUndefined() }) @@ -1142,9 +1256,17 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { expect(errorSpy).toHaveBeenCalledOnce() errorSpy.mockRestore() expect(res.map((r) => r.id)).toEqual(['good']) - expect((await readDocument('post', 'bad'))?.published).toBe(false) - expect((await readDocument('post', 'good'))?.published).toBe(true) - const expired = await readDocument('post', 'expire') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'bad'))?.published, + ).toBe(false) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'good'))?.published, + ).toBe(true) + const expired = await readDocumentAs( + systemContext('test'), + 'post', + 'expire', + ) expect(expired?.published).toBe(false) expect(expired?.unpublishAt).toBeUndefined() }) @@ -1180,7 +1302,7 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { }) expect(await listPending()).toHaveLength(0) - const doc = await readDocument('post', 'auto-1') + const doc = await readDocumentAs(systemContext('test'), 'post', 'auto-1') expect(doc?.title).toBe('Auto Approved') const audits = await listAudit() expect(audits[0]?.actor).toContain('auto-approve') @@ -1193,6 +1315,8 @@ describe('SQLite store, revisions, scheduling, and i18n', () => { actor: 'manual-review-agent', }) expect(await listPending()).toHaveLength(1) - expect(await readDocument('post', 'manual-1')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'manual-1'), + ).toBeNull() }) }) diff --git a/packages/core/tests/transfer.test.ts b/packages/core/tests/transfer.test.ts index bae3683d..feed37ce 100644 --- a/packages/core/tests/transfer.test.ts +++ b/packages/core/tests/transfer.test.ts @@ -10,10 +10,8 @@ import { commitDocument, exportContent, importContent, - listRevisions, migrateStorage, parseCmsExport, - readDocument, saveMedia, seedContent, storageStatus, @@ -25,6 +23,9 @@ import { createApiKey, listApiKeys, resolveSession, + systemContext, + readDocumentAs, + listRevisionsAs, } from '../src/server' import { createSqliteStorage } from '../src/storage' import type { CmsConfig } from '../src/index' @@ -83,11 +84,17 @@ describe('export / import', () => { parseCmsExport(JSON.parse(JSON.stringify(snapshot))), ) expect(result).toMatchObject({ created: 2, updated: 0, revisions: 3 }) - expect((await readDocument('post', 'a'))?.title).toBe('A2') - expect((await readDocument('post', 'a'))?._revision).toBe(2) - expect((await listRevisions('post', 'a')).map((r) => r.revision)).toEqual([ - 2, 1, - ]) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.title, + ).toBe('A2') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?._revision, + ).toBe(2) + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'a')).map( + (r) => r.revision, + ), + ).toEqual([2, 1]) }) it('skip-existing keeps stored documents; replace deletes missing ones', async () => { @@ -102,13 +109,19 @@ describe('export / import', () => { }) const skip = await importContent(file, { mode: 'skip-existing' }) expect(skip).toMatchObject({ skipped: 1, created: 0 }) - expect((await readDocument('post', 'a'))?.title).toBe('Stored') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.title, + ).toBe('Stored') const replace = await importContent(file, { mode: 'replace' }) expect(replace).toMatchObject({ updated: 1, deleted: 1 }) - expect((await readDocument('post', 'a'))?.title).toBe('From file') - expect((await readDocument('post', 'a'))?._revision).toBe(2) - expect(await readDocument('post', 'b')).toBeNull() + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?.title, + ).toBe('From file') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'a'))?._revision, + ).toBe(2) + expect(await readDocumentAs(systemContext('test'), 'post', 'b')).toBeNull() }) it('replace deletes every missing document past the first page', async () => { @@ -186,7 +199,9 @@ describe('seed, migrate, backup', () => { await closeStore() setup() await importContent(snapshot) - expect((await readDocument('post', 'live'))?.title).toBe('Live') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'live'))?.title, + ).toBe('Live') expect( (await listPending()).map((pending) => pending.source).sort(), ).toEqual(['agent', 'draft']) @@ -226,12 +241,16 @@ describe('seed, migrate, backup', () => { }) await commitDocument('post', 'hello', { title: 'Edited', published: true }) expect(await seedContent()).toEqual({ seeded: 0, skipped: true }) - expect((await readDocument('post', 'hello'))?.title).toBe('Edited') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'hello'))?.title, + ).toBe('Edited') expect(await seedContent({ force: true })).toEqual({ seeded: 1, skipped: false, }) - expect((await readDocument('post', 'hello'))?.title).toBe('Hello') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'hello'))?.title, + ).toBe('Hello') }) it('reports and applies schema migrations', async () => { @@ -307,7 +326,9 @@ describe('seed, migrate, backup', () => { seeded: 1, skipped: false, }) - expect((await readDocument('post', 'p1'))?.title).toBe('Seeded Post') + expect( + (await readDocumentAs(systemContext('test'), 'post', 'p1'))?.title, + ).toBe('Seeded Post') const imported = await importContent( parseCmsExport({ diff --git a/packages/core/tests/where.test.ts b/packages/core/tests/where.test.ts index a26a059e..219c4fa3 100644 --- a/packages/core/tests/where.test.ts +++ b/packages/core/tests/where.test.ts @@ -3,7 +3,13 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { defineCms, normalizeSession } from '../src/index' -import { closeStore, commitDocument, queryDocuments } from '../src/server' +import { + closeStore, + commitDocument, + accessContext, + systemContext, + queryDocumentsAs, +} from '../src/server' import { evaluateStorageQuery, createSqliteStorage } from '../src/storage' import type { Collection } from '../src/index' import type { IndexedDocumentRecord, WhereClause } from '../src/storage' @@ -192,7 +198,7 @@ describe('queryDocuments where and cursors', () => { setup() await seed() const q = (where: Record) => - queryDocuments({ + queryDocumentsAs(systemContext('test'), { collection: 'article', where, sort: { field: 'rank' }, @@ -218,11 +224,17 @@ describe('queryDocuments where and cursors', () => { { rank: { in: 'x' } }, ]) { await expect( - queryDocuments({ collection: 'article', where }), + queryDocumentsAs(systemContext('test'), { + collection: 'article', + where, + }), ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) } await expect( - queryDocuments({ collection: 'article', sort: { field: 'a;b' } }), + queryDocumentsAs(systemContext('test'), { + collection: 'article', + sort: { field: 'a;b' }, + }), ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) }) @@ -250,14 +262,16 @@ describe('queryDocuments where and cursors', () => { { sort: { field: 'rank' } }, ]) { await expect( - queryDocuments({ collection: 'article', ...options, session: viewer }), + queryDocumentsAs(accessContext({ session: viewer, mode: 'edit' }), { + collection: 'article', + ...options, + }), ).rejects.toMatchObject({ code: 'FORBIDDEN' }) } - const ok = await queryDocuments({ - collection: 'article', - where: { rank: { gt: 3 } }, - session: admin, - }) + const ok = await queryDocumentsAs( + accessContext({ session: admin, mode: 'edit' }), + { collection: 'article', where: { rank: { gt: 3 } } }, + ) expect(ok.total).toBe(2) }) @@ -273,7 +287,10 @@ describe('queryDocuments where and cursors', () => { let cursor: string | undefined let pages = 0 do { - const page = await queryDocuments({ ...base, cursor }) + const page = await queryDocumentsAs(systemContext('test'), { + ...base, + cursor, + }) expect(page.total).toBe(5) seen.push(...ids(page)) cursor = page.nextCursor @@ -282,16 +299,16 @@ describe('queryDocuments where and cursors', () => { expect(pages).toBe(3) expect(seen).toEqual(['a1', 'a2', 'a3', 'a4', 'a5']) - const first = await queryDocuments(base) + const first = await queryDocumentsAs(systemContext('test'), base) await expect( - queryDocuments({ + queryDocumentsAs(systemContext('test'), { ...base, sort: { field: 'rank', dir: 'desc' }, cursor: first.nextCursor, }), ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) await expect( - queryDocuments({ ...base, cursor: 'garbage' }), + queryDocumentsAs(systemContext('test'), { ...base, cursor: 'garbage' }), ).rejects.toMatchObject({ code: 'BAD_REQUEST' }) }) }) diff --git a/packages/search-cms/src/index.ts b/packages/search-cms/src/index.ts index 26155ce3..c995b04f 100644 --- a/packages/search-cms/src/index.ts +++ b/packages/search-cms/src/index.ts @@ -6,14 +6,13 @@ import { SearchValidationError, validateFilter, } from '@tanstack/search-core' -import { UNAUTHENTICATED_SESSION } from '@tanstack/cms-core' import { - accessContext, groupDocumentsAs, + publicContext, queryDocumentsAs, } from '@tanstack/cms-core/server' import type { AccessContext } from '@tanstack/cms-core/server' -import type { CmsSession, Collection, Doc, Field } from '@tanstack/cms-core' +import type { Collection, Doc, Field } from '@tanstack/cms-core' import type { WhereClause } from '@tanstack/cms-core/storage' import type { FieldRegistry, @@ -173,34 +172,15 @@ export interface CmsSearchOptions { /** * Who searches, and in which mode: `publicContext()` for a public site * search (the default), `accessContext({ session, mode: 'edit' })` for an - * editor searching drafts. Results are what this context may read. When - * set, `session`, `publishedOnly` and `publicRead` are ignored. + * editor searching drafts. Results are what this context may read. */ access?: AccessContext - /** @deprecated Pass `access: accessContext({ session })`. */ - session?: CmsSession - /** - * @deprecated The context's mode decides it (`live` is published only). - * Default `true`. - */ - publishedOnly?: boolean - /** @deprecated Pass `access: accessContext({ session, publicRead: true })`. */ - publicRead?: boolean locale?: string } -function searchContext(options: CmsSearchOptions): AccessContext { - if (options.access) return options.access - return accessContext({ - session: options.session ?? UNAUTHENTICATED_SESSION, - mode: (options.publishedOnly ?? true) ? 'live' : 'edit', - publicRead: options.publicRead ?? !options.session?.isAuthenticated, - }) -} - export function createCmsSearch(options: CmsSearchOptions) { const fields = cmsSearchFields(options.collection) - const access = searchContext(options) + const access = options.access ?? publicContext() const base = { collection: options.collection.name, locale: options.locale, diff --git a/packages/search-cms/tests/cms.test.ts b/packages/search-cms/tests/cms.test.ts index 2f0441f1..048bd811 100644 --- a/packages/search-cms/tests/cms.test.ts +++ b/packages/search-cms/tests/cms.test.ts @@ -144,8 +144,7 @@ it('searches as the access context it is given', async () => { ( await createCmsSearch({ collection: current, - session: viewer(), - publishedOnly: false, + access: accessContext({ session: viewer(), mode: 'edit' }), }).search({ text: 'warm strumming' }) ).total, ).toBe(3) @@ -156,7 +155,7 @@ it('applies document-dependent access to totals and all facet counts', async () }) const result = await createCmsSearch({ collection: current, - session: viewer(), + access: accessContext({ session: viewer() }), }).search({ facets: ['vendor', 'material'] }) expect(result.total).toBe(2) expect(result.facetCounts.vendor).toEqual([{ value: 'A', count: 2 }]) @@ -173,7 +172,10 @@ it('rejects filters, requested facets, and text queries on unreadable fields', a : field, ), }) - const search = createCmsSearch({ collection: current, session: viewer() }) + const search = createCmsSearch({ + collection: current, + access: accessContext({ session: viewer() }), + }) await expect(search.search({ facets: ['vendor'] })).rejects.toMatchObject({ code: 'FORBIDDEN', }) @@ -188,7 +190,10 @@ it('rejects filters, requested facets, and text queries on unreadable fields', a ), }) await expect( - createCmsSearch({ collection: notesHidden, session: viewer() }).search({ + createCmsSearch({ + collection: notesHidden, + access: accessContext({ session: viewer() }), + }).search({ text: 'warm', facets: [], }), @@ -209,10 +214,13 @@ it('redacts complete hits for anonymous and authenticated viewers, after read ho : field, ), }) - for (const session of [undefined, viewer()]) { + for (const access of [ + publicContext(), + accessContext({ session: viewer() }), + ]) { const result = await createCmsSearch({ collection: current, - session, + access, }).search({ facets: [] }) expect(result.total).toBe(3) expect(result.hits).toHaveLength(3) diff --git a/packages/store-postgres/tests/events.test.ts b/packages/store-postgres/tests/events.test.ts index 8635fd9e..b90f272d 100644 --- a/packages/store-postgres/tests/events.test.ts +++ b/packages/store-postgres/tests/events.test.ts @@ -8,9 +8,10 @@ import { getStorage, listDeadLetterEvents, listEventSchedules, - readDocument, runEventDispatch, signWebhook, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createPostgresStorage } from '../src' import { newPrefix, pool, url } from './helpers' @@ -239,7 +240,9 @@ describe.skipIf(!url)('async events over Postgres', () => { if (r.claimed === 0) break } expect(created).toEqual(['root']) - expect(await readDocument('post', 'child')).not.toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'post', 'child'), + ).not.toBeNull() }) it('emits document.deleted with the last snapshot', async () => { diff --git a/packages/store-postgres/tests/invariants.test.ts b/packages/store-postgres/tests/invariants.test.ts index 4124e4a9..86a6b81e 100644 --- a/packages/store-postgres/tests/invariants.test.ts +++ b/packages/store-postgres/tests/invariants.test.ts @@ -9,11 +9,12 @@ import { exportContent, getStorage, importContent, - listRevisions, - readDocument, reject, runEventDispatch, stageWrite, + systemContext, + readDocumentAs, + listRevisionsAs, } from '@tanstack/cms-core/server' import { sqliteStorage } from '@tanstack/cms-core/storage' import { createCmsApiHandler } from '../../api/src/index' @@ -369,8 +370,13 @@ describe.skipIf(!url)( created: 2, revisions: 2, }) - expect((await readDocument('post', 'fr'))?.translationOf).toBe('en') - expect(await listRevisions('post', 'en')).toHaveLength(1) + expect( + (await readDocumentAs(systemContext('test'), 'post', 'fr')) + ?.translationOf, + ).toBe('en') + expect( + await listRevisionsAs(systemContext('test'), 'post', 'en'), + ).toHaveLength(1) expect(await second.listPending()).toHaveLength(1) // The restored decisions, plus the restore's own import audit. expect( @@ -404,7 +410,10 @@ describe.skipIf(!url)( created: 1, revisions: 1, }) - expect((await listRevisions('post', 'one'))[0]?.doc.title).toBe('One') + expect( + (await listRevisionsAs(systemContext('test'), 'post', 'one'))[0]?.doc + .title, + ).toBe('One') }) it('persists each handler retry ceiling and completed deliveries through adapter restart', async () => { @@ -485,7 +494,9 @@ describe.skipIf(!url)( await reader.cancel() expect(body).not.toContain('"hidden"') expect(body).not.toContain('Mine') - expect(await listRevisions('post', 'mine')).toEqual([]) + expect( + await listRevisionsAs(systemContext('test'), 'post', 'mine'), + ).toEqual([]) }) }, ) diff --git a/packages/store-postgres/tests/postgres.test.ts b/packages/store-postgres/tests/postgres.test.ts index aaa9e5fa..aa4f1d56 100644 --- a/packages/store-postgres/tests/postgres.test.ts +++ b/packages/store-postgres/tests/postgres.test.ts @@ -4,8 +4,9 @@ import { CmsError, defineCms, runWithCmsConfig } from '@tanstack/cms-core' import { commitDocument, deleteDocument, - readDocument, stageWrite, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { sqliteStorage } from '@tanstack/cms-core/storage' import { @@ -715,8 +716,13 @@ describe.skipIf(!url)('Postgres integrity and transactions', () => { }) expect((await storage.getDocument('post', 'en'))?.title).toBe('English') await deleteDocument('post', 'en', { purge: true }) - expect(await readDocument('post', 'en')).toBeNull() - expect((await readDocument('post', 'fr'))?.translationOf).toBeUndefined() + expect( + await readDocumentAs(systemContext('test'), 'post', 'en'), + ).toBeNull() + expect( + (await readDocumentAs(systemContext('test'), 'post', 'fr')) + ?.translationOf, + ).toBeUndefined() expect(await storage.listRevisions('post', 'en')).toEqual([]) await stageWrite({ collection: 'post', diff --git a/packages/ui-react/tests/s2-blog-propagation.test.ts b/packages/ui-react/tests/s2-blog-propagation.test.ts index bc3cc6ba..9c474e8f 100644 --- a/packages/ui-react/tests/s2-blog-propagation.test.ts +++ b/packages/ui-react/tests/s2-blog-propagation.test.ts @@ -6,7 +6,8 @@ import { collections, defineCms, schemaFor } from '@tanstack/cms-core' import { closeStore, commitDocument, - queryDocumentSummaries, + systemContext, + queryDocumentSummariesAs, } from '@tanstack/cms-core/server' import { createCmsApiHandler } from '@tanstack/cms-api/http' import { invokeAnyOp } from '@tanstack/cms-api' @@ -112,7 +113,7 @@ describe('Seam S2 on blog representative — add-one-field propagation across al expect(body.result.doc.readingTimeMinutes).toBe(7) // 5. Search index - const search = await queryDocumentSummaries({ + const search = await queryDocumentSummariesAs(systemContext('test'), { collection: 'post', search: 'UniqueTokenXYZ', columns: ['title', 'readingTimeMinutes'], diff --git a/scripts/codemods/__fixtures__/access-context/ambient.input.ts b/scripts/codemods/__fixtures__/access-context/ambient.input.ts new file mode 100644 index 00000000..3253d6d2 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/ambient.input.ts @@ -0,0 +1,11 @@ +import { readDocument, runWithSession } from '@tanstack/cms-core/server' +import type { CmsSession } from '@tanstack/cms-core' + +export async function load(session: CmsSession, id: string) { + return runWithSession(session, () => readDocument('post', id)) +} + +export async function current() { + const { currentSession } = await import('@tanstack/cms-core/server') + return currentSession() +} diff --git a/scripts/codemods/__fixtures__/access-context/ambient.output.ts b/scripts/codemods/__fixtures__/access-context/ambient.output.ts new file mode 100644 index 00000000..658927e3 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/ambient.output.ts @@ -0,0 +1,11 @@ +import { runWithSession, systemContext, readDocumentAs } from '@tanstack/cms-core/server' +import type { CmsSession } from '@tanstack/cms-core' + +export async function load(session: CmsSession, id: string) { + return runWithSession(session, () => readDocumentAs(systemContext('access-context codemod: was an unscoped read'), 'post', id)) +} + +export async function current() { + const { currentSession } = await import('@tanstack/cms-core/server') + return currentSession() +} diff --git a/scripts/codemods/__fixtures__/access-context/ambient.warnings.json b/scripts/codemods/__fixtures__/access-context/ambient.warnings.json new file mode 100644 index 00000000..792b1f9b --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/ambient.warnings.json @@ -0,0 +1,5 @@ +[ + "ambient.ts:1:24: runWithSession is removed: pass the session, or an access context, to each call by hand", + "ambient.ts:9:11: currentSession is removed: pass the session, or an access context, to each call by hand", + "ambient.ts:5:40: readDocument: unscoped read kept as systemContext(…): use publicContext() or the request’s context if it serves visitors" +] diff --git a/scripts/codemods/__fixtures__/access-context/calls.input.ts b/scripts/codemods/__fixtures__/access-context/calls.input.ts new file mode 100644 index 00000000..310e12c3 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/calls.input.ts @@ -0,0 +1,29 @@ +import { + queryDocuments, + readDocument, + readDocumentBySlug, + resolveSession, +} from '@tanstack/cms-core/server' + +export async function page(request: Request, slug: string) { + const session = await resolveSession(request) + const posts = await queryDocuments({ + collection: 'post', + publishedOnly: true, + limit: 10, + }) + const mine = await queryDocuments({ + collection: 'post', + session, + sort: { field: 'title' }, + }) + const staff = await queryDocuments({ + collection: 'post', + session: session, + publishedOnly: true, + publicRead: true, + }) + const found = await readDocumentBySlug('post', slug, { publishedOnly: true }) + const raw = await readDocument('post', 'one') + return { posts, mine, staff, found, raw } +} diff --git a/scripts/codemods/__fixtures__/access-context/calls.output.ts b/scripts/codemods/__fixtures__/access-context/calls.output.ts new file mode 100644 index 00000000..a8a8ebc0 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/calls.output.ts @@ -0,0 +1,11 @@ +import { resolveSession, accessContext, publicContext, systemContext, queryDocumentsAs, readDocumentBySlugAs, readDocumentAs } from '@tanstack/cms-core/server' + +export async function page(request: Request, slug: string) { + const session = await resolveSession(request) + const posts = await queryDocumentsAs(publicContext(), { collection: 'post', limit: 10 }) + const mine = await queryDocumentsAs(accessContext({ session, mode: 'edit' }), { collection: 'post', sort: { field: 'title' } }) + const staff = await queryDocumentsAs(accessContext({ session, publicRead: true }), { collection: 'post' }) + const found = await readDocumentBySlugAs(publicContext(), 'post', slug) + const raw = await readDocumentAs(systemContext('access-context codemod: was an unscoped read'), 'post', 'one') + return { posts, mine, staff, found, raw } +} diff --git a/scripts/codemods/__fixtures__/access-context/calls.warnings.json b/scripts/codemods/__fixtures__/access-context/calls.warnings.json new file mode 100644 index 00000000..74319159 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/calls.warnings.json @@ -0,0 +1,3 @@ +[ + "calls.ts:27:21: readDocument: unscoped read kept as systemContext(…): use publicContext() or the request’s context if it serves visitors" +] diff --git a/scripts/codemods/__fixtures__/access-context/docs.input.md b/scripts/codemods/__fixtures__/access-context/docs.input.md new file mode 100644 index 00000000..153293eb --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/docs.input.md @@ -0,0 +1,13 @@ +# Reading + +```ts +import { queryDocuments } from '@tanstack/cms-core/server' + +const posts = await queryDocuments({ collection: 'post', publishedOnly: true }) +``` + +A snippet without its import is left alone: + +```ts +const posts = await queryDocuments({ collection: 'post', publishedOnly: true }) +``` diff --git a/scripts/codemods/__fixtures__/access-context/docs.output.md b/scripts/codemods/__fixtures__/access-context/docs.output.md new file mode 100644 index 00000000..7f30fe54 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/docs.output.md @@ -0,0 +1,13 @@ +# Reading + +```ts +import { publicContext, queryDocumentsAs } from '@tanstack/cms-core/server' + +const posts = await queryDocumentsAs(publicContext(), { collection: 'post' }) +``` + +A snippet without its import is left alone: + +```ts +const posts = await queryDocuments({ collection: 'post', publishedOnly: true }) +``` diff --git a/scripts/codemods/__fixtures__/access-context/dynamic.input.ts b/scripts/codemods/__fixtures__/access-context/dynamic.input.ts new file mode 100644 index 00000000..a0faeda2 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/dynamic.input.ts @@ -0,0 +1,20 @@ +import type { CmsSession } from '@tanstack/cms-core' +import type { QueryDocumentsOptions } from '@tanstack/cms-core/server' + +export async function listing(live: boolean) { + const { queryDocuments } = await import('@tanstack/cms-core/server') + return queryDocuments({ collection: 'post', publishedOnly: live }) +} + +export async function search( + session: CmsSession, + options: QueryDocumentsOptions, +) { + const { queryDocuments, systemContext } = + await import('@tanstack/cms-core/server') + void systemContext + return [ + await queryDocuments({ ...options, session }), + await queryDocuments(options), + ] +} diff --git a/scripts/codemods/__fixtures__/access-context/dynamic.output.ts b/scripts/codemods/__fixtures__/access-context/dynamic.output.ts new file mode 100644 index 00000000..c8f6eee6 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/dynamic.output.ts @@ -0,0 +1,20 @@ +import type { CmsSession } from '@tanstack/cms-core' +import type { QueryDocumentsOptions } from '@tanstack/cms-core/server' + +export async function listing(live: boolean) { + const { systemContext, queryDocumentsAs } = await import('@tanstack/cms-core/server') + return queryDocumentsAs(systemContext('access-context codemod: was an unscoped read', { mode: live ? 'live' : 'edit' }), { collection: 'post' }) +} + +export async function search( + session: CmsSession, + options: QueryDocumentsOptions, +) { + const { systemContext, accessContext, queryDocumentsAs } = + await import('@tanstack/cms-core/server') + void systemContext + return [ + await queryDocumentsAs(accessContext({ session, mode: 'edit' }), { ...options }), + await queryDocumentsAs(systemContext('access-context codemod: was an unscoped read'), options), + ] +} diff --git a/scripts/codemods/__fixtures__/access-context/dynamic.warnings.json b/scripts/codemods/__fixtures__/access-context/dynamic.warnings.json new file mode 100644 index 00000000..28d0b620 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/dynamic.warnings.json @@ -0,0 +1,6 @@ +[ + "dynamic.ts:6:10: queryDocuments: publishedOnly is not a literal: kept as a system read in that mode; use publicContext() if this serves visitors", + "dynamic.ts:17:28: options spread: check it for session / publishedOnly / publicRead", + "dynamic.ts:18:11: queryDocuments: options passed by reference: check them for session / publishedOnly / publicRead", + "dynamic.ts:18:11: queryDocuments: unscoped read kept as systemContext(…): use publicContext() or the request’s context if it serves visitors" +] diff --git a/scripts/codemods/__fixtures__/access-context/positional.input.ts b/scripts/codemods/__fixtures__/access-context/positional.input.ts new file mode 100644 index 00000000..11fbeec4 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/positional.input.ts @@ -0,0 +1,22 @@ +import { + findReferences, + groupDocuments, + listTranslations, + populateRelations, + queryDocumentSummaries, +} from '@tanstack/cms-core/server' +import type { CmsSession, Doc } from '@tanstack/cms-core' + +export async function editor(session: CmsSession, doc: Doc) { + return { + refs: await findReferences('author', 'ada', undefined, session), + translations: await listTranslations('post', 'one', session), + related: await populateRelations('post', doc, session), + published: await populateRelations('post', doc, { publishedOnly: true }), + tags: await groupDocuments('tags', { + collection: 'post', + publishedOnly: true, + }), + list: await queryDocumentSummaries({ collection: 'post', session }), + } +} diff --git a/scripts/codemods/__fixtures__/access-context/positional.output.ts b/scripts/codemods/__fixtures__/access-context/positional.output.ts new file mode 100644 index 00000000..1b450ff1 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/positional.output.ts @@ -0,0 +1,13 @@ +import { accessContext, publicContext, findReferencesAs, listTranslationsAs, populateRelationsAs, groupDocumentsAs, queryDocumentSummariesAs } from '@tanstack/cms-core/server' +import type { CmsSession, Doc } from '@tanstack/cms-core' + +export async function editor(session: CmsSession, doc: Doc) { + return { + refs: await findReferencesAs(accessContext({ session, mode: 'edit' }), 'author', 'ada', undefined), + translations: await listTranslationsAs(accessContext({ session, mode: 'edit' }), 'post', 'one'), + related: await populateRelationsAs(accessContext({ session, mode: 'edit' }), 'post', doc), + published: await populateRelationsAs(publicContext(), 'post', doc), + tags: await groupDocumentsAs(publicContext(), 'tags', { collection: 'post' }), + list: await queryDocumentSummariesAs(accessContext({ session, mode: 'edit' }), { collection: 'post' }), + } +} diff --git a/scripts/codemods/__fixtures__/access-context/store.test.input.ts b/scripts/codemods/__fixtures__/access-context/store.test.input.ts new file mode 100644 index 00000000..360ca9d4 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/store.test.input.ts @@ -0,0 +1,18 @@ +import { expect, it } from 'vitest' +import { + commitDocument, + listRevisions, + queryDocuments, + readDocument, +} from '../src/server' + +it('commits', async () => { + await commitDocument('post', 'one', { title: 'One' }) + expect(await readDocument('post', 'one')).toMatchObject({ title: 'One' }) + expect(await listRevisions('post', 'one')).toHaveLength(1) + const { items } = await queryDocuments({ collection: 'post' }) + expect(items).toHaveLength(1) + const storage = { listRevisions: async () => [] } + expect(await storage.listRevisions()).toEqual([]) + expect(typeof readDocument).toBe('function') +}) diff --git a/scripts/codemods/__fixtures__/access-context/store.test.output.ts b/scripts/codemods/__fixtures__/access-context/store.test.output.ts new file mode 100644 index 00000000..a59d1c4c --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/store.test.output.ts @@ -0,0 +1,13 @@ +import { expect, it } from 'vitest' +import { commitDocument, readDocument, systemContext, readDocumentAs, listRevisionsAs, queryDocumentsAs } from '../src/server' + +it('commits', async () => { + await commitDocument('post', 'one', { title: 'One' }) + expect(await readDocumentAs(systemContext('test'), 'post', 'one')).toMatchObject({ title: 'One' }) + expect(await listRevisionsAs(systemContext('test'), 'post', 'one')).toHaveLength(1) + const { items } = await queryDocumentsAs(systemContext('test'), { collection: 'post' }) + expect(items).toHaveLength(1) + const storage = { listRevisions: async () => [] } + expect(await storage.listRevisions()).toEqual([]) + expect(typeof readDocument).toBe('function') +}) diff --git a/scripts/codemods/__fixtures__/access-context/untouched.input.ts b/scripts/codemods/__fixtures__/access-context/untouched.input.ts new file mode 100644 index 00000000..c2ef6bb3 --- /dev/null +++ b/scripts/codemods/__fixtures__/access-context/untouched.input.ts @@ -0,0 +1,7 @@ +import { queryDocuments } from '@tanstack/cms-client' +import type { StorageOps } from '@tanstack/cms-core/storage' + +export async function run(storage: StorageOps) { + await storage.queryDocuments({ collections: ['post'] }) + return queryDocuments({ collection: 'post', publishedOnly: true }) +} diff --git a/scripts/codemods/access-context.ts b/scripts/codemods/access-context.ts new file mode 100644 index 00000000..fdbd626f --- /dev/null +++ b/scripts/codemods/access-context.ts @@ -0,0 +1,452 @@ +/** + * The deprecated read verbs → their `…As(ctx, …)` forms, with the context + * the old call meant spelled out: + * + * - `{ session: s }` → `accessContext({ session: s, mode: 'edit' })`, or + * `mode` left at `live` with `publishedOnly: true`, plus any `publicRead`; + * - `publishedOnly: true` without a session → `publicContext()`; + * - nothing → `systemContext(reason)`, the trusted read the call used to be. + * The reason is `'test'` in tests; elsewhere the call is reported so a + * read that serves visitors can switch to `publicContext()` or the + * request's context. + * + * `session` / `publishedOnly` / `publicRead` are dropped from the options, + * and positional sessions (`findReferences`, `listTranslations`, + * `populateRelations`) become the context. Calls are rewritten only for + * verbs imported from `@tanstack/cms-core/server` (or core's own `server` + * module, relatively), statically or as `await import(…)` destructuring. + * Options passed by reference, spreads and namespace imports are reported. + */ +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' + +interface Verb { + /** Index of the options object carrying `session` / `publishedOnly`. */ + options?: number + /** The options object is required, so an emptied one stays `{}`. */ + required?: boolean + /** Index of a positional session argument. */ + session?: number +} + +const VERBS: Record = { + queryDocuments: { options: 0 }, + groupDocuments: { options: 1, required: true }, + queryDocumentSummaries: { options: 0, required: true }, + listDocuments: { options: 1 }, + readDocument: {}, + readDocumentWithPending: {}, + readSingleton: { options: 1 }, + readDocumentBySlug: { options: 2 }, + findDocumentBySlug: { options: 1 }, + populateRelations: { options: 2, session: 2 }, + findReferences: { session: 3 }, + listTranslations: { session: 2 }, + listRevisions: {}, +} +const LEGACY_KEYS = new Set(['session', 'publishedOnly', 'publicRead']) +/** Removed with the ambient session; each use needs a hand rewrite. */ +const REMOVED = new Set(['runWithSession', 'currentSession']) +const BUILDERS = ['accessContext', 'publicContext', 'systemContext'] as const +type Builder = (typeof BUILDERS)[number] + +const SERVER_SPECIFIER = + /^(@tanstack\/cms-core\/server|\.{1,2}(\/[\w.-]+)*\/server(\/store(\/(read|query|revisions))?)?)$/ +const TEST_FILE = /(\.test\.|\.spec\.|(^|\/)(tests?|__tests__|bench)\/)/ + +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): node is CallExpression { + 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 warnRemoved(name: string, node: Node, ctx: CodemodContext): void { + if (!REMOVED.has(name)) return + ctx.warn( + `${name} is removed: pass the session, or an access context, to each call by hand`, + node, + ) +} + +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) + } + warnRemoved(spec.getName(), spec, ctx) + } + const list = named[0]!.getParentOrThrow() + out.push({ list, 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 + for (const e of pattern.getElements()) { + warnRemoved( + (e.getPropertyNameNode() ?? e.getNameNode()).getText(), + e, + ctx, + ) + } + 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 localVerbs(bindings: ReadonlyArray): Set { + const out = new Set() + for (const b of bindings) { + for (const name of b.names) if (VERBS[name]) out.add(name) + } + return out +} + +function propertyName(prop: Node): string | undefined { + if ( + Node.isPropertyAssignment(prop) || + Node.isShorthandPropertyAssignment(prop) + ) { + return prop.getName() + } + return undefined +} + +function propertyValue(prop: Node): string { + if (Node.isShorthandPropertyAssignment(prop)) return prop.getName() + if (Node.isPropertyAssignment(prop)) { + return prop.getInitializerOrThrow().getText() + } + return prop.getText() +} + +interface Legacy { + session?: string + /** `true`, `false`, or an expression. */ + publishedOnly?: string + publicRead?: string + /** The options object without the legacy keys, or `null` if emptied. */ + rest: string | null + changed: boolean +} + +function splitOptions( + obj: ObjectLiteralExpression, + ctx: CodemodContext, +): Legacy { + const legacy: Legacy = { rest: null, changed: false } + const kept: Array = [] + for (const prop of obj.getProperties()) { + const name = propertyName(prop) + if (name && LEGACY_KEYS.has(name)) { + legacy[name as 'session' | 'publishedOnly' | 'publicRead'] = + propertyValue(prop) + legacy.changed = true + continue + } + if (Node.isSpreadAssignment(prop)) { + ctx.warn( + 'options spread: check it for session / publishedOnly / publicRead', + prop, + ) + } + kept.push(prop.getText()) + } + legacy.rest = legacy.changed + ? kept.length + ? `{ ${kept.join(', ')} }` + : null + : obj.getText() + return legacy +} + +function looksLikeSession(expr: Expression): boolean { + return ( + /session/i.test(expr.getText()) && !Node.isObjectLiteralExpression(expr) + ) +} + +function modeFor(publishedOnly: string | undefined): string | undefined { + if (publishedOnly === undefined || publishedOnly === 'false') return `'edit'` + if (publishedOnly === 'true') return undefined + return `${publishedOnly} ? 'live' : 'edit'` +} + +function contextFor( + legacy: Pick, + reason: string, + used: Set, + warn: (message: string) => void, +): string { + if (legacy.session !== undefined) { + used.add('accessContext') + const parts = [ + legacy.session === 'session' ? 'session' : `session: ${legacy.session}`, + ] + const mode = modeFor(legacy.publishedOnly) + if (mode) parts.push(`mode: ${mode}`) + if (legacy.publicRead !== undefined && legacy.publicRead !== 'false') { + parts.push( + legacy.publicRead === 'true' + ? 'publicRead: true' + : `publicRead: ${legacy.publicRead}`, + ) + } + return `accessContext({ ${parts.join(', ')} })` + } + if (legacy.publishedOnly === 'true') { + used.add('publicContext') + return 'publicContext()' + } + used.add('systemContext') + if (legacy.publishedOnly !== undefined && legacy.publishedOnly !== 'false') { + warn( + 'publishedOnly is not a literal: kept as a system read in that mode; use publicContext() if this serves visitors', + ) + return `systemContext(${reason}, { mode: ${legacy.publishedOnly} ? 'live' : 'edit' })` + } + if (reason !== `'test'`) { + warn( + 'unscoped read kept as systemContext(…): use publicContext() or the request’s context if it serves visitors', + ) + } + return `systemContext(${reason})` +} + +function rewriteCall( + call: CallExpression, + name: string, + reason: string, + used: Set, + ctx: CodemodContext, +): string { + const verb = VERBS[name]! + const args = call.getArguments() as Array + const texts: Array = args.map((a) => a.getText()) + const warn = (message: string) => ctx.warn(`${name}: ${message}`, call) + let legacy: Pick = {} + + if (verb.session !== undefined && args[verb.session]) { + const arg = args[verb.session]! + if (verb.options !== verb.session || looksLikeSession(arg)) { + legacy = { session: arg.getText() } + texts[verb.session] = null + } + } + if ( + verb.options !== undefined && + args[verb.options] && + texts[verb.options] !== null + ) { + const arg = args[verb.options]! + if (Node.isObjectLiteralExpression(arg)) { + const split = splitOptions(arg, ctx) + legacy = split + texts[verb.options] = split.rest ?? (verb.required ? '{}' : null) + } else { + warn( + 'options passed by reference: check them for session / publishedOnly / publicRead', + ) + } + } + while (texts.length && texts[texts.length - 1] === null) texts.pop() + const kept = texts.map((t) => t ?? 'undefined') + const context = contextFor(legacy, reason, used, warn) + return `${name}As(${[context, ...kept].join(', ')})` +} + +/** Names already in scope where `binding`'s names are. */ +function namesInScope( + file: SourceFile, + bindings: ReadonlyArray, + binding: Binding, +): Set { + const out = new Set() + for (const decl of file.getImportDeclarations()) { + for (const n of decl.getNamedImports()) { + out.add(n.getAliasNode()?.getText() ?? n.getName()) + } + } + for (const b of bindings) { + if ( + !contains(b.scope, binding.scope) || + !Node.isObjectBindingPattern(b.list) + ) + continue + for (const e of b.list.getElements()) out.add(e.getName()) + } + return out +} + +/** `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 contains(outer: Node, inner: Node): boolean { + return outer.getPos() <= inner.getPos() && inner.getEnd() <= outer.getEnd() +} + +/** The innermost binding that brings `name` into scope at `node`. */ +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] +} + +function transform(file: SourceFile, ctx: CodemodContext): void { + const bindings = findBindings(file, ctx) + const verbs = localVerbs(bindings) + if (!verbs.size) return + const reason = TEST_FILE.test(file.getFilePath().replace(/\\/g, '/')) + ? `'test'` + : `'access-context codemod: was an unscoped read'` + const used = new Map>() + const rewritten = new Map>() + const callees = new Set() + const edits: Array = [] + + const calls = file + .getDescendantsOfKind(SyntaxKind.CallExpression) + .filter((c) => { + const callee = c.getExpression() + return ( + Node.isIdentifier(callee) && + verbs.has(callee.getText()) && + bindingAt(bindings, callee.getText(), c) !== undefined + ) + }) + const outermost = calls.filter( + (c) => !calls.some((o) => o !== c && contains(o, c)), + ) + for (const call of calls) { + if (!outermost.includes(call)) { + ctx.warn('nested legacy read: rewrite by hand', call) + } + } + for (const call of outermost) { + const callee = call.getExpression() as Identifier + const name = callee.getText() + const binding = bindingAt(bindings, name, call)! + const builders = used.get(binding) ?? new Set() + used.set(binding, builders) + edits.push({ + start: call.getStart(), + end: call.getEnd(), + text: rewriteCall(call, name, reason, builders, ctx), + }) + const names = rewritten.get(binding) ?? new Set() + names.add(name) + rewritten.set(binding, names) + callees.add(callee) + } + if (!edits.length) return + + const stillUsed = new Map>() + for (const id of file.getDescendantsOfKind(SyntaxKind.Identifier)) { + const text = id.getText() + if (!verbs.has(text) || callees.has(id) || isPropertyName(id)) continue + if ( + id.getFirstAncestorByKind(SyntaxKind.ImportDeclaration) || + id.getFirstAncestorByKind(SyntaxKind.ObjectBindingPattern) + ) + continue + const binding = bindingAt(bindings, text, id) + if (!binding) continue + const names = stillUsed.get(binding) ?? new Set() + names.add(text) + stillUsed.set(binding, names) + } + for (const b of bindings) { + const done = rewritten.get(b) + if (!done) continue + const existing = namesInScope(file, bindings, b) + const keep = stillUsed.get(b) ?? new Set() + const names = b.names.filter((n) => !done.has(n) || keep.has(n)) + for (const builder of BUILDERS) { + if (used.get(b)?.has(builder) && !existing.has(builder)) + names.push(builder) + } + for (const n of done) { + if (!existing.has(`${n}As`)) names.push(`${n}As`) + } + edits.push({ + start: b.list.getStart(), + end: b.list.getEnd(), + text: `{ ${[...new Set(names)].join(', ')} }`, + }) + } + applyEdits(file, edits) +} + +export const accessContextCodemod: Codemod = { + name: 'access-context', + description: + 'Deprecated read verbs → `…As(ctx, …)`, with session / publishedOnly / publicRead turned into the access context.', + mightApply: (text) => + /\bserver\b/.test(text) && + (Object.keys(VERBS).some((verb) => text.includes(`${verb}(`)) || + [...REMOVED].some((name) => text.includes(name))), + transform, +} diff --git a/scripts/codemods/index.ts b/scripts/codemods/index.ts index 47838b02..b96a24ea 100644 --- a/scripts/codemods/index.ts +++ b/scripts/codemods/index.ts @@ -1,3 +1,4 @@ +import { accessContextCodemod } from './access-context' import { collectionsArray } from './collections-array' import { createRoutes } from './create-routes' import { definitionSplit } from './definition-split' @@ -7,6 +8,7 @@ import type { Codemod } from './lib/harness' /** Every codemod `pnpm codemod ` can run, keyed by name. */ export const CODEMODS: Record = { [collectionsArray.name]: collectionsArray, + [accessContextCodemod.name]: accessContextCodemod, [createRoutes.name]: createRoutes, [definitionSplit.name]: definitionSplit, [explicitRoles.name]: explicitRoles, diff --git a/scripts/dialect-inventory.baseline.json b/scripts/dialect-inventory.baseline.json index c8b65a9d..0acb563b 100644 --- a/scripts/dialect-inventory.baseline.json +++ b/scripts/dialect-inventory.baseline.json @@ -2,36 +2,36 @@ "$comment": "Dialect-inventory baseline. A marker with nonTest 0 is retired and must not come back in non-test code; regenerate with `pnpm dialects:update` when a PR retires one.", "markers": { "publishedOnly": { - "nonTest": 68, - "test": 36 + "nonTest": 21, + "test": 9 }, "publicRead": { - "nonTest": 31, - "test": 8 + "nonTest": 26, + "test": 7 }, "queryDocuments": { - "nonTest": 173, - "test": 112 + "nonTest": 98, + "test": 20 }, "readDocument": { - "nonTest": 141, - "test": 244 + "nonTest": 24, + "test": 9 }, "readDocumentBySlug": { - "nonTest": 17, - "test": 33 + "nonTest": 13, + "test": 7 }, "findDocumentBySlug": { - "nonTest": 13, - "test": 0 + "nonTest": 9, + "test": 1 }, "getPublicDocument": { - "nonTest": 30, + "nonTest": 31, "test": 13 }, "listPublishedDocuments": { - "nonTest": 45, - "test": 16 + "nonTest": 46, + "test": 20 }, "collectionsRecord": { "nonTest": 0, @@ -54,28 +54,28 @@ "test": 76 }, "hookBeforeValidate": { - "nonTest": 11, - "test": 1 + "nonTest": 3, + "test": 0 }, "hookBeforeChange": { - "nonTest": 9, - "test": 17 + "nonTest": 3, + "test": 0 }, "hookBeforeDelete": { - "nonTest": 10, - "test": 4 + "nonTest": 3, + "test": 0 }, "hookAfterRead": { - "nonTest": 12, - "test": 10 + "nonTest": 3, + "test": 0 }, "currentSession": { - "nonTest": 18, + "nonTest": 0, "test": 0 }, "runWithSession": { - "nonTest": 7, - "test": 58 + "nonTest": 0, + "test": 0 }, "searchContexts": { "nonTest": 0, diff --git a/starters/admin-only/CMS-INTEGRATION.md b/starters/admin-only/CMS-INTEGRATION.md index ff38084e..913bf8ff 100644 --- a/starters/admin-only/CMS-INTEGRATION.md +++ b/starters/admin-only/CMS-INTEGRATION.md @@ -28,7 +28,7 @@ A schema meant to be run entirely from the canned admin. It defines two related ### Read paths and search -- `queryDocumentSummaries({ collection, status: 'published', search, columns })` is the admin list query: FTS search over the title and document JSON, a status filter, and selected columns. +- `queryDocumentSummariesAs(ctx, { collection, status: 'published', search, columns })` is the admin list query: FTS search over the title and document JSON, a status filter, and selected columns. ### Writes, review, and revisions diff --git a/starters/admin-only/tests/seam.test.ts b/starters/admin-only/tests/seam.test.ts index ec20e84b..afa8e538 100644 --- a/starters/admin-only/tests/seam.test.ts +++ b/starters/admin-only/tests/seam.test.ts @@ -5,7 +5,8 @@ import { afterEach, describe, expect, it } from 'vitest' import { closeStore, commitDocument, - queryDocumentSummaries, + systemContext, + queryDocumentSummariesAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { columnFields } from '@tanstack/cms-ui-react/primitives' @@ -77,7 +78,7 @@ describe('starter-admin-only — Mode #2 (Seam S1, S2, S3) acceptance suite', () { request: new Request('http://localhost') }, ) - const published = await queryDocumentSummaries({ + const published = await queryDocumentSummariesAs(systemContext('test'), { collection: 'assetRecord', status: 'published', search: 'SN-900', diff --git a/starters/contact-cards/CMS-INTEGRATION.md b/starters/contact-cards/CMS-INTEGRATION.md index 456e54cd..a1dbe3d4 100644 --- a/starters/contact-cards/CMS-INTEGRATION.md +++ b/starters/contact-cards/CMS-INTEGRATION.md @@ -28,12 +28,12 @@ A bespoke people-and-relationships app on the CMS database. It has custom card, ### Read paths and search -- `queryDocumentSummaries({ search, columns })` searches free text over the FTS index, which also matches `specialty` values. +- `queryDocumentSummariesAs(ctx, { search, columns })` searches free text over the FTS index, which also matches `specialty` values. - `askContacts` filters the results by `specialty` in memory and returns an answer string plus `person:` citations, or `"Not in the data."`. ### Writes, review, and revisions -- An `agent:card-assistant` actor's `POST /api/cms/v1/ops/create_document` is staged (`readDocument` returns `null`) until `approve()`. +- An `agent:card-assistant` actor's `POST /api/cms/v1/ops/create_document` is staged (`readDocumentAs` returns `null`) until `approve()`. ### Auth, roles, and access diff --git a/starters/contact-cards/src/cms.config.ts b/starters/contact-cards/src/cms.config.ts index 8f376161..4d680216 100644 --- a/starters/contact-cards/src/cms.config.ts +++ b/starters/contact-cards/src/cms.config.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import { defineCms, defineOp } from '@tanstack/cms-core' -import { queryDocumentSummaries } from '@tanstack/cms-core/server' +import { queryDocumentSummariesAs } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' import type { CreateRoutesSpec } from '@tanstack/cms-ui-react/virtual-routes' import { definition } from './cms.definition' @@ -87,8 +87,8 @@ export function registerContactCardsCms(options: { dataDir?: string } = {}) { question: z.string().min(1), specialty: z.string().optional(), }), - run: async (input) => { - const summary = await queryDocumentSummaries({ + run: async (input, ctx) => { + const summary = await queryDocumentSummariesAs(ctx.access, { collection: 'person', search: input.question, columns: ['name', 'whatTheyDo', 'specialty', 'organization'], diff --git a/starters/contact-cards/tests/seam.test.ts b/starters/contact-cards/tests/seam.test.ts index c2afec0f..1933cd6c 100644 --- a/starters/contact-cards/tests/seam.test.ts +++ b/starters/contact-cards/tests/seam.test.ts @@ -9,8 +9,9 @@ import { closeStore, commitDocument, listPending, - queryDocumentSummaries, - readDocument, + systemContext, + queryDocumentSummariesAs, + readDocumentAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { createCmsApiHandler } from '@tanstack/cms-api/http' @@ -71,7 +72,7 @@ describe('starter-contact-cards — Class #10 (Seam S1, S3, S5, S6) acceptance s } // Faceted search by what-people-do + specialty facet - const analytical = await queryDocumentSummaries({ + const analytical = await queryDocumentSummariesAs(systemContext('test'), { collection: 'person', search: 'Analytical', columns: ['name', 'whatTheyDo', 'specialty'], @@ -79,7 +80,7 @@ describe('starter-contact-cards — Class #10 (Seam S1, S3, S5, S6) acceptance s expect(analytical.total).toBe(1) expect(analytical.items[0]?.id).toBe('ada-lovelace') - const compilers = await queryDocumentSummaries({ + const compilers = await queryDocumentSummariesAs(systemContext('test'), { collection: 'person', search: 'compilers', columns: ['name', 'whatTheyDo', 'specialty'], @@ -131,14 +132,20 @@ describe('starter-contact-cards — Class #10 (Seam S1, S3, S5, S6) acceptance s }), ) expect(agentRes.status).toBe(200) - expect(await readDocument('relationship', 'rel-1')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'relationship', 'rel-1'), + ).toBeNull() const pending = await listPending() expect(pending).toHaveLength(1) expect(pending[0]?.docId).toBe('rel-1') await approve(pending[0]!.id) - const committedRel = await readDocument('relationship', 'rel-1') + const committedRel = await readDocumentAs( + systemContext('test'), + 'relationship', + 'rel-1', + ) expect(committedRel?.summary).toBe('Discussed compiler passes with Ada') // Confirm no PRM product-only collections exist in contact-cards diff --git a/starters/directory-listings/CMS-INTEGRATION.md b/starters/directory-listings/CMS-INTEGRATION.md index 680ba0d2..115d8ee3 100644 --- a/starters/directory-listings/CMS-INTEGRATION.md +++ b/starters/directory-listings/CMS-INTEGRATION.md @@ -22,7 +22,7 @@ A moderated directory. Strangers submit listings and claims through public ops, ### Read paths and search -- `searchDirectoryListings` runs `queryDocumentSummaries({ search, status: 'published', columns })`, then filters `category` and `city` in memory. Staged submissions stay invisible until approved. +- `searchDirectoryListings` runs `queryDocumentSummariesAs(ctx, { search, status: 'published', columns })`, then filters `category` and `city` in memory. Staged submissions stay invisible until approved. ### Writes, review, and revisions diff --git a/starters/directory-listings/src/cms.config.ts b/starters/directory-listings/src/cms.config.ts index 4a56d020..efbb424c 100644 --- a/starters/directory-listings/src/cms.config.ts +++ b/starters/directory-listings/src/cms.config.ts @@ -1,9 +1,11 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { - queryDocumentSummaries, - readDocument, + publicContext, + queryDocumentSummariesAs, + readDocumentAs, stageWrite, + systemContext, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -72,7 +74,13 @@ export function registerDirectoryListingsCms( claimantEmail: z.string().email(), }), run: async (input) => { - const existing = await readDocument('listing', input.listingId) + const existing = await readDocumentAs( + systemContext( + 'claimListing: stages an update over the stored listing', + ), + 'listing', + input.listingId, + ) if (!existing || !existing.published) { throw new CmsError('Listing not found.', 'NOT_FOUND') } @@ -104,7 +112,7 @@ export function registerDirectoryListingsCms( city: z.string().optional(), }), run: async (input) => { - const summary = await queryDocumentSummaries({ + const summary = await queryDocumentSummariesAs(publicContext(), { collection: 'listing', search: input.query, status: 'published', diff --git a/starters/directory-listings/tests/seam.test.ts b/starters/directory-listings/tests/seam.test.ts index 99876f0d..b1a1982e 100644 --- a/starters/directory-listings/tests/seam.test.ts +++ b/starters/directory-listings/tests/seam.test.ts @@ -6,7 +6,8 @@ import { approve, closeStore, listPending, - readDocument, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { createCmsApiHandler } from '@tanstack/cms-api/http' @@ -86,7 +87,11 @@ describe('starter-directory-listings — Class #13 (Seam S3, S4, S6) acceptance expect(await listPending()).toHaveLength(1) await approve(claim.pendingId) - const updated = await readDocument('listing', 'roaster-olympia') + const updated = await readDocumentAs( + systemContext('test'), + 'listing', + 'roaster-olympia', + ) expect(updated?.claimedByEmail).toBe('owner@cascadia-espresso.example.com') }) }) diff --git a/starters/documentation-kb/CMS-INTEGRATION.md b/starters/documentation-kb/CMS-INTEGRATION.md index a7caa99d..ead4a8dc 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'`, `queryDocuments` with `where`, `queryDocumentSummaries` 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'`, `queryDocumentsAs` with `where`, `queryDocumentSummariesAs` FTS search, and public `defineOp` ops. ## Files @@ -23,8 +23,8 @@ Two product versions of one small docs set. Version, section, and order are fiel ### Read paths and search -- `getDocsNavTree` runs `queryDocuments({ where: { version }, publishedOnly: true, limit: 200 })`, then groups by `section` and sorts by `order`. -- `searchVersionedDocs` runs `queryDocumentSummaries({ search, columns })`, which is the built-in SQLite FTS5 trigram index, and filters `version` in memory afterwards. +- `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. +- `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): `queryDocuments`, `queryDocumentSummaries`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `queryDocumentsAs`, `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 67266084..bedd724b 100644 --- a/starters/documentation-kb/src/cms.config.ts +++ b/starters/documentation-kb/src/cms.config.ts @@ -1,8 +1,9 @@ import { z } from 'zod' import { defineCms, defineOp } from '@tanstack/cms-core' import { - queryDocumentSummaries, - queryDocuments, + publicContext, + queryDocumentsAs, + queryDocumentSummariesAs, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -27,10 +28,9 @@ 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 queryDocuments({ + const res = await queryDocumentsAs(publicContext(), { collection: 'docPage', where: { version: input.version }, - publishedOnly: true, limit: 200, }) const sections = new Map< @@ -65,7 +65,7 @@ export function registerDocumentationKbCms(options: { dataDir?: string } = {}) { version: z.enum(['v1', 'v2']).optional(), }), run: async (input) => { - const summary = await queryDocumentSummaries({ + const summary = await queryDocumentSummariesAs(publicContext(), { collection: 'docPage', search: input.query, columns: ['title', 'version', 'section', 'deprecatedInV2'], diff --git a/starters/ecommerce-storefront/src/cms.config.ts b/starters/ecommerce-storefront/src/cms.config.ts index 3a5cba8a..365579a3 100644 --- a/starters/ecommerce-storefront/src/cms.config.ts +++ b/starters/ecommerce-storefront/src/cms.config.ts @@ -1,6 +1,11 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' -import { commitDocument, readDocument } from '@tanstack/cms-core/server' +import { + commitDocument, + publicContext, + readDocumentAs, + systemContext, +} from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -60,14 +65,22 @@ export function registerEcommerceStorefrontCms( quantity: z.number().int().positive(), }), run: async (input) => { - const variant = await readDocument('variant', input.variantId) + const variant = await readDocumentAs( + publicContext(), + 'variant', + input.variantId, + ) if (!variant || !variant.published) { throw new CmsError('Variant not found.', 'NOT_FOUND') } if (Number(variant.inventory ?? 0) < input.quantity) { throw new CmsError('Insufficient inventory.', 'BAD_REQUEST') } - const existing = await readDocument('cart', input.cartId) + const existing = await readDocumentAs( + systemContext('storefront: carts are server-owned records'), + 'cart', + input.cartId, + ) const currentItems = existing?.itemsJson ? (JSON.parse(String(existing.itemsJson)) as Array<{ variantId: string @@ -100,7 +113,11 @@ export function registerEcommerceStorefrontCms( paymentToken: z.string(), }), run: async (input) => { - const cart = await readDocument('cart', input.cartId) + const cart = await readDocumentAs( + systemContext('storefront: carts are server-owned records'), + 'cart', + input.cartId, + ) if (!cart) { throw new CmsError('Cart not found.', 'NOT_FOUND') } diff --git a/starters/ecommerce-storefront/tests/seam.test.ts b/starters/ecommerce-storefront/tests/seam.test.ts index 2a5225ab..de00322d 100644 --- a/starters/ecommerce-storefront/tests/seam.test.ts +++ b/starters/ecommerce-storefront/tests/seam.test.ts @@ -5,7 +5,8 @@ import { afterEach, describe, expect, it } from 'vitest' import { closeStore, commitDocument, - readDocument, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { createCmsApiHandler } from '@tanstack/cms-api/http' @@ -84,7 +85,9 @@ describe('starter-ecommerce-storefront — Class #8 (Seam S1, S4, S5, S6) accept { request: new Request('http://localhost') }, ), ).rejects.toThrow(/Payment declined/) - expect(await readDocument('order', '1001')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'order', '1001'), + ).toBeNull() // Valid checkout charges payment adapter and commits order const orderRes = (await invokeAnyOp( diff --git a/starters/editorial-publication/CMS-INTEGRATION.md b/starters/editorial-publication/CMS-INTEGRATION.md index 1f7579ba..938cb430 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 `queryDocuments` 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 `queryDocumentsAs` 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 with `readDocument`. For paid issues it looks up the reader with `queryDocuments({ collection: 'memberSubscription', where: { email }, limit: 1 })`, and returns `body: null, paywalled: true` unless that reader's tier is `paid`. -- `sendNewsletterIssue` loads subscribers with `queryDocuments({ publishedOnly: true, limit: 200 })`. +- `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 })`. ### Writes, review, and revisions @@ -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): `queryDocuments`, `commitDocument`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `queryDocumentsAs`, `commitDocument`. diff --git a/starters/editorial-publication/src/cms.config.ts b/starters/editorial-publication/src/cms.config.ts index 14bc5081..e514f725 100644 --- a/starters/editorial-publication/src/cms.config.ts +++ b/starters/editorial-publication/src/cms.config.ts @@ -2,8 +2,10 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, - queryDocuments, - readDocument, + publicContext, + queryDocumentsAs, + readDocumentAs, + systemContext, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -56,7 +58,11 @@ export function registerEditorialPublicationCms( memberEmail: z.string().email().optional(), }), run: async (input) => { - const doc = await readDocument('issue', input.issueId) + const doc = await readDocumentAs( + publicContext(), + 'issue', + input.issueId, + ) if (!doc || !doc.published) { throw new CmsError('Issue not found.', 'NOT_FOUND') } @@ -69,11 +75,14 @@ export function registerEditorialPublicationCms( body: null, } } - const subs = await queryDocuments({ - collection: 'memberSubscription', - where: { email: input.memberEmail }, - limit: 1, - }) + const subs = await queryDocumentsAs( + systemContext('paywall: subscriptions are server-owned records'), + { + collection: 'memberSubscription', + where: { email: input.memberEmail }, + limit: 1, + }, + ) const memberTier = subs.items[0]?.doc.tier if (memberTier !== 'paid') { return { @@ -99,19 +108,21 @@ export function registerEditorialPublicationCms( description: 'Send a published editorial issue by email to all active paid/free subscribers.', input: z.object({ issueId: z.string() }), - run: async (input) => { - const doc = await readDocument('issue', input.issueId) + run: async (input, ctx) => { + const doc = await readDocumentAs(ctx.access, 'issue', input.issueId) if (!doc || !doc.published) { throw new CmsError( 'Only published issues can be sent as newsletters.', 'BAD_REQUEST', ) } - const subs = await queryDocuments({ - collection: 'memberSubscription', - publishedOnly: true, - limit: 200, - }) + const subs = await queryDocumentsAs( + systemContext('newsletter: active subscriptions', { mode: 'live' }), + { + collection: 'memberSubscription', + limit: 200, + }, + ) const recipients = subs.items .filter((s) => doc.accessTier === 'free' || s.doc.tier === 'paid') .map((s) => String(s.doc.email)) diff --git a/starters/headless-api/CMS-INTEGRATION.md b/starters/headless-api/CMS-INTEGRATION.md index 914f5289..8f0d23e0 100644 --- a/starters/headless-api/CMS-INTEGRATION.md +++ b/starters/headless-api/CMS-INTEGRATION.md @@ -24,7 +24,7 @@ A backend-only package. It registers one schema and serves it through `createCms ### Writes, review, and revisions -- Writes made through the agent tool `create_document`, whether from the typed client or from MCP, are always staged with `stageWrite`. The test asserts that both writes sit in `listPending()`, that `readDocument()` returns `null` for them, and that they become visible only after `approve()`. +- Writes made through the agent tool `create_document`, whether from the typed client or from MCP, are always staged with `stageWrite`. The test asserts that both writes sit in `listPending()`, that `readDocumentAs(ctx, …)` returns `null` for them, and that they become visible only after `approve()`. ### Auth, roles, and access diff --git a/starters/headless-api/tests/contract.test.ts b/starters/headless-api/tests/contract.test.ts index 62500240..3ca4b8d2 100644 --- a/starters/headless-api/tests/contract.test.ts +++ b/starters/headless-api/tests/contract.test.ts @@ -8,7 +8,8 @@ import { approve, closeStore, listPending, - readDocument, + systemContext, + readDocumentAs, } from '@tanstack/cms-core/server' import { createHeadlessHandler } from '../src/server' @@ -99,8 +100,12 @@ describe('starter-headless-api — Seam S3 & S5 acceptance tests', () => { // Both writes are staged in Governance and invisible before approval const pending = await listPending() expect(pending).toHaveLength(2) - expect(await readDocument('contentItem', 'item-client')).toBeNull() - expect(await readDocument('contentItem', 'item-mcp')).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'contentItem', 'item-client'), + ).toBeNull() + expect( + await readDocumentAs(systemContext('test'), 'contentItem', 'item-mcp'), + ).toBeNull() // Viewer key is denied write access across HTTP and MCP const viewerRes = await handler( @@ -123,7 +128,11 @@ describe('starter-headless-api — Seam S3 & S5 acceptance tests', () => { for (const p of pending) { await approve(p.id) } - const committed = await readDocument('contentItem', 'item-client') + const committed = await readDocumentAs( + systemContext('test'), + 'contentItem', + 'item-client', + ) expect(committed?.title).toBe('Omnichannel Item') }) }) diff --git a/starters/membership-course/CMS-INTEGRATION.md b/starters/membership-course/CMS-INTEGRATION.md index 10b1b7c5..1327ceff 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 `readDocument`, `queryDocuments`, 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 `readDocumentAs`, `queryDocumentsAs`, 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 and lesson with `readDocument`, then lists all published lessons with `queryDocuments({ publishedOnly: true })` to check prerequisites and completion. +- 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. ### Writes, review, and revisions @@ -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): `readDocument`, `queryDocuments`, `commitDocument`. +- [`docs/api/cms-core-server.md`](../../docs/api/cms-core-server.md): `readDocumentAs`, `queryDocumentsAs`, `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 7fd5751b..a8561542 100644 --- a/starters/membership-course/src/cms.config.ts +++ b/starters/membership-course/src/cms.config.ts @@ -2,8 +2,10 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, - queryDocuments, - readDocument, + publicContext, + queryDocumentsAs, + readDocumentAs, + systemContext, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -41,11 +43,21 @@ export function registerMembershipCourseCms( submittedQuizAnswer: z.string().optional(), }), run: async (input) => { - const enrolment = await readDocument('enrolment', input.enrolmentId) + const enrolment = await readDocumentAs( + systemContext( + 'course progress: enrolments are server-owned records', + ), + 'enrolment', + input.enrolmentId, + ) if (!enrolment) { throw new CmsError('Enrolment not found.', 'NOT_FOUND') } - const lesson = await readDocument('lesson', input.lessonId) + const lesson = await readDocumentAs( + publicContext(), + 'lesson', + input.lessonId, + ) if (!lesson || !lesson.published) { throw new CmsError('Lesson not found.', 'NOT_FOUND') } @@ -59,9 +71,8 @@ export function registerMembershipCourseCms( ) } - const allLessons = await queryDocuments({ + const allLessons = await queryDocumentsAs(publicContext(), { collection: 'lesson', - publishedOnly: true, limit: 100, }) const completed = new Set( diff --git a/starters/multi-tenant-fleet/CMS-INTEGRATION.md b/starters/multi-tenant-fleet/CMS-INTEGRATION.md index 3b6e959e..cc90c63d 100644 --- a/starters/multi-tenant-fleet/CMS-INTEGRATION.md +++ b/starters/multi-tenant-fleet/CMS-INTEGRATION.md @@ -24,9 +24,9 @@ Many tenant sites run on one instance. Every document carries a `tenantId` field ### Read paths and search -- `listTenantPages` and `listTenantAssets` use `queryDocuments({ where: { tenantId } })`. -- The search path runs `queryDocumentSummaries({ search })`, then drops other tenants' rows in memory. -- `readTenantPage` uses `readDocument` and returns `NOT_FOUND` when the `tenantId` doesn't match, even if the id was guessed correctly. +- `listTenantPages` and `listTenantAssets` use `queryDocumentsAs(ctx, { where: { tenantId } })`. +- 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. ### Auth, roles, and access diff --git a/starters/multi-tenant-fleet/src/cms.config.ts b/starters/multi-tenant-fleet/src/cms.config.ts index fc1f6936..adb8b651 100644 --- a/starters/multi-tenant-fleet/src/cms.config.ts +++ b/starters/multi-tenant-fleet/src/cms.config.ts @@ -2,9 +2,9 @@ import { z } from 'zod' import { CmsError, defineCms, defineOp } from '@tanstack/cms-core' import { commitDocument, - queryDocumentSummaries, - queryDocuments, - readDocument, + queryDocumentsAs, + queryDocumentSummariesAs, + readDocumentAs, } from '@tanstack/cms-core/server' import type { CmsConfig } from '@tanstack/cms-core' import { definition } from './cms.definition' @@ -147,7 +147,7 @@ export function registerMultiTenantFleetCms( const actor = resolveTenantActor(ctx.request) const tenantId = effectiveTenantId(actor, input.targetTenantId) if (input.search) { - const searched = await queryDocumentSummaries({ + const searched = await queryDocumentSummariesAs(ctx.access, { collection: 'tenantPage', search: input.search, columns: ['tenantId', 'title', 'slug'], @@ -158,7 +158,7 @@ export function registerMultiTenantFleetCms( ), } } - const res = await queryDocuments({ + const res = await queryDocumentsAs(ctx.access, { collection: 'tenantPage', where: { tenantId }, limit: 100, @@ -179,7 +179,11 @@ export function registerMultiTenantFleetCms( run: async (input, ctx) => { const actor = resolveTenantActor(ctx.request) const tenantId = effectiveTenantId(actor, input.targetTenantId) - const doc = await readDocument('tenantPage', input.pageId) + const doc = await readDocumentAs( + ctx.access, + 'tenantPage', + input.pageId, + ) if (!doc || doc.tenantId !== tenantId) { throw new CmsError('Page not found in tenant.', 'NOT_FOUND') } @@ -196,7 +200,7 @@ export function registerMultiTenantFleetCms( run: async (input, ctx) => { const actor = resolveTenantActor(ctx.request) const tenantId = effectiveTenantId(actor, input.targetTenantId) - const res = await queryDocuments({ + const res = await queryDocumentsAs(ctx.access, { collection: 'tenantAsset', where: { tenantId }, limit: 100, diff --git a/starters/runtime-tables/CMS-INTEGRATION.md b/starters/runtime-tables/CMS-INTEGRATION.md index eef923d2..9cae0b1a 100644 --- a/starters/runtime-tables/CMS-INTEGRATION.md +++ b/starters/runtime-tables/CMS-INTEGRATION.md @@ -23,8 +23,8 @@ Tables defined at runtime. A proposed table is stored as a `schemaDefinition` do ### Read paths and search -- `syncRuntimeTablesFromStore()` reads approved definitions with `queryDocuments({ publishedOnly: true })`. -- Rows in a runtime table are searchable right away through `queryDocumentSummaries({ search })`. +- `syncRuntimeTablesFromStore()` reads approved definitions with `queryDocumentsAs(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 0d325ebf..db02dae1 100644 --- a/starters/runtime-tables/src/cms.config.ts +++ b/starters/runtime-tables/src/cms.config.ts @@ -1,5 +1,10 @@ import { defineCms, defineCollection } from '@tanstack/cms-core' -import { approve, queryDocuments, stageWrite } from '@tanstack/cms-core/server' +import { + approve, + stageWrite, + systemContext, + queryDocumentsAs, +} from '@tanstack/cms-core/server' import type { CmsConfig, Collection, Field } from '@tanstack/cms-core' export interface RuntimeFieldSpec { @@ -117,10 +122,14 @@ export async function approveRuntimeTableChange( return syncRuntimeTablesFromStore() } +const APPROVED_DEFINITIONS = systemContext( + 'runtime tables: the approved schema definitions', + { mode: 'live' }, +) + export async function syncRuntimeTablesFromStore() { - const { items } = await queryDocuments({ + const { items } = await queryDocumentsAs(APPROVED_DEFINITIONS, { collection: 'schemaDefinition', - publishedOnly: true, limit: 100, }) // Keyed by table name so a later schema document replaces an earlier one. diff --git a/starters/runtime-tables/tests/seam.test.ts b/starters/runtime-tables/tests/seam.test.ts index 944749ba..18ad3cc1 100644 --- a/starters/runtime-tables/tests/seam.test.ts +++ b/starters/runtime-tables/tests/seam.test.ts @@ -9,7 +9,8 @@ import { closeStore, commitDocument, listPending, - queryDocumentSummaries, + systemContext, + queryDocumentSummariesAs, } from '@tanstack/cms-core/server' import { invokeAnyOp } from '@tanstack/cms-api' import { createCmsApiHandler } from '@tanstack/cms-api/http' @@ -115,7 +116,7 @@ describe('starter-runtime-tables — Class #12 (Seam S1, S2, S3, S6) acceptance ) expect(apiRes.status).toBe(200) - const search = await queryDocumentSummaries({ + const search = await queryDocumentSummariesAs(systemContext('test'), { collection: 'dealTrack', search: 'NebulaWidgetsCorp', columns: ['company', 'stage', 'dealSize'],