@sanity-labs/client-fake-for-test 0.0.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 +125 -0
- package/dist/index.cjs +522 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +465 -0
- package/dist/index.d.ts +465 -0
- package/dist/index.js +522 -0
- package/dist/index.js.map +1 -0
- package/package.json +70 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/access-control.ts","../src/patch.ts","../src/store.ts","../src/transaction.ts","../src/client.ts"],"sourcesContent":["/**\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\";\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 new Error(\n `TestClient.request: no handler for path \"${path}\". The TestClient only serves ` +\n `\"/users/me\" and \"${aclPath}\". Configure additional endpoints via createTestClient({ accessControl }).`,\n );\n };\n}\n","import type { SanityDocument } from \"@sanity/types\";\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) throw new Error(`Unsupported patch path segment: ${raw}`);\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 new Error(`Unsupported array selector in patch path: ${selectorRaw}`);\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 new Error(`No array entry matched ${selector.field}==\"${selector.value}\" in patch path`);\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) throw new Error(`Empty patch path`);\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 new Error(`Patch path crosses non-array at segment ${seg.key}`);\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 new Error(`Patch path crosses non-array at segment ${last.key}`);\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) throw new Error(`Empty insert anchor`);\n const last = segments[segments.length - 1] as PathSegment;\n if (last.selector === undefined) {\n throw new Error(`Insert anchor must end with an array selector: ${anchor}`);\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 new Error(`Insert anchor traverses missing field: ${seg.key}`);\n }\n if (seg.selector !== undefined) {\n if (!Array.isArray(next)) {\n throw new Error(`Insert anchor traverses non-array at: ${seg.key}`);\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 new Error(`Insert anchor target is not an array: ${last.key}`);\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","import type { SanityDocument, SanityDocumentLike } from \"@sanity/types\";\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 new Error(`document is missing _id: ${JSON.stringify(doc)}`);\n }\n if (typeof doc._type !== \"string\" || doc._type.length === 0) {\n throw new Error(`document ${doc._id} is missing _type`);\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, 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 /** If true, returns the resulting documents instead of just ids. */\n returnDocuments?: boolean;\n /** With `returnDocuments`, return only the first updated doc. */\n returnFirst?: boolean;\n}\n\nexport type TxnCommitResult =\n | {\n transactionId: string;\n results: { id: string; operation: \"create\" | \"update\" | \"delete\" }[];\n }\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","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 { applyPatchOps, createPatch, type PatchHandle, type PatchOp } from \"./patch.ts\";\nimport { createTestStore, cryptoRandomKey, type TestStore } from \"./store.ts\";\nimport {\n createTransaction,\n type TransactionHandle,\n type TxnCommitOptions,\n type TxnCommitResult,\n type TxnMutation,\n} from \"./transaction.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 * - Perspective handling.\n */\nexport interface TestClient {\n // --- query ---\n fetch: <T = unknown>(query: string, params?: Record<string, unknown>) => Promise<T>;\n getDocument: <T = SanityDocument>(id: string) => Promise<T | null>;\n getDocuments: <T = SanityDocument>(ids: string[]) => 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 // --- config ---\n /** Current `(projectId, dataset)`. */\n config: () => { projectId: string; dataset: string };\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: (config: Partial<{ projectId: string; dataset: string }>) => 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\nexport interface MutationOptions {\n ifRevisionId?: 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\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\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 registry: Registry = new Map();\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(registry, defaultProjectId, defaultDataset, options.accessControl);\n}\n\nfunction makeHandle(\n registry: Registry,\n projectId: string,\n dataset: string,\n accessControl: TestClientAccessControl | undefined,\n): TestClient {\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 const promote = (doc: SanityDocumentLike): SanityDocument & SystemFields => {\n const now = new Date().toISOString();\n if (typeof doc._id !== \"string\" || doc._id.length === 0) {\n throw new Error(`document is missing _id`);\n }\n if (typeof doc._type !== \"string\" || doc._type.length === 0) {\n throw new Error(`document ${doc._id} is missing _type`);\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 new Error(`ifRevisionId check failed: document ${id} does not exist`);\n }\n if (existing._rev !== ifRevisionId) {\n throw new Error(\n `ifRevisionId check failed: document ${id} has _rev=${existing._rev}, expected ${ifRevisionId}`,\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 new Error(`Cannot patch document ${documentId}: not found`);\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 snapshot = new Map<string, SanityDocument | undefined>();\n const touchedIds: string[] = [];\n const operations: { id: string; operation: \"create\" | \"update\" | \"delete\" }[] = [];\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 new Error(`create failed: document ${promoted._id} already exists`);\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 if (txnOptions?.returnDocuments) {\n const docs = touchedIds\n .map((id) => store.get(id))\n .filter((d): d is SanityDocument => d !== undefined);\n return txnOptions.returnFirst ? (docs[0] as SanityDocument) : docs;\n }\n\n return {\n transactionId: cryptoRandomKey(),\n results: operations,\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 visibleDocs = 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 const client: TestClient = {\n fetch: async (query, params) => {\n const tree = parse(query, params ? { params } : undefined);\n const value = await evaluate(tree, {\n dataset: await visibleDocs(),\n ...(params !== undefined ? { params } : {}),\n });\n return (await value.get()) as never;\n },\n\n getDocument: async (id) => {\n const doc = store.get(id);\n if (doc === undefined) return null;\n if (!(await canRead(doc))) return null;\n return doc as never;\n },\n\n getDocuments: async (ids) => {\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\n create: async (doc, opts) => {\n checkRevision(doc._id as string, opts?.ifRevisionId);\n if (store.get(doc._id as string) !== undefined) {\n throw new Error(`create failed: document ${doc._id} already exists`);\n }\n const promoted = promote(doc);\n await gate(promoted, \"create\");\n store.put(promoted);\n return promoted as typeof doc & SystemFields;\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 store.put(promoted);\n return promoted as typeof doc & SystemFields;\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 if (existing !== undefined) return existing as typeof doc & SystemFields;\n const promoted = promote(doc);\n await gate(promoted, \"create\");\n store.put(promoted);\n return promoted as typeof doc & SystemFields;\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 removed = store.remove(id);\n return removed ? { _id: id } : null;\n },\n\n patch: (documentId) => createPatch(documentId, { apply: applyPatch }),\n\n transaction: () => createTransaction({ apply: applyTransaction }),\n\n ...(accessControl !== undefined\n ? { request: makeRequestImpl(accessControl, projectId, dataset) }\n : {}),\n\n config: () => ({ projectId, dataset }),\n\n withConfig: (config) =>\n makeHandle(registry, config.projectId ?? projectId, config.dataset ?? dataset, accessControl),\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.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CAAA;AAAA,IAEJ,QAAQ,OAAO,EAAE,WAAW;IAE5B,YAAY,CAAC,WACX,WAAW,UAAU,OAAO,aAAa,WAAW,OAAO,WAAW,SAAS,aAAa;AAAA,IAE9F,MAAM,CAAC,cAAc,MAAM,KAAK,SAAS;AAAA,IACzC,KAAK,CAAC,cAAc,MAAM,IAAI,SAAS;AAAA,IACvC,OAAO,MAAM,MAAM,MAAA;AAAA,IACnB,UAAU,MAAM,MAAM,SAAA;AAAA,IACtB,OAAO,MAAM;AAAA,IACb,UAAU,MAAM,CAAC,GAAG,SAAS,KAAA,CAAM,EAAE,IAAI,gBAAgB;AAAA,EAAA;AAI7D;;;;;;;;;"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apply an ordered list of patch ops to a document, returning the new doc.
|
|
3
|
+
*
|
|
4
|
+
* The path semantics are deliberately a small subset:
|
|
5
|
+
*
|
|
6
|
+
* - **Dotted paths** (`a.b.c`) for nested object fields.
|
|
7
|
+
* - **Array index** (`a.b[0]`) for positional access into arrays.
|
|
8
|
+
* - **Keyed lookup** (`a.b[_key=="x"]`) for finding an array entry by `_key`.
|
|
9
|
+
*
|
|
10
|
+
* Anything more exotic (recursive `..`, GROQ filter expressions, multi-match)
|
|
11
|
+
* is intentionally out of scope and will throw — the workflow engine only
|
|
12
|
+
* needs the three forms above.
|
|
13
|
+
*/
|
|
14
|
+
export declare function applyPatchOps(
|
|
15
|
+
doc: SanityDocument,
|
|
16
|
+
ops: PatchOp[],
|
|
17
|
+
): SanityDocument;
|
|
18
|
+
|
|
19
|
+
export declare function createPatch(
|
|
20
|
+
documentId: string,
|
|
21
|
+
executor: PatchExecutor,
|
|
22
|
+
): PatchHandle;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Create a fresh, isolated test client backed by a private multi-dataset
|
|
26
|
+
* registry. `withConfig` returns a sibling handle into the same registry.
|
|
27
|
+
*
|
|
28
|
+
* ```
|
|
29
|
+
* const client = createTestClient({
|
|
30
|
+
* datasets: {
|
|
31
|
+
* "test:definitions": [...],
|
|
32
|
+
* "test:instances": [...],
|
|
33
|
+
* },
|
|
34
|
+
* });
|
|
35
|
+
* const defs = client.withConfig({ dataset: "definitions" });
|
|
36
|
+
* const inst = client.withConfig({ dataset: "instances" });
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare function createTestClient(
|
|
40
|
+
options?: CreateTestClientOptions,
|
|
41
|
+
): TestClient;
|
|
42
|
+
|
|
43
|
+
export declare interface CreateTestClientOptions {
|
|
44
|
+
/** Default project id. Defaults to `"test"`. */
|
|
45
|
+
projectId?: string;
|
|
46
|
+
/** Default dataset name. Defaults to `"test"`. */
|
|
47
|
+
dataset?: string;
|
|
48
|
+
/** Documents to seed into the default `(projectId, dataset)` store. */
|
|
49
|
+
documents?: SanityDocumentLike[];
|
|
50
|
+
/**
|
|
51
|
+
* Optional: seed multiple datasets at once. Keys are `"projectId:dataset"`
|
|
52
|
+
* pairs. Useful when workflows span multiple datasets.
|
|
53
|
+
*/
|
|
54
|
+
datasets?: Record<string, SanityDocumentLike[]>;
|
|
55
|
+
/**
|
|
56
|
+
* Opt-in access-control simulation. When set, the client exposes
|
|
57
|
+
* `request({ url })` that serves `/users/me` + the configured ACL
|
|
58
|
+
* path, AND every mutation is gated through the supplied `grants`
|
|
59
|
+
* — writes that the grants don't permit throw a `WriteAccessDeniedError`
|
|
60
|
+
* shaped like Sanity's 403. Lets tests demonstrate the full
|
|
61
|
+
* "engine soft-gate + lake hard-gate" contract end-to-end without
|
|
62
|
+
* a real HTTP round-trip.
|
|
63
|
+
*
|
|
64
|
+
* When omitted, `request` is undefined and all writes proceed
|
|
65
|
+
* unconditionally — the legacy behavior.
|
|
66
|
+
*/
|
|
67
|
+
accessControl?: TestClientAccessControl;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Create a fresh, isolated store. The returned object closes over a private
|
|
72
|
+
* Map; two stores created from two calls do not see each other.
|
|
73
|
+
*/
|
|
74
|
+
export declare function createTestStore(
|
|
75
|
+
initial?: SanityDocumentLike[],
|
|
76
|
+
): TestStore;
|
|
77
|
+
|
|
78
|
+
export declare function createTransaction(
|
|
79
|
+
executor: TxnExecutor,
|
|
80
|
+
): TransactionHandle;
|
|
81
|
+
|
|
82
|
+
export declare interface CurrentUser {
|
|
83
|
+
id: string;
|
|
84
|
+
name?: string;
|
|
85
|
+
email?: string;
|
|
86
|
+
/** @deprecated singular `role` on legacy responses */
|
|
87
|
+
role?: string;
|
|
88
|
+
roles?: {
|
|
89
|
+
name: string;
|
|
90
|
+
title?: string;
|
|
91
|
+
description?: string;
|
|
92
|
+
}[];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Default ACL path the engine pulls grants from. Mirrors Sanity's
|
|
97
|
+
* project/dataset ACL endpoint. Callers can override via
|
|
98
|
+
* `accessControl.aclPath`.
|
|
99
|
+
*/
|
|
100
|
+
export declare function defaultAclPath(
|
|
101
|
+
projectId: string,
|
|
102
|
+
dataset: string,
|
|
103
|
+
): string;
|
|
104
|
+
|
|
105
|
+
export declare type DocumentValuePermission = "create" | "read" | "update";
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Resolve whether `grants` allow `permission` on `document` for the
|
|
109
|
+
* given user. Same logic the engine uses in `permissions.grantsPermissionOn`
|
|
110
|
+
* (most-permissive wins; multiple grants compose).
|
|
111
|
+
*
|
|
112
|
+
* Returns `{ allowed: boolean, matchingGrants: number }` so callers
|
|
113
|
+
* can build the structured error without re-counting.
|
|
114
|
+
*/
|
|
115
|
+
export declare function evaluateWriteAccess(args: {
|
|
116
|
+
document: SanityDocumentLike & {
|
|
117
|
+
_id?: string;
|
|
118
|
+
_type?: string;
|
|
119
|
+
};
|
|
120
|
+
grants: Grant[];
|
|
121
|
+
permission: DocumentValuePermission;
|
|
122
|
+
userId: string;
|
|
123
|
+
}): Promise<{
|
|
124
|
+
allowed: boolean;
|
|
125
|
+
matchingGrants: number;
|
|
126
|
+
}>;
|
|
127
|
+
|
|
128
|
+
export declare interface Grant {
|
|
129
|
+
filter: string;
|
|
130
|
+
permissions: DocumentValuePermission[];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export declare interface MutationOptions {
|
|
134
|
+
ifRevisionId?: string;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export declare interface PatchExecutor {
|
|
138
|
+
apply: (
|
|
139
|
+
documentId: string,
|
|
140
|
+
ops: PatchOp[],
|
|
141
|
+
ifRev: string | undefined,
|
|
142
|
+
) => Promise<SanityDocument>;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export declare interface PatchHandle {
|
|
146
|
+
set: (props: Record<string, unknown>) => PatchHandle;
|
|
147
|
+
setIfMissing: (props: Record<string, unknown>) => PatchHandle;
|
|
148
|
+
unset: (paths: string[]) => PatchHandle;
|
|
149
|
+
inc: (props: Record<string, number>) => PatchHandle;
|
|
150
|
+
dec: (props: Record<string, number>) => PatchHandle;
|
|
151
|
+
insert: (
|
|
152
|
+
position: "before" | "after" | "replace",
|
|
153
|
+
anchor: string,
|
|
154
|
+
items: unknown[],
|
|
155
|
+
) => PatchHandle;
|
|
156
|
+
ifRevisionId: (rev: string) => PatchHandle;
|
|
157
|
+
commit: () => Promise<SanityDocument>;
|
|
158
|
+
/** Test-only introspection — not on real Patch */
|
|
159
|
+
toJSON: () => {
|
|
160
|
+
id: string;
|
|
161
|
+
ops: PatchOp[];
|
|
162
|
+
ifRev?: string;
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Patch operations the test client supports.
|
|
168
|
+
*
|
|
169
|
+
* Subset of `@sanity/client`'s PatchOperations. Each entry is one
|
|
170
|
+
* mutation step applied in order at commit time.
|
|
171
|
+
*/
|
|
172
|
+
export declare type PatchOp =
|
|
173
|
+
| {
|
|
174
|
+
kind: "set";
|
|
175
|
+
props: Record<string, unknown>;
|
|
176
|
+
}
|
|
177
|
+
| {
|
|
178
|
+
kind: "setIfMissing";
|
|
179
|
+
props: Record<string, unknown>;
|
|
180
|
+
}
|
|
181
|
+
| {
|
|
182
|
+
kind: "unset";
|
|
183
|
+
paths: string[];
|
|
184
|
+
}
|
|
185
|
+
| {
|
|
186
|
+
kind: "inc";
|
|
187
|
+
props: Record<string, number>;
|
|
188
|
+
}
|
|
189
|
+
| {
|
|
190
|
+
kind: "dec";
|
|
191
|
+
props: Record<string, number>;
|
|
192
|
+
}
|
|
193
|
+
| {
|
|
194
|
+
kind: "insert";
|
|
195
|
+
position: "before" | "after" | "replace";
|
|
196
|
+
anchor: string;
|
|
197
|
+
items: unknown[];
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** @public */
|
|
201
|
+
declare interface SanityDocument {
|
|
202
|
+
_id: string;
|
|
203
|
+
_type: string;
|
|
204
|
+
_createdAt: string;
|
|
205
|
+
_updatedAt: string;
|
|
206
|
+
_rev: string;
|
|
207
|
+
[key: string]: unknown;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Similar to `SanityDocument` but only requires the `_id` and `_type`
|
|
212
|
+
*
|
|
213
|
+
* @see SanityDocument
|
|
214
|
+
*
|
|
215
|
+
* @public
|
|
216
|
+
*/
|
|
217
|
+
declare interface SanityDocumentLike {
|
|
218
|
+
_id: string;
|
|
219
|
+
_type: string;
|
|
220
|
+
_createdAt?: string;
|
|
221
|
+
_updatedAt?: string;
|
|
222
|
+
_rev?: string;
|
|
223
|
+
_system?: {
|
|
224
|
+
delete?: boolean;
|
|
225
|
+
};
|
|
226
|
+
[key: string]: unknown;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export declare interface SystemFields {
|
|
230
|
+
_rev: string;
|
|
231
|
+
_createdAt: string;
|
|
232
|
+
_updatedAt: string;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Data-plane subset of `@sanity/client`'s surface, with multi-dataset support.
|
|
237
|
+
*
|
|
238
|
+
* One `createTestClient()` call creates a registry of stores keyed by
|
|
239
|
+
* `(projectId, dataset)`. The returned client points at one of them.
|
|
240
|
+
* `withConfig({ projectId, dataset })` returns a new handle into the same
|
|
241
|
+
* registry but pointing at a different store — useful for workflows where
|
|
242
|
+
* definitions live in one dataset and instances live in another.
|
|
243
|
+
*
|
|
244
|
+
* Two separate `createTestClient()` calls have separate registries, so
|
|
245
|
+
* tests stay isolated from each other.
|
|
246
|
+
*
|
|
247
|
+
* Methods not on the real client:
|
|
248
|
+
*
|
|
249
|
+
* - `seed`, `add`, `reset`, `snapshot`, `store` — bulk-load helpers,
|
|
250
|
+
* scoped to the current dataset.
|
|
251
|
+
* - `datasets()` — lists known dataset keys in this registry.
|
|
252
|
+
*
|
|
253
|
+
* Methods deliberately omitted:
|
|
254
|
+
*
|
|
255
|
+
* - Project / agent / asset / live / listen APIs.
|
|
256
|
+
* - Perspective handling.
|
|
257
|
+
*/
|
|
258
|
+
export declare interface TestClient {
|
|
259
|
+
fetch: <T = unknown>(
|
|
260
|
+
query: string,
|
|
261
|
+
params?: Record<string, unknown>,
|
|
262
|
+
) => Promise<T>;
|
|
263
|
+
getDocument: <T = SanityDocument>(id: string) => Promise<T | null>;
|
|
264
|
+
getDocuments: <T = SanityDocument>(ids: string[]) => Promise<(T | null)[]>;
|
|
265
|
+
/**
|
|
266
|
+
* Sanity-style HTTP request hook. Present iff the client was
|
|
267
|
+
* created with `accessControl`. The engine's access resolver pokes
|
|
268
|
+
* `/users/me` and the configured ACL path through this — without it
|
|
269
|
+
* the engine throws on any verb that needs an actor (which is the
|
|
270
|
+
* cue for the bench to supply an `access` override).
|
|
271
|
+
*
|
|
272
|
+
* Test cases that want to exercise the engine's token-resolution
|
|
273
|
+
* path should configure `accessControl`; cases that want bench-style
|
|
274
|
+
* always-allow should leave it off and pass `access` through the
|
|
275
|
+
* bench.
|
|
276
|
+
*/
|
|
277
|
+
request?: <T>(opts: {
|
|
278
|
+
url?: string;
|
|
279
|
+
uri?: string;
|
|
280
|
+
signal?: AbortSignal;
|
|
281
|
+
tag?: string;
|
|
282
|
+
}) => Promise<T>;
|
|
283
|
+
create: <T extends SanityDocumentLike>(
|
|
284
|
+
doc: T,
|
|
285
|
+
options?: MutationOptions,
|
|
286
|
+
) => Promise<T & SystemFields>;
|
|
287
|
+
createOrReplace: <T extends SanityDocumentLike>(
|
|
288
|
+
doc: T,
|
|
289
|
+
options?: MutationOptions,
|
|
290
|
+
) => Promise<T & SystemFields>;
|
|
291
|
+
createIfNotExists: <T extends SanityDocumentLike>(
|
|
292
|
+
doc: T,
|
|
293
|
+
options?: MutationOptions,
|
|
294
|
+
) => Promise<T & SystemFields>;
|
|
295
|
+
delete: (
|
|
296
|
+
id: string,
|
|
297
|
+
options?: MutationOptions,
|
|
298
|
+
) => Promise<{
|
|
299
|
+
_id: string;
|
|
300
|
+
} | null>;
|
|
301
|
+
patch: (documentId: string) => PatchHandle;
|
|
302
|
+
transaction: () => TransactionHandle;
|
|
303
|
+
/** Current `(projectId, dataset)`. */
|
|
304
|
+
config: () => {
|
|
305
|
+
projectId: string;
|
|
306
|
+
dataset: string;
|
|
307
|
+
};
|
|
308
|
+
/**
|
|
309
|
+
* Return a new client handle pointing at a different `(projectId, dataset)`
|
|
310
|
+
* within the SAME backing registry. Either field can be omitted to keep
|
|
311
|
+
* the current value. Two clients produced by `withConfig` see each
|
|
312
|
+
* other's writes if they point at the same `(projectId, dataset)`.
|
|
313
|
+
*/
|
|
314
|
+
withConfig: (
|
|
315
|
+
config: Partial<{
|
|
316
|
+
projectId: string;
|
|
317
|
+
dataset: string;
|
|
318
|
+
}>,
|
|
319
|
+
) => TestClient;
|
|
320
|
+
/** Replace the current dataset with the given documents. */
|
|
321
|
+
seed: (documents: SanityDocumentLike[]) => void;
|
|
322
|
+
/** Add documents to the current dataset without dropping existing ones. */
|
|
323
|
+
add: (documents: SanityDocumentLike[]) => void;
|
|
324
|
+
/** Drop all documents in the current dataset. */
|
|
325
|
+
reset: () => void;
|
|
326
|
+
/** Read-only snapshot of all documents in the current dataset. */
|
|
327
|
+
snapshot: () => readonly SanityDocument[];
|
|
328
|
+
/** Direct store access for the current dataset. */
|
|
329
|
+
store: () => TestStore;
|
|
330
|
+
/** List `(projectId, dataset)` pairs known in this registry. */
|
|
331
|
+
datasets: () => {
|
|
332
|
+
projectId: string;
|
|
333
|
+
dataset: string;
|
|
334
|
+
}[];
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export declare interface TestClientAccessControl {
|
|
338
|
+
/** What `client.request({ url: "/users/me" })` returns. */
|
|
339
|
+
currentUser: CurrentUser;
|
|
340
|
+
/** What `client.request({ url: aclPath })` returns. */
|
|
341
|
+
grants: Grant[];
|
|
342
|
+
/**
|
|
343
|
+
* URL path the engine's access resolver hits to fetch grants.
|
|
344
|
+
* Defaults to `/projects/<projectId>/datasets/<dataset>/acl`.
|
|
345
|
+
*/
|
|
346
|
+
aclPath?: string;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* In-memory document store backing a TestClient. Closure-scoped — created
|
|
351
|
+
* fresh per test, no global state.
|
|
352
|
+
*
|
|
353
|
+
* The shape mirrors what `groq-js` evaluates against: an array of
|
|
354
|
+
* documents. Internally we keep a Map by `_id` for O(1) lookup, and
|
|
355
|
+
* project to an array on each query.
|
|
356
|
+
*/
|
|
357
|
+
export declare interface TestStore {
|
|
358
|
+
/** Replace the entire dataset with the given documents. Existing docs are dropped. */
|
|
359
|
+
seed: (documents: SanityDocumentLike[]) => void;
|
|
360
|
+
/** Add documents without dropping existing ones. Conflicts (same _id) overwrite. */
|
|
361
|
+
add: (documents: SanityDocumentLike[]) => void;
|
|
362
|
+
/** Remove all documents. */
|
|
363
|
+
reset: () => void;
|
|
364
|
+
/** All documents as an array, in insertion order. */
|
|
365
|
+
all: () => SanityDocument[];
|
|
366
|
+
/** Get one document by _id, or undefined. */
|
|
367
|
+
get: (id: string) => SanityDocument | undefined;
|
|
368
|
+
/** Insert a fully-formed document by _id. Replaces if it already exists. */
|
|
369
|
+
put: (doc: SanityDocument) => void;
|
|
370
|
+
/** Remove a document by _id. Returns the removed doc or undefined. */
|
|
371
|
+
remove: (id: string) => SanityDocument | undefined;
|
|
372
|
+
/** Snapshot of all docs, useful for assertions. */
|
|
373
|
+
snapshot: () => readonly SanityDocument[];
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export declare interface TransactionHandle {
|
|
377
|
+
create: (doc: SanityDocumentLike) => TransactionHandle;
|
|
378
|
+
createOrReplace: (doc: SanityDocumentLike) => TransactionHandle;
|
|
379
|
+
createIfNotExists: (doc: SanityDocumentLike) => TransactionHandle;
|
|
380
|
+
delete: (id: string) => TransactionHandle;
|
|
381
|
+
/** Accept either a Patch builder (drained at commit) or an inline doc id + ops. */
|
|
382
|
+
patch: (
|
|
383
|
+
documentIdOrPatch: string | PatchHandle,
|
|
384
|
+
ops?: PatchOp[],
|
|
385
|
+
ifRev?: string,
|
|
386
|
+
) => TransactionHandle;
|
|
387
|
+
commit: (options?: TxnCommitOptions) => Promise<TxnCommitResult>;
|
|
388
|
+
/** Test-only introspection — not on real Transaction. */
|
|
389
|
+
toJSON: () => TxnMutation[];
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export declare interface TxnCommitOptions {
|
|
393
|
+
/** If true, returns the resulting documents instead of just ids. */
|
|
394
|
+
returnDocuments?: boolean;
|
|
395
|
+
/** With `returnDocuments`, return only the first updated doc. */
|
|
396
|
+
returnFirst?: boolean;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export declare type TxnCommitResult =
|
|
400
|
+
| {
|
|
401
|
+
transactionId: string;
|
|
402
|
+
results: {
|
|
403
|
+
id: string;
|
|
404
|
+
operation: "create" | "update" | "delete";
|
|
405
|
+
}[];
|
|
406
|
+
}
|
|
407
|
+
| SanityDocument
|
|
408
|
+
| SanityDocument[];
|
|
409
|
+
|
|
410
|
+
export declare interface TxnExecutor {
|
|
411
|
+
apply: (
|
|
412
|
+
mutations: TxnMutation[],
|
|
413
|
+
options?: TxnCommitOptions,
|
|
414
|
+
) => Promise<TxnCommitResult>;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* A transaction collects mutations and applies them atomically at commit
|
|
419
|
+
* time. Mutations are applied in declaration order; if any one fails, the
|
|
420
|
+
* whole transaction throws and no writes land in the store.
|
|
421
|
+
*
|
|
422
|
+
* Subset of `@sanity/client`'s Transaction. Same shape, narrower surface.
|
|
423
|
+
*/
|
|
424
|
+
export declare type TxnMutation =
|
|
425
|
+
| {
|
|
426
|
+
kind: "create";
|
|
427
|
+
doc: SanityDocumentLike;
|
|
428
|
+
}
|
|
429
|
+
| {
|
|
430
|
+
kind: "createOrReplace";
|
|
431
|
+
doc: SanityDocumentLike;
|
|
432
|
+
}
|
|
433
|
+
| {
|
|
434
|
+
kind: "createIfNotExists";
|
|
435
|
+
doc: SanityDocumentLike;
|
|
436
|
+
}
|
|
437
|
+
| {
|
|
438
|
+
kind: "delete";
|
|
439
|
+
id: string;
|
|
440
|
+
}
|
|
441
|
+
| {
|
|
442
|
+
kind: "patch";
|
|
443
|
+
documentId: string;
|
|
444
|
+
ops: PatchOp[];
|
|
445
|
+
ifRev?: string;
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Sanity-style 403 raised when a configured-grants check rejects a
|
|
450
|
+
* write. The thrown object carries the doc id, the attempted
|
|
451
|
+
* permission, and the count of matching grants (for parity with the
|
|
452
|
+
* engine's `permission-denied` disabled-reason).
|
|
453
|
+
*/
|
|
454
|
+
export declare class WriteAccessDeniedError extends Error {
|
|
455
|
+
readonly documentId: string;
|
|
456
|
+
readonly permission: DocumentValuePermission;
|
|
457
|
+
readonly matchingGrants: number;
|
|
458
|
+
constructor(args: {
|
|
459
|
+
documentId: string;
|
|
460
|
+
permission: DocumentValuePermission;
|
|
461
|
+
matchingGrants: number;
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export {};
|