@sanity-labs/client-fake-for-test 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -1
- package/dist/index.cjs +38 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +78 -0
- package/dist/index.d.ts +78 -0
- package/dist/index.js +38 -15
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/errors.ts","../src/access-control.ts","../src/store.ts","../src/patch.ts","../src/actions.ts","../src/perspective.ts","../src/transaction.ts","../src/unsupported.ts","../src/client.ts"],"sourcesContent":["/**\n * Error helpers shared across the fake.\n *\n * Every error the fake throws is prefixed with {@link ERR_PREFIX} so it's\n * unmistakably attributable to *this fake* — not to `@sanity/client`,\n * groq-js, or the code under test — and carries enough context to fix\n * the problem without reading the fake's source. Short, bare messages\n * (\"not found\", \"invalid id\") are a poor developer experience in a test\n * double: prefer stating what happened, the offending value, and what to\n * do about it.\n */\nexport const ERR_PREFIX = \"[client-fake-for-test]\";\n\n/** Build a prefixed Error. Pass a fully-formed, dev-facing message. */\nexport function fakeError(message: string): Error {\n return new Error(`${ERR_PREFIX} ${message}`);\n}\n","/**\n * Optional access-control simulation for the in-memory test client.\n *\n * When configured, the TestClient does two things a real `@sanity/client`\n * does over the wire but the bare in-memory client otherwise skips:\n *\n * 1. **Exposes `client.request({ url })`** that serves:\n * - `GET /users/me` → the configured `CurrentUser`\n * - `GET <aclPath>` → the configured `Grant[]`\n * This is what the engine reads from to resolve `WorkflowAccess`\n * when no override is passed.\n *\n * 2. **Gates writes through the configured grants.** Every mutation\n * (`create`, `createOrReplace`, `createIfNotExists`, `delete`,\n * `patch`, and per-op inside `transaction`) checks whether the\n * configured grants allow the relevant `DocumentValuePermission`\n * on the target document. On denial the client throws a\n * `WriteAccessDeniedError` shaped like Sanity's 403 — the same\n * failure mode a production write would hit, surfaced in tests.\n *\n * When `accessControl` is omitted, the client behaves as before:\n * `request` is undefined, writes are unconditional, and the engine\n * falls through to whatever override the caller (typically the\n * bench's `ALL_ACCESS`) provides.\n *\n * The grant evaluation runs the GROQ filter on a singleton dataset\n * containing the doc being checked — same shape as the engine's\n * `permissions.matchesFilter`, lifted from canvas.\n */\n\nimport type { SanityDocumentLike } from \"@sanity/types\";\nimport { evaluate, parse } from \"groq-js\";\nimport { fakeError } from \"./errors.ts\";\n\nexport type DocumentValuePermission = \"create\" | \"read\" | \"update\";\n\nexport interface CurrentUser {\n id: string;\n name?: string;\n email?: string;\n /** @deprecated singular `role` on legacy responses */\n role?: string;\n roles?: { name: string; title?: string; description?: string }[];\n}\n\nexport interface Grant {\n filter: string;\n permissions: DocumentValuePermission[];\n}\n\nexport interface TestClientAccessControl {\n /** What `client.request({ url: \"/users/me\" })` returns. */\n currentUser: CurrentUser;\n /** What `client.request({ url: aclPath })` returns. */\n grants: Grant[];\n /**\n * URL path the engine's access resolver hits to fetch grants.\n * Defaults to `/projects/<projectId>/datasets/<dataset>/acl`.\n */\n aclPath?: string;\n}\n\n/**\n * Sanity-style 403 raised when a configured-grants check rejects a\n * write. The thrown object carries the doc id, the attempted\n * permission, and the count of matching grants (for parity with the\n * engine's `permission-denied` disabled-reason).\n */\nexport class WriteAccessDeniedError extends Error {\n readonly documentId: string;\n readonly permission: DocumentValuePermission;\n readonly matchingGrants: number;\n\n constructor(args: {\n documentId: string;\n permission: DocumentValuePermission;\n matchingGrants: number;\n }) {\n super(\n `Sanity (test): permission denied — actor lacks \"${args.permission}\" on document \"${args.documentId}\" ` +\n `(${args.matchingGrants} grant${args.matchingGrants === 1 ? \"\" : \"s\"} matched the document but ` +\n `none included \"${args.permission}\").`,\n );\n this.name = \"WriteAccessDeniedError\";\n this.documentId = args.documentId;\n this.permission = args.permission;\n this.matchingGrants = args.matchingGrants;\n }\n}\n\n/**\n * Predicate variant of `evaluateWriteAccess` — same logic but only\n * returns the boolean. Used by read-gating paths\n * (`fetch`/`getDocument`/`getDocuments`) where the documented Sanity\n * behavior is \"invisible doc → 404\", not \"throw 403\". So callers\n * can filter the dataset before GROQ runs and return `null` from\n * single-doc reads, instead of leaking a denial through the read\n * surface.\n */\nexport async function canAccess(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n grants: Grant[];\n permission: DocumentValuePermission;\n userId: string;\n}): Promise<boolean> {\n const result = await evaluateWriteAccess(args);\n return result.allowed;\n}\n\n// Parsed-filter cache. The GROQ AST is cheap to reuse; only the\n// per-document evaluation needs to re-run.\nconst parsedFilters = new Map<string, ReturnType<typeof parse>>();\n\nasync function matchesFilter(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n filter: string;\n userId: string;\n}): Promise<boolean> {\n const { document, filter, userId } = args;\n if (!parsedFilters.has(filter)) {\n parsedFilters.set(filter, parse(`*[${filter}]`));\n }\n const ast = parsedFilters.get(filter)!;\n const result = await evaluate(ast, {\n dataset: [document as Record<string, unknown>],\n identity: userId,\n });\n const data = await result.get();\n return Array.isArray(data) && data.length === 1;\n}\n\n/**\n * Resolve whether `grants` allow `permission` on `document` for the\n * given user. Same logic the engine uses in `permissions.grantsPermissionOn`\n * (most-permissive wins; multiple grants compose).\n *\n * Returns `{ allowed: boolean, matchingGrants: number }` so callers\n * can build the structured error without re-counting.\n */\nexport async function evaluateWriteAccess(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n grants: Grant[];\n permission: DocumentValuePermission;\n userId: string;\n}): Promise<{ allowed: boolean; matchingGrants: number }> {\n const { document, grants, permission, userId } = args;\n let matching = 0;\n for (const grant of grants) {\n if (\n await matchesFilter({\n document,\n filter: grant.filter,\n userId,\n })\n ) {\n matching++;\n if (grant.permissions.includes(permission)) {\n return { allowed: true, matchingGrants: matching };\n }\n }\n }\n return { allowed: false, matchingGrants: matching };\n}\n\n/**\n * Throw a `WriteAccessDeniedError` if `grants` don't permit the\n * supplied `permission` on `document`. No-op when allowed. Use this\n * from every mutation entrypoint that wants to simulate Sanity's\n * write boundary.\n */\nexport async function enforceWriteAccess(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n grants: Grant[];\n permission: DocumentValuePermission;\n userId: string;\n}): Promise<void> {\n const { document, grants, permission, userId } = args;\n const { allowed, matchingGrants } = await evaluateWriteAccess({\n document,\n grants,\n permission,\n userId,\n });\n if (allowed) return;\n if (typeof document._id !== \"string\") {\n throw new WriteAccessDeniedError({\n documentId: \"(unknown)\",\n permission,\n matchingGrants,\n });\n }\n throw new WriteAccessDeniedError({\n documentId: document._id,\n permission,\n matchingGrants,\n });\n}\n\n/**\n * Default ACL path the engine pulls grants from. Mirrors Sanity's\n * project/dataset ACL endpoint. Callers can override via\n * `accessControl.aclPath`.\n */\nexport function defaultAclPath(projectId: string, dataset: string): string {\n return `/projects/${projectId}/datasets/${dataset}/acl`;\n}\n\n/**\n * Internal helper: turn the `accessControl` config into the bound\n * `request` function the client exposes, plus a helper to gate writes.\n * Returns `undefined` when no config — leaves `request` off so the\n * engine's \"no token available\" path triggers (which is the cue for\n * the bench to supply an `access` override).\n */\nexport function makeRequestImpl(\n accessControl: TestClientAccessControl,\n projectId: string,\n dataset: string,\n): <T>(opts: { url?: string; uri?: string; signal?: AbortSignal; tag?: string }) => Promise<T> {\n const aclPath = accessControl.aclPath ?? defaultAclPath(projectId, dataset);\n return async <T>(opts: {\n url?: string;\n uri?: string;\n signal?: AbortSignal;\n tag?: string;\n }): Promise<T> => {\n // `@sanity/client` distinguishes `uri` (project-scoped, e.g.\n // `/users/me`) from `url` (raw). Studio uses `uri` for global\n // endpoints. Treat both identically for the mock.\n const path = opts.uri ?? opts.url;\n if (path === \"/users/me\") {\n return accessControl.currentUser as unknown as T;\n }\n if (path === aclPath) {\n return accessControl.grants as unknown as T;\n }\n throw fakeError(\n `request(): no handler for path \"${path}\". With accessControl configured, the fake only serves ` +\n `\"/users/me\" and \"${aclPath}\". For any other endpoint, register a stub ` +\n `(client.stub(\"request\", fn)) or intercept the HTTP call with a tool like MSW.`,\n );\n };\n}\n","import type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport { fakeError } from \"./errors.ts\";\n\n/**\n * In-memory document store backing a TestClient. Closure-scoped — created\n * fresh per test, no global state.\n *\n * The shape mirrors what `groq-js` evaluates against: an array of\n * documents. Internally we keep a Map by `_id` for O(1) lookup, and\n * project to an array on each query.\n */\nexport interface TestStore {\n /** Replace the entire dataset with the given documents. Existing docs are dropped. */\n seed: (documents: SanityDocumentLike[]) => void;\n /** Add documents without dropping existing ones. Conflicts (same _id) overwrite. */\n add: (documents: SanityDocumentLike[]) => void;\n /** Remove all documents. */\n reset: () => void;\n /** All documents as an array, in insertion order. */\n all: () => SanityDocument[];\n /** Get one document by _id, or undefined. */\n get: (id: string) => SanityDocument | undefined;\n /** Insert a fully-formed document by _id. Replaces if it already exists. */\n put: (doc: SanityDocument) => void;\n /** Remove a document by _id. Returns the removed doc or undefined. */\n remove: (id: string) => SanityDocument | undefined;\n /** Snapshot of all docs, useful for assertions. */\n snapshot: () => readonly SanityDocument[];\n}\n\n/**\n * Create a fresh, isolated store. The returned object closes over a private\n * Map; two stores created from two calls do not see each other.\n */\nexport function createTestStore(initial?: SanityDocumentLike[]): TestStore {\n const docs = new Map<string, SanityDocument>();\n\n const promote = (doc: SanityDocumentLike): SanityDocument => {\n if (typeof doc._id !== \"string\" || doc._id.length === 0) {\n throw fakeError(\n `Cannot seed/store a document without a non-empty string \\`_id\\` (got ${JSON.stringify(doc._id)}). ` +\n `This fake never auto-generates ids — give every document an explicit _id. Document: ${JSON.stringify(doc)}`,\n );\n }\n if (typeof doc._type !== \"string\" || doc._type.length === 0) {\n throw fakeError(\n `Document \"${doc._id}\" is missing a non-empty string \\`_type\\` (got ${JSON.stringify(doc._type)}). ` +\n `Every Sanity document needs a _type.`,\n );\n }\n const now = new Date().toISOString();\n return {\n ...doc,\n _id: doc._id,\n _type: doc._type,\n _rev: doc._rev ?? cryptoRandomKey(),\n _createdAt: doc._createdAt ?? now,\n _updatedAt: doc._updatedAt ?? now,\n } as SanityDocument;\n };\n\n const seed = (documents: SanityDocumentLike[]) => {\n docs.clear();\n for (const d of documents) {\n const promoted = promote(d);\n docs.set(promoted._id, promoted);\n }\n };\n\n if (initial) seed(initial);\n\n return {\n seed,\n add: (documents) => {\n for (const d of documents) {\n const promoted = promote(d);\n docs.set(promoted._id, promoted);\n }\n },\n reset: () => docs.clear(),\n all: () => [...docs.values()],\n get: (id) => docs.get(id),\n put: (doc) => {\n docs.set(doc._id, doc);\n },\n remove: (id) => {\n const doc = docs.get(id);\n if (doc) docs.delete(id);\n return doc;\n },\n snapshot: () => [...docs.values()],\n };\n}\n\n/**\n * Generate a stable-ish random key without pulling in a dependency.\n * Use cases: synthesising `_rev` for newly-stored documents.\n */\nexport function cryptoRandomKey(length = 12): string {\n const bytes = new Uint8Array(length);\n // globalThis.crypto is available in Node 22+ and all modern browsers.\n globalThis.crypto.getRandomValues(bytes);\n return [...bytes]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")\n .slice(0, length);\n}\n","import type { SanityDocument } from \"@sanity/types\";\nimport { fakeError } from \"./errors.ts\";\n\n/** Human-readable type of a value, for \"expected an array but got …\" errors. */\nfunction describeType(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return `a ${typeof value}`;\n}\n\n/**\n * Patch operations the test client supports.\n *\n * Subset of `@sanity/client`'s PatchOperations. Each entry is one\n * mutation step applied in order at commit time.\n */\nexport type PatchOp =\n | { kind: \"set\"; props: Record<string, unknown> }\n | { kind: \"setIfMissing\"; props: Record<string, unknown> }\n | { kind: \"unset\"; paths: string[] }\n | { kind: \"inc\"; props: Record<string, number> }\n | { kind: \"dec\"; props: Record<string, number> }\n | {\n kind: \"insert\";\n position: \"before\" | \"after\" | \"replace\";\n anchor: string;\n items: unknown[];\n };\n\nexport interface PatchHandle {\n set: (props: Record<string, unknown>) => PatchHandle;\n setIfMissing: (props: Record<string, unknown>) => PatchHandle;\n unset: (paths: string[]) => PatchHandle;\n inc: (props: Record<string, number>) => PatchHandle;\n dec: (props: Record<string, number>) => PatchHandle;\n insert: (\n position: \"before\" | \"after\" | \"replace\",\n anchor: string,\n items: unknown[],\n ) => PatchHandle;\n ifRevisionId: (rev: string) => PatchHandle;\n commit: () => Promise<SanityDocument>;\n /** Test-only introspection — not on real Patch */\n toJSON: () => { id: string; ops: PatchOp[]; ifRev?: string };\n}\n\nexport interface PatchExecutor {\n apply: (documentId: string, ops: PatchOp[], ifRev: string | undefined) => Promise<SanityDocument>;\n}\n\nexport function createPatch(documentId: string, executor: PatchExecutor): PatchHandle {\n const ops: PatchOp[] = [];\n let ifRev: string | undefined;\n\n const handle: PatchHandle = {\n set: (props) => {\n ops.push({ kind: \"set\", props });\n return handle;\n },\n setIfMissing: (props) => {\n ops.push({ kind: \"setIfMissing\", props });\n return handle;\n },\n unset: (paths) => {\n ops.push({ kind: \"unset\", paths });\n return handle;\n },\n inc: (props) => {\n ops.push({ kind: \"inc\", props });\n return handle;\n },\n dec: (props) => {\n ops.push({ kind: \"dec\", props });\n return handle;\n },\n insert: (position, anchor, items) => {\n ops.push({ kind: \"insert\", position, anchor, items });\n return handle;\n },\n ifRevisionId: (rev) => {\n ifRev = rev;\n return handle;\n },\n commit: () => executor.apply(documentId, ops, ifRev),\n toJSON: () => ({\n id: documentId,\n ops: [...ops],\n ...(ifRev !== undefined ? { ifRev } : {}),\n }),\n };\n\n return handle;\n}\n\n/**\n * Apply an ordered list of patch ops to a document, returning the new doc.\n *\n * The path semantics are deliberately a small subset:\n *\n * - **Dotted paths** (`a.b.c`) for nested object fields.\n * - **Array index** (`a.b[0]`) for positional access into arrays.\n * - **Keyed lookup** (`a.b[_key==\"x\"]`) for finding an array entry by `_key`.\n *\n * Anything more exotic (recursive `..`, GROQ filter expressions, multi-match)\n * is intentionally out of scope and will throw — the workflow engine only\n * needs the three forms above.\n */\nexport function applyPatchOps(doc: SanityDocument, ops: PatchOp[]): SanityDocument {\n let next: SanityDocument = structuredClone(doc);\n for (const op of ops) {\n next = applyOne(next, op);\n }\n return next;\n}\n\nfunction applyOne(doc: SanityDocument, op: PatchOp): SanityDocument {\n switch (op.kind) {\n case \"set\":\n for (const [path, value] of Object.entries(op.props)) {\n setAtPath(doc, path, value);\n }\n return doc;\n case \"setIfMissing\":\n for (const [path, value] of Object.entries(op.props)) {\n if (getAtPath(doc, path) === undefined) {\n setAtPath(doc, path, value);\n }\n }\n return doc;\n case \"unset\":\n for (const path of op.paths) {\n unsetAtPath(doc, path);\n }\n return doc;\n case \"inc\":\n for (const [path, delta] of Object.entries(op.props)) {\n const current = getAtPath(doc, path);\n const base = typeof current === \"number\" ? current : 0;\n setAtPath(doc, path, base + delta);\n }\n return doc;\n case \"dec\":\n for (const [path, delta] of Object.entries(op.props)) {\n const current = getAtPath(doc, path);\n const base = typeof current === \"number\" ? current : 0;\n setAtPath(doc, path, base - delta);\n }\n return doc;\n case \"insert\": {\n insertIntoArray(doc, op.position, op.anchor, op.items);\n return doc;\n }\n }\n}\n\ninterface PathSegment {\n key: string;\n // Optional array selector. Either a numeric index or a key=value match.\n selector?: { kind: \"index\"; index: number } | { kind: \"keyed\"; field: string; value: string };\n}\n\nfunction parsePath(path: string): PathSegment[] {\n // Examples:\n // \"currentStageId\"\n // \"taskStatus[0].status\"\n // \"taskStatus[_key==\\\"approve\\\"].status\"\n // \"context[key==\\\"releaseId\\\"].value\"\n const segments: PathSegment[] = [];\n for (const raw of path.split(\".\")) {\n const match = /^([A-Za-z_$][\\w$]*)(?:\\[(.+)\\])?$/.exec(raw);\n if (!match) {\n throw fakeError(\n `Unsupported patch path segment \"${raw}\" (in path \"${path}\"). This fake supports dotted ` +\n `field access (\"a.b.c\"), array index (\"items[0]\"), and keyed lookup (\\`items[_key==\"x\"]\\`). ` +\n `Recursive descent (\"..\") and GROQ filter expressions are not supported.`,\n );\n }\n const key = match[1] as string;\n const selectorRaw = match[2];\n if (selectorRaw === undefined) {\n segments.push({ key });\n continue;\n }\n const indexMatch = /^(\\d+)$/.exec(selectorRaw);\n if (indexMatch) {\n segments.push({ key, selector: { kind: \"index\", index: Number(indexMatch[1]) } });\n continue;\n }\n const keyedMatch = /^([A-Za-z_$][\\w$]*)\\s*==\\s*\"([^\"]*)\"$/.exec(selectorRaw);\n if (keyedMatch) {\n segments.push({\n key,\n selector: { kind: \"keyed\", field: keyedMatch[1] as string, value: keyedMatch[2] as string },\n });\n continue;\n }\n throw fakeError(\n `Unsupported array selector \"[${selectorRaw}]\" in patch path \"${path}\". Supported selectors ` +\n `are a numeric index (e.g. \"[0]\") and a single keyed match (e.g. \\`[_key==\"abc\"]\\`). ` +\n `Multi-key matches and arbitrary GROQ filters are not supported.`,\n );\n }\n return segments;\n}\n\nfunction resolveSelector(array: unknown[], selector: NonNullable<PathSegment[\"selector\"]>): number {\n if (selector.kind === \"index\") return selector.index;\n const idx = array.findIndex(\n (entry) =>\n typeof entry === \"object\" &&\n entry !== null &&\n (entry as Record<string, unknown>)[selector.field] === selector.value,\n );\n if (idx === -1) {\n throw fakeError(\n `Patch path matched no array entry where ${selector.field}==\"${selector.value}\". The array has ` +\n `${array.length} item(s); check the key exists (and that you're patching the right document).`,\n );\n }\n return idx;\n}\n\nfunction getAtPath(doc: SanityDocument, path: string): unknown {\n const segments = parsePath(path);\n let cursor: unknown = doc;\n for (const seg of segments) {\n if (cursor === undefined || cursor === null) return undefined;\n cursor = (cursor as Record<string, unknown>)[seg.key];\n if (seg.selector !== undefined) {\n if (!Array.isArray(cursor)) return undefined;\n const idx = resolveSelector(cursor, seg.selector);\n cursor = cursor[idx];\n }\n }\n return cursor;\n}\n\nfunction setAtPath(doc: SanityDocument, path: string, value: unknown): void {\n const segments = parsePath(path);\n if (segments.length === 0)\n throw fakeError(`Empty patch path — a set/setIfMissing op needs a target field.`);\n let cursor: Record<string, unknown> = doc as unknown as Record<string, unknown>;\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i] as PathSegment;\n let next = cursor[seg.key];\n if (next === undefined) {\n next = seg.selector?.kind === \"index\" || seg.selector?.kind === \"keyed\" ? [] : {};\n cursor[seg.key] = next;\n }\n if (seg.selector !== undefined) {\n if (!Array.isArray(next)) {\n throw fakeError(\n `Patch path \"${path}\" applies an array selector to field \"${seg.key}\", but that field ` +\n `holds ${describeType(next)}, not an array.`,\n );\n }\n const idx = resolveSelector(next, seg.selector);\n cursor = next[idx] as Record<string, unknown>;\n } else {\n cursor = next as Record<string, unknown>;\n }\n }\n const last = segments[segments.length - 1] as PathSegment;\n if (last.selector !== undefined) {\n const arr = cursor[last.key];\n if (!Array.isArray(arr)) {\n throw fakeError(\n `Patch path \"${path}\" applies an array selector to field \"${last.key}\", but that field ` +\n `holds ${describeType(arr)}, not an array.`,\n );\n }\n const idx = resolveSelector(arr, last.selector);\n arr[idx] = value;\n } else {\n cursor[last.key] = value;\n }\n}\n\nfunction unsetAtPath(doc: SanityDocument, path: string): void {\n const segments = parsePath(path);\n if (segments.length === 0) return;\n let cursor: Record<string, unknown> = doc as unknown as Record<string, unknown>;\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i] as PathSegment;\n let next = cursor[seg.key];\n if (next === undefined || next === null) return;\n if (seg.selector !== undefined) {\n if (!Array.isArray(next)) return;\n const idx = resolveSelector(next, seg.selector);\n next = next[idx];\n }\n cursor = next as Record<string, unknown>;\n }\n const last = segments[segments.length - 1] as PathSegment;\n if (last.selector !== undefined) {\n const arr = cursor[last.key];\n if (!Array.isArray(arr)) return;\n const idx = resolveSelector(arr, last.selector);\n arr.splice(idx, 1);\n } else {\n delete cursor[last.key];\n }\n}\n\nfunction insertIntoArray(\n doc: SanityDocument,\n position: \"before\" | \"after\" | \"replace\",\n anchor: string,\n items: unknown[],\n): void {\n // anchor is a path that must terminate at an array entry (selector required).\n // For \"replace\", we replace the entry; for \"before\"/\"after\", we insert\n // adjacent to it.\n const segments = parsePath(anchor);\n if (segments.length === 0)\n throw fakeError(`Empty insert anchor — insert() needs an array path to anchor against.`);\n const last = segments[segments.length - 1] as PathSegment;\n if (last.selector === undefined) {\n throw fakeError(\n `Insert anchor \"${anchor}\" must end with an array selector (an index like \"[0]\" or a keyed ` +\n `match like \\`[_key==\"x\"]\\`) so the fake knows where in the array to insert.`,\n );\n }\n\n let cursor: Record<string, unknown> = doc as unknown as Record<string, unknown>;\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i] as PathSegment;\n const next = cursor[seg.key];\n if (next === undefined || next === null) {\n throw fakeError(\n `Insert anchor \"${anchor}\" traverses field \"${seg.key}\", which is missing on the document. ` +\n `setIfMissing the parent first, or anchor against an existing array.`,\n );\n }\n if (seg.selector !== undefined) {\n if (!Array.isArray(next)) {\n throw fakeError(\n `Insert anchor \"${anchor}\" applies an array selector to field \"${seg.key}\", but it holds ` +\n `${describeType(next)}, not an array.`,\n );\n }\n cursor = next[resolveSelector(next, seg.selector)] as Record<string, unknown>;\n } else {\n cursor = next as Record<string, unknown>;\n }\n }\n const arr = cursor[last.key];\n if (!Array.isArray(arr)) {\n throw fakeError(\n `Insert anchor \"${anchor}\" targets field \"${last.key}\", but it holds ${describeType(arr)}, ` +\n `not an array.`,\n );\n }\n const idx = resolveSelector(arr, last.selector);\n if (position === \"replace\") {\n arr.splice(idx, 1, ...items);\n } else if (position === \"before\") {\n arr.splice(idx, 0, ...items);\n } else {\n arr.splice(idx + 1, 0, ...items);\n }\n}\n","/**\n * Content Releases action handlers — `client.action()` plus the\n * `client.releases.*` and `client.createVersion` / `client.unpublishVersion`\n * helpers.\n *\n * Mirrors enough of the real `@sanity/client` action surface for tests\n * to exercise release-aware workflows. Transient states\n * (`scheduling`/`publishing`/`unscheduling`) are skipped — releases\n * transition synchronously between settled states.\n */\n\nimport type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport type { TestStore } from \"./store.ts\";\nimport { cryptoRandomKey } from \"./store.ts\";\nimport { applyPatchOps, type PatchOp } from \"./patch.ts\";\nimport { fakeError } from \"./errors.ts\";\n\n/**\n * Document body accepted by `version.create` / `createVersion`. The id\n * is derived from `releaseId + publishedId` so callers may omit `_id`\n * here. `version.replace` requires `_id` since it identifies the doc\n * to replace.\n */\nexport interface DocumentBody {\n _id?: string;\n _type: string;\n [field: string]: unknown;\n}\n\nexport type ReleaseState = \"active\" | \"scheduled\" | \"published\" | \"archived\";\n\nexport type ReleaseType = \"asap\" | \"scheduled\" | \"undecided\";\n\nexport interface ReleaseMetadata {\n title?: string;\n description?: string;\n releaseType?: ReleaseType;\n intendedPublishAt?: string;\n}\n\nexport interface ReleaseDocument extends SanityDocument {\n _type: \"system.release\";\n name: string;\n state: ReleaseState;\n metadata: ReleaseMetadata;\n publishAt?: string;\n}\n\nexport type ReleaseAction =\n | {\n actionType: \"sanity.action.release.create\";\n releaseId: string;\n metadata?: Partial<ReleaseMetadata>;\n }\n | {\n actionType: \"sanity.action.release.edit\";\n releaseId: string;\n patch: { set?: Record<string, unknown>; unset?: string[] };\n }\n | { actionType: \"sanity.action.release.schedule\"; releaseId: string; publishAt: string }\n | { actionType: \"sanity.action.release.unschedule\"; releaseId: string }\n | { actionType: \"sanity.action.release.publish\"; releaseId: string }\n | { actionType: \"sanity.action.release.archive\"; releaseId: string }\n | { actionType: \"sanity.action.release.unarchive\"; releaseId: string }\n | { actionType: \"sanity.action.release.delete\"; releaseId: string };\n\nexport type VersionAction =\n | {\n actionType: \"sanity.action.document.version.create\";\n publishedId: string;\n document: DocumentBody;\n releaseId?: string; // inferred from document._id when omitted\n }\n | {\n actionType: \"sanity.action.document.version.replace\";\n document: SanityDocumentLike;\n }\n | {\n actionType: \"sanity.action.document.version.discard\";\n versionId: string;\n }\n | {\n actionType: \"sanity.action.document.version.unpublish\";\n versionId: string;\n publishedId: string;\n };\n\nexport type Action = ReleaseAction | VersionAction;\n\nexport interface ActionResult {\n transactionId: string;\n}\n\nconst RELEASE_DOC_PREFIX = \"_.releases.\";\nconst VERSIONS_PREFIX = \"versions.\";\n\nconst releaseDocId = (releaseId: string): string => `${RELEASE_DOC_PREFIX}${releaseId}`;\nconst versionDocId = (releaseId: string, publishedId: string): string =>\n `${VERSIONS_PREFIX}${releaseId}.${publishedId}`;\n\n/** Parse `versions.<release>.<id>` → `{ releaseId, publishedId }`. Throws otherwise. */\nfunction parseVersionId(versionId: string): { releaseId: string; publishedId: string } {\n if (!versionId.startsWith(VERSIONS_PREFIX)) {\n throw fakeError(\n `\"${versionId}\" is not a version document id. Version ids look like ` +\n `\"versions.<releaseId>.<publishedId>\" (e.g. \"versions.summer-drop.product-1\").`,\n );\n }\n const rest = versionId.slice(VERSIONS_PREFIX.length);\n const dot = rest.indexOf(\".\");\n if (dot === -1) {\n throw fakeError(\n `\"${versionId}\" is not a version document id. Version ids look like ` +\n `\"versions.<releaseId>.<publishedId>\" (e.g. \"versions.summer-drop.product-1\").`,\n );\n }\n return { releaseId: rest.slice(0, dot), publishedId: rest.slice(dot + 1) };\n}\n\nfunction getRelease(store: TestStore, releaseId: string): ReleaseDocument {\n const doc = store.get(releaseDocId(releaseId)) as ReleaseDocument | undefined;\n if (doc === undefined) {\n throw fakeError(\n `Release \"${releaseId}\" not found. Create it first with ` +\n `client.releases.create({ releaseId: \"${releaseId}\" }) (or a ` +\n `\"sanity.action.release.create\" action) before editing, scheduling, or adding versions to it.`,\n );\n }\n return doc;\n}\n\nfunction maybeRelease(store: TestStore, releaseId: string): ReleaseDocument | undefined {\n return store.get(releaseDocId(releaseId)) as ReleaseDocument | undefined;\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nfunction promote(doc: SanityDocumentLike): SanityDocument {\n const now = nowIso();\n return {\n ...doc,\n _id: doc._id as string,\n _type: doc._type as string,\n _rev: cryptoRandomKey(),\n _createdAt: doc._createdAt ?? now,\n _updatedAt: now,\n } as SanityDocument;\n}\n\nfunction bumpRev(doc: SanityDocument, patch: Partial<SanityDocument>): SanityDocument {\n return {\n ...doc,\n ...patch,\n _rev: cryptoRandomKey(),\n _updatedAt: nowIso(),\n } as SanityDocument;\n}\n\nfunction requireActive(release: ReleaseDocument): void {\n if (release.state !== \"active\") {\n throw fakeError(\n `Release \"${release.name}\" is \"${release.state}\", but only \"active\" releases accept version ` +\n `writes (create / replace / discard / unpublish). Unschedule or unarchive it back to ` +\n `\"active\" first, or target a different release.`,\n );\n }\n}\n\n/**\n * Apply a single action to the store. Returns a synthetic transactionId.\n * Throws on any invariant violation — callers wrap multi-action arrays\n * with a snapshot/rollback to keep atomicity.\n */\nexport function applyAction(store: TestStore, action: Action): ActionResult {\n switch (action.actionType) {\n case \"sanity.action.release.create\": {\n if (maybeRelease(store, action.releaseId) !== undefined) {\n throw fakeError(\n `Release \"${action.releaseId}\" already exists. release.create expects a new releaseId; ` +\n `use release.edit to change its metadata, or pick a different releaseId.`,\n );\n }\n const now = nowIso();\n const metadata: ReleaseMetadata = {\n releaseType: \"undecided\",\n ...action.metadata,\n };\n const doc: ReleaseDocument = {\n _id: releaseDocId(action.releaseId),\n _type: \"system.release\",\n _rev: cryptoRandomKey(),\n _createdAt: now,\n _updatedAt: now,\n name: action.releaseId,\n state: \"active\",\n metadata,\n };\n store.put(doc);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.edit\": {\n const release = getRelease(store, action.releaseId);\n const patchOps: PatchOp[] = [];\n if (action.patch.set !== undefined) {\n patchOps.push({ kind: \"set\", props: action.patch.set });\n }\n if (action.patch.unset !== undefined) {\n patchOps.push({ kind: \"unset\", paths: action.patch.unset });\n }\n const patched = applyPatchOps(release, patchOps);\n store.put(bumpRev(patched, {}));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.schedule\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"active\") {\n throw fakeError(\n `Cannot schedule release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"active\" releases can be scheduled.`,\n );\n }\n store.put(\n bumpRev(release, {\n state: \"scheduled\",\n publishAt: action.publishAt,\n } as Partial<SanityDocument>),\n );\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.unschedule\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"scheduled\") {\n throw fakeError(\n `Cannot unschedule release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"scheduled\" releases can be unscheduled.`,\n );\n }\n const next: ReleaseDocument = { ...release, state: \"active\" };\n delete (next as { publishAt?: string }).publishAt;\n store.put(bumpRev(next, {}));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.publish\": {\n const release = getRelease(store, action.releaseId);\n if (release.state === \"published\") {\n // Idempotent.\n return { transactionId: cryptoRandomKey() };\n }\n if (release.state !== \"active\" && release.state !== \"scheduled\") {\n throw fakeError(\n `Cannot publish release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"active\" or \"scheduled\" releases can be published.`,\n );\n }\n // Materialise versions onto published ids, then drop the versions.\n const prefix = `${VERSIONS_PREFIX}${action.releaseId}.`;\n const sources = store.all().filter((d) => d._id.startsWith(prefix));\n for (const v of sources) {\n const pubId = v._id.slice(prefix.length);\n const isUnpublishStub = (v as { _system?: { delete?: boolean } })._system?.delete === true;\n if (isUnpublishStub) {\n store.remove(pubId);\n } else {\n const body: SanityDocumentLike = {\n ...(v as SanityDocumentLike),\n _id: pubId,\n };\n // Strip transient fields we projected through the version.\n delete (body as { _originalId?: string })._originalId;\n delete (body as { _system?: unknown })._system;\n const promoted = promote(body);\n // Preserve _createdAt of the existing published doc if present.\n const existing = store.get(pubId);\n if (existing !== undefined) {\n promoted._createdAt = existing._createdAt;\n }\n store.put(promoted);\n }\n store.remove(v._id);\n }\n store.put(bumpRev(release, { state: \"published\" } as Partial<SanityDocument>));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.archive\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"active\" && release.state !== \"scheduled\") {\n throw fakeError(\n `Cannot archive release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"active\" or \"scheduled\" releases can be archived.`,\n );\n }\n store.put(bumpRev(release, { state: \"archived\" } as Partial<SanityDocument>));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.unarchive\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"archived\") {\n throw fakeError(\n `Cannot unarchive release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"archived\" releases can be unarchived.`,\n );\n }\n store.put(bumpRev(release, { state: \"active\" } as Partial<SanityDocument>));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.delete\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"archived\" && release.state !== \"published\") {\n throw fakeError(\n `Cannot delete release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"archived\" or \"published\" releases can be deleted. Archive it first ` +\n `(sanity.action.release.archive) or publish it.`,\n );\n }\n // Clean up any leftover version docs (archived releases keep them around).\n const prefix = `${VERSIONS_PREFIX}${action.releaseId}.`;\n for (const v of store.all()) {\n if (v._id.startsWith(prefix)) store.remove(v._id);\n }\n store.remove(release._id);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.create\": {\n const releaseId =\n action.releaseId ??\n (action.document._id !== undefined\n ? parseVersionId(action.document._id as string).releaseId\n : undefined);\n if (releaseId === undefined) {\n throw fakeError(\n `version.create needs a release to attach to: pass \\`releaseId\\`, or a \\`document._id\\` ` +\n `shaped \"versions.<releaseId>.<publishedId>\" so the release can be inferred.`,\n );\n }\n const release = getRelease(store, releaseId);\n requireActive(release);\n const vid = versionDocId(releaseId, action.publishedId);\n const doc: SanityDocumentLike = {\n ...action.document,\n _id: vid,\n };\n const existing = store.get(vid);\n const promoted = promote(doc);\n if (existing !== undefined) {\n promoted._createdAt = existing._createdAt;\n }\n store.put(promoted);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.replace\": {\n const id = action.document._id;\n if (typeof id !== \"string\") {\n throw fakeError(\n `version.replace needs \\`document._id\\` (a version id like ` +\n `\"versions.<releaseId>.<publishedId>\") to identify which version document to replace.`,\n );\n }\n const { releaseId } = parseVersionId(id);\n const release = getRelease(store, releaseId);\n requireActive(release);\n const existing = store.get(id);\n const promoted = promote(action.document);\n if (existing !== undefined) {\n promoted._createdAt = existing._createdAt;\n }\n store.put(promoted);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.discard\": {\n const { releaseId } = parseVersionId(action.versionId);\n const release = getRelease(store, releaseId);\n requireActive(release);\n store.remove(action.versionId);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.unpublish\": {\n const { releaseId } = parseVersionId(action.versionId);\n const release = getRelease(store, releaseId);\n requireActive(release);\n const doc: SanityDocumentLike = {\n _id: action.versionId,\n _type: \"stub\",\n _system: { delete: true },\n } as SanityDocumentLike;\n store.put(promote(doc));\n return { transactionId: cryptoRandomKey() };\n }\n }\n}\n\n/**\n * Apply an action or a list of actions atomically. On any failure all\n * mutations within the batch are rolled back to the pre-batch snapshot.\n */\nexport function applyActions(store: TestStore, actions: Action | Action[]): ActionResult {\n const list = Array.isArray(actions) ? actions : [actions];\n const snapshot = new Map<string, SanityDocument | undefined>();\n const remember = (id: string) => {\n if (!snapshot.has(id)) snapshot.set(id, store.get(id));\n };\n\n try {\n let last: ActionResult = { transactionId: cryptoRandomKey() };\n for (const a of list) {\n // Pre-record everything we might touch so rollback is precise.\n switch (a.actionType) {\n case \"sanity.action.release.create\":\n case \"sanity.action.release.edit\":\n case \"sanity.action.release.schedule\":\n case \"sanity.action.release.unschedule\":\n case \"sanity.action.release.archive\":\n case \"sanity.action.release.unarchive\":\n case \"sanity.action.release.delete\":\n remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);\n break;\n case \"sanity.action.release.publish\": {\n remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);\n const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;\n for (const d of store.all()) {\n if (d._id.startsWith(prefix)) {\n remember(d._id);\n remember(d._id.slice(prefix.length));\n }\n }\n break;\n }\n case \"sanity.action.document.version.create\": {\n // version.create derives its id from releaseId + publishedId,\n // so we don't rely on document._id being set.\n const releaseId =\n a.releaseId ??\n (typeof a.document._id === \"string\"\n ? parseVersionId(a.document._id).releaseId\n : undefined);\n if (releaseId !== undefined) {\n remember(versionDocId(releaseId, a.publishedId));\n }\n break;\n }\n case \"sanity.action.document.version.replace\":\n if (typeof a.document._id === \"string\") remember(a.document._id);\n break;\n case \"sanity.action.document.version.discard\":\n case \"sanity.action.document.version.unpublish\":\n remember(a.versionId);\n break;\n }\n last = applyAction(store, a);\n }\n return last;\n } catch (err) {\n for (const [id, doc] of snapshot) {\n if (doc === undefined) {\n store.remove(id);\n } else {\n store.put(doc);\n }\n }\n throw err;\n }\n}\n","/**\n * Perspective layering — read-side filtering that mirrors Sanity's\n * `perspective` query/client option.\n *\n * The store always holds raw documents. Each fetch builds a *view* of\n * the store filtered by the active perspective before passing the\n * dataset to `groq-js`.\n *\n * Reference: https://www.sanity.io/docs/content-lake/perspectives\n */\n\nimport type { SanityDocument } from \"@sanity/types\";\n\nexport type Perspective = \"raw\" | \"published\" | \"drafts\" | string[];\n\nconst DRAFTS_PREFIX = \"drafts.\";\nconst VERSIONS_PREFIX = \"versions.\";\nconst SYSTEM_PREFIX = \"_.\";\nconst RELEASE_DOC_PREFIX = \"_.releases.\";\n\n/** Strip `drafts.` / `versions.<name>.` prefix to recover the published id. */\nexport function publishedIdOf(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) return id.slice(DRAFTS_PREFIX.length);\n if (id.startsWith(VERSIONS_PREFIX)) {\n // versions.<name>.<id> — split off the prefix + name\n const rest = id.slice(VERSIONS_PREFIX.length);\n const dot = rest.indexOf(\".\");\n if (dot === -1) return rest;\n return rest.slice(dot + 1);\n }\n return id;\n}\n\n/** Extract the release name from a `versions.<name>.<id>` id, else undefined. */\nexport function releaseNameOf(id: string): string | undefined {\n if (!id.startsWith(VERSIONS_PREFIX)) return undefined;\n const rest = id.slice(VERSIONS_PREFIX.length);\n const dot = rest.indexOf(\".\");\n if (dot === -1) return undefined;\n return rest.slice(0, dot);\n}\n\nexport const isDraftId = (id: string): boolean => id.startsWith(DRAFTS_PREFIX);\nexport const isVersionId = (id: string): boolean => id.startsWith(VERSIONS_PREFIX);\nexport const isSystemId = (id: string): boolean => id.startsWith(SYSTEM_PREFIX);\nexport const isReleaseDocId = (id: string): boolean => id.startsWith(RELEASE_DOC_PREFIX);\n\n/**\n * Apply a perspective to a raw set of documents and return the view\n * groq-js should evaluate against.\n *\n * For non-raw perspectives, each output document for a non-system id\n * gets `_id` projected to its published id and `_originalId` carrying\n * the source id (matching the wire shape of the real Content Lake).\n */\nexport function applyPerspective(\n docs: readonly SanityDocument[],\n perspective: Perspective,\n): SanityDocument[] {\n if (perspective === \"raw\") return [...docs];\n\n if (perspective === \"published\") {\n return docs.filter((d) => !isDraftId(d._id) && !isVersionId(d._id) && !isSystemId(d._id));\n }\n\n if (perspective === \"drafts\") {\n return mergeStack(docs, [], { includeDrafts: true, includeReleaseDocs: false });\n }\n\n // string[] — release stack with optional \"drafts\" entry\n const stack: string[] = [];\n let includeDrafts = false;\n for (const entry of perspective) {\n if (entry === \"drafts\") {\n includeDrafts = true;\n } else {\n stack.push(entry);\n }\n }\n return mergeStack(docs, stack, { includeDrafts, includeReleaseDocs: true });\n}\n\ninterface MergeOptions {\n includeDrafts: boolean;\n includeReleaseDocs: boolean;\n}\n\n/**\n * Walk the raw docs once, group by published id, then for each group\n * pick the highest-priority source according to `releaseStack` and\n * `includeDrafts`. Project the chosen doc to the published id.\n */\nfunction mergeStack(\n docs: readonly SanityDocument[],\n releaseStack: readonly string[],\n options: MergeOptions,\n): SanityDocument[] {\n // Group docs by published id. Track which sources exist.\n type Group = {\n published?: SanityDocument;\n draft?: SanityDocument;\n versions: Map<string, SanityDocument>;\n };\n const groups = new Map<string, Group>();\n const systemReleases: SanityDocument[] = [];\n\n for (const doc of docs) {\n if (isReleaseDocId(doc._id)) {\n if (options.includeReleaseDocs) systemReleases.push(doc);\n continue;\n }\n if (isSystemId(doc._id)) continue; // other system docs are hidden\n const pubId = publishedIdOf(doc._id);\n let group = groups.get(pubId);\n if (group === undefined) {\n group = { versions: new Map() };\n groups.set(pubId, group);\n }\n if (isDraftId(doc._id)) {\n group.draft = doc;\n } else if (isVersionId(doc._id)) {\n const releaseName = releaseNameOf(doc._id);\n if (releaseName !== undefined) group.versions.set(releaseName, doc);\n } else {\n group.published = doc;\n }\n }\n\n const out: SanityDocument[] = [];\n for (const [pubId, group] of groups) {\n // Walk the release stack first, then drafts (if enabled, in its\n // slot — here we model \"drafts after the stack\" matching the\n // typical `[r1, r2, \"drafts\"]` shape), then fall through to\n // published.\n let chosen: SanityDocument | undefined;\n for (const releaseName of releaseStack) {\n const v = group.versions.get(releaseName);\n if (v !== undefined) {\n // version.unpublish stub: hide the doc entirely\n if (isUnpublishStub(v)) {\n chosen = undefined;\n break;\n }\n chosen = v;\n break;\n }\n }\n if (chosen === undefined && options.includeDrafts && group.draft !== undefined) {\n chosen = group.draft;\n }\n if (chosen === undefined && group.published !== undefined) {\n // skip if any release in the stack carried an unpublish stub\n const blocked = releaseStack.some((name) => {\n const v = group.versions.get(name);\n return v !== undefined && isUnpublishStub(v);\n });\n if (!blocked) chosen = group.published;\n }\n if (chosen !== undefined) {\n out.push(projectToPublishedId(chosen, pubId));\n }\n }\n\n return [...out, ...systemReleases];\n}\n\nfunction isUnpublishStub(doc: SanityDocument): boolean {\n const sys = (doc as { _system?: { delete?: boolean } })._system;\n return sys?.delete === true;\n}\n\nfunction projectToPublishedId(doc: SanityDocument, pubId: string): SanityDocument {\n if (doc._id === pubId) return doc;\n return { ...doc, _id: pubId, _originalId: doc._id } as SanityDocument;\n}\n\n/**\n * `getDocument(id)` resolution under a perspective. Returns the chosen\n * source's *raw* doc (not projected), so the caller can decide whether\n * to expose `_originalId` etc. For perspective=\"raw\", this is just\n * `docs.find(d => d._id === id)`.\n */\nexport function resolveDocument(\n docs: readonly SanityDocument[],\n id: string,\n perspective: Perspective,\n): SanityDocument | undefined {\n if (perspective === \"raw\") {\n return docs.find((d) => d._id === id);\n }\n // Match the rules of applyPerspective: resolve to the same chosen\n // doc but key by the requested id (which the caller treated as a\n // published id under non-raw perspectives).\n const view = applyPerspective(docs, perspective);\n return view.find((d) => d._id === id);\n}\n","import type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport type { PatchHandle, PatchOp } from \"./patch.ts\";\n\n/**\n * A transaction collects mutations and applies them atomically at commit\n * time. Mutations are applied in declaration order; if any one fails, the\n * whole transaction throws and no writes land in the store.\n *\n * Subset of `@sanity/client`'s Transaction. Same shape, narrower surface.\n */\nexport type TxnMutation =\n | { kind: \"create\"; doc: SanityDocumentLike }\n | { kind: \"createOrReplace\"; doc: SanityDocumentLike }\n | { kind: \"createIfNotExists\"; doc: SanityDocumentLike }\n | { kind: \"delete\"; id: string }\n | { kind: \"patch\"; documentId: string; ops: PatchOp[]; ifRev?: string };\n\nexport interface TransactionHandle {\n create: (doc: SanityDocumentLike) => TransactionHandle;\n createOrReplace: (doc: SanityDocumentLike) => TransactionHandle;\n createIfNotExists: (doc: SanityDocumentLike) => TransactionHandle;\n delete: (id: string) => TransactionHandle;\n /** Accept either a Patch builder (drained at commit) or an inline doc id + ops. */\n patch: (\n documentIdOrPatch: string | PatchHandle,\n ops?: PatchOp[],\n ifRev?: string,\n ) => TransactionHandle;\n commit: (options?: TxnCommitOptions) => Promise<TxnCommitResult>;\n /** Test-only introspection — not on real Transaction. */\n toJSON: () => TxnMutation[];\n}\n\nexport interface TxnCommitOptions {\n /**\n * Shape the resolved value (mirrors `@sanity/client`):\n * - default (both unset) → {@link MultipleMutationResult}\n * - `returnDocuments: true` → the resulting document(s)\n * - `returnFirst: true` with `returnDocuments` → a single document\n * - `returnDocuments: false` → an id-shaped mutation result\n */\n returnDocuments?: boolean;\n returnFirst?: boolean;\n /** Override the synthetic transaction id (mirrors `client.transaction(undefined, { transactionId })`). */\n transactionId?: string;\n}\n\n/** The operation recorded per affected document, matching `@sanity/client`. */\nexport type MutationOperation = \"create\" | \"update\" | \"delete\" | \"none\";\n\n/** Result of a mutation when `returnFirst` resolves true and ids are requested. */\nexport interface SingleMutationResult {\n transactionId: string;\n documentId: string;\n results: { id: string; operation: MutationOperation }[];\n}\n\n/** Result of a mutation when ids are requested for all affected documents. */\nexport interface MultipleMutationResult {\n transactionId: string;\n documentIds: string[];\n results: { id: string; operation: MutationOperation }[];\n}\n\nexport type TxnCommitResult =\n | MultipleMutationResult\n | SingleMutationResult\n | SanityDocument\n | SanityDocument[];\n\nexport interface TxnExecutor {\n apply: (mutations: TxnMutation[], options?: TxnCommitOptions) => Promise<TxnCommitResult>;\n}\n\nexport function createTransaction(executor: TxnExecutor): TransactionHandle {\n const mutations: TxnMutation[] = [];\n\n const handle: TransactionHandle = {\n create: (doc) => {\n mutations.push({ kind: \"create\", doc });\n return handle;\n },\n createOrReplace: (doc) => {\n mutations.push({ kind: \"createOrReplace\", doc });\n return handle;\n },\n createIfNotExists: (doc) => {\n mutations.push({ kind: \"createIfNotExists\", doc });\n return handle;\n },\n delete: (id) => {\n mutations.push({ kind: \"delete\", id });\n return handle;\n },\n patch: (documentIdOrPatch, ops, ifRev) => {\n if (typeof documentIdOrPatch === \"string\") {\n mutations.push({\n kind: \"patch\",\n documentId: documentIdOrPatch,\n ops: ops ?? [],\n ...(ifRev !== undefined ? { ifRev } : {}),\n });\n } else {\n const json = documentIdOrPatch.toJSON();\n mutations.push({\n kind: \"patch\",\n documentId: json.id,\n ops: json.ops,\n ...(json.ifRev !== undefined ? { ifRev: json.ifRev } : {}),\n });\n }\n return handle;\n },\n commit: (options) => executor.apply(mutations, options),\n toJSON: () => [...mutations],\n };\n\n return handle;\n}\n","/**\n * Graceful-degradation layer for the parts of `@sanity/client` this fake\n * doesn't implement.\n *\n * The client object is a fixed surface. Without a guard, reaching for a\n * member the fake doesn't have (`client.listen`, `client.assets.upload`,\n * a typo) yields a bare `TypeError: x is not a function` — no hint that\n * it's an intentional gap in a *fake*, no pointer to a workaround. The\n * `Proxy` built here turns every such access into an actionable error,\n * and lets tests fill gaps via a stub registry.\n *\n * Resolution order for a property read on the wrapped client:\n * 1. Real implemented member → passed straight through.\n * 2. Thenable / inspection probes (`then`, symbols, …) → pass through\n * so `await client` and `console.log(client)` stay well-behaved.\n * 3. User-registered stub (`client.stub(name, fn)`) → returned.\n * 4. Known-but-unimplemented `@sanity/client` member → a guard that\n * throws a curated, workaround-bearing error on call or deeper access.\n * 5. Anything else (typo / unknown) → a guard that throws a\n * \"no such method\" error listing the supported surface.\n */\n\nconst ISSUES_URL = \"https://github.com/sanity-labs/client-fake-for-test/issues\";\n\n/** Members this fake actually implements — surfaced in error messages. */\nexport const SUPPORTED_SURFACE = [\n \"fetch\",\n \"getDocument\",\n \"getDocuments\",\n \"create\",\n \"createOrReplace\",\n \"createIfNotExists\",\n \"delete\",\n \"patch\",\n \"transaction\",\n \"mutate\",\n \"action\",\n \"releases\",\n \"createVersion\",\n \"unpublishVersion\",\n \"request (only with accessControl)\",\n \"config\",\n \"withConfig\",\n] as const;\n\ninterface UnsupportedEntry {\n /** What the real member is. */\n what: string;\n /** What to do instead. */\n workaround: string;\n}\n\n/**\n * Curated map of real `@sanity/client` members the fake deliberately omits.\n * Keyed by the top-level property name; nested access (e.g.\n * `assets.upload`) is reported with the full dotted path.\n */\nexport const UNSUPPORTED_MEMBERS: Record<string, UnsupportedEntry> = {\n listen: {\n what: \"real-time listener (returns an RxJS Observable of mutation events)\",\n workaround:\n \"Test your subscription logic in isolation, or register a fake: \" +\n `client.stub(\"listen\", () => myFakeObservable).`,\n },\n observable: {\n what: \"the RxJS-flavoured mirror of the client API\",\n workaround:\n \"Use the Promise-based methods and wrap them with `from()` if you need an Observable.\",\n },\n clone: {\n what: \"clone the client with the same config\",\n workaround: \"Use `withConfig({})` — it returns a sibling handle into the same store.\",\n },\n getUrl: {\n what: \"build an absolute API URL for a path\",\n workaround: \"Hard-code the expected URL in your test, or stub it.\",\n },\n getDataUrl: {\n what: \"build an absolute data-API URL\",\n workaround: \"Hard-code the expected URL in your test, or stub it.\",\n },\n assets: {\n what: \"asset upload / metadata namespace\",\n workaround: \"Seed asset documents into the store directly with `seed()` / `add()`.\",\n },\n agent: {\n what: \"Agent Actions namespace (generate / transform / …)\",\n workaround: `Stub the call site: client.stub(\"agent\", myFakeAgent).`,\n },\n projects: {\n what: \"project-management namespace\",\n workaround: \"Out of scope for a data-plane fake — stub the call site.\",\n },\n users: {\n what: \"user-management namespace\",\n workaround: \"Out of scope for a data-plane fake — stub the call site.\",\n },\n live: {\n what: \"Live Content API namespace\",\n workaround: \"Out of scope — stub the call site or test the consumer separately.\",\n },\n mediaLibrary: {\n what: \"Media Library namespace\",\n workaround: \"Out of scope — seed documents directly or stub the call site.\",\n },\n request: {\n what: \"generic HTTP request hook — only wired up when accessControl is configured\",\n workaround:\n \"Create the client with `accessControl` to enable request() (it serves \" +\n \"/users/me + the ACL path), or register a stub.\",\n },\n dryRun: {\n what: \"not a method — did you mean the `{ dryRun }` mutation option?\",\n workaround: \"Pass `{ dryRun: true }` as the second arg to create / mutate / delete.\",\n },\n};\n\n/**\n * Property names read by promise-resolution, serialization, and test\n * frameworks while probing an unknown object. These must resolve to\n * `undefined` (not a throwing guard) so `await client`,\n * `JSON.stringify(client)`, and matcher diffs stay well-behaved. Members\n * inherited from `Object.prototype` (`toString`, `valueOf`, …) already\n * pass through via the `in` check and don't need listing here.\n */\nconst PROBE_NAMES = new Set([\n \"then\",\n \"catch\",\n \"finally\",\n \"toJSON\",\n \"asymmetricMatch\",\n \"$$typeof\",\n \"nodeType\",\n \"_isMockFunction\",\n]);\n\n/** Build the multi-line error body shared by both guard flavours. */\nfunction guardMessage(path: string, detail: string, workaround: string): string {\n return [\n `[client-fake-for-test] \\`client.${path}\\` ${detail}`,\n \"\",\n \"This is an in-memory fake of @sanity/client. It implements:\",\n ` ${SUPPORTED_SURFACE.join(\", \")}.`,\n \"\",\n `→ ${workaround}`,\n \"\",\n `Register a stub to fill any gap: client.stub(${JSON.stringify(path.split(\".\")[0])}, handler)`,\n `If this should be supported, open an issue: ${ISSUES_URL}`,\n ].join(\"\\n\");\n}\n\n/**\n * A callable, infinitely-chainable guard. Reading any property returns a\n * deeper guard (so `client.assets.upload` reports the full path), and\n * calling at any depth throws the actionable error. `then` / symbols\n * resolve to `undefined` so `await` and inspection don't trip the guard.\n */\nfunction makeGuard(path: string, message: string): unknown {\n const thrower = () => {\n throw new Error(message);\n };\n return new Proxy(thrower, {\n apply: () => thrower(),\n get: (_t, prop) => {\n if (typeof prop === \"symbol\") return undefined;\n if (PROBE_NAMES.has(prop)) return undefined;\n // Re-derive the message for the deeper path so the error names the\n // exact member that was reached for.\n const childPath = `${path}.${String(prop)}`;\n const top = path.split(\".\")[0] as string;\n const entry = UNSUPPORTED_MEMBERS[top];\n const detail = entry ? `is not implemented (${entry.what}).` : \"is not implemented.\";\n const workaround = entry?.workaround ?? \"Register a stub or use a different test strategy.\";\n return makeGuard(childPath, guardMessage(childPath, detail, workaround));\n },\n });\n}\n\n/** Outcome of a recorded call, reported once a (possibly async) result is known. */\nexport type CallSettler = (outcome: { result?: unknown; error?: unknown }) => void;\n\nexport interface GuardConfig {\n /**\n * Resolve a registered stub for an unimplemented member, or `undefined`.\n * Checked only for members the client doesn't already implement, so\n * stubs fill gaps without shadowing core behaviour.\n */\n getStub: (name: string) => unknown;\n /**\n * Called synchronously when a recorded method is invoked, with the\n * method name and its arguments. Returns a settler the wrapper invokes\n * once the result (or rejection) is known. Omit to disable recording.\n */\n onCall?: (method: string, args: unknown[]) => CallSettler;\n /**\n * Top-level member names whose calls are recorded via `onCall`. A\n * recorded member that resolves to a namespace object (e.g. `releases`)\n * has each of its methods recorded as `name.method`.\n */\n recorded?: Set<string>;\n}\n\n/** Wrap a function so each call is reported to `onCall` (args now, outcome on settle). */\nfunction wrapRecorded(\n method: string,\n fn: (...args: unknown[]) => unknown,\n onCall: NonNullable<GuardConfig[\"onCall\"]>,\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n const settle = onCall(method, args);\n try {\n const out = fn(...args);\n if (\n out !== null &&\n typeof out === \"object\" &&\n typeof (out as PromiseLike<unknown>).then === \"function\"\n ) {\n return (out as Promise<unknown>).then(\n (result) => {\n settle({ result });\n return result;\n },\n (error: unknown) => {\n settle({ error });\n throw error;\n },\n );\n }\n settle({ result: out });\n return out;\n } catch (error) {\n settle({ error });\n throw error;\n }\n };\n}\n\n/** Wrap a namespace object so its method calls record as `prefix.method`. */\nfunction wrapNamespace(\n ns: Record<string, unknown>,\n prefix: string,\n onCall: NonNullable<GuardConfig[\"onCall\"]>,\n): Record<string, unknown> {\n return new Proxy(ns, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (typeof prop === \"string\" && typeof value === \"function\") {\n return wrapRecorded(`${prefix}.${prop}`, value as (...a: unknown[]) => unknown, onCall);\n }\n return value;\n },\n });\n}\n\n/**\n * Wrap a client object so unimplemented members fail informatively,\n * registered stubs are served, and recorded methods report their calls.\n *\n * @param client - the fully-built client object (plain literal).\n * @param config - stub resolver plus optional call-recording hooks.\n */\nexport function wrapWithGuards<T extends object>(client: T, config: GuardConfig): T {\n const { getStub, onCall, recorded } = config;\n return new Proxy(client, {\n get(target, prop, receiver) {\n if (typeof prop === \"symbol\") return Reflect.get(target, prop, receiver);\n if (prop in target) {\n const value = Reflect.get(target, prop, receiver);\n if (onCall !== undefined && recorded?.has(prop) === true) {\n if (typeof value === \"function\") {\n return wrapRecorded(prop, value as (...a: unknown[]) => unknown, onCall);\n }\n if (value !== null && typeof value === \"object\") {\n return wrapNamespace(value as Record<string, unknown>, prop, onCall);\n }\n }\n return value;\n }\n // Promise / serialization / framework probes on a non-thenable object.\n if (PROBE_NAMES.has(prop)) return undefined;\n\n const stub = getStub(prop);\n if (stub !== undefined) return stub;\n\n const entry = UNSUPPORTED_MEMBERS[prop];\n if (entry !== undefined) {\n return makeGuard(\n prop,\n guardMessage(prop, `is not implemented (${entry.what}).`, entry.workaround),\n );\n }\n return makeGuard(\n prop,\n guardMessage(\n prop,\n \"is not a method on this fake (unknown member or unimplemented @sanity/client API).\",\n \"Check for a typo, register a stub, or use a different test strategy.\",\n ),\n );\n },\n });\n}\n","import type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport { evaluate, parse } from \"groq-js\";\nimport {\n canAccess,\n enforceWriteAccess,\n makeRequestImpl,\n type DocumentValuePermission,\n type TestClientAccessControl,\n} from \"./access-control.ts\";\nimport {\n applyActions,\n type Action,\n type ActionResult,\n type DocumentBody,\n type ReleaseDocument,\n type ReleaseMetadata,\n} from \"./actions.ts\";\nimport { applyPerspective, resolveDocument, type Perspective } from \"./perspective.ts\";\nimport { applyPatchOps, createPatch, type PatchHandle, type PatchOp } from \"./patch.ts\";\nimport { fakeError } from \"./errors.ts\";\nimport { createTestStore, cryptoRandomKey, type TestStore } from \"./store.ts\";\nimport {\n createTransaction,\n type MultipleMutationResult,\n type MutationOperation,\n type SingleMutationResult,\n type TransactionHandle,\n type TxnCommitOptions,\n type TxnCommitResult,\n type TxnMutation,\n} from \"./transaction.ts\";\nimport { wrapWithGuards, type CallSettler } from \"./unsupported.ts\";\n\n/**\n * Data-plane subset of `@sanity/client`'s surface, with multi-dataset support.\n *\n * One `createTestClient()` call creates a registry of stores keyed by\n * `(projectId, dataset)`. The returned client points at one of them.\n * `withConfig({ projectId, dataset })` returns a new handle into the same\n * registry but pointing at a different store — useful for workflows where\n * definitions live in one dataset and instances live in another.\n *\n * Two separate `createTestClient()` calls have separate registries, so\n * tests stay isolated from each other.\n *\n * Methods not on the real client:\n *\n * - `seed`, `add`, `reset`, `snapshot`, `store` — bulk-load helpers,\n * scoped to the current dataset.\n * - `datasets()` — lists known dataset keys in this registry.\n *\n * Methods deliberately omitted:\n *\n * - Project / agent / asset / live / listen APIs.\n */\nexport interface FetchOptions {\n /** Override the client's configured perspective for this read. */\n perspective?: Perspective;\n /**\n * When `false`, resolve to a {@link RawQueryResponse} (`{ query, ms,\n * result }`) instead of the bare result — mirrors `@sanity/client`.\n * Defaults to `true`.\n */\n filterResponse?: boolean;\n /**\n * With `filterResponse: false`, set to `false` to omit `query` from the\n * raw response. Ignored when `filterResponse` is not `false`.\n */\n returnQuery?: boolean;\n /** Accepted for signature parity; not simulated. */\n tag?: string;\n /** Accepted for signature parity; not simulated. */\n signal?: AbortSignal;\n}\n\n/**\n * Shape returned by `fetch` when `filterResponse: false`. Matches\n * `@sanity/client`'s `RawQueryResponse`. `query` is omitted when the\n * caller also passes `returnQuery: false`.\n */\nexport interface RawQueryResponse<R> {\n query?: string;\n ms: number;\n result: R;\n}\n\n/**\n * A single mutation in the raw array form accepted by `mutate()` — the\n * same shape `@sanity/client` accepts. The inline `patch` form mirrors\n * the real client's keyed patch object.\n */\nexport type FakeMutation =\n | { create: SanityDocumentLike }\n | { createOrReplace: SanityDocumentLike }\n | { createIfNotExists: SanityDocumentLike }\n | { delete: { id: string } }\n | {\n patch: {\n id: string;\n ifRevisionID?: string;\n set?: Record<string, unknown>;\n setIfMissing?: Record<string, unknown>;\n unset?: string[];\n inc?: Record<string, number>;\n dec?: Record<string, number>;\n insert?: {\n before?: string;\n after?: string;\n replace?: string;\n items: unknown[];\n };\n };\n };\n\n/** Append-only record of one committed transaction (a single mutation is a 1-entry transaction). */\nexport interface MutationLogEntry {\n transactionId: string;\n projectId: string;\n dataset: string;\n mutations: TxnMutation[];\n}\n\n/**\n * One recorded invocation of a client method — the spy layer behind\n * `client.calls()` / `client.callCount()`. `result` holds the resolved\n * value (awaited, for async methods); `error` holds the thrown/rejected\n * value. Builder-returning methods (`patch`, `transaction`) record the\n * builder as `result`; their eventual writes show up in the mutation log.\n */\nexport interface CallRecord {\n /** Method name; namespace methods are dotted, e.g. `releases.create`. */\n method: string;\n /** Arguments as passed (stored by reference, like `vi.fn`). */\n args: unknown[];\n /** Resolved/returned value, set once the call settles successfully. */\n result?: unknown;\n /** Thrown or rejected value, set if the call failed. */\n error?: unknown;\n projectId: string;\n dataset: string;\n}\n\n/** Client methods whose calls are recorded for `calls()` / `callCount()`. */\nconst RECORDED_METHODS = new Set([\n \"fetch\",\n \"getDocument\",\n \"getDocuments\",\n \"create\",\n \"createOrReplace\",\n \"createIfNotExists\",\n \"delete\",\n \"patch\",\n \"transaction\",\n \"mutate\",\n \"action\",\n \"releases\",\n \"createVersion\",\n \"unpublishVersion\",\n \"request\",\n]);\n\nexport interface TestClient {\n // --- query ---\n fetch: <T = unknown>(\n query: string,\n params?: Record<string, unknown>,\n options?: FetchOptions,\n ) => Promise<T>;\n getDocument: <T = SanityDocument>(id: string, options?: FetchOptions) => Promise<T | undefined>;\n getDocuments: <T = SanityDocument>(\n ids: string[],\n options?: FetchOptions,\n ) => Promise<(T | null)[]>;\n /**\n * Sanity-style HTTP request hook. Present iff the client was\n * created with `accessControl`. The engine's access resolver pokes\n * `/users/me` and the configured ACL path through this — without it\n * the engine throws on any verb that needs an actor (which is the\n * cue for the bench to supply an `access` override).\n *\n * Test cases that want to exercise the engine's token-resolution\n * path should configure `accessControl`; cases that want bench-style\n * always-allow should leave it off and pass `access` through the\n * bench.\n */\n request?: <T>(opts: {\n url?: string;\n uri?: string;\n signal?: AbortSignal;\n tag?: string;\n }) => Promise<T>;\n\n // --- mutate ---\n create: <T extends SanityDocumentLike>(\n doc: T,\n options?: MutationOptions,\n ) => Promise<T & SystemFields>;\n createOrReplace: <T extends SanityDocumentLike>(\n doc: T,\n options?: MutationOptions,\n ) => Promise<T & SystemFields>;\n createIfNotExists: <T extends SanityDocumentLike>(\n doc: T,\n options?: MutationOptions,\n ) => Promise<T & SystemFields>;\n delete: (id: string, options?: MutationOptions) => Promise<{ _id: string } | null>;\n patch: (documentId: string) => PatchHandle;\n transaction: () => TransactionHandle;\n /**\n * Apply a batch of mutations in the raw array form (or a `patch()` /\n * `transaction()` builder) — mirrors `@sanity/client`'s `mutate()`.\n * Atomic: any failure rolls the whole batch back. The resolved shape\n * follows `options.returnDocuments` / `returnFirst` exactly like the\n * real client (default → {@link MultipleMutationResult}).\n */\n mutate: (\n operations: FakeMutation[] | PatchHandle | TransactionHandle,\n options?: TxnCommitOptions,\n ) => Promise<TxnCommitResult>;\n\n // --- actions / releases ---\n /**\n * Dispatch one or more release / version actions against the store.\n * Returns a synthetic `transactionId`. Multi-action arrays are applied\n * atomically — any failure rolls back the batch.\n */\n action: (action: Action | Action[]) => Promise<ActionResult>;\n /** Helpers mirroring `@sanity/client`'s `client.releases.*` surface. */\n releases: ReleasesHandle;\n /** Helper for `sanity.action.document.version.create`. */\n createVersion: (params: {\n releaseId: string;\n publishedId: string;\n document: DocumentBody;\n }) => Promise<ActionResult>;\n /** Helper for `sanity.action.document.version.unpublish`. */\n unpublishVersion: (params: { releaseId: string; publishedId: string }) => Promise<ActionResult>;\n\n // --- config ---\n /** Current `(projectId, dataset)` and active perspective. */\n config: () => { projectId: string; dataset: string; perspective: Perspective };\n /**\n * Return a new client handle pointing at a different `(projectId, dataset)`\n * within the SAME backing registry. Either field can be omitted to keep\n * the current value. Two clients produced by `withConfig` see each\n * other's writes if they point at the same `(projectId, dataset)`.\n */\n withConfig: (\n config: Partial<{ projectId: string; dataset: string; perspective: Perspective }>,\n ) => TestClient;\n\n // --- test helpers (not on real SanityClient) ---\n /** Replace the current dataset with the given documents. */\n seed: (documents: SanityDocumentLike[]) => void;\n /** Add documents to the current dataset without dropping existing ones. */\n add: (documents: SanityDocumentLike[]) => void;\n /** Drop all documents in the current dataset. */\n reset: () => void;\n /** Read-only snapshot of all documents in the current dataset. */\n snapshot: () => readonly SanityDocument[];\n /** Direct store access for the current dataset. */\n store: () => TestStore;\n /** List `(projectId, dataset)` pairs known in this registry. */\n datasets: () => { projectId: string; dataset: string }[];\n /**\n * Register a handler for a `@sanity/client` member the fake doesn't\n * implement (e.g. `listen`, `assets`). Accessing that member on the\n * client then returns the handler instead of throwing the\n * \"not implemented\" guard error. Shared across sibling `withConfig`\n * handles. Stubs fill gaps only — they don't shadow implemented methods.\n */\n stub: (name: string, handler: unknown) => void;\n /** The currently-registered stubs, keyed by member name. */\n stubs: () => Record<string, unknown>;\n /**\n * Every mutation committed through this client's registry, flattened\n * and in order — `create` / `createOrReplace` / `createIfNotExists` /\n * `delete` / `patch`, whether issued directly, via `transaction()`, or\n * via `mutate()`. The spy hook for \"assert exactly what writes my code\n * submitted\".\n */\n mutations: () => TxnMutation[];\n /**\n * Every committed transaction, in order. A direct mutation is recorded\n * as a one-mutation transaction. Each entry carries its synthetic\n * `transactionId` and the `(projectId, dataset)` it targeted.\n */\n transactions: () => MutationLogEntry[];\n /** Clear the recorded mutation / transaction log. */\n clearLog: () => void;\n /**\n * Every recorded method call, in order — the spy layer for \"was `fetch`\n * called, how many times, and with what params\". Records the\n * `@sanity/client`-surface methods (`fetch`, `getDocument`, `create`,\n * `patch`, `mutate`, `releases.*`, …), not the test-only helpers.\n * Pass a method name to filter (e.g. `calls(\"fetch\")`); namespace\n * methods are dotted (`calls(\"releases.create\")`). Shared across\n * `withConfig` siblings.\n */\n calls: (method?: string) => CallRecord[];\n /** Number of recorded calls, optionally filtered by method name. */\n callCount: (method?: string) => number;\n /** Clear the recorded call log. */\n clearCalls: () => void;\n}\n\nexport interface ReleasesHandle {\n create: (params: {\n releaseId: string;\n metadata?: Partial<ReleaseMetadata>;\n }) => Promise<ActionResult & { releaseId: string; metadata: ReleaseMetadata }>;\n edit: (params: {\n releaseId: string;\n patch: { set?: Record<string, unknown>; unset?: string[] };\n }) => Promise<ActionResult>;\n get: (params: { releaseId: string }) => Promise<ReleaseDocument | undefined>;\n fetchDocuments: (params: { releaseId: string }) => Promise<SanityDocument[]>;\n schedule: (params: { releaseId: string; publishAt: string }) => Promise<ActionResult>;\n unschedule: (params: { releaseId: string }) => Promise<ActionResult>;\n publish: (params: { releaseId: string }) => Promise<ActionResult>;\n archive: (params: { releaseId: string }) => Promise<ActionResult>;\n unarchive: (params: { releaseId: string }) => Promise<ActionResult>;\n delete: (params: { releaseId: string }) => Promise<ActionResult>;\n}\n\nexport interface MutationOptions {\n ifRevisionId?: string;\n /**\n * Shape the resolved value, mirroring `@sanity/client`:\n * - default → the mutated document\n * - `returnDocuments: false` → an id-shaped mutation result\n * ({@link SingleMutationResult} / {@link MultipleMutationResult})\n * - `returnFirst: false` with documents → an array\n *\n * The static return type reflects the default (the document); pass a\n * type argument or cast when requesting an id-shaped result.\n */\n returnDocuments?: boolean;\n returnFirst?: boolean;\n /** Override the synthetic transaction id used in the result and log. */\n transactionId?: string;\n /** When `true`, validate + shape the result but don't persist. */\n dryRun?: boolean;\n /** Accepted for signature parity; not simulated. */\n visibility?: \"sync\" | \"async\" | \"deferred\";\n /** Accepted for signature parity; not simulated. */\n autoGenerateArrayKeys?: boolean;\n /** Accepted for signature parity; not simulated. */\n tag?: string;\n}\n\nexport interface SystemFields {\n _rev: string;\n _createdAt: string;\n _updatedAt: string;\n}\n\nexport interface CreateTestClientOptions {\n /** Default project id. Defaults to `\"test\"`. */\n projectId?: string;\n /** Default dataset name. Defaults to `\"test\"`. */\n dataset?: string;\n /** Documents to seed into the default `(projectId, dataset)` store. */\n documents?: SanityDocumentLike[];\n /**\n * Optional: seed multiple datasets at once. Keys are `\"projectId:dataset\"`\n * pairs. Useful when workflows span multiple datasets.\n */\n datasets?: Record<string, SanityDocumentLike[]>;\n /**\n * Opt-in access-control simulation. When set, the client exposes\n * `request({ url })` that serves `/users/me` + the configured ACL\n * path, AND every mutation is gated through the supplied `grants`\n * — writes that the grants don't permit throw a `WriteAccessDeniedError`\n * shaped like Sanity's 403. Lets tests demonstrate the full\n * \"engine soft-gate + lake hard-gate\" contract end-to-end without\n * a real HTTP round-trip.\n *\n * When omitted, `request` is undefined and all writes proceed\n * unconditionally — the legacy behavior.\n */\n accessControl?: TestClientAccessControl;\n /**\n * Default perspective applied to reads. Per-fetch `options.perspective`\n * overrides this. `withConfig({ perspective })` returns a sibling\n * handle with a different default. Defaults to `\"raw\"` so existing\n * tests stay green.\n */\n perspective?: Perspective;\n}\n\nexport type { Perspective } from \"./perspective.ts\";\nexport type {\n Action,\n ActionResult,\n DocumentBody,\n ReleaseAction,\n ReleaseDocument,\n ReleaseMetadata,\n ReleaseState,\n ReleaseType,\n VersionAction,\n} from \"./actions.ts\";\n\nexport type { TestClientAccessControl, DocumentValuePermission } from \"./access-control.ts\";\nexport { WriteAccessDeniedError } from \"./access-control.ts\";\n\nconst DEFAULT_PROJECT_ID = \"test\";\nconst DEFAULT_DATASET = \"test\";\n\ntype Registry = Map<string, TestStore>;\n\n/**\n * Shared backing context for one `createTestClient()` call and all the\n * `withConfig` siblings it spawns: the multi-dataset store registry, the\n * append-only mutation log, and the stub registry. Sibling handles see\n * each other's writes, log entries, and stubs.\n */\ninterface Backend {\n registry: Registry;\n log: MutationLogEntry[];\n stubs: Map<string, unknown>;\n calls: CallRecord[];\n}\n\nconst registryKey = (projectId: string, dataset: string) => `${projectId}:${dataset}`;\n\nconst parseRegistryKey = (key: string): { projectId: string; dataset: string } => {\n const [projectId, dataset] = key.split(\":\") as [string, string];\n return { projectId, dataset };\n};\n\n/**\n * Create a fresh, isolated test client backed by a private multi-dataset\n * registry. `withConfig` returns a sibling handle into the same registry.\n *\n * ```\n * const client = createTestClient({\n * datasets: {\n * \"test:definitions\": [...],\n * \"test:instances\": [...],\n * },\n * });\n * const defs = client.withConfig({ dataset: \"definitions\" });\n * const inst = client.withConfig({ dataset: \"instances\" });\n * ```\n */\nexport function createTestClient(options: CreateTestClientOptions = {}): TestClient {\n const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID;\n const defaultDataset = options.dataset ?? DEFAULT_DATASET;\n\n const backend: Backend = { registry: new Map(), log: [], stubs: new Map(), calls: [] };\n const registry = backend.registry;\n\n const ensureStore = (projectId: string, dataset: string): TestStore => {\n const key = registryKey(projectId, dataset);\n let store = registry.get(key);\n if (store === undefined) {\n store = createTestStore();\n registry.set(key, store);\n }\n return store;\n };\n\n // Seed defaults.\n if (options.documents) {\n ensureStore(defaultProjectId, defaultDataset).seed(options.documents);\n }\n if (options.datasets) {\n for (const [key, docs] of Object.entries(options.datasets)) {\n const { projectId, dataset } = parseRegistryKey(key);\n ensureStore(projectId, dataset).seed(docs);\n }\n }\n\n return makeHandle(\n backend,\n defaultProjectId,\n defaultDataset,\n options.accessControl,\n options.perspective ?? \"raw\",\n );\n}\n\n/** Affected ids in order, de-duplicated — the `documentIds` of a result. */\nfunction dedupeIds(results: { id: string }[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const r of results) {\n if (!seen.has(r.id)) {\n seen.add(r.id);\n out.push(r.id);\n }\n }\n return out;\n}\n\n/**\n * Resolve a mutation's return value the way `@sanity/client` does, from\n * already-resolved `returnDocuments` / `returnFirst` booleans (callers\n * apply their own defaults: document-first for create-family,\n * ids-for-all for transaction / mutate).\n */\nfunction formatMutationResult(\n documents: SanityDocument[],\n results: { id: string; operation: MutationOperation }[],\n transactionId: string,\n returnDocuments: boolean,\n returnFirst: boolean,\n): TxnCommitResult {\n if (returnDocuments) {\n return returnFirst ? (documents[0] as SanityDocument) : documents;\n }\n if (returnFirst) {\n return {\n transactionId,\n documentId: results[0]?.id as string,\n results,\n } satisfies SingleMutationResult;\n }\n return {\n transactionId,\n documentIds: dedupeIds(results),\n results,\n } satisfies MultipleMutationResult;\n}\n\n/** Convert one raw `mutate()` operation object into a {@link TxnMutation}. */\nfunction toSingleTxnMutation(op: FakeMutation): TxnMutation {\n if (\"create\" in op) return { kind: \"create\", doc: op.create };\n if (\"createOrReplace\" in op) return { kind: \"createOrReplace\", doc: op.createOrReplace };\n if (\"createIfNotExists\" in op) return { kind: \"createIfNotExists\", doc: op.createIfNotExists };\n if (\"delete\" in op) return { kind: \"delete\", id: op.delete.id };\n\n const p = op.patch;\n const ops: PatchOp[] = [];\n if (p.set !== undefined) ops.push({ kind: \"set\", props: p.set });\n if (p.setIfMissing !== undefined) ops.push({ kind: \"setIfMissing\", props: p.setIfMissing });\n if (p.unset !== undefined) ops.push({ kind: \"unset\", paths: p.unset });\n if (p.inc !== undefined) ops.push({ kind: \"inc\", props: p.inc });\n if (p.dec !== undefined) ops.push({ kind: \"dec\", props: p.dec });\n if (p.insert !== undefined) {\n const { before, after, replace, items } = p.insert;\n const position = before !== undefined ? \"before\" : after !== undefined ? \"after\" : \"replace\";\n const anchor = before ?? after ?? replace;\n if (anchor === undefined) {\n throw fakeError(\n \"mutate(): a `patch.insert` operation must name exactly one anchor — `before`, `after`, \" +\n 'or `replace` — pointing at an array path (e.g. \"tags[-1]\" or `tags[_key==\"x\"]`), ' +\n \"alongside `items`. None was set.\",\n );\n }\n ops.push({ kind: \"insert\", position, anchor, items });\n }\n return {\n kind: \"patch\",\n documentId: p.id,\n ops,\n ...(p.ifRevisionID !== undefined ? { ifRev: p.ifRevisionID } : {}),\n };\n}\n\n/** Normalise `mutate()` input (raw array, Patch, or Transaction) to mutations. */\nfunction toTxnMutations(\n operations: FakeMutation[] | PatchHandle | TransactionHandle,\n): TxnMutation[] {\n if (Array.isArray(operations)) return operations.map(toSingleTxnMutation);\n // Both builders expose toJSON(); a Transaction yields an array, a Patch\n // yields a single `{ id, ops, ifRev? }`.\n const json = operations.toJSON();\n if (Array.isArray(json)) return json;\n return [\n {\n kind: \"patch\",\n documentId: json.id,\n ops: json.ops,\n ...(json.ifRev !== undefined ? { ifRev: json.ifRev } : {}),\n },\n ];\n}\n\nfunction makeHandle(\n backend: Backend,\n projectId: string,\n dataset: string,\n accessControl: TestClientAccessControl | undefined,\n perspective: Perspective,\n): TestClient {\n const { registry } = backend;\n const store = (() => {\n const key = registryKey(projectId, dataset);\n let s = registry.get(key);\n if (s === undefined) {\n s = createTestStore();\n registry.set(key, s);\n }\n return s;\n })();\n\n /** Append a committed transaction to the shared log. */\n const record = (transactionId: string, mutations: TxnMutation[]): void => {\n backend.log.push({ transactionId, projectId, dataset, mutations });\n };\n\n /**\n * Shape a single-document write result. Create-family methods default\n * to returning the document (first), unlike transaction / mutate.\n */\n const writeResult = (\n documents: SanityDocument[],\n results: { id: string; operation: MutationOperation }[],\n transactionId: string,\n opts: MutationOptions | undefined,\n ): TxnCommitResult =>\n formatMutationResult(\n documents,\n results,\n transactionId,\n opts?.returnDocuments ?? true,\n opts?.returnFirst ?? true,\n );\n\n const promote = (doc: SanityDocumentLike): SanityDocument & SystemFields => {\n const now = new Date().toISOString();\n if (typeof doc._id !== \"string\" || doc._id.length === 0) {\n throw fakeError(\n `Cannot store a document without a non-empty string \\`_id\\` (got ${JSON.stringify(doc._id)}). ` +\n `Unlike @sanity/client, this fake never auto-generates ids — give every document an explicit _id.`,\n );\n }\n if (typeof doc._type !== \"string\" || doc._type.length === 0) {\n throw fakeError(\n `Document \"${doc._id}\" is missing a non-empty string \\`_type\\` (got ${JSON.stringify(doc._type)}). ` +\n `Every Sanity document needs a _type.`,\n );\n }\n return {\n ...doc,\n _id: doc._id,\n _type: doc._type,\n _rev: cryptoRandomKey(),\n _createdAt: doc._createdAt ?? now,\n _updatedAt: now,\n } as SanityDocument & SystemFields;\n };\n\n const checkRevision = (id: string, ifRevisionId: string | undefined) => {\n if (ifRevisionId === undefined) return;\n const existing = store.get(id);\n if (existing === undefined) {\n throw fakeError(\n `ifRevisionId check failed: document \"${id}\" does not exist, so its revision cannot match ` +\n `the expected _rev=\"${ifRevisionId}\". Drop ifRevisionId when creating a new document, or ` +\n `seed/create the document before guarding on its revision.`,\n );\n }\n if (existing._rev !== ifRevisionId) {\n throw fakeError(\n `ifRevisionId check failed: document \"${id}\" is at _rev=\"${existing._rev}\" but the mutation ` +\n `required _rev=\"${ifRevisionId}\". The document changed since you read it — re-read it and ` +\n `retry. (This mirrors Sanity's optimistic-locking 409.)`,\n );\n }\n };\n\n /**\n * Gate a mutation through the configured `accessControl.grants`. No-op\n * when accessControl is absent (legacy bench behavior). On denial\n * throws `WriteAccessDeniedError` — same failure mode tests get from\n * a real Sanity 403.\n *\n * Pass the doc as-it-would-be at evaluation time: for `create` /\n * `createOrReplace`-as-create / `createIfNotExists`, that's the new\n * doc with its incoming fields; for `update` / `patch` / `delete`,\n * that's the existing doc (the grant filter identifies what the\n * actor can touch).\n */\n const gate = async (\n document: SanityDocumentLike & { _id?: string; _type?: string },\n permission: DocumentValuePermission,\n ): Promise<void> => {\n if (accessControl === undefined) return;\n await enforceWriteAccess({\n document,\n grants: accessControl.grants,\n permission,\n userId: accessControl.currentUser.id,\n });\n };\n\n /**\n * Read-gate predicate. Sanity surfaces invisible docs as \"doesn't\n * exist\" on the wire (404 / null) rather than throwing 403 — so\n * reads filter rather than refuse.\n *\n * - `fetch` filters the dataset before running GROQ.\n * - `getDocument` / `getDocuments` return null for invisible docs.\n * - `snapshot` is a test-helper that bypasses the read gate\n * intentionally (tests need raw inspection).\n *\n * Returns `true` when accessControl is absent (no gating).\n */\n const canRead = async (\n document: SanityDocumentLike & { _id?: string; _type?: string },\n ): Promise<boolean> => {\n if (accessControl === undefined) return true;\n return canAccess({\n document,\n grants: accessControl.grants,\n permission: \"read\",\n userId: accessControl.currentUser.id,\n });\n };\n\n const applyPatch = async (\n documentId: string,\n ops: PatchOp[],\n ifRev: string | undefined,\n ): Promise<SanityDocument> => {\n const existing = store.get(documentId);\n if (existing === undefined) {\n throw fakeError(\n `Cannot patch document \"${documentId}\": not found — no document with that _id exists in ` +\n `dataset \"${projectId}:${dataset}\". patch() requires the target to already exist; use ` +\n `createOrReplace() / createIfNotExists() to upsert, or seed the document first.`,\n );\n }\n checkRevision(documentId, ifRev);\n // Gate against the existing doc — that's what the grant filter\n // matches: \"what docs can this actor update?\".\n await gate(existing, \"update\");\n const patched = applyPatchOps(existing, ops);\n const now = new Date().toISOString();\n const next: SanityDocument = {\n ...patched,\n _rev: cryptoRandomKey(),\n _updatedAt: now,\n };\n store.put(next);\n return next;\n };\n\n const applyTransaction = async (\n mutations: TxnMutation[],\n txnOptions?: TxnCommitOptions,\n ): Promise<TxnCommitResult> => {\n const transactionId = txnOptions?.transactionId ?? cryptoRandomKey();\n const snapshot = new Map<string, SanityDocument | undefined>();\n const touchedIds: string[] = [];\n const operations: { id: string; operation: MutationOperation }[] = [];\n\n const remember = (id: string) => {\n if (!snapshot.has(id)) snapshot.set(id, store.get(id));\n };\n\n try {\n for (const mut of mutations) {\n switch (mut.kind) {\n case \"create\": {\n remember(mut.doc._id as string);\n const promoted = promote(mut.doc);\n if (store.get(promoted._id) !== undefined) {\n throw fakeError(\n `create() failed: a document with _id \"${promoted._id}\" already exists in dataset ` +\n `\"${projectId}:${dataset}\". Use createOrReplace() to overwrite it, or ` +\n `createIfNotExists() to leave the existing one untouched.`,\n );\n }\n await gate(promoted, \"create\");\n store.put(promoted);\n touchedIds.push(promoted._id);\n operations.push({ id: promoted._id, operation: \"create\" });\n break;\n }\n case \"createOrReplace\": {\n remember(mut.doc._id as string);\n const promoted = promote(mut.doc);\n const existing = store.get(promoted._id);\n // For an existing doc, \"update\" is the relevant permission;\n // for a net-new one, \"create\".\n await gate(existing ?? promoted, existing !== undefined ? \"update\" : \"create\");\n const wasPresent = existing !== undefined;\n store.put(promoted);\n touchedIds.push(promoted._id);\n operations.push({ id: promoted._id, operation: wasPresent ? \"update\" : \"create\" });\n break;\n }\n case \"createIfNotExists\": {\n remember(mut.doc._id as string);\n if (store.get(mut.doc._id as string) === undefined) {\n const promoted = promote(mut.doc);\n await gate(promoted, \"create\");\n store.put(promoted);\n touchedIds.push(promoted._id);\n operations.push({ id: promoted._id, operation: \"create\" });\n }\n break;\n }\n case \"delete\": {\n remember(mut.id);\n const existing = store.get(mut.id);\n // Sanity's permission model has no separate \"delete\" —\n // delete is gated as an update against the existing doc.\n if (existing !== undefined) await gate(existing, \"update\");\n const removed = store.remove(mut.id);\n if (removed) {\n touchedIds.push(mut.id);\n operations.push({ id: mut.id, operation: \"delete\" });\n }\n break;\n }\n case \"patch\": {\n remember(mut.documentId);\n // applyPatch already gates internally.\n await applyPatch(mut.documentId, mut.ops, mut.ifRev);\n touchedIds.push(mut.documentId);\n operations.push({ id: mut.documentId, operation: \"update\" });\n break;\n }\n }\n }\n } catch (error) {\n for (const [id, doc] of snapshot) {\n if (doc === undefined) {\n store.remove(id);\n } else {\n store.put(doc);\n }\n }\n throw error;\n }\n\n // A committed transaction is logged whole; a single-mutation form\n // (create / patch / mutate of one op) lands as a one-entry transaction.\n record(transactionId, mutations);\n\n const documents = touchedIds\n .map((id) => store.get(id))\n .filter((d): d is SanityDocument => d !== undefined);\n // Transaction / mutate default to the id-shaped `MultipleMutationResult`,\n // matching `@sanity/client` (create-family defaults differ).\n return formatMutationResult(\n documents,\n operations,\n transactionId,\n txnOptions?.returnDocuments ?? false,\n txnOptions?.returnFirst ?? false,\n );\n };\n\n /**\n * Filter the store's docs to only those `canRead` returns true\n * for. When accessControl is unset, returns the full set (no\n * filtering cost). Used by `fetch` so GROQ runs against the\n * actor-visible subset, matching Sanity's per-token query behavior.\n */\n const accessVisibleDocs = async (): Promise<SanityDocument[]> => {\n const all = store.all();\n if (accessControl === undefined) return all;\n const out: SanityDocument[] = [];\n for (const doc of all) {\n if (await canRead(doc)) out.push(doc);\n }\n return out;\n };\n\n /**\n * Apply both access-control gating and perspective layering. The order\n * matters: access first (an invisible doc shouldn't even be a candidate\n * for perspective layering), perspective second (which can hide / merge\n * docs that the actor would otherwise see).\n */\n const visibleDocs = async (override?: Perspective): Promise<SanityDocument[]> => {\n const accessible = await accessVisibleDocs();\n return applyPerspective(accessible, override ?? perspective);\n };\n\n const client: TestClient = {\n fetch: async (query, params, opts) => {\n const start = Date.now();\n const tree = parse(query, params ? { params } : undefined);\n const value = await evaluate(tree, {\n dataset: await visibleDocs(opts?.perspective),\n ...(params !== undefined ? { params } : {}),\n });\n const result = await value.get();\n if (opts?.filterResponse === false) {\n const ms = Date.now() - start;\n const raw = opts.returnQuery === false ? { ms, result } : { query, ms, result };\n return raw as never;\n }\n return result as never;\n },\n\n getDocument: async (id, opts) => {\n const effective = opts?.perspective ?? perspective;\n if (effective === \"raw\") {\n const doc = store.get(id);\n if (doc === undefined) return undefined;\n if (!(await canRead(doc))) return undefined;\n return doc as never;\n }\n const view = await visibleDocs(effective);\n const found = resolveDocument(view, id, effective);\n return (found ?? undefined) as never;\n },\n\n getDocuments: async (ids, opts) => {\n const effective = opts?.perspective ?? perspective;\n if (effective === \"raw\") {\n const result: (SanityDocument | null)[] = [];\n for (const id of ids) {\n const doc = store.get(id);\n if (doc === undefined) result.push(null);\n else if (await canRead(doc)) result.push(doc);\n else result.push(null);\n }\n return result as never;\n }\n const view = await visibleDocs(effective);\n return ids.map((id) => resolveDocument(view, id, effective) ?? null) as never;\n },\n\n create: async (doc, opts) => {\n checkRevision(doc._id as string, opts?.ifRevisionId);\n if (store.get(doc._id as string) !== undefined) {\n throw fakeError(\n `create() failed: a document with _id \"${doc._id}\" already exists in dataset ` +\n `\"${projectId}:${dataset}\". Use createOrReplace() to overwrite it, or ` +\n `createIfNotExists() to leave the existing one untouched.`,\n );\n }\n const promoted = promote(doc);\n await gate(promoted, \"create\");\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n if (opts?.dryRun !== true) {\n store.put(promoted);\n record(transactionId, [{ kind: \"create\", doc }]);\n }\n return writeResult(\n [promoted],\n [{ id: promoted._id, operation: \"create\" }],\n transactionId,\n opts,\n ) as never;\n },\n\n createOrReplace: async (doc, opts) => {\n checkRevision(doc._id as string, opts?.ifRevisionId);\n const promoted = promote(doc);\n const existing = store.get(doc._id as string);\n await gate(existing ?? promoted, existing !== undefined ? \"update\" : \"create\");\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n if (opts?.dryRun !== true) {\n store.put(promoted);\n record(transactionId, [{ kind: \"createOrReplace\", doc }]);\n }\n const operation: MutationOperation = existing !== undefined ? \"update\" : \"create\";\n return writeResult(\n [promoted],\n [{ id: promoted._id, operation }],\n transactionId,\n opts,\n ) as never;\n },\n\n createIfNotExists: async (doc, opts) => {\n checkRevision(doc._id as string, opts?.ifRevisionId);\n const existing = store.get(doc._id as string);\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n if (existing !== undefined) {\n return writeResult(\n [existing],\n [{ id: existing._id, operation: \"none\" }],\n transactionId,\n opts,\n ) as never;\n }\n const promoted = promote(doc);\n await gate(promoted, \"create\");\n if (opts?.dryRun !== true) {\n store.put(promoted);\n record(transactionId, [{ kind: \"createIfNotExists\", doc }]);\n }\n return writeResult(\n [promoted],\n [{ id: promoted._id, operation: \"create\" }],\n transactionId,\n opts,\n ) as never;\n },\n\n delete: async (id, opts) => {\n checkRevision(id, opts?.ifRevisionId);\n const existing = store.get(id);\n if (existing !== undefined) await gate(existing, \"update\");\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n let removed: SanityDocument | undefined = existing;\n if (opts?.dryRun !== true) {\n removed = store.remove(id);\n if (removed !== undefined) record(transactionId, [{ kind: \"delete\", id }]);\n }\n // Legacy default shape ({ _id } | null) unless the caller asked for\n // a specific return shape via returnDocuments / returnFirst.\n if (opts?.returnDocuments === undefined && opts?.returnFirst === undefined) {\n return (removed !== undefined ? { _id: id } : null) as never;\n }\n const results = removed !== undefined ? [{ id, operation: \"delete\" as const }] : [];\n const docs = removed !== undefined ? [removed] : [];\n return formatMutationResult(\n docs,\n results,\n transactionId,\n opts.returnDocuments ?? true,\n opts.returnFirst ?? true,\n ) as never;\n },\n\n patch: (documentId) =>\n createPatch(documentId, {\n apply: async (docId, ops, ifRev) => {\n const doc = await applyPatch(docId, ops, ifRev);\n record(cryptoRandomKey(), [\n { kind: \"patch\", documentId: docId, ops, ...(ifRev !== undefined ? { ifRev } : {}) },\n ]);\n return doc;\n },\n }),\n\n transaction: () => createTransaction({ apply: applyTransaction }),\n\n mutate: async (operations, options) => applyTransaction(toTxnMutations(operations), options),\n\n action: async (action) => applyActions(store, action),\n\n releases: {\n create: async ({ releaseId, metadata }) => {\n const result = applyActions(store, {\n actionType: \"sanity.action.release.create\",\n releaseId,\n ...(metadata !== undefined ? { metadata } : {}),\n });\n const doc = store.get(`_.releases.${releaseId}`) as ReleaseDocument | undefined;\n return {\n ...result,\n releaseId,\n metadata: doc?.metadata ?? { releaseType: \"undecided\" },\n };\n },\n edit: async ({ releaseId, patch }) =>\n applyActions(store, { actionType: \"sanity.action.release.edit\", releaseId, patch }),\n get: async ({ releaseId }) => {\n const doc = store.get(`_.releases.${releaseId}`) as ReleaseDocument | undefined;\n return doc;\n },\n fetchDocuments: async ({ releaseId }) => {\n const prefix = `versions.${releaseId}.`;\n return store.all().filter((d) => d._id.startsWith(prefix));\n },\n schedule: async ({ releaseId, publishAt }) =>\n applyActions(store, {\n actionType: \"sanity.action.release.schedule\",\n releaseId,\n publishAt,\n }),\n unschedule: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.unschedule\", releaseId }),\n publish: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.publish\", releaseId }),\n archive: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.archive\", releaseId }),\n unarchive: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.unarchive\", releaseId }),\n delete: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.delete\", releaseId }),\n },\n\n createVersion: async ({ releaseId, publishedId, document }) =>\n applyActions(store, {\n actionType: \"sanity.action.document.version.create\",\n releaseId,\n publishedId,\n document,\n }),\n\n unpublishVersion: async ({ releaseId, publishedId }) =>\n applyActions(store, {\n actionType: \"sanity.action.document.version.unpublish\",\n versionId: `versions.${releaseId}.${publishedId}`,\n publishedId,\n }),\n\n ...(accessControl !== undefined\n ? { request: makeRequestImpl(accessControl, projectId, dataset) }\n : {}),\n\n config: () => ({ projectId, dataset, perspective }),\n\n withConfig: (config) =>\n makeHandle(\n backend,\n config.projectId ?? projectId,\n config.dataset ?? dataset,\n accessControl,\n config.perspective ?? perspective,\n ),\n\n seed: (documents) => store.seed(documents),\n add: (documents) => store.add(documents),\n reset: () => store.reset(),\n snapshot: () => store.snapshot(),\n store: () => store,\n datasets: () => [...registry.keys()].map(parseRegistryKey),\n stub: (name, handler) => {\n backend.stubs.set(name, handler);\n },\n stubs: () => Object.fromEntries(backend.stubs),\n mutations: () => backend.log.flatMap((entry) => entry.mutations),\n transactions: () => [...backend.log],\n clearLog: () => {\n backend.log.length = 0;\n },\n calls: (method) =>\n method === undefined ? [...backend.calls] : backend.calls.filter((c) => c.method === method),\n callCount: (method) =>\n method === undefined\n ? backend.calls.length\n : backend.calls.filter((c) => c.method === method).length,\n clearCalls: () => {\n backend.calls.length = 0;\n },\n };\n\n // Record an invocation: capture args now, fill the outcome on settle.\n const onCall = (method: string, args: unknown[]): CallSettler => {\n const rec: CallRecord = { method, args, projectId, dataset };\n backend.calls.push(rec);\n return (outcome) => {\n if (\"error\" in outcome) rec.error = outcome.error;\n else rec.result = outcome.result;\n };\n };\n\n // Wrap so unimplemented members fail with actionable errors, registered\n // stubs are served, and surface-method calls are recorded (see\n // ./unsupported.ts).\n return wrapWithGuards(client, {\n getStub: (name) => backend.stubs.get(name),\n onCall,\n recorded: RECORDED_METHODS,\n });\n}\n"],"names":["promote","RELEASE_DOC_PREFIX","VERSIONS_PREFIX"],"mappings":";AAWO,MAAM,aAAa;AAGnB,SAAS,UAAU,SAAwB;AAChD,SAAO,IAAI,MAAM,GAAG,UAAU,IAAI,OAAO,EAAE;AAC7C;ACoDO,MAAM,+BAA+B,MAAM;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAIT;AACD;AAAA,MACE,wDAAmD,KAAK,UAAU,kBAAkB,KAAK,UAAU,MAC7F,KAAK,cAAc,SAAS,KAAK,mBAAmB,IAAI,KAAK,GAAG,4CAClD,KAAK,UAAU;AAAA,IAAA,GAErC,KAAK,OAAO,0BACZ,KAAK,aAAa,KAAK,YACvB,KAAK,aAAa,KAAK,YACvB,KAAK,iBAAiB,KAAK;AAAA,EAC7B;AACF;AAWA,eAAsB,UAAU,MAKX;AAEnB,UADe,MAAM,oBAAoB,IAAI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H;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/errors.ts","../src/access-control.ts","../src/store.ts","../src/patch.ts","../src/actions.ts","../src/perspective.ts","../src/transaction.ts","../src/unsupported.ts","../src/client.ts"],"sourcesContent":["/**\n * Error helpers shared across the fake.\n *\n * Every error the fake throws is prefixed with {@link ERR_PREFIX} so it's\n * unmistakably attributable to *this fake* — not to `@sanity/client`,\n * groq-js, or the code under test — and carries enough context to fix\n * the problem without reading the fake's source. Short, bare messages\n * (\"not found\", \"invalid id\") are a poor developer experience in a test\n * double: prefer stating what happened, the offending value, and what to\n * do about it.\n */\nexport const ERR_PREFIX = \"[client-fake-for-test]\";\n\n/** Build a prefixed Error. Pass a fully-formed, dev-facing message. */\nexport function fakeError(message: string): Error {\n return new Error(`${ERR_PREFIX} ${message}`);\n}\n","/**\n * Optional access-control simulation for the in-memory test client.\n *\n * When configured, the TestClient does two things a real `@sanity/client`\n * does over the wire but the bare in-memory client otherwise skips:\n *\n * 1. **Exposes `client.request({ url })`** that serves:\n * - `GET /users/me` → the configured `CurrentUser`\n * - `GET <aclPath>` → the configured `Grant[]`\n * This is what the engine reads from to resolve `WorkflowAccess`\n * when no override is passed.\n *\n * 2. **Gates writes through the configured grants.** Every mutation\n * (`create`, `createOrReplace`, `createIfNotExists`, `delete`,\n * `patch`, and per-op inside `transaction`) checks whether the\n * configured grants allow the relevant `DocumentValuePermission`\n * on the target document. On denial the client throws a\n * `WriteAccessDeniedError` shaped like Sanity's 403 — the same\n * failure mode a production write would hit, surfaced in tests.\n *\n * When `accessControl` is omitted, the client behaves as before:\n * `request` is undefined, writes are unconditional, and the engine\n * falls through to whatever override the caller (typically the\n * bench's `ALL_ACCESS`) provides.\n *\n * The grant evaluation runs the GROQ filter on a singleton dataset\n * containing the doc being checked — same shape as the engine's\n * `permissions.matchesFilter`, lifted from canvas.\n */\n\nimport type { SanityDocumentLike } from \"@sanity/types\";\nimport { evaluate, parse } from \"groq-js\";\nimport { fakeError } from \"./errors.ts\";\n\nexport type DocumentValuePermission = \"create\" | \"read\" | \"update\";\n\nexport interface CurrentUser {\n id: string;\n name?: string;\n email?: string;\n /** @deprecated singular `role` on legacy responses */\n role?: string;\n roles?: { name: string; title?: string; description?: string }[];\n}\n\nexport interface Grant {\n filter: string;\n permissions: DocumentValuePermission[];\n}\n\nexport interface TestClientAccessControl {\n /** What `client.request({ url: \"/users/me\" })` returns. */\n currentUser: CurrentUser;\n /** What `client.request({ url: aclPath })` returns. */\n grants: Grant[];\n /**\n * URL path the engine's access resolver hits to fetch grants.\n * Defaults to `/projects/<projectId>/datasets/<dataset>/acl`.\n */\n aclPath?: string;\n}\n\n/**\n * Sanity-style 403 raised when a configured-grants check rejects a\n * write. The thrown object carries the doc id, the attempted\n * permission, and the count of matching grants (for parity with the\n * engine's `permission-denied` disabled-reason).\n */\nexport class WriteAccessDeniedError extends Error {\n readonly documentId: string;\n readonly permission: DocumentValuePermission;\n readonly matchingGrants: number;\n\n constructor(args: {\n documentId: string;\n permission: DocumentValuePermission;\n matchingGrants: number;\n }) {\n super(\n `Sanity (test): permission denied — actor lacks \"${args.permission}\" on document \"${args.documentId}\" ` +\n `(${args.matchingGrants} grant${args.matchingGrants === 1 ? \"\" : \"s\"} matched the document but ` +\n `none included \"${args.permission}\").`,\n );\n this.name = \"WriteAccessDeniedError\";\n this.documentId = args.documentId;\n this.permission = args.permission;\n this.matchingGrants = args.matchingGrants;\n }\n}\n\n/**\n * Predicate variant of `evaluateWriteAccess` — same logic but only\n * returns the boolean. Used by read-gating paths\n * (`fetch`/`getDocument`/`getDocuments`) where the documented Sanity\n * behavior is \"invisible doc → 404\", not \"throw 403\". So callers\n * can filter the dataset before GROQ runs and return `null` from\n * single-doc reads, instead of leaking a denial through the read\n * surface.\n */\nexport async function canAccess(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n grants: Grant[];\n permission: DocumentValuePermission;\n userId: string;\n}): Promise<boolean> {\n const result = await evaluateWriteAccess(args);\n return result.allowed;\n}\n\n// Parsed-filter cache. The GROQ AST is cheap to reuse; only the\n// per-document evaluation needs to re-run.\nconst parsedFilters = new Map<string, ReturnType<typeof parse>>();\n\nasync function matchesFilter(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n filter: string;\n userId: string;\n}): Promise<boolean> {\n const { document, filter, userId } = args;\n if (!parsedFilters.has(filter)) {\n parsedFilters.set(filter, parse(`*[${filter}]`));\n }\n const ast = parsedFilters.get(filter)!;\n const result = await evaluate(ast, {\n dataset: [document as Record<string, unknown>],\n identity: userId,\n });\n const data = await result.get();\n return Array.isArray(data) && data.length === 1;\n}\n\n/**\n * Resolve whether `grants` allow `permission` on `document` for the\n * given user. Same logic the engine uses in `permissions.grantsPermissionOn`\n * (most-permissive wins; multiple grants compose).\n *\n * Returns `{ allowed: boolean, matchingGrants: number }` so callers\n * can build the structured error without re-counting.\n */\nexport async function evaluateWriteAccess(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n grants: Grant[];\n permission: DocumentValuePermission;\n userId: string;\n}): Promise<{ allowed: boolean; matchingGrants: number }> {\n const { document, grants, permission, userId } = args;\n let matching = 0;\n for (const grant of grants) {\n if (\n await matchesFilter({\n document,\n filter: grant.filter,\n userId,\n })\n ) {\n matching++;\n if (grant.permissions.includes(permission)) {\n return { allowed: true, matchingGrants: matching };\n }\n }\n }\n return { allowed: false, matchingGrants: matching };\n}\n\n/**\n * Throw a `WriteAccessDeniedError` if `grants` don't permit the\n * supplied `permission` on `document`. No-op when allowed. Use this\n * from every mutation entrypoint that wants to simulate Sanity's\n * write boundary.\n */\nexport async function enforceWriteAccess(args: {\n document: SanityDocumentLike & { _id?: string; _type?: string };\n grants: Grant[];\n permission: DocumentValuePermission;\n userId: string;\n}): Promise<void> {\n const { document, grants, permission, userId } = args;\n const { allowed, matchingGrants } = await evaluateWriteAccess({\n document,\n grants,\n permission,\n userId,\n });\n if (allowed) return;\n if (typeof document._id !== \"string\") {\n throw new WriteAccessDeniedError({\n documentId: \"(unknown)\",\n permission,\n matchingGrants,\n });\n }\n throw new WriteAccessDeniedError({\n documentId: document._id,\n permission,\n matchingGrants,\n });\n}\n\n/**\n * Default ACL path the engine pulls grants from. Mirrors Sanity's\n * project/dataset ACL endpoint. Callers can override via\n * `accessControl.aclPath`.\n */\nexport function defaultAclPath(projectId: string, dataset: string): string {\n return `/projects/${projectId}/datasets/${dataset}/acl`;\n}\n\n/**\n * Internal helper: turn the `accessControl` config into the bound\n * `request` function the client exposes, plus a helper to gate writes.\n * Returns `undefined` when no config — leaves `request` off so the\n * engine's \"no token available\" path triggers (which is the cue for\n * the bench to supply an `access` override).\n */\nexport function makeRequestImpl(\n accessControl: TestClientAccessControl,\n projectId: string,\n dataset: string,\n): <T>(opts: { url?: string; uri?: string; signal?: AbortSignal; tag?: string }) => Promise<T> {\n const aclPath = accessControl.aclPath ?? defaultAclPath(projectId, dataset);\n return async <T>(opts: {\n url?: string;\n uri?: string;\n signal?: AbortSignal;\n tag?: string;\n }): Promise<T> => {\n // `@sanity/client` distinguishes `uri` (project-scoped, e.g.\n // `/users/me`) from `url` (raw). Studio uses `uri` for global\n // endpoints. Treat both identically for the mock.\n const path = opts.uri ?? opts.url;\n if (path === \"/users/me\") {\n return accessControl.currentUser as unknown as T;\n }\n if (path === aclPath) {\n return accessControl.grants as unknown as T;\n }\n throw fakeError(\n `request(): no handler for path \"${path}\". With accessControl configured, the fake only serves ` +\n `\"/users/me\" and \"${aclPath}\". For any other endpoint, register a stub ` +\n `(client.stub(\"request\", fn)) or intercept the HTTP call with a tool like MSW.`,\n );\n };\n}\n","import type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport { fakeError } from \"./errors.ts\";\n\n/**\n * In-memory document store backing a TestClient. Closure-scoped — created\n * fresh per test, no global state.\n *\n * The shape mirrors what `groq-js` evaluates against: an array of\n * documents. Internally we keep a Map by `_id` for O(1) lookup, and\n * project to an array on each query.\n */\nexport interface TestStore {\n /** Replace the entire dataset with the given documents. Existing docs are dropped. */\n seed: (documents: SanityDocumentLike[]) => void;\n /** Add documents without dropping existing ones. Conflicts (same _id) overwrite. */\n add: (documents: SanityDocumentLike[]) => void;\n /** Remove all documents. */\n reset: () => void;\n /** All documents as an array, in insertion order. */\n all: () => SanityDocument[];\n /** Get one document by _id, or undefined. */\n get: (id: string) => SanityDocument | undefined;\n /** Insert a fully-formed document by _id. Replaces if it already exists. */\n put: (doc: SanityDocument) => void;\n /** Remove a document by _id. Returns the removed doc or undefined. */\n remove: (id: string) => SanityDocument | undefined;\n /** Snapshot of all docs, useful for assertions. */\n snapshot: () => readonly SanityDocument[];\n}\n\n/**\n * Create a fresh, isolated store. The returned object closes over a private\n * Map; two stores created from two calls do not see each other.\n */\nexport function createTestStore(initial?: SanityDocumentLike[]): TestStore {\n const docs = new Map<string, SanityDocument>();\n\n const promote = (doc: SanityDocumentLike): SanityDocument => {\n if (typeof doc._id !== \"string\" || doc._id.length === 0) {\n throw fakeError(\n `Cannot seed/store a document without a non-empty string \\`_id\\` (got ${JSON.stringify(doc._id)}). ` +\n `This fake never auto-generates ids — give every document an explicit _id. Document: ${JSON.stringify(doc)}`,\n );\n }\n if (typeof doc._type !== \"string\" || doc._type.length === 0) {\n throw fakeError(\n `Document \"${doc._id}\" is missing a non-empty string \\`_type\\` (got ${JSON.stringify(doc._type)}). ` +\n `Every Sanity document needs a _type.`,\n );\n }\n const now = new Date().toISOString();\n return {\n ...doc,\n _id: doc._id,\n _type: doc._type,\n _rev: doc._rev ?? cryptoRandomKey(),\n _createdAt: doc._createdAt ?? now,\n _updatedAt: doc._updatedAt ?? now,\n } as SanityDocument;\n };\n\n const seed = (documents: SanityDocumentLike[]) => {\n docs.clear();\n for (const d of documents) {\n const promoted = promote(d);\n docs.set(promoted._id, promoted);\n }\n };\n\n if (initial) seed(initial);\n\n return {\n seed,\n add: (documents) => {\n for (const d of documents) {\n const promoted = promote(d);\n docs.set(promoted._id, promoted);\n }\n },\n reset: () => docs.clear(),\n all: () => [...docs.values()],\n get: (id) => docs.get(id),\n put: (doc) => {\n docs.set(doc._id, doc);\n },\n remove: (id) => {\n const doc = docs.get(id);\n if (doc) docs.delete(id);\n return doc;\n },\n snapshot: () => [...docs.values()],\n };\n}\n\n/**\n * Generate a stable-ish random key without pulling in a dependency.\n * Use cases: synthesising `_rev` for newly-stored documents.\n */\nexport function cryptoRandomKey(length = 12): string {\n const bytes = new Uint8Array(length);\n // globalThis.crypto is available in Node 22+ and all modern browsers.\n globalThis.crypto.getRandomValues(bytes);\n return [...bytes]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")\n .slice(0, length);\n}\n","import type { SanityDocument } from \"@sanity/types\";\nimport { fakeError } from \"./errors.ts\";\n\n/** Human-readable type of a value, for \"expected an array but got …\" errors. */\nfunction describeType(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return `a ${typeof value}`;\n}\n\n/**\n * Patch operations the test client supports.\n *\n * Subset of `@sanity/client`'s PatchOperations. Each entry is one\n * mutation step applied in order at commit time.\n */\nexport type PatchOp =\n | { kind: \"set\"; props: Record<string, unknown> }\n | { kind: \"setIfMissing\"; props: Record<string, unknown> }\n | { kind: \"unset\"; paths: string[] }\n | { kind: \"inc\"; props: Record<string, number> }\n | { kind: \"dec\"; props: Record<string, number> }\n | {\n kind: \"insert\";\n position: \"before\" | \"after\" | \"replace\";\n anchor: string;\n items: unknown[];\n };\n\nexport interface PatchHandle {\n set: (props: Record<string, unknown>) => PatchHandle;\n setIfMissing: (props: Record<string, unknown>) => PatchHandle;\n unset: (paths: string[]) => PatchHandle;\n inc: (props: Record<string, number>) => PatchHandle;\n dec: (props: Record<string, number>) => PatchHandle;\n insert: (\n position: \"before\" | \"after\" | \"replace\",\n anchor: string,\n items: unknown[],\n ) => PatchHandle;\n ifRevisionId: (rev: string) => PatchHandle;\n commit: () => Promise<SanityDocument>;\n /** Test-only introspection — not on real Patch */\n toJSON: () => { id: string; ops: PatchOp[]; ifRev?: string };\n}\n\nexport interface PatchExecutor {\n apply: (documentId: string, ops: PatchOp[], ifRev: string | undefined) => Promise<SanityDocument>;\n}\n\nexport function createPatch(documentId: string, executor: PatchExecutor): PatchHandle {\n const ops: PatchOp[] = [];\n let ifRev: string | undefined;\n\n const handle: PatchHandle = {\n set: (props) => {\n ops.push({ kind: \"set\", props });\n return handle;\n },\n setIfMissing: (props) => {\n ops.push({ kind: \"setIfMissing\", props });\n return handle;\n },\n unset: (paths) => {\n ops.push({ kind: \"unset\", paths });\n return handle;\n },\n inc: (props) => {\n ops.push({ kind: \"inc\", props });\n return handle;\n },\n dec: (props) => {\n ops.push({ kind: \"dec\", props });\n return handle;\n },\n insert: (position, anchor, items) => {\n ops.push({ kind: \"insert\", position, anchor, items });\n return handle;\n },\n ifRevisionId: (rev) => {\n ifRev = rev;\n return handle;\n },\n commit: () => executor.apply(documentId, ops, ifRev),\n toJSON: () => ({\n id: documentId,\n ops: [...ops],\n ...(ifRev !== undefined ? { ifRev } : {}),\n }),\n };\n\n return handle;\n}\n\n/**\n * Apply an ordered list of patch ops to a document, returning the new doc.\n *\n * The path semantics are deliberately a small subset:\n *\n * - **Dotted paths** (`a.b.c`) for nested object fields.\n * - **Array index** (`a.b[0]`) for positional access into arrays.\n * - **Keyed lookup** (`a.b[_key==\"x\"]`) for finding an array entry by `_key`.\n *\n * Anything more exotic (recursive `..`, GROQ filter expressions, multi-match)\n * is intentionally out of scope and will throw — the workflow engine only\n * needs the three forms above.\n */\nexport function applyPatchOps(doc: SanityDocument, ops: PatchOp[]): SanityDocument {\n let next: SanityDocument = structuredClone(doc);\n for (const op of ops) {\n next = applyOne(next, op);\n }\n return next;\n}\n\nfunction applyOne(doc: SanityDocument, op: PatchOp): SanityDocument {\n switch (op.kind) {\n case \"set\":\n for (const [path, value] of Object.entries(op.props)) {\n setAtPath(doc, path, value);\n }\n return doc;\n case \"setIfMissing\":\n for (const [path, value] of Object.entries(op.props)) {\n if (getAtPath(doc, path) === undefined) {\n setAtPath(doc, path, value);\n }\n }\n return doc;\n case \"unset\":\n for (const path of op.paths) {\n unsetAtPath(doc, path);\n }\n return doc;\n case \"inc\":\n for (const [path, delta] of Object.entries(op.props)) {\n const current = getAtPath(doc, path);\n const base = typeof current === \"number\" ? current : 0;\n setAtPath(doc, path, base + delta);\n }\n return doc;\n case \"dec\":\n for (const [path, delta] of Object.entries(op.props)) {\n const current = getAtPath(doc, path);\n const base = typeof current === \"number\" ? current : 0;\n setAtPath(doc, path, base - delta);\n }\n return doc;\n case \"insert\": {\n insertIntoArray(doc, op.position, op.anchor, op.items);\n return doc;\n }\n }\n}\n\ninterface PathSegment {\n key: string;\n // Optional array selector. Either a numeric index or a key=value match.\n selector?: { kind: \"index\"; index: number } | { kind: \"keyed\"; field: string; value: string };\n}\n\nfunction parsePath(path: string): PathSegment[] {\n // Examples:\n // \"currentStageId\"\n // \"taskStatus[0].status\"\n // \"taskStatus[_key==\\\"approve\\\"].status\"\n // \"context[key==\\\"releaseId\\\"].value\"\n const segments: PathSegment[] = [];\n for (const raw of path.split(\".\")) {\n const match = /^([A-Za-z_$][\\w$]*)(?:\\[(.+)\\])?$/.exec(raw);\n if (!match) {\n throw fakeError(\n `Unsupported patch path segment \"${raw}\" (in path \"${path}\"). This fake supports dotted ` +\n `field access (\"a.b.c\"), array index (\"items[0]\"), and keyed lookup (\\`items[_key==\"x\"]\\`). ` +\n `Recursive descent (\"..\") and GROQ filter expressions are not supported.`,\n );\n }\n const key = match[1] as string;\n const selectorRaw = match[2];\n if (selectorRaw === undefined) {\n segments.push({ key });\n continue;\n }\n const indexMatch = /^(\\d+)$/.exec(selectorRaw);\n if (indexMatch) {\n segments.push({ key, selector: { kind: \"index\", index: Number(indexMatch[1]) } });\n continue;\n }\n const keyedMatch = /^([A-Za-z_$][\\w$]*)\\s*==\\s*\"([^\"]*)\"$/.exec(selectorRaw);\n if (keyedMatch) {\n segments.push({\n key,\n selector: { kind: \"keyed\", field: keyedMatch[1] as string, value: keyedMatch[2] as string },\n });\n continue;\n }\n throw fakeError(\n `Unsupported array selector \"[${selectorRaw}]\" in patch path \"${path}\". Supported selectors ` +\n `are a numeric index (e.g. \"[0]\") and a single keyed match (e.g. \\`[_key==\"abc\"]\\`). ` +\n `Multi-key matches and arbitrary GROQ filters are not supported.`,\n );\n }\n return segments;\n}\n\nfunction resolveSelector(array: unknown[], selector: NonNullable<PathSegment[\"selector\"]>): number {\n if (selector.kind === \"index\") return selector.index;\n const idx = array.findIndex(\n (entry) =>\n typeof entry === \"object\" &&\n entry !== null &&\n (entry as Record<string, unknown>)[selector.field] === selector.value,\n );\n if (idx === -1) {\n throw fakeError(\n `Patch path matched no array entry where ${selector.field}==\"${selector.value}\". The array has ` +\n `${array.length} item(s); check the key exists (and that you're patching the right document).`,\n );\n }\n return idx;\n}\n\nfunction getAtPath(doc: SanityDocument, path: string): unknown {\n const segments = parsePath(path);\n let cursor: unknown = doc;\n for (const seg of segments) {\n if (cursor === undefined || cursor === null) return undefined;\n cursor = (cursor as Record<string, unknown>)[seg.key];\n if (seg.selector !== undefined) {\n if (!Array.isArray(cursor)) return undefined;\n const idx = resolveSelector(cursor, seg.selector);\n cursor = cursor[idx];\n }\n }\n return cursor;\n}\n\nfunction setAtPath(doc: SanityDocument, path: string, value: unknown): void {\n const segments = parsePath(path);\n if (segments.length === 0)\n throw fakeError(`Empty patch path — a set/setIfMissing op needs a target field.`);\n let cursor: Record<string, unknown> = doc as unknown as Record<string, unknown>;\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i] as PathSegment;\n let next = cursor[seg.key];\n if (next === undefined) {\n next = seg.selector?.kind === \"index\" || seg.selector?.kind === \"keyed\" ? [] : {};\n cursor[seg.key] = next;\n }\n if (seg.selector !== undefined) {\n if (!Array.isArray(next)) {\n throw fakeError(\n `Patch path \"${path}\" applies an array selector to field \"${seg.key}\", but that field ` +\n `holds ${describeType(next)}, not an array.`,\n );\n }\n const idx = resolveSelector(next, seg.selector);\n cursor = next[idx] as Record<string, unknown>;\n } else {\n cursor = next as Record<string, unknown>;\n }\n }\n const last = segments[segments.length - 1] as PathSegment;\n if (last.selector !== undefined) {\n const arr = cursor[last.key];\n if (!Array.isArray(arr)) {\n throw fakeError(\n `Patch path \"${path}\" applies an array selector to field \"${last.key}\", but that field ` +\n `holds ${describeType(arr)}, not an array.`,\n );\n }\n const idx = resolveSelector(arr, last.selector);\n arr[idx] = value;\n } else {\n cursor[last.key] = value;\n }\n}\n\nfunction unsetAtPath(doc: SanityDocument, path: string): void {\n const segments = parsePath(path);\n if (segments.length === 0) return;\n let cursor: Record<string, unknown> = doc as unknown as Record<string, unknown>;\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i] as PathSegment;\n let next = cursor[seg.key];\n if (next === undefined || next === null) return;\n if (seg.selector !== undefined) {\n if (!Array.isArray(next)) return;\n const idx = resolveSelector(next, seg.selector);\n next = next[idx];\n }\n cursor = next as Record<string, unknown>;\n }\n const last = segments[segments.length - 1] as PathSegment;\n if (last.selector !== undefined) {\n const arr = cursor[last.key];\n if (!Array.isArray(arr)) return;\n const idx = resolveSelector(arr, last.selector);\n arr.splice(idx, 1);\n } else {\n delete cursor[last.key];\n }\n}\n\nfunction insertIntoArray(\n doc: SanityDocument,\n position: \"before\" | \"after\" | \"replace\",\n anchor: string,\n items: unknown[],\n): void {\n // anchor is a path that must terminate at an array entry (selector required).\n // For \"replace\", we replace the entry; for \"before\"/\"after\", we insert\n // adjacent to it.\n const segments = parsePath(anchor);\n if (segments.length === 0)\n throw fakeError(`Empty insert anchor — insert() needs an array path to anchor against.`);\n const last = segments[segments.length - 1] as PathSegment;\n if (last.selector === undefined) {\n throw fakeError(\n `Insert anchor \"${anchor}\" must end with an array selector (an index like \"[0]\" or a keyed ` +\n `match like \\`[_key==\"x\"]\\`) so the fake knows where in the array to insert.`,\n );\n }\n\n let cursor: Record<string, unknown> = doc as unknown as Record<string, unknown>;\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i] as PathSegment;\n const next = cursor[seg.key];\n if (next === undefined || next === null) {\n throw fakeError(\n `Insert anchor \"${anchor}\" traverses field \"${seg.key}\", which is missing on the document. ` +\n `setIfMissing the parent first, or anchor against an existing array.`,\n );\n }\n if (seg.selector !== undefined) {\n if (!Array.isArray(next)) {\n throw fakeError(\n `Insert anchor \"${anchor}\" applies an array selector to field \"${seg.key}\", but it holds ` +\n `${describeType(next)}, not an array.`,\n );\n }\n cursor = next[resolveSelector(next, seg.selector)] as Record<string, unknown>;\n } else {\n cursor = next as Record<string, unknown>;\n }\n }\n const arr = cursor[last.key];\n if (!Array.isArray(arr)) {\n throw fakeError(\n `Insert anchor \"${anchor}\" targets field \"${last.key}\", but it holds ${describeType(arr)}, ` +\n `not an array.`,\n );\n }\n const idx = resolveSelector(arr, last.selector);\n if (position === \"replace\") {\n arr.splice(idx, 1, ...items);\n } else if (position === \"before\") {\n arr.splice(idx, 0, ...items);\n } else {\n arr.splice(idx + 1, 0, ...items);\n }\n}\n","/**\n * Content Releases action handlers — `client.action()` plus the\n * `client.releases.*` and `client.createVersion` / `client.unpublishVersion`\n * helpers.\n *\n * Mirrors enough of the real `@sanity/client` action surface for tests\n * to exercise release-aware workflows. Transient states\n * (`scheduling`/`publishing`/`unscheduling`) are skipped — releases\n * transition synchronously between settled states.\n */\n\nimport type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport type { TestStore } from \"./store.ts\";\nimport { cryptoRandomKey } from \"./store.ts\";\nimport { applyPatchOps, type PatchOp } from \"./patch.ts\";\nimport { fakeError } from \"./errors.ts\";\n\n/**\n * Document body accepted by `version.create` / `createVersion`. The id\n * is derived from `releaseId + publishedId` so callers may omit `_id`\n * here. `version.replace` requires `_id` since it identifies the doc\n * to replace.\n */\nexport interface DocumentBody {\n _id?: string;\n _type: string;\n [field: string]: unknown;\n}\n\nexport type ReleaseState = \"active\" | \"scheduled\" | \"published\" | \"archived\";\n\nexport type ReleaseType = \"asap\" | \"scheduled\" | \"undecided\";\n\nexport interface ReleaseMetadata {\n title?: string;\n description?: string;\n releaseType?: ReleaseType;\n intendedPublishAt?: string;\n}\n\nexport interface ReleaseDocument extends SanityDocument {\n _type: \"system.release\";\n name: string;\n state: ReleaseState;\n metadata: ReleaseMetadata;\n publishAt?: string;\n}\n\nexport type ReleaseAction =\n | {\n actionType: \"sanity.action.release.create\";\n releaseId: string;\n metadata?: Partial<ReleaseMetadata>;\n }\n | {\n actionType: \"sanity.action.release.edit\";\n releaseId: string;\n patch: { set?: Record<string, unknown>; unset?: string[] };\n }\n | { actionType: \"sanity.action.release.schedule\"; releaseId: string; publishAt: string }\n | { actionType: \"sanity.action.release.unschedule\"; releaseId: string }\n | { actionType: \"sanity.action.release.publish\"; releaseId: string }\n | { actionType: \"sanity.action.release.archive\"; releaseId: string }\n | { actionType: \"sanity.action.release.unarchive\"; releaseId: string }\n | { actionType: \"sanity.action.release.delete\"; releaseId: string };\n\nexport type VersionAction =\n | {\n actionType: \"sanity.action.document.version.create\";\n publishedId: string;\n document: DocumentBody;\n releaseId?: string; // inferred from document._id when omitted\n }\n | {\n actionType: \"sanity.action.document.version.replace\";\n document: SanityDocumentLike;\n }\n | {\n actionType: \"sanity.action.document.version.discard\";\n versionId: string;\n }\n | {\n actionType: \"sanity.action.document.version.unpublish\";\n versionId: string;\n publishedId: string;\n };\n\nexport type Action = ReleaseAction | VersionAction;\n\nexport interface ActionResult {\n transactionId: string;\n}\n\nconst RELEASE_DOC_PREFIX = \"_.releases.\";\nconst VERSIONS_PREFIX = \"versions.\";\n\nconst releaseDocId = (releaseId: string): string => `${RELEASE_DOC_PREFIX}${releaseId}`;\nconst versionDocId = (releaseId: string, publishedId: string): string =>\n `${VERSIONS_PREFIX}${releaseId}.${publishedId}`;\n\n/** Parse `versions.<release>.<id>` → `{ releaseId, publishedId }`. Throws otherwise. */\nfunction parseVersionId(versionId: string): { releaseId: string; publishedId: string } {\n if (!versionId.startsWith(VERSIONS_PREFIX)) {\n throw fakeError(\n `\"${versionId}\" is not a version document id. Version ids look like ` +\n `\"versions.<releaseId>.<publishedId>\" (e.g. \"versions.summer-drop.product-1\").`,\n );\n }\n const rest = versionId.slice(VERSIONS_PREFIX.length);\n const dot = rest.indexOf(\".\");\n if (dot === -1) {\n throw fakeError(\n `\"${versionId}\" is not a version document id. Version ids look like ` +\n `\"versions.<releaseId>.<publishedId>\" (e.g. \"versions.summer-drop.product-1\").`,\n );\n }\n return { releaseId: rest.slice(0, dot), publishedId: rest.slice(dot + 1) };\n}\n\nfunction getRelease(store: TestStore, releaseId: string): ReleaseDocument {\n const doc = store.get(releaseDocId(releaseId)) as ReleaseDocument | undefined;\n if (doc === undefined) {\n throw fakeError(\n `Release \"${releaseId}\" not found. Create it first with ` +\n `client.releases.create({ releaseId: \"${releaseId}\" }) (or a ` +\n `\"sanity.action.release.create\" action) before editing, scheduling, or adding versions to it.`,\n );\n }\n return doc;\n}\n\nfunction maybeRelease(store: TestStore, releaseId: string): ReleaseDocument | undefined {\n return store.get(releaseDocId(releaseId)) as ReleaseDocument | undefined;\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nfunction promote(doc: SanityDocumentLike): SanityDocument {\n const now = nowIso();\n return {\n ...doc,\n _id: doc._id as string,\n _type: doc._type as string,\n _rev: cryptoRandomKey(),\n _createdAt: doc._createdAt ?? now,\n _updatedAt: now,\n } as SanityDocument;\n}\n\nfunction bumpRev(doc: SanityDocument, patch: Partial<SanityDocument>): SanityDocument {\n return {\n ...doc,\n ...patch,\n _rev: cryptoRandomKey(),\n _updatedAt: nowIso(),\n } as SanityDocument;\n}\n\nfunction requireActive(release: ReleaseDocument): void {\n if (release.state !== \"active\") {\n throw fakeError(\n `Release \"${release.name}\" is \"${release.state}\", but only \"active\" releases accept version ` +\n `writes (create / replace / discard / unpublish). Unschedule or unarchive it back to ` +\n `\"active\" first, or target a different release.`,\n );\n }\n}\n\n/**\n * Apply a single action to the store. Returns a synthetic transactionId.\n * Throws on any invariant violation — callers wrap multi-action arrays\n * with a snapshot/rollback to keep atomicity.\n */\nexport function applyAction(store: TestStore, action: Action): ActionResult {\n switch (action.actionType) {\n case \"sanity.action.release.create\": {\n if (maybeRelease(store, action.releaseId) !== undefined) {\n throw fakeError(\n `Release \"${action.releaseId}\" already exists. release.create expects a new releaseId; ` +\n `use release.edit to change its metadata, or pick a different releaseId.`,\n );\n }\n const now = nowIso();\n const metadata: ReleaseMetadata = {\n releaseType: \"undecided\",\n ...action.metadata,\n };\n const doc: ReleaseDocument = {\n _id: releaseDocId(action.releaseId),\n _type: \"system.release\",\n _rev: cryptoRandomKey(),\n _createdAt: now,\n _updatedAt: now,\n name: action.releaseId,\n state: \"active\",\n metadata,\n };\n store.put(doc);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.edit\": {\n const release = getRelease(store, action.releaseId);\n const patchOps: PatchOp[] = [];\n if (action.patch.set !== undefined) {\n patchOps.push({ kind: \"set\", props: action.patch.set });\n }\n if (action.patch.unset !== undefined) {\n patchOps.push({ kind: \"unset\", paths: action.patch.unset });\n }\n const patched = applyPatchOps(release, patchOps);\n store.put(bumpRev(patched, {}));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.schedule\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"active\") {\n throw fakeError(\n `Cannot schedule release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"active\" releases can be scheduled.`,\n );\n }\n store.put(\n bumpRev(release, {\n state: \"scheduled\",\n publishAt: action.publishAt,\n } as Partial<SanityDocument>),\n );\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.unschedule\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"scheduled\") {\n throw fakeError(\n `Cannot unschedule release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"scheduled\" releases can be unscheduled.`,\n );\n }\n const next: ReleaseDocument = { ...release, state: \"active\" };\n delete (next as { publishAt?: string }).publishAt;\n store.put(bumpRev(next, {}));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.publish\": {\n const release = getRelease(store, action.releaseId);\n if (release.state === \"published\") {\n // Idempotent.\n return { transactionId: cryptoRandomKey() };\n }\n if (release.state !== \"active\" && release.state !== \"scheduled\") {\n throw fakeError(\n `Cannot publish release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"active\" or \"scheduled\" releases can be published.`,\n );\n }\n // Materialise versions onto published ids, then drop the versions.\n const prefix = `${VERSIONS_PREFIX}${action.releaseId}.`;\n const sources = store.all().filter((d) => d._id.startsWith(prefix));\n for (const v of sources) {\n const pubId = v._id.slice(prefix.length);\n const isUnpublishStub = (v as { _system?: { delete?: boolean } })._system?.delete === true;\n if (isUnpublishStub) {\n store.remove(pubId);\n } else {\n const body: SanityDocumentLike = {\n ...(v as SanityDocumentLike),\n _id: pubId,\n };\n // Strip transient fields we projected through the version.\n delete (body as { _originalId?: string })._originalId;\n delete (body as { _system?: unknown })._system;\n const promoted = promote(body);\n // Preserve _createdAt of the existing published doc if present.\n const existing = store.get(pubId);\n if (existing !== undefined) {\n promoted._createdAt = existing._createdAt;\n }\n store.put(promoted);\n }\n store.remove(v._id);\n }\n store.put(bumpRev(release, { state: \"published\" } as Partial<SanityDocument>));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.archive\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"active\" && release.state !== \"scheduled\") {\n throw fakeError(\n `Cannot archive release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"active\" or \"scheduled\" releases can be archived.`,\n );\n }\n store.put(bumpRev(release, { state: \"archived\" } as Partial<SanityDocument>));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.unarchive\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"archived\") {\n throw fakeError(\n `Cannot unarchive release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"archived\" releases can be unarchived.`,\n );\n }\n store.put(bumpRev(release, { state: \"active\" } as Partial<SanityDocument>));\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.release.delete\": {\n const release = getRelease(store, action.releaseId);\n if (release.state !== \"archived\" && release.state !== \"published\") {\n throw fakeError(\n `Cannot delete release \"${action.releaseId}\": it is \"${release.state}\", and only ` +\n `\"archived\" or \"published\" releases can be deleted. Archive it first ` +\n `(sanity.action.release.archive) or publish it.`,\n );\n }\n // Clean up any leftover version docs (archived releases keep them around).\n const prefix = `${VERSIONS_PREFIX}${action.releaseId}.`;\n for (const v of store.all()) {\n if (v._id.startsWith(prefix)) store.remove(v._id);\n }\n store.remove(release._id);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.create\": {\n const releaseId =\n action.releaseId ??\n (action.document._id !== undefined\n ? parseVersionId(action.document._id as string).releaseId\n : undefined);\n if (releaseId === undefined) {\n throw fakeError(\n `version.create needs a release to attach to: pass \\`releaseId\\`, or a \\`document._id\\` ` +\n `shaped \"versions.<releaseId>.<publishedId>\" so the release can be inferred.`,\n );\n }\n const release = getRelease(store, releaseId);\n requireActive(release);\n const vid = versionDocId(releaseId, action.publishedId);\n const doc: SanityDocumentLike = {\n ...action.document,\n _id: vid,\n };\n const existing = store.get(vid);\n const promoted = promote(doc);\n if (existing !== undefined) {\n promoted._createdAt = existing._createdAt;\n }\n store.put(promoted);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.replace\": {\n const id = action.document._id;\n if (typeof id !== \"string\") {\n throw fakeError(\n `version.replace needs \\`document._id\\` (a version id like ` +\n `\"versions.<releaseId>.<publishedId>\") to identify which version document to replace.`,\n );\n }\n const { releaseId } = parseVersionId(id);\n const release = getRelease(store, releaseId);\n requireActive(release);\n const existing = store.get(id);\n const promoted = promote(action.document);\n if (existing !== undefined) {\n promoted._createdAt = existing._createdAt;\n }\n store.put(promoted);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.discard\": {\n const { releaseId } = parseVersionId(action.versionId);\n const release = getRelease(store, releaseId);\n requireActive(release);\n store.remove(action.versionId);\n return { transactionId: cryptoRandomKey() };\n }\n\n case \"sanity.action.document.version.unpublish\": {\n const { releaseId } = parseVersionId(action.versionId);\n const release = getRelease(store, releaseId);\n requireActive(release);\n const doc: SanityDocumentLike = {\n _id: action.versionId,\n _type: \"stub\",\n _system: { delete: true },\n } as SanityDocumentLike;\n store.put(promote(doc));\n return { transactionId: cryptoRandomKey() };\n }\n }\n}\n\n/**\n * Apply an action or a list of actions atomically. On any failure all\n * mutations within the batch are rolled back to the pre-batch snapshot.\n */\nexport function applyActions(store: TestStore, actions: Action | Action[]): ActionResult {\n const list = Array.isArray(actions) ? actions : [actions];\n const snapshot = new Map<string, SanityDocument | undefined>();\n const remember = (id: string) => {\n if (!snapshot.has(id)) snapshot.set(id, store.get(id));\n };\n\n try {\n let last: ActionResult = { transactionId: cryptoRandomKey() };\n for (const a of list) {\n // Pre-record everything we might touch so rollback is precise.\n switch (a.actionType) {\n case \"sanity.action.release.create\":\n case \"sanity.action.release.edit\":\n case \"sanity.action.release.schedule\":\n case \"sanity.action.release.unschedule\":\n case \"sanity.action.release.archive\":\n case \"sanity.action.release.unarchive\":\n case \"sanity.action.release.delete\":\n remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);\n break;\n case \"sanity.action.release.publish\": {\n remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);\n const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;\n for (const d of store.all()) {\n if (d._id.startsWith(prefix)) {\n remember(d._id);\n remember(d._id.slice(prefix.length));\n }\n }\n break;\n }\n case \"sanity.action.document.version.create\": {\n // version.create derives its id from releaseId + publishedId,\n // so we don't rely on document._id being set.\n const releaseId =\n a.releaseId ??\n (typeof a.document._id === \"string\"\n ? parseVersionId(a.document._id).releaseId\n : undefined);\n if (releaseId !== undefined) {\n remember(versionDocId(releaseId, a.publishedId));\n }\n break;\n }\n case \"sanity.action.document.version.replace\":\n if (typeof a.document._id === \"string\") remember(a.document._id);\n break;\n case \"sanity.action.document.version.discard\":\n case \"sanity.action.document.version.unpublish\":\n remember(a.versionId);\n break;\n }\n last = applyAction(store, a);\n }\n return last;\n } catch (err) {\n for (const [id, doc] of snapshot) {\n if (doc === undefined) {\n store.remove(id);\n } else {\n store.put(doc);\n }\n }\n throw err;\n }\n}\n","/**\n * Perspective layering — read-side filtering that mirrors Sanity's\n * `perspective` query/client option.\n *\n * The store always holds raw documents. Each fetch builds a *view* of\n * the store filtered by the active perspective before passing the\n * dataset to `groq-js`.\n *\n * Reference: https://www.sanity.io/docs/content-lake/perspectives\n */\n\nimport type { SanityDocument } from \"@sanity/types\";\n\nexport type Perspective = \"raw\" | \"published\" | \"drafts\" | string[];\n\nconst DRAFTS_PREFIX = \"drafts.\";\nconst VERSIONS_PREFIX = \"versions.\";\nconst SYSTEM_PREFIX = \"_.\";\nconst RELEASE_DOC_PREFIX = \"_.releases.\";\n\n/** Strip `drafts.` / `versions.<name>.` prefix to recover the published id. */\nexport function publishedIdOf(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) return id.slice(DRAFTS_PREFIX.length);\n if (id.startsWith(VERSIONS_PREFIX)) {\n // versions.<name>.<id> — split off the prefix + name\n const rest = id.slice(VERSIONS_PREFIX.length);\n const dot = rest.indexOf(\".\");\n if (dot === -1) return rest;\n return rest.slice(dot + 1);\n }\n return id;\n}\n\n/** Extract the release name from a `versions.<name>.<id>` id, else undefined. */\nexport function releaseNameOf(id: string): string | undefined {\n if (!id.startsWith(VERSIONS_PREFIX)) return undefined;\n const rest = id.slice(VERSIONS_PREFIX.length);\n const dot = rest.indexOf(\".\");\n if (dot === -1) return undefined;\n return rest.slice(0, dot);\n}\n\nexport const isDraftId = (id: string): boolean => id.startsWith(DRAFTS_PREFIX);\nexport const isVersionId = (id: string): boolean => id.startsWith(VERSIONS_PREFIX);\nexport const isSystemId = (id: string): boolean => id.startsWith(SYSTEM_PREFIX);\nexport const isReleaseDocId = (id: string): boolean => id.startsWith(RELEASE_DOC_PREFIX);\n\n/**\n * Apply a perspective to a raw set of documents and return the view\n * groq-js should evaluate against.\n *\n * For non-raw perspectives, each output document for a non-system id\n * gets `_id` projected to its published id and `_originalId` carrying\n * the source id (matching the wire shape of the real Content Lake).\n */\nexport function applyPerspective(\n docs: readonly SanityDocument[],\n perspective: Perspective,\n): SanityDocument[] {\n if (perspective === \"raw\") return [...docs];\n\n if (perspective === \"published\") {\n return docs.filter((d) => !isDraftId(d._id) && !isVersionId(d._id) && !isSystemId(d._id));\n }\n\n if (perspective === \"drafts\") {\n return mergeStack(docs, [], { includeDrafts: true, includeReleaseDocs: false });\n }\n\n // string[] — release stack with optional \"drafts\" entry\n const stack: string[] = [];\n let includeDrafts = false;\n for (const entry of perspective) {\n if (entry === \"drafts\") {\n includeDrafts = true;\n } else {\n stack.push(entry);\n }\n }\n return mergeStack(docs, stack, { includeDrafts, includeReleaseDocs: true });\n}\n\ninterface MergeOptions {\n includeDrafts: boolean;\n includeReleaseDocs: boolean;\n}\n\n/**\n * Walk the raw docs once, group by published id, then for each group\n * pick the highest-priority source according to `releaseStack` and\n * `includeDrafts`. Project the chosen doc to the published id.\n */\nfunction mergeStack(\n docs: readonly SanityDocument[],\n releaseStack: readonly string[],\n options: MergeOptions,\n): SanityDocument[] {\n // Group docs by published id. Track which sources exist.\n type Group = {\n published?: SanityDocument;\n draft?: SanityDocument;\n versions: Map<string, SanityDocument>;\n };\n const groups = new Map<string, Group>();\n const systemReleases: SanityDocument[] = [];\n\n for (const doc of docs) {\n if (isReleaseDocId(doc._id)) {\n if (options.includeReleaseDocs) systemReleases.push(doc);\n continue;\n }\n if (isSystemId(doc._id)) continue; // other system docs are hidden\n const pubId = publishedIdOf(doc._id);\n let group = groups.get(pubId);\n if (group === undefined) {\n group = { versions: new Map() };\n groups.set(pubId, group);\n }\n if (isDraftId(doc._id)) {\n group.draft = doc;\n } else if (isVersionId(doc._id)) {\n const releaseName = releaseNameOf(doc._id);\n if (releaseName !== undefined) group.versions.set(releaseName, doc);\n } else {\n group.published = doc;\n }\n }\n\n const out: SanityDocument[] = [];\n for (const [pubId, group] of groups) {\n // Walk the release stack first, then drafts (if enabled, in its\n // slot — here we model \"drafts after the stack\" matching the\n // typical `[r1, r2, \"drafts\"]` shape), then fall through to\n // published.\n let chosen: SanityDocument | undefined;\n for (const releaseName of releaseStack) {\n const v = group.versions.get(releaseName);\n if (v !== undefined) {\n // version.unpublish stub: hide the doc entirely\n if (isUnpublishStub(v)) {\n chosen = undefined;\n break;\n }\n chosen = v;\n break;\n }\n }\n if (chosen === undefined && options.includeDrafts && group.draft !== undefined) {\n chosen = group.draft;\n }\n if (chosen === undefined && group.published !== undefined) {\n // skip if any release in the stack carried an unpublish stub\n const blocked = releaseStack.some((name) => {\n const v = group.versions.get(name);\n return v !== undefined && isUnpublishStub(v);\n });\n if (!blocked) chosen = group.published;\n }\n if (chosen !== undefined) {\n out.push(projectToPublishedId(chosen, pubId));\n }\n }\n\n return [...out, ...systemReleases];\n}\n\nfunction isUnpublishStub(doc: SanityDocument): boolean {\n const sys = (doc as { _system?: { delete?: boolean } })._system;\n return sys?.delete === true;\n}\n\nfunction projectToPublishedId(doc: SanityDocument, pubId: string): SanityDocument {\n if (doc._id === pubId) return doc;\n return { ...doc, _id: pubId, _originalId: doc._id } as SanityDocument;\n}\n\n/**\n * `getDocument(id)` resolution under a perspective. Returns the chosen\n * source's *raw* doc (not projected), so the caller can decide whether\n * to expose `_originalId` etc. For perspective=\"raw\", this is just\n * `docs.find(d => d._id === id)`.\n */\nexport function resolveDocument(\n docs: readonly SanityDocument[],\n id: string,\n perspective: Perspective,\n): SanityDocument | undefined {\n if (perspective === \"raw\") {\n return docs.find((d) => d._id === id);\n }\n // Match the rules of applyPerspective: resolve to the same chosen\n // doc but key by the requested id (which the caller treated as a\n // published id under non-raw perspectives).\n const view = applyPerspective(docs, perspective);\n return view.find((d) => d._id === id);\n}\n","import type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport type { PatchHandle, PatchOp } from \"./patch.ts\";\n\n/**\n * A transaction collects mutations and applies them atomically at commit\n * time. Mutations are applied in declaration order; if any one fails, the\n * whole transaction throws and no writes land in the store.\n *\n * Subset of `@sanity/client`'s Transaction. Same shape, narrower surface.\n */\nexport type TxnMutation =\n | { kind: \"create\"; doc: SanityDocumentLike }\n | { kind: \"createOrReplace\"; doc: SanityDocumentLike }\n | { kind: \"createIfNotExists\"; doc: SanityDocumentLike }\n | { kind: \"delete\"; id: string }\n | { kind: \"patch\"; documentId: string; ops: PatchOp[]; ifRev?: string };\n\nexport interface TransactionHandle {\n create: (doc: SanityDocumentLike) => TransactionHandle;\n createOrReplace: (doc: SanityDocumentLike) => TransactionHandle;\n createIfNotExists: (doc: SanityDocumentLike) => TransactionHandle;\n delete: (id: string) => TransactionHandle;\n /** Accept either a Patch builder (drained at commit) or an inline doc id + ops. */\n patch: (\n documentIdOrPatch: string | PatchHandle,\n ops?: PatchOp[],\n ifRev?: string,\n ) => TransactionHandle;\n commit: (options?: TxnCommitOptions) => Promise<TxnCommitResult>;\n /** Test-only introspection — not on real Transaction. */\n toJSON: () => TxnMutation[];\n}\n\nexport interface TxnCommitOptions {\n /**\n * Shape the resolved value (mirrors `@sanity/client`):\n * - default (both unset) → {@link MultipleMutationResult}\n * - `returnDocuments: true` → the resulting document(s)\n * - `returnFirst: true` with `returnDocuments` → a single document\n * - `returnDocuments: false` → an id-shaped mutation result\n */\n returnDocuments?: boolean;\n returnFirst?: boolean;\n /** Override the synthetic transaction id (mirrors `client.transaction(undefined, { transactionId })`). */\n transactionId?: string;\n}\n\n/** The operation recorded per affected document, matching `@sanity/client`. */\nexport type MutationOperation = \"create\" | \"update\" | \"delete\" | \"none\";\n\n/** Result of a mutation when `returnFirst` resolves true and ids are requested. */\nexport interface SingleMutationResult {\n transactionId: string;\n documentId: string;\n results: { id: string; operation: MutationOperation }[];\n}\n\n/** Result of a mutation when ids are requested for all affected documents. */\nexport interface MultipleMutationResult {\n transactionId: string;\n documentIds: string[];\n results: { id: string; operation: MutationOperation }[];\n}\n\nexport type TxnCommitResult =\n | MultipleMutationResult\n | SingleMutationResult\n | SanityDocument\n | SanityDocument[];\n\nexport interface TxnExecutor {\n apply: (mutations: TxnMutation[], options?: TxnCommitOptions) => Promise<TxnCommitResult>;\n}\n\nexport function createTransaction(executor: TxnExecutor): TransactionHandle {\n const mutations: TxnMutation[] = [];\n\n const handle: TransactionHandle = {\n create: (doc) => {\n mutations.push({ kind: \"create\", doc });\n return handle;\n },\n createOrReplace: (doc) => {\n mutations.push({ kind: \"createOrReplace\", doc });\n return handle;\n },\n createIfNotExists: (doc) => {\n mutations.push({ kind: \"createIfNotExists\", doc });\n return handle;\n },\n delete: (id) => {\n mutations.push({ kind: \"delete\", id });\n return handle;\n },\n patch: (documentIdOrPatch, ops, ifRev) => {\n if (typeof documentIdOrPatch === \"string\") {\n mutations.push({\n kind: \"patch\",\n documentId: documentIdOrPatch,\n ops: ops ?? [],\n ...(ifRev !== undefined ? { ifRev } : {}),\n });\n } else {\n const json = documentIdOrPatch.toJSON();\n mutations.push({\n kind: \"patch\",\n documentId: json.id,\n ops: json.ops,\n ...(json.ifRev !== undefined ? { ifRev: json.ifRev } : {}),\n });\n }\n return handle;\n },\n commit: (options) => executor.apply(mutations, options),\n toJSON: () => [...mutations],\n };\n\n return handle;\n}\n","/**\n * Graceful-degradation layer for the parts of `@sanity/client` this fake\n * doesn't implement.\n *\n * The client object is a fixed surface. Without a guard, reaching for a\n * member the fake doesn't have (`client.listen`, `client.assets.upload`,\n * a typo) yields a bare `TypeError: x is not a function` — no hint that\n * it's an intentional gap in a *fake*, no pointer to a workaround. The\n * `Proxy` built here turns every such access into an actionable error,\n * and lets tests fill gaps via a stub registry.\n *\n * Resolution order for a property read on the wrapped client:\n * 1. Real implemented member → passed straight through.\n * 2. Thenable / inspection probes (`then`, symbols, …) → pass through\n * so `await client` and `console.log(client)` stay well-behaved.\n * 3. User-registered stub (`client.stub(name, fn)`) → returned.\n * 4. Known-but-unimplemented `@sanity/client` member → a guard that\n * throws a curated, workaround-bearing error on call or deeper access.\n * 5. Anything else (typo / unknown) → a guard that throws a\n * \"no such method\" error listing the supported surface.\n */\n\nconst ISSUES_URL = \"https://github.com/sanity-labs/client-fake-for-test/issues\";\n\n/** Members this fake actually implements — surfaced in error messages. */\nexport const SUPPORTED_SURFACE = [\n \"fetch\",\n \"getDocument\",\n \"getDocuments\",\n \"create\",\n \"createOrReplace\",\n \"createIfNotExists\",\n \"delete\",\n \"patch\",\n \"transaction\",\n \"mutate\",\n \"action\",\n \"releases\",\n \"createVersion\",\n \"unpublishVersion\",\n \"request (only with accessControl)\",\n \"config\",\n \"withConfig\",\n] as const;\n\ninterface UnsupportedEntry {\n /** What the real member is. */\n what: string;\n /** What to do instead. */\n workaround: string;\n}\n\n/**\n * Curated map of real `@sanity/client` members the fake deliberately omits.\n * Keyed by the top-level property name; nested access (e.g.\n * `assets.upload`) is reported with the full dotted path.\n */\nexport const UNSUPPORTED_MEMBERS: Record<string, UnsupportedEntry> = {\n listen: {\n what: \"real-time listener (returns an RxJS Observable of mutation events)\",\n workaround:\n \"Test your subscription logic in isolation, or register a fake: \" +\n `client.stub(\"listen\", () => myFakeObservable).`,\n },\n observable: {\n what: \"the RxJS-flavoured mirror of the client API\",\n workaround:\n \"Use the Promise-based methods and wrap them with `from()` if you need an Observable.\",\n },\n clone: {\n what: \"clone the client with the same config\",\n workaround: \"Use `withConfig({})` — it returns a sibling handle into the same store.\",\n },\n getUrl: {\n what: \"build an absolute API URL for a path\",\n workaround: \"Hard-code the expected URL in your test, or stub it.\",\n },\n getDataUrl: {\n what: \"build an absolute data-API URL\",\n workaround: \"Hard-code the expected URL in your test, or stub it.\",\n },\n assets: {\n what: \"asset upload / metadata namespace\",\n workaround: \"Seed asset documents into the store directly with `seed()` / `add()`.\",\n },\n agent: {\n what: \"Agent Actions namespace (generate / transform / …)\",\n workaround: `Stub the call site: client.stub(\"agent\", myFakeAgent).`,\n },\n projects: {\n what: \"project-management namespace\",\n workaround: \"Out of scope for a data-plane fake — stub the call site.\",\n },\n users: {\n what: \"user-management namespace\",\n workaround: \"Out of scope for a data-plane fake — stub the call site.\",\n },\n live: {\n what: \"Live Content API namespace\",\n workaround: \"Out of scope — stub the call site or test the consumer separately.\",\n },\n mediaLibrary: {\n what: \"Media Library namespace\",\n workaround: \"Out of scope — seed documents directly or stub the call site.\",\n },\n request: {\n what: \"generic HTTP request hook — only wired up when accessControl is configured\",\n workaround:\n \"Create the client with `accessControl` to enable request() (it serves \" +\n \"/users/me + the ACL path), or register a stub.\",\n },\n dryRun: {\n what: \"not a method — did you mean the `{ dryRun }` mutation option?\",\n workaround: \"Pass `{ dryRun: true }` as the second arg to create / mutate / delete.\",\n },\n};\n\n/**\n * Property names read by promise-resolution, serialization, and test\n * frameworks while probing an unknown object. These must resolve to\n * `undefined` (not a throwing guard) so `await client`,\n * `JSON.stringify(client)`, and matcher diffs stay well-behaved. Members\n * inherited from `Object.prototype` (`toString`, `valueOf`, …) already\n * pass through via the `in` check and don't need listing here.\n */\nconst PROBE_NAMES = new Set([\n \"then\",\n \"catch\",\n \"finally\",\n \"toJSON\",\n \"asymmetricMatch\",\n \"$$typeof\",\n \"nodeType\",\n \"_isMockFunction\",\n]);\n\n/** Build the multi-line error body shared by both guard flavours. */\nfunction guardMessage(path: string, detail: string, workaround: string): string {\n return [\n `[client-fake-for-test] \\`client.${path}\\` ${detail}`,\n \"\",\n \"This is an in-memory fake of @sanity/client. It implements:\",\n ` ${SUPPORTED_SURFACE.join(\", \")}.`,\n \"\",\n `→ ${workaround}`,\n \"\",\n `Register a stub to fill any gap: client.stub(${JSON.stringify(path.split(\".\")[0])}, handler)`,\n `If this should be supported, open an issue: ${ISSUES_URL}`,\n ].join(\"\\n\");\n}\n\n/**\n * A callable, infinitely-chainable guard. Reading any property returns a\n * deeper guard (so `client.assets.upload` reports the full path), and\n * calling at any depth throws the actionable error. `then` / symbols\n * resolve to `undefined` so `await` and inspection don't trip the guard.\n */\nfunction makeGuard(path: string, message: string): unknown {\n const thrower = () => {\n throw new Error(message);\n };\n return new Proxy(thrower, {\n apply: () => thrower(),\n get: (_t, prop) => {\n if (typeof prop === \"symbol\") return undefined;\n if (PROBE_NAMES.has(prop)) return undefined;\n // Re-derive the message for the deeper path so the error names the\n // exact member that was reached for.\n const childPath = `${path}.${String(prop)}`;\n const top = path.split(\".\")[0] as string;\n const entry = UNSUPPORTED_MEMBERS[top];\n const detail = entry ? `is not implemented (${entry.what}).` : \"is not implemented.\";\n const workaround = entry?.workaround ?? \"Register a stub or use a different test strategy.\";\n return makeGuard(childPath, guardMessage(childPath, detail, workaround));\n },\n });\n}\n\n/** Outcome of a recorded call, reported once a (possibly async) result is known. */\nexport type CallSettler = (outcome: { result?: unknown; error?: unknown }) => void;\n\nexport interface GuardConfig {\n /**\n * Resolve a registered stub for an unimplemented member, or `undefined`.\n * Checked only for members the client doesn't already implement, so\n * stubs fill gaps without shadowing core behaviour.\n */\n getStub: (name: string) => unknown;\n /**\n * Called synchronously when a recorded method is invoked, with the\n * method name and its arguments. Returns a settler the wrapper invokes\n * once the result (or rejection) is known. Omit to disable recording.\n */\n onCall?: (method: string, args: unknown[]) => CallSettler;\n /**\n * Top-level member names whose calls are recorded via `onCall`. A\n * recorded member that resolves to a namespace object (e.g. `releases`)\n * has each of its methods recorded as `name.method`.\n */\n recorded?: Set<string>;\n}\n\n/** Wrap a function so each call is reported to `onCall` (args now, outcome on settle). */\nfunction wrapRecorded(\n method: string,\n fn: (...args: unknown[]) => unknown,\n onCall: NonNullable<GuardConfig[\"onCall\"]>,\n): (...args: unknown[]) => unknown {\n return (...args: unknown[]) => {\n const settle = onCall(method, args);\n try {\n const out = fn(...args);\n if (\n out !== null &&\n typeof out === \"object\" &&\n typeof (out as PromiseLike<unknown>).then === \"function\"\n ) {\n return (out as Promise<unknown>).then(\n (result) => {\n settle({ result });\n return result;\n },\n (error: unknown) => {\n settle({ error });\n throw error;\n },\n );\n }\n settle({ result: out });\n return out;\n } catch (error) {\n settle({ error });\n throw error;\n }\n };\n}\n\n/** Wrap a namespace object so its method calls record as `prefix.method`. */\nfunction wrapNamespace(\n ns: Record<string, unknown>,\n prefix: string,\n onCall: NonNullable<GuardConfig[\"onCall\"]>,\n): Record<string, unknown> {\n return new Proxy(ns, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (typeof prop === \"string\" && typeof value === \"function\") {\n return wrapRecorded(`${prefix}.${prop}`, value as (...a: unknown[]) => unknown, onCall);\n }\n return value;\n },\n });\n}\n\n/**\n * Wrap a client object so unimplemented members fail informatively,\n * registered stubs are served, and recorded methods report their calls.\n *\n * @param client - the fully-built client object (plain literal).\n * @param config - stub resolver plus optional call-recording hooks.\n */\nexport function wrapWithGuards<T extends object>(client: T, config: GuardConfig): T {\n const { getStub, onCall, recorded } = config;\n return new Proxy(client, {\n get(target, prop, receiver) {\n if (typeof prop === \"symbol\") return Reflect.get(target, prop, receiver);\n if (prop in target) {\n const value = Reflect.get(target, prop, receiver);\n if (onCall !== undefined && recorded?.has(prop) === true) {\n if (typeof value === \"function\") {\n return wrapRecorded(prop, value as (...a: unknown[]) => unknown, onCall);\n }\n if (value !== null && typeof value === \"object\") {\n return wrapNamespace(value as Record<string, unknown>, prop, onCall);\n }\n }\n return value;\n }\n // Promise / serialization / framework probes on a non-thenable object.\n if (PROBE_NAMES.has(prop)) return undefined;\n\n const stub = getStub(prop);\n if (stub !== undefined) return stub;\n\n const entry = UNSUPPORTED_MEMBERS[prop];\n if (entry !== undefined) {\n return makeGuard(\n prop,\n guardMessage(prop, `is not implemented (${entry.what}).`, entry.workaround),\n );\n }\n return makeGuard(\n prop,\n guardMessage(\n prop,\n \"is not a method on this fake (unknown member or unimplemented @sanity/client API).\",\n \"Check for a typo, register a stub, or use a different test strategy.\",\n ),\n );\n },\n });\n}\n","import type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\nimport { evaluate, parse } from \"groq-js\";\n\nimport {\n canAccess,\n enforceWriteAccess,\n makeRequestImpl,\n type DocumentValuePermission,\n type TestClientAccessControl,\n} from \"./access-control.ts\";\nimport {\n applyActions,\n type Action,\n type ActionResult,\n type DocumentBody,\n type ReleaseDocument,\n type ReleaseMetadata,\n} from \"./actions.ts\";\nimport { fakeError } from \"./errors.ts\";\nimport type { MutationGuard, MutationGuardContext } from \"./mutation-guard.ts\";\nimport { applyPatchOps, createPatch, type PatchHandle, type PatchOp } from \"./patch.ts\";\nimport { applyPerspective, resolveDocument, type Perspective } from \"./perspective.ts\";\nimport { createTestStore, cryptoRandomKey, type TestStore } from \"./store.ts\";\nimport {\n createTransaction,\n type MultipleMutationResult,\n type MutationOperation,\n type SingleMutationResult,\n type TransactionHandle,\n type TxnCommitOptions,\n type TxnCommitResult,\n type TxnMutation,\n} from \"./transaction.ts\";\nimport { wrapWithGuards, type CallSettler } from \"./unsupported.ts\";\n\n/**\n * Data-plane subset of `@sanity/client`'s surface, with multi-dataset support.\n *\n * One `createTestClient()` call creates a registry of stores keyed by\n * `(projectId, dataset)`. The returned client points at one of them.\n * `withConfig({ projectId, dataset })` returns a new handle into the same\n * registry but pointing at a different store — useful for workflows where\n * definitions live in one dataset and instances live in another.\n *\n * Two separate `createTestClient()` calls have separate registries, so\n * tests stay isolated from each other.\n *\n * Methods not on the real client:\n *\n * - `seed`, `add`, `reset`, `snapshot`, `store` — bulk-load helpers,\n * scoped to the current dataset.\n * - `simulateConcurrentEdit()` — force the next N revision-guarded writes\n * to a document to 409, for optimistic-locking retry tests.\n * - `datasets()` — lists known dataset keys in this registry.\n *\n * Methods deliberately omitted:\n *\n * - Project / agent / asset / live / listen APIs.\n */\nexport interface FetchOptions {\n /** Override the client's configured perspective for this read. */\n perspective?: Perspective;\n /**\n * When `false`, resolve to a {@link RawQueryResponse} (`{ query, ms,\n * result }`) instead of the bare result — mirrors `@sanity/client`.\n * Defaults to `true`.\n */\n filterResponse?: boolean;\n /**\n * With `filterResponse: false`, set to `false` to omit `query` from the\n * raw response. Ignored when `filterResponse` is not `false`.\n */\n returnQuery?: boolean;\n /** Accepted for signature parity; not simulated. */\n tag?: string;\n /** Accepted for signature parity; not simulated. */\n signal?: AbortSignal;\n}\n\n/**\n * Shape returned by `fetch` when `filterResponse: false`. Matches\n * `@sanity/client`'s `RawQueryResponse`. `query` is omitted when the\n * caller also passes `returnQuery: false`.\n */\nexport interface RawQueryResponse<R> {\n query?: string;\n ms: number;\n result: R;\n}\n\n/**\n * A single mutation in the raw array form accepted by `mutate()` — the\n * same shape `@sanity/client` accepts. The inline `patch` form mirrors\n * the real client's keyed patch object.\n */\nexport type FakeMutation =\n | { create: SanityDocumentLike }\n | { createOrReplace: SanityDocumentLike }\n | { createIfNotExists: SanityDocumentLike }\n | { delete: { id: string } }\n | {\n patch: {\n id: string;\n ifRevisionID?: string;\n set?: Record<string, unknown>;\n setIfMissing?: Record<string, unknown>;\n unset?: string[];\n inc?: Record<string, number>;\n dec?: Record<string, number>;\n insert?: {\n before?: string;\n after?: string;\n replace?: string;\n items: unknown[];\n };\n };\n };\n\n/** Append-only record of one committed transaction (a single mutation is a 1-entry transaction). */\nexport interface MutationLogEntry {\n transactionId: string;\n projectId: string;\n dataset: string;\n mutations: TxnMutation[];\n}\n\n/**\n * One recorded invocation of a client method — the spy layer behind\n * `client.calls()` / `client.callCount()`. `result` holds the resolved\n * value (awaited, for async methods); `error` holds the thrown/rejected\n * value. Builder-returning methods (`patch`, `transaction`) record the\n * builder as `result`; their eventual writes show up in the mutation log.\n */\nexport interface CallRecord {\n /** Method name; namespace methods are dotted, e.g. `releases.create`. */\n method: string;\n /** Arguments as passed (stored by reference, like `vi.fn`). */\n args: unknown[];\n /** Resolved/returned value, set once the call settles successfully. */\n result?: unknown;\n /** Thrown or rejected value, set if the call failed. */\n error?: unknown;\n projectId: string;\n dataset: string;\n}\n\n/** Client methods whose calls are recorded for `calls()` / `callCount()`. */\nconst RECORDED_METHODS = new Set([\n \"fetch\",\n \"getDocument\",\n \"getDocuments\",\n \"create\",\n \"createOrReplace\",\n \"createIfNotExists\",\n \"delete\",\n \"patch\",\n \"transaction\",\n \"mutate\",\n \"action\",\n \"releases\",\n \"createVersion\",\n \"unpublishVersion\",\n \"request\",\n]);\n\nexport interface TestClient {\n // --- query ---\n fetch: <T = unknown>(\n query: string,\n params?: Record<string, unknown>,\n options?: FetchOptions,\n ) => Promise<T>;\n getDocument: <T = SanityDocument>(id: string, options?: FetchOptions) => Promise<T | undefined>;\n getDocuments: <T = SanityDocument>(\n ids: string[],\n options?: FetchOptions,\n ) => Promise<(T | null)[]>;\n /**\n * Sanity-style HTTP request hook. Present iff the client was\n * created with `accessControl`. The engine's access resolver pokes\n * `/users/me` and the configured ACL path through this — without it\n * the engine throws on any verb that needs an actor (which is the\n * cue for the bench to supply an `access` override).\n *\n * Test cases that want to exercise the engine's token-resolution\n * path should configure `accessControl`; cases that want bench-style\n * always-allow should leave it off and pass `access` through the\n * bench.\n */\n request?: <T>(opts: {\n url?: string;\n uri?: string;\n signal?: AbortSignal;\n tag?: string;\n }) => Promise<T>;\n\n // --- mutate ---\n create: <T extends SanityDocumentLike>(\n doc: T,\n options?: MutationOptions,\n ) => Promise<T & SystemFields>;\n createOrReplace: <T extends SanityDocumentLike>(\n doc: T,\n options?: MutationOptions,\n ) => Promise<T & SystemFields>;\n createIfNotExists: <T extends SanityDocumentLike>(\n doc: T,\n options?: MutationOptions,\n ) => Promise<T & SystemFields>;\n delete: (id: string, options?: MutationOptions) => Promise<{ _id: string } | null>;\n patch: (documentId: string) => PatchHandle;\n transaction: () => TransactionHandle;\n /**\n * Apply a batch of mutations in the raw array form (or a `patch()` /\n * `transaction()` builder) — mirrors `@sanity/client`'s `mutate()`.\n * Atomic: any failure rolls the whole batch back. The resolved shape\n * follows `options.returnDocuments` / `returnFirst` exactly like the\n * real client (default → {@link MultipleMutationResult}).\n */\n mutate: (\n operations: FakeMutation[] | PatchHandle | TransactionHandle,\n options?: TxnCommitOptions,\n ) => Promise<TxnCommitResult>;\n\n // --- actions / releases ---\n /**\n * Dispatch one or more release / version actions against the store.\n * Returns a synthetic `transactionId`. Multi-action arrays are applied\n * atomically — any failure rolls back the batch.\n */\n action: (action: Action | Action[]) => Promise<ActionResult>;\n /** Helpers mirroring `@sanity/client`'s `client.releases.*` surface. */\n releases: ReleasesHandle;\n /** Helper for `sanity.action.document.version.create`. */\n createVersion: (params: {\n releaseId: string;\n publishedId: string;\n document: DocumentBody;\n }) => Promise<ActionResult>;\n /** Helper for `sanity.action.document.version.unpublish`. */\n unpublishVersion: (params: { releaseId: string; publishedId: string }) => Promise<ActionResult>;\n\n // --- config ---\n /** Current `(projectId, dataset)` and active perspective. */\n config: () => { projectId: string; dataset: string; perspective: Perspective };\n /**\n * Return a new client handle pointing at a different `(projectId, dataset)`\n * within the SAME backing registry. Either field can be omitted to keep\n * the current value. Two clients produced by `withConfig` see each\n * other's writes if they point at the same `(projectId, dataset)`.\n */\n withConfig: (\n config: Partial<{\n projectId: string;\n dataset: string;\n perspective: Perspective;\n /**\n * Rebind the acting identity (and its grants) on a sibling that shares\n * the same store — the test analogue of a token-scoped client. Lets two\n * actors write the same dataset, e.g. for `identity()`-based guards.\n */\n accessControl: TestClientAccessControl;\n }>,\n ) => TestClient;\n\n // --- test helpers (not on real SanityClient) ---\n /** Replace the current dataset with the given documents. */\n seed: (documents: SanityDocumentLike[]) => void;\n /** Add documents to the current dataset without dropping existing ones. */\n add: (documents: SanityDocumentLike[]) => void;\n /** Drop all documents in the current dataset. */\n reset: () => void;\n /** Read-only snapshot of all documents in the current dataset. */\n snapshot: () => readonly SanityDocument[];\n /** Direct store access for the current dataset. */\n store: () => TestStore;\n /**\n * Simulate `count` concurrent edits to `id` in the current dataset: the\n * next `count` revision-guarded mutations (those passing `ifRevisionId`)\n * to that document throw a 409-shaped conflict, as if another client\n * committed between the caller's read and write. Lets a test exercise\n * optimistic-locking retry paths deterministically, without timing or\n * interleaving. Mutations that don't pass `ifRevisionId` are unaffected.\n */\n simulateConcurrentEdit: (id: string, count?: number) => void;\n /** List `(projectId, dataset)` pairs known in this registry. */\n datasets: () => { projectId: string; dataset: string }[];\n /**\n * Register a handler for a `@sanity/client` member the fake doesn't\n * implement (e.g. `listen`, `assets`). Accessing that member on the\n * client then returns the handler instead of throwing the\n * \"not implemented\" guard error. Shared across sibling `withConfig`\n * handles. Stubs fill gaps only — they don't shadow implemented methods.\n */\n stub: (name: string, handler: unknown) => void;\n /** The currently-registered stubs, keyed by member name. */\n stubs: () => Record<string, unknown>;\n /**\n * Every mutation committed through this client's registry, flattened\n * and in order — `create` / `createOrReplace` / `createIfNotExists` /\n * `delete` / `patch`, whether issued directly, via `transaction()`, or\n * via `mutate()`. The spy hook for \"assert exactly what writes my code\n * submitted\".\n */\n mutations: () => TxnMutation[];\n /**\n * Every committed transaction, in order. A direct mutation is recorded\n * as a one-mutation transaction. Each entry carries its synthetic\n * `transactionId` and the `(projectId, dataset)` it targeted.\n */\n transactions: () => MutationLogEntry[];\n /** Clear the recorded mutation / transaction log. */\n clearLog: () => void;\n /**\n * Every recorded method call, in order — the spy layer for \"was `fetch`\n * called, how many times, and with what params\". Records the\n * `@sanity/client`-surface methods (`fetch`, `getDocument`, `create`,\n * `patch`, `mutate`, `releases.*`, …), not the test-only helpers.\n * Pass a method name to filter (e.g. `calls(\"fetch\")`); namespace\n * methods are dotted (`calls(\"releases.create\")`). Shared across\n * `withConfig` siblings.\n */\n calls: (method?: string) => CallRecord[];\n /** Number of recorded calls, optionally filtered by method name. */\n callCount: (method?: string) => number;\n /** Clear the recorded call log. */\n clearCalls: () => void;\n}\n\nexport interface ReleasesHandle {\n create: (params: {\n releaseId: string;\n metadata?: Partial<ReleaseMetadata>;\n }) => Promise<ActionResult & { releaseId: string; metadata: ReleaseMetadata }>;\n edit: (params: {\n releaseId: string;\n patch: { set?: Record<string, unknown>; unset?: string[] };\n }) => Promise<ActionResult>;\n get: (params: { releaseId: string }) => Promise<ReleaseDocument | undefined>;\n fetchDocuments: (params: { releaseId: string }) => Promise<SanityDocument[]>;\n schedule: (params: { releaseId: string; publishAt: string }) => Promise<ActionResult>;\n unschedule: (params: { releaseId: string }) => Promise<ActionResult>;\n publish: (params: { releaseId: string }) => Promise<ActionResult>;\n archive: (params: { releaseId: string }) => Promise<ActionResult>;\n unarchive: (params: { releaseId: string }) => Promise<ActionResult>;\n delete: (params: { releaseId: string }) => Promise<ActionResult>;\n}\n\nexport interface MutationOptions {\n ifRevisionId?: string;\n /**\n * Shape the resolved value, mirroring `@sanity/client`:\n * - default → the mutated document\n * - `returnDocuments: false` → an id-shaped mutation result\n * ({@link SingleMutationResult} / {@link MultipleMutationResult})\n * - `returnFirst: false` with documents → an array\n *\n * The static return type reflects the default (the document); pass a\n * type argument or cast when requesting an id-shaped result.\n */\n returnDocuments?: boolean;\n returnFirst?: boolean;\n /** Override the synthetic transaction id used in the result and log. */\n transactionId?: string;\n /** When `true`, validate + shape the result but don't persist. */\n dryRun?: boolean;\n /** Accepted for signature parity; not simulated. */\n visibility?: \"sync\" | \"async\" | \"deferred\";\n /** Accepted for signature parity; not simulated. */\n autoGenerateArrayKeys?: boolean;\n /** Accepted for signature parity; not simulated. */\n tag?: string;\n}\n\nexport interface SystemFields {\n _rev: string;\n _createdAt: string;\n _updatedAt: string;\n}\n\nexport interface CreateTestClientOptions {\n /** Default project id. Defaults to `\"test\"`. */\n projectId?: string;\n /** Default dataset name. Defaults to `\"test\"`. */\n dataset?: string;\n /** Documents to seed into the default `(projectId, dataset)` store. */\n documents?: SanityDocumentLike[];\n /**\n * Optional: seed multiple datasets at once. Keys are `\"projectId:dataset\"`\n * pairs. Useful when workflows span multiple datasets.\n */\n datasets?: Record<string, SanityDocumentLike[]>;\n /**\n * Opt-in access-control simulation. When set, the client exposes\n * `request({ url })` that serves `/users/me` + the configured ACL\n * path, AND every mutation is gated through the supplied `grants`\n * — writes that the grants don't permit throw a `WriteAccessDeniedError`\n * shaped like Sanity's 403. Lets tests demonstrate the full\n * \"engine soft-gate + lake hard-gate\" contract end-to-end without\n * a real HTTP round-trip.\n *\n * When omitted, `request` is undefined and all writes proceed\n * unconditionally — the legacy behavior.\n */\n accessControl?: TestClientAccessControl;\n /**\n * Pluggable write interceptor — runs on each write through the document\n * mutation API (create/patch/delete/transaction; not the release/version\n * action API) before the store changes, and may throw to reject it. The\n * client has no opinion about the policy; callers (e.g. a workflow test bench\n * enforcing lake mutation guards) supply it. Inherited by `withConfig`\n * siblings. See {@link MutationGuard}.\n */\n mutationGuard?: MutationGuard;\n /**\n * Default perspective applied to reads. Per-fetch `options.perspective`\n * overrides this. `withConfig({ perspective })` returns a sibling\n * handle with a different default. Defaults to `\"raw\"` so existing\n * tests stay green.\n */\n perspective?: Perspective;\n}\n\nexport type { Perspective } from \"./perspective.ts\";\nexport type {\n Action,\n ActionResult,\n DocumentBody,\n ReleaseAction,\n ReleaseDocument,\n ReleaseMetadata,\n ReleaseState,\n ReleaseType,\n VersionAction,\n} from \"./actions.ts\";\n\nexport type { TestClientAccessControl, DocumentValuePermission } from \"./access-control.ts\";\nexport { WriteAccessDeniedError } from \"./access-control.ts\";\n\nconst DEFAULT_PROJECT_ID = \"test\";\nconst DEFAULT_DATASET = \"test\";\n\ntype Registry = Map<string, TestStore>;\n\n/**\n * Shared backing context for one `createTestClient()` call and all the\n * `withConfig` siblings it spawns: the multi-dataset store registry, the\n * append-only mutation log, and the stub registry. Sibling handles see\n * each other's writes, log entries, and stubs.\n */\ninterface Backend {\n registry: Registry;\n log: MutationLogEntry[];\n stubs: Map<string, unknown>;\n calls: CallRecord[];\n /**\n * Pending simulated concurrent edits, keyed per (dataset, document id).\n * Each entry is a count of upcoming revision-guarded mutations that\n * should 409 as if another client raced them. See\n * {@link TestClient.simulateConcurrentEdit}.\n */\n concurrentEdits: Map<string, number>;\n}\n\nconst registryKey = (projectId: string, dataset: string) => `${projectId}:${dataset}`;\n\nconst parseRegistryKey = (key: string): { projectId: string; dataset: string } => {\n const [projectId, dataset] = key.split(\":\") as [string, string];\n return { projectId, dataset };\n};\n\n/**\n * Create a fresh, isolated test client backed by a private multi-dataset\n * registry. `withConfig` returns a sibling handle into the same registry.\n *\n * ```\n * const client = createTestClient({\n * datasets: {\n * \"test:definitions\": [...],\n * \"test:instances\": [...],\n * },\n * });\n * const defs = client.withConfig({ dataset: \"definitions\" });\n * const inst = client.withConfig({ dataset: \"instances\" });\n * ```\n */\nexport function createTestClient(options: CreateTestClientOptions = {}): TestClient {\n const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID;\n const defaultDataset = options.dataset ?? DEFAULT_DATASET;\n\n const backend: Backend = {\n registry: new Map(),\n log: [],\n stubs: new Map(),\n calls: [],\n concurrentEdits: new Map(),\n };\n const registry = backend.registry;\n\n const ensureStore = (projectId: string, dataset: string): TestStore => {\n const key = registryKey(projectId, dataset);\n let store = registry.get(key);\n if (store === undefined) {\n store = createTestStore();\n registry.set(key, store);\n }\n return store;\n };\n\n // Seed defaults.\n if (options.documents) {\n ensureStore(defaultProjectId, defaultDataset).seed(options.documents);\n }\n if (options.datasets) {\n for (const [key, docs] of Object.entries(options.datasets)) {\n const { projectId, dataset } = parseRegistryKey(key);\n ensureStore(projectId, dataset).seed(docs);\n }\n }\n\n return makeHandle(\n backend,\n defaultProjectId,\n defaultDataset,\n options.accessControl,\n options.perspective ?? \"raw\",\n options.mutationGuard,\n );\n}\n\n/** Affected ids in order, de-duplicated — the `documentIds` of a result. */\nfunction dedupeIds(results: { id: string }[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const r of results) {\n if (!seen.has(r.id)) {\n seen.add(r.id);\n out.push(r.id);\n }\n }\n return out;\n}\n\n/**\n * Resolve a mutation's return value the way `@sanity/client` does, from\n * already-resolved `returnDocuments` / `returnFirst` booleans (callers\n * apply their own defaults: document-first for create-family,\n * ids-for-all for transaction / mutate).\n */\nfunction formatMutationResult(\n documents: SanityDocument[],\n results: { id: string; operation: MutationOperation }[],\n transactionId: string,\n returnDocuments: boolean,\n returnFirst: boolean,\n): TxnCommitResult {\n if (returnDocuments) {\n return returnFirst ? (documents[0] as SanityDocument) : documents;\n }\n if (returnFirst) {\n return {\n transactionId,\n documentId: results[0]?.id as string,\n results,\n } satisfies SingleMutationResult;\n }\n return {\n transactionId,\n documentIds: dedupeIds(results),\n results,\n } satisfies MultipleMutationResult;\n}\n\n/** Convert one raw `mutate()` operation object into a {@link TxnMutation}. */\nfunction toSingleTxnMutation(op: FakeMutation): TxnMutation {\n if (\"create\" in op) return { kind: \"create\", doc: op.create };\n if (\"createOrReplace\" in op) return { kind: \"createOrReplace\", doc: op.createOrReplace };\n if (\"createIfNotExists\" in op) return { kind: \"createIfNotExists\", doc: op.createIfNotExists };\n if (\"delete\" in op) return { kind: \"delete\", id: op.delete.id };\n\n const p = op.patch;\n const ops: PatchOp[] = [];\n if (p.set !== undefined) ops.push({ kind: \"set\", props: p.set });\n if (p.setIfMissing !== undefined) ops.push({ kind: \"setIfMissing\", props: p.setIfMissing });\n if (p.unset !== undefined) ops.push({ kind: \"unset\", paths: p.unset });\n if (p.inc !== undefined) ops.push({ kind: \"inc\", props: p.inc });\n if (p.dec !== undefined) ops.push({ kind: \"dec\", props: p.dec });\n if (p.insert !== undefined) {\n const { before, after, replace, items } = p.insert;\n const position = before !== undefined ? \"before\" : after !== undefined ? \"after\" : \"replace\";\n const anchor = before ?? after ?? replace;\n if (anchor === undefined) {\n throw fakeError(\n \"mutate(): a `patch.insert` operation must name exactly one anchor — `before`, `after`, \" +\n 'or `replace` — pointing at an array path (e.g. \"tags[-1]\" or `tags[_key==\"x\"]`), ' +\n \"alongside `items`. None was set.\",\n );\n }\n ops.push({ kind: \"insert\", position, anchor, items });\n }\n return {\n kind: \"patch\",\n documentId: p.id,\n ops,\n ...(p.ifRevisionID !== undefined ? { ifRev: p.ifRevisionID } : {}),\n };\n}\n\n/** Normalise `mutate()` input (raw array, Patch, or Transaction) to mutations. */\nfunction toTxnMutations(\n operations: FakeMutation[] | PatchHandle | TransactionHandle,\n): TxnMutation[] {\n if (Array.isArray(operations)) return operations.map(toSingleTxnMutation);\n // Both builders expose toJSON(); a Transaction yields an array, a Patch\n // yields a single `{ id, ops, ifRev? }`.\n const json = operations.toJSON();\n if (Array.isArray(json)) return json;\n return [\n {\n kind: \"patch\",\n documentId: json.id,\n ops: json.ops,\n ...(json.ifRev !== undefined ? { ifRev: json.ifRev } : {}),\n },\n ];\n}\n\nfunction makeHandle(\n backend: Backend,\n projectId: string,\n dataset: string,\n accessControl: TestClientAccessControl | undefined,\n perspective: Perspective,\n mutationGuard: MutationGuard | undefined,\n): TestClient {\n const { registry } = backend;\n const store = (() => {\n const key = registryKey(projectId, dataset);\n let s = registry.get(key);\n if (s === undefined) {\n s = createTestStore();\n registry.set(key, s);\n }\n return s;\n })();\n\n /** Key into {@link Backend.concurrentEdits} for a doc in this dataset. */\n const concurrentEditKey = (id: string): string => registryKey(projectId, dataset) + \" \" + id;\n\n /** Append a committed transaction to the shared log. */\n const record = (transactionId: string, mutations: TxnMutation[]): void => {\n backend.log.push({ transactionId, projectId, dataset, mutations });\n };\n\n /**\n * Shape a single-document write result. Create-family methods default\n * to returning the document (first), unlike transaction / mutate.\n */\n const writeResult = (\n documents: SanityDocument[],\n results: { id: string; operation: MutationOperation }[],\n transactionId: string,\n opts: MutationOptions | undefined,\n ): TxnCommitResult =>\n formatMutationResult(\n documents,\n results,\n transactionId,\n opts?.returnDocuments ?? true,\n opts?.returnFirst ?? true,\n );\n\n const promote = (doc: SanityDocumentLike): SanityDocument & SystemFields => {\n const now = new Date().toISOString();\n if (typeof doc._id !== \"string\" || doc._id.length === 0) {\n throw fakeError(\n `Cannot store a document without a non-empty string \\`_id\\` (got ${JSON.stringify(doc._id)}). ` +\n `Unlike @sanity/client, this fake never auto-generates ids — give every document an explicit _id.`,\n );\n }\n if (typeof doc._type !== \"string\" || doc._type.length === 0) {\n throw fakeError(\n `Document \"${doc._id}\" is missing a non-empty string \\`_type\\` (got ${JSON.stringify(doc._type)}). ` +\n `Every Sanity document needs a _type.`,\n );\n }\n return {\n ...doc,\n _id: doc._id,\n _type: doc._type,\n _rev: cryptoRandomKey(),\n _createdAt: doc._createdAt ?? now,\n _updatedAt: now,\n } as SanityDocument & SystemFields;\n };\n\n const checkRevision = (id: string, ifRevisionId: string | undefined) => {\n if (ifRevisionId === undefined) return;\n // A pending simulated concurrent edit beats the real revision check —\n // the guarded write loses the race even if its _rev currently matches.\n const editKey = concurrentEditKey(id);\n const pendingEdits = backend.concurrentEdits.get(editKey) ?? 0;\n if (pendingEdits > 0) {\n backend.concurrentEdits.set(editKey, pendingEdits - 1);\n throw fakeError(\n `ifRevisionId check failed: document \"${id}\" was concurrently edited (simulated via ` +\n `simulateConcurrentEdit) — the revision-guarded mutation lost the race; re-read and retry. ` +\n `(This mirrors Sanity's optimistic-locking 409.)`,\n );\n }\n const existing = store.get(id);\n if (existing === undefined) {\n throw fakeError(\n `ifRevisionId check failed: document \"${id}\" does not exist, so its revision cannot match ` +\n `the expected _rev=\"${ifRevisionId}\". Drop ifRevisionId when creating a new document, or ` +\n `seed/create the document before guarding on its revision.`,\n );\n }\n if (existing._rev !== ifRevisionId) {\n throw fakeError(\n `ifRevisionId check failed: document \"${id}\" is at _rev=\"${existing._rev}\" but the mutation ` +\n `required _rev=\"${ifRevisionId}\". The document changed since you read it — re-read it and ` +\n `retry. (This mirrors Sanity's optimistic-locking 409.)`,\n );\n }\n };\n\n /**\n * Gate a mutation through the configured `accessControl.grants`. No-op\n * when accessControl is absent (legacy bench behavior). On denial\n * throws `WriteAccessDeniedError` — same failure mode tests get from\n * a real Sanity 403.\n *\n * Pass the doc as-it-would-be at evaluation time: for `create` /\n * `createOrReplace`-as-create / `createIfNotExists`, that's the new\n * doc with its incoming fields; for `update` / `patch` / `delete`,\n * that's the existing doc (the grant filter identifies what the\n * actor can touch).\n */\n const gate = async (\n document: SanityDocumentLike & { _id?: string; _type?: string },\n permission: DocumentValuePermission,\n ): Promise<void> => {\n if (accessControl === undefined) return;\n await enforceWriteAccess({\n document,\n grants: accessControl.grants,\n permission,\n userId: accessControl.currentUser.id,\n });\n };\n\n /**\n * Run the configured {@link MutationGuard} for one write (no-op when none is\n * configured). `identity` is the client's bound user — its token's\n * `accessControl.currentUser` — so guard predicates resolve `identity()` to\n * whoever the client is acting as. Throws propagate, rejecting the write.\n */\n const guardGate = async (\n action: MutationGuardContext[\"action\"],\n before: MutationGuardContext[\"before\"],\n after: MutationGuardContext[\"after\"],\n ): Promise<void> => {\n if (mutationGuard === undefined) return;\n await mutationGuard({ action, before, after, identity: accessControl?.currentUser.id });\n };\n\n /**\n * Read-gate predicate. Sanity surfaces invisible docs as \"doesn't\n * exist\" on the wire (404 / null) rather than throwing 403 — so\n * reads filter rather than refuse.\n *\n * - `fetch` filters the dataset before running GROQ.\n * - `getDocument` / `getDocuments` return null for invisible docs.\n * - `snapshot` is a test-helper that bypasses the read gate\n * intentionally (tests need raw inspection).\n *\n * Returns `true` when accessControl is absent (no gating).\n */\n const canRead = async (\n document: SanityDocumentLike & { _id?: string; _type?: string },\n ): Promise<boolean> => {\n if (accessControl === undefined) return true;\n return canAccess({\n document,\n grants: accessControl.grants,\n permission: \"read\",\n userId: accessControl.currentUser.id,\n });\n };\n\n const applyPatch = async (\n documentId: string,\n ops: PatchOp[],\n ifRev: string | undefined,\n ): Promise<SanityDocument> => {\n const existing = store.get(documentId);\n if (existing === undefined) {\n throw fakeError(\n `Cannot patch document \"${documentId}\": not found — no document with that _id exists in ` +\n `dataset \"${projectId}:${dataset}\". patch() requires the target to already exist; use ` +\n `createOrReplace() / createIfNotExists() to upsert, or seed the document first.`,\n );\n }\n checkRevision(documentId, ifRev);\n // Gate against the existing doc — that's what the grant filter\n // matches: \"what docs can this actor update?\".\n await gate(existing, \"update\");\n const patched = applyPatchOps(existing, ops);\n const now = new Date().toISOString();\n const next: SanityDocument = {\n ...patched,\n _rev: cryptoRandomKey(),\n _updatedAt: now,\n };\n await guardGate(\"update\", existing, next);\n store.put(next);\n return next;\n };\n\n const applyTransaction = async (\n mutations: TxnMutation[],\n txnOptions?: TxnCommitOptions,\n ): Promise<TxnCommitResult> => {\n const transactionId = txnOptions?.transactionId ?? cryptoRandomKey();\n const snapshot = new Map<string, SanityDocument | undefined>();\n const touchedIds: string[] = [];\n const operations: { id: string; operation: MutationOperation }[] = [];\n\n const remember = (id: string) => {\n if (!snapshot.has(id)) snapshot.set(id, store.get(id));\n };\n\n try {\n for (const mut of mutations) {\n switch (mut.kind) {\n case \"create\": {\n remember(mut.doc._id as string);\n const promoted = promote(mut.doc);\n if (store.get(promoted._id) !== undefined) {\n throw fakeError(\n `create() failed: a document with _id \"${promoted._id}\" already exists in dataset ` +\n `\"${projectId}:${dataset}\". Use createOrReplace() to overwrite it, or ` +\n `createIfNotExists() to leave the existing one untouched.`,\n );\n }\n await gate(promoted, \"create\");\n await guardGate(\"create\", null, promoted);\n store.put(promoted);\n touchedIds.push(promoted._id);\n operations.push({ id: promoted._id, operation: \"create\" });\n break;\n }\n case \"createOrReplace\": {\n remember(mut.doc._id as string);\n const promoted = promote(mut.doc);\n const existing = store.get(promoted._id);\n // For an existing doc, \"update\" is the relevant permission;\n // for a net-new one, \"create\".\n await gate(existing ?? promoted, existing !== undefined ? \"update\" : \"create\");\n await guardGate(\n existing !== undefined ? \"update\" : \"create\",\n existing ?? null,\n promoted,\n );\n const wasPresent = existing !== undefined;\n store.put(promoted);\n touchedIds.push(promoted._id);\n operations.push({ id: promoted._id, operation: wasPresent ? \"update\" : \"create\" });\n break;\n }\n case \"createIfNotExists\": {\n remember(mut.doc._id as string);\n if (store.get(mut.doc._id as string) === undefined) {\n const promoted = promote(mut.doc);\n await gate(promoted, \"create\");\n await guardGate(\"create\", null, promoted);\n store.put(promoted);\n touchedIds.push(promoted._id);\n operations.push({ id: promoted._id, operation: \"create\" });\n }\n break;\n }\n case \"delete\": {\n remember(mut.id);\n const existing = store.get(mut.id);\n // Sanity's permission model has no separate \"delete\" —\n // delete is gated as an update against the existing doc.\n if (existing !== undefined) await gate(existing, \"update\");\n if (existing !== undefined) await guardGate(\"delete\", existing, null);\n const removed = store.remove(mut.id);\n if (removed) {\n touchedIds.push(mut.id);\n operations.push({ id: mut.id, operation: \"delete\" });\n }\n break;\n }\n case \"patch\": {\n remember(mut.documentId);\n // applyPatch already gates internally.\n await applyPatch(mut.documentId, mut.ops, mut.ifRev);\n touchedIds.push(mut.documentId);\n operations.push({ id: mut.documentId, operation: \"update\" });\n break;\n }\n }\n }\n } catch (error) {\n for (const [id, doc] of snapshot) {\n if (doc === undefined) {\n store.remove(id);\n } else {\n store.put(doc);\n }\n }\n throw error;\n }\n\n // A committed transaction is logged whole; a single-mutation form\n // (create / patch / mutate of one op) lands as a one-entry transaction.\n record(transactionId, mutations);\n\n const documents = touchedIds\n .map((id) => store.get(id))\n .filter((d): d is SanityDocument => d !== undefined);\n // Transaction / mutate default to the id-shaped `MultipleMutationResult`,\n // matching `@sanity/client` (create-family defaults differ).\n return formatMutationResult(\n documents,\n operations,\n transactionId,\n txnOptions?.returnDocuments ?? false,\n txnOptions?.returnFirst ?? false,\n );\n };\n\n /**\n * Filter the store's docs to only those `canRead` returns true\n * for. When accessControl is unset, returns the full set (no\n * filtering cost). Used by `fetch` so GROQ runs against the\n * actor-visible subset, matching Sanity's per-token query behavior.\n */\n const accessVisibleDocs = async (): Promise<SanityDocument[]> => {\n const all = store.all();\n if (accessControl === undefined) return all;\n const out: SanityDocument[] = [];\n for (const doc of all) {\n if (await canRead(doc)) out.push(doc);\n }\n return out;\n };\n\n /**\n * Apply both access-control gating and perspective layering. The order\n * matters: access first (an invisible doc shouldn't even be a candidate\n * for perspective layering), perspective second (which can hide / merge\n * docs that the actor would otherwise see).\n */\n const visibleDocs = async (override?: Perspective): Promise<SanityDocument[]> => {\n const accessible = await accessVisibleDocs();\n return applyPerspective(accessible, override ?? perspective);\n };\n\n const client: TestClient = {\n fetch: async (query, params, opts) => {\n const start = Date.now();\n const tree = parse(query, params ? { params } : undefined);\n const value = await evaluate(tree, {\n dataset: await visibleDocs(opts?.perspective),\n ...(params !== undefined ? { params } : {}),\n });\n const result = await value.get();\n if (opts?.filterResponse === false) {\n const ms = Date.now() - start;\n const raw = opts.returnQuery === false ? { ms, result } : { query, ms, result };\n return raw as never;\n }\n return result as never;\n },\n\n getDocument: async (id, opts) => {\n const effective = opts?.perspective ?? perspective;\n if (effective === \"raw\") {\n const doc = store.get(id);\n if (doc === undefined) return undefined;\n if (!(await canRead(doc))) return undefined;\n return doc as never;\n }\n const view = await visibleDocs(effective);\n const found = resolveDocument(view, id, effective);\n return (found ?? undefined) as never;\n },\n\n getDocuments: async (ids, opts) => {\n const effective = opts?.perspective ?? perspective;\n if (effective === \"raw\") {\n const result: (SanityDocument | null)[] = [];\n for (const id of ids) {\n const doc = store.get(id);\n if (doc === undefined) result.push(null);\n else if (await canRead(doc)) result.push(doc);\n else result.push(null);\n }\n return result as never;\n }\n const view = await visibleDocs(effective);\n return ids.map((id) => resolveDocument(view, id, effective) ?? null) as never;\n },\n\n create: async (doc, opts) => {\n checkRevision(doc._id as string, opts?.ifRevisionId);\n if (store.get(doc._id as string) !== undefined) {\n throw fakeError(\n `create() failed: a document with _id \"${doc._id}\" already exists in dataset ` +\n `\"${projectId}:${dataset}\". Use createOrReplace() to overwrite it, or ` +\n `createIfNotExists() to leave the existing one untouched.`,\n );\n }\n const promoted = promote(doc);\n await gate(promoted, \"create\");\n await guardGate(\"create\", null, promoted);\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n if (opts?.dryRun !== true) {\n store.put(promoted);\n record(transactionId, [{ kind: \"create\", doc }]);\n }\n return writeResult(\n [promoted],\n [{ id: promoted._id, operation: \"create\" }],\n transactionId,\n opts,\n ) as never;\n },\n\n createOrReplace: async (doc, opts) => {\n checkRevision(doc._id as string, opts?.ifRevisionId);\n const promoted = promote(doc);\n const existing = store.get(doc._id as string);\n await gate(existing ?? promoted, existing !== undefined ? \"update\" : \"create\");\n await guardGate(existing !== undefined ? \"update\" : \"create\", existing ?? null, promoted);\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n if (opts?.dryRun !== true) {\n store.put(promoted);\n record(transactionId, [{ kind: \"createOrReplace\", doc }]);\n }\n const operation: MutationOperation = existing !== undefined ? \"update\" : \"create\";\n return writeResult(\n [promoted],\n [{ id: promoted._id, operation }],\n transactionId,\n opts,\n ) as never;\n },\n\n createIfNotExists: async (doc, opts) => {\n checkRevision(doc._id as string, opts?.ifRevisionId);\n const existing = store.get(doc._id as string);\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n if (existing !== undefined) {\n return writeResult(\n [existing],\n [{ id: existing._id, operation: \"none\" }],\n transactionId,\n opts,\n ) as never;\n }\n const promoted = promote(doc);\n await gate(promoted, \"create\");\n await guardGate(\"create\", null, promoted);\n if (opts?.dryRun !== true) {\n store.put(promoted);\n record(transactionId, [{ kind: \"createIfNotExists\", doc }]);\n }\n return writeResult(\n [promoted],\n [{ id: promoted._id, operation: \"create\" }],\n transactionId,\n opts,\n ) as never;\n },\n\n delete: async (id, opts) => {\n checkRevision(id, opts?.ifRevisionId);\n const existing = store.get(id);\n if (existing !== undefined) await gate(existing, \"update\");\n if (existing !== undefined) await guardGate(\"delete\", existing, null);\n const transactionId = opts?.transactionId ?? cryptoRandomKey();\n let removed: SanityDocument | undefined = existing;\n if (opts?.dryRun !== true) {\n removed = store.remove(id);\n if (removed !== undefined) record(transactionId, [{ kind: \"delete\", id }]);\n }\n // Legacy default shape ({ _id } | null) unless the caller asked for\n // a specific return shape via returnDocuments / returnFirst.\n if (opts?.returnDocuments === undefined && opts?.returnFirst === undefined) {\n return (removed !== undefined ? { _id: id } : null) as never;\n }\n const results = removed !== undefined ? [{ id, operation: \"delete\" as const }] : [];\n const docs = removed !== undefined ? [removed] : [];\n return formatMutationResult(\n docs,\n results,\n transactionId,\n opts.returnDocuments ?? true,\n opts.returnFirst ?? true,\n ) as never;\n },\n\n patch: (documentId) =>\n createPatch(documentId, {\n apply: async (docId, ops, ifRev) => {\n const doc = await applyPatch(docId, ops, ifRev);\n record(cryptoRandomKey(), [\n { kind: \"patch\", documentId: docId, ops, ...(ifRev !== undefined ? { ifRev } : {}) },\n ]);\n return doc;\n },\n }),\n\n transaction: () => createTransaction({ apply: applyTransaction }),\n\n mutate: async (operations, options) => applyTransaction(toTxnMutations(operations), options),\n\n action: async (action) => applyActions(store, action),\n\n releases: {\n create: async ({ releaseId, metadata }) => {\n const result = applyActions(store, {\n actionType: \"sanity.action.release.create\",\n releaseId,\n ...(metadata !== undefined ? { metadata } : {}),\n });\n const doc = store.get(`_.releases.${releaseId}`) as ReleaseDocument | undefined;\n return {\n ...result,\n releaseId,\n metadata: doc?.metadata ?? { releaseType: \"undecided\" },\n };\n },\n edit: async ({ releaseId, patch }) =>\n applyActions(store, { actionType: \"sanity.action.release.edit\", releaseId, patch }),\n get: async ({ releaseId }) => {\n const doc = store.get(`_.releases.${releaseId}`) as ReleaseDocument | undefined;\n return doc;\n },\n fetchDocuments: async ({ releaseId }) => {\n const prefix = `versions.${releaseId}.`;\n return store.all().filter((d) => d._id.startsWith(prefix));\n },\n schedule: async ({ releaseId, publishAt }) =>\n applyActions(store, {\n actionType: \"sanity.action.release.schedule\",\n releaseId,\n publishAt,\n }),\n unschedule: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.unschedule\", releaseId }),\n publish: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.publish\", releaseId }),\n archive: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.archive\", releaseId }),\n unarchive: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.unarchive\", releaseId }),\n delete: async ({ releaseId }) =>\n applyActions(store, { actionType: \"sanity.action.release.delete\", releaseId }),\n },\n\n createVersion: async ({ releaseId, publishedId, document }) =>\n applyActions(store, {\n actionType: \"sanity.action.document.version.create\",\n releaseId,\n publishedId,\n document,\n }),\n\n unpublishVersion: async ({ releaseId, publishedId }) =>\n applyActions(store, {\n actionType: \"sanity.action.document.version.unpublish\",\n versionId: `versions.${releaseId}.${publishedId}`,\n publishedId,\n }),\n\n ...(accessControl !== undefined\n ? { request: makeRequestImpl(accessControl, projectId, dataset) }\n : {}),\n\n config: () => ({ projectId, dataset, perspective }),\n\n withConfig: (config) =>\n makeHandle(\n backend,\n config.projectId ?? projectId,\n config.dataset ?? dataset,\n config.accessControl ?? accessControl,\n config.perspective ?? perspective,\n mutationGuard,\n ),\n\n seed: (documents) => store.seed(documents),\n add: (documents) => store.add(documents),\n reset: () => store.reset(),\n snapshot: () => store.snapshot(),\n store: () => store,\n simulateConcurrentEdit: (id, count = 1) => {\n const editKey = concurrentEditKey(id);\n backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);\n },\n datasets: () => [...registry.keys()].map(parseRegistryKey),\n stub: (name, handler) => {\n backend.stubs.set(name, handler);\n },\n stubs: () => Object.fromEntries(backend.stubs),\n mutations: () => backend.log.flatMap((entry) => entry.mutations),\n transactions: () => [...backend.log],\n clearLog: () => {\n backend.log.length = 0;\n },\n calls: (method) =>\n method === undefined ? [...backend.calls] : backend.calls.filter((c) => c.method === method),\n callCount: (method) =>\n method === undefined\n ? backend.calls.length\n : backend.calls.filter((c) => c.method === method).length,\n clearCalls: () => {\n backend.calls.length = 0;\n },\n };\n\n // Record an invocation: capture args now, fill the outcome on settle.\n const onCall = (method: string, args: unknown[]): CallSettler => {\n const rec: CallRecord = { method, args, projectId, dataset };\n backend.calls.push(rec);\n return (outcome) => {\n if (\"error\" in outcome) rec.error = outcome.error;\n else rec.result = outcome.result;\n };\n };\n\n // Wrap so unimplemented members fail with actionable errors, registered\n // stubs are served, and surface-method calls are recorded (see\n // ./unsupported.ts).\n return wrapWithGuards(client, {\n getStub: (name) => backend.stubs.get(name),\n onCall,\n recorded: RECORDED_METHODS,\n });\n}\n"],"names":["promote","RELEASE_DOC_PREFIX","VERSIONS_PREFIX"],"mappings":";AAWO,MAAM,aAAa;AAGnB,SAAS,UAA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