import { AbortInstanceArgs, ActivityStatus, Actor, ChildrenArgs, Clock, CompleteEffectArgs, CreateEngineArgs, DeclaredExecutionContext, DefinitionsForDocumentArgs, DeleteDefinitionArgs, DeleteDefinitionResult, DeployDefinitionsArgs, DeployDefinitionsResult, DeployedDefinition, EditFieldArgs, Engine, EvaluateArgs, EvaluateStartArgs, FindPendingEffectsArgs, FireActionArgs, Grant, InitialFieldValue, InstanceRefArgs, InstanceSession, InstancesForDocumentArgs, InstancesQueryFilter, MutationGuardAction, MutationGuardDoc, OperationArgs, OperationResult, PendingEffect, ResetActivityArgs, ResourceClientResolver, SessionArgs, StartEvaluation, StartInstanceArgs, UserAttributes, WorkflowAccess, WorkflowDefinition, WorkflowDefinitionInput, WorkflowEvaluation, WorkflowInstance, WorkflowPerspective, WorkflowResource } from "@sanity/workflow-engine"; import { GuardDeniedError, TestClient, WriteAccessDeniedError } from "@sanity-labs/client-fake-for-test"; /** A document as stored in the bench's fake lake. */ type StoreDocument = { _id: string; _type: string; [key: string]: unknown; }; /** The bench-owned engine call context injected into every wrapped verb. */ type EngineScope = { client: TestClient; partition: string; workflowResource: WorkflowResource; resourceClients?: ResourceClientResolver; executionContext: DeclaredExecutionContext; }; /** * Per-call access fields a bench verb accepts: the canonical `access` * shape plus the `actor` / `grants` / `attributes` shortcuts that compose * into it. The composed pair is the call's identity: it commits with its own * token, or reaches the engine as `access` on a bench with a committer. */ type AccessShortcuts = { /** Replaces the bench's access for this call. When supplied, individual access shortcuts are ignored. */ access?: WorkflowAccess; /** Actor for this call. Omit to use the bench's actor. Changing only the actor retains the bench's default grants and attributes. */ actor?: Actor; /** Grants for this call. Omit to retain the bench's default grants; pass `[]` to grant nothing. */ grants?: Grant[]; /** Attributes for this call. Omit to retain the bench's defaults; pass `{}` to clear them. */ attributes?: UserAttributes; }; /** @inline */ type BenchArgsWithAccessShortcuts = T & AccessShortcuts; /** @interface */ type BenchStartInstanceArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchFireActionArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchEditFieldArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchCompleteEffectArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchTickArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchAbortInstanceArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchResetActivityArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchEvaluateArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchDeleteDefinitionArgs = BenchArgsWithAccessShortcuts; /** @interface */ type BenchSessionArgs = BenchArgsWithAccessShortcuts; /** Engine-call wrappers that inject the bench-owned client + tag + identity. */ type EngineWrappers = { deployDefinitions: >(args: DeployDefinitionsArgs) => Promise; deleteDefinition: (args: BenchDeleteDefinitionArgs) => Promise; startInstance: (args: BenchStartInstanceArgs) => Promise; fireAction: (args: BenchFireActionArgs) => Promise; editField: (args: BenchEditFieldArgs) => Promise; completeEffect: (args: BenchCompleteEffectArgs) => Promise; tick: (args: BenchTickArgs) => Promise; evaluate: (args: BenchEvaluateArgs) => Promise; /** Admin override — hard-stop an in-flight instance where it stands. */ abortInstance: (args: BenchAbortInstanceArgs) => Promise; /** Admin override — reset a failed/terminal activity in the current stage. */ resetActivity: (args: BenchResetActivityArgs) => Promise; guardsForInstance: (instanceId: string) => Promise; guardsForDefinition: (definition: string) => Promise; /** A reactive instance session bound to `instance`, acting as the call's identity like every other wrapper. */ session: (args: BenchSessionArgs) => InstanceSession; }; /** * How {@link GuardHelpers.editDocument} mutates the document. Each present * key becomes one patch op, applied in `set` → `unset` → `insert` order in a * single commit; the shapes mirror the client's patch builder. */ type EditDocumentPatch = { set?: Record; unset?: string[]; insert?: { position: 'before' | 'after' | 'replace'; anchor: string; items: unknown[]; }; }; /** * The write {@link GuardHelpers.editDocument} performs. Every arm commits one * or more real client writes that the guard seam vets as their underlying lake * mutations. `create` is deliberately absent because editing addresses an * existing document; create through the client (`bench.client.create` / * `clientFor(...).create`), which the same seam gates as a create. */ type EditDocumentAction = Exclude; type GuardHelpers = { /** All deployed guard docs ({@link MutationGuardDoc}) in the store. */ listGuards: () => Promise; /** * Guards that would deny an arbitrary edit to `documentId` right now (i.e. * active locks). Probes by changing every non-system field; a guard whose * predicate is `"true"` returns nothing. */ activeGuardsForDocument: (documentId: string, as?: Actor) => Promise; /** * Write to a document through the client's guarded write seam. The bench * client gates the write against deployed guards (incl. `identity()`) and * throws the package's re-exported `GuardDeniedError` on denial — the lake-shaped * rejection simulated by the bench. `as` routes the write through a * token-scoped sibling so `identity()` resolves to that actor. * * Each {@link EditDocumentAction} performs that real write, so a guard * scoped to its underlying lake mutations is genuinely consulted: `update` * (default) applies `patch`; `delete` deletes; `publish` promotes the existing * draft (`drafts.`) onto `documentId` and deletes the draft; * `unpublish` creates the draft and deletes `documentId`. `documentId` is * always the published id. * A `patch` ({@link EditDocumentPatch}) is required for `update` and * rejected for every other action — the combination is contradictory input. * * Resolves to the post-write document as the DEFAULT identity reads it — * `undefined` after `delete`/`unpublish` (the doc is gone), or when the * default identity cannot read the written doc. */ editDocument: (opts: { documentId: string; patch?: EditDocumentPatch; action?: EditDocumentAction; as?: Actor; }) => Promise; }; /** Controls for a bench created with {@link CreateBenchOptions.laggingQueryIndex}, whose GROQ query index lags its commits. */ interface QueryIndexControls { /** Make every commit so far visible to GROQ queries. */ advanceQueryIndex: () => void; /** Whether a commit is waiting for {@link QueryIndexControls.advanceQueryIndex}. */ queryIndexBehind: () => boolean; } type QueryHelpers = { /** * Run an arbitrary GROQ query through `workflow.query`. The query MUST * filter on the auto-injected `$tag` param (e.g. `*[... && tag == $tag]`) * or it throws — the engine refuses to run a query that could read * across partitions. Caller is responsible for narrowing the result. */ query: (groq: string, params?: Record) => Promise; /** * Snapshot-aware GROQ for `instanceId` — runs against the same * in-memory view the engine's filters see, with the caller-free * rendered scope auto-bound: every always-bound condition var, * `$fields` with the open stage's overlay merged, `$assigned` at its * caller-free `false`, and the author's pre-evaluated `$` * booleans, ids in GDR URI form. Use to ask "what does the engine see * for this workflow?" — useful for filter debugging, UIs that mirror * engine state, etc. */ queryInScope: ({ instanceId, groq, params }: { instanceId: string; groq: string; params?: Record; }) => Promise; }; type ReadHelpers = { /** * The engine's instance point-read: throws typed `InstanceNotFoundError` * when the doc is missing or belongs to another engine's partition. */ getInstance: (args: InstanceRefArgs) => Promise; /** Current stage name of an instance. */ currentStage: (instanceId: string) => Promise; /** Every pending effect on an instance — claimed and unclaimed alike. */ listPendingEffects: (args: InstanceRefArgs) => Promise; /** Pending effects filtered by claim presence and/or effect names. */ findPendingEffects: (args: FindPendingEffectsArgs) => Promise; /** Status of a single activity on an instance, or undefined if missing. */ activityStatus: (instanceId: string, activity: string) => Promise; /** The rendered `$context` map — the start-time seed + a parent's spawn * handoff, keyed by entry `name`. */ contextMap: (instanceId: string) => Promise>; /** The rendered `$effects` map — completed effects' outputs, namespaced * by effect name. */ effectOutputsMap: (instanceId: string) => Promise>; /** * Spawned children of the instance, optionally restricted to those * spawned by `activity`. Ordered by `startedAt` ascending. */ children: (args: ChildrenArgs) => Promise; /** * Instances whose named `subject` or `doc.ref` field matches a full global * document reference (GDR) URI, such as `dataset:test:test:article-1`. * Bare document IDs accepted by {@link subjectField} do not match here. * `entryName` defaults to `"subject"`. Includes completed and aborted * instances, ordered by `startedAt` ascending. */ instancesForSubject: (subjectRef: string, entryName?: string) => Promise; /** * All instances of `definition` currently at `stage`. In-flight only by * default; `includeCompleted: true` widens to completed/aborted instances. * The options derive from the engine's {@link InstancesQueryFilter}, so a * vocabulary drift is a compile error here, not a silently-dropped filter. */ instancesByStage: (options: Required> & Pick) => Promise; /** * Every in-flight instance whose reactive watch-set includes `document` * (a resource-qualified GDR URI) — the reverse of the forward watch-set. * Answers "which instances should this changed doc `tick`?" the way a * non-reactive content forwarder needs. Sorted by `startedAt` ascending. */ instancesForDocument: (args: InstancesForDocumentArgs) => Promise; /** * The startable half of {@link ReadHelpers.instancesForDocument}: the * latest deployed version of every definition applicable to the LOADED * candidate document — startable, the `subject`-kind entry accepts its * `_type`, `start.filter` (browse-time-pure) passes. All matches, name * ascending. */ definitionsForDocument: (args: DefinitionsForDocumentArgs) => Promise; /** * Pre-flight `startInstance`'s gates for a definition + candidate * `initialFields`: one ordered result per declared start requirement, plus * still-missing required inputs; the read a start surface renders before * committing. */ evaluateStart: (args: EvaluateStartArgs) => Promise; /** Snapshot of all documents in the store — for inspecting the world. */ snapshot: () => readonly StoreDocument[]; }; /** * Build an out-of-band {@link Engine} on a bench's client, inheriting the * bench's partition, workflow resource, asserted caller (on a bench with a * committer, the engine commits with the committer's client and asserts the * bench's default identity as `access`), and clock (so `setNow` / `advance` govern * the engine's `$now` too). A `retry` policy's backoff moves that clock * instead of spending real time, so a paced policy runs to its end inside one * drain. Use this when a test needs an engine of its own — * custom effect handlers, racing two drainers — rather than the wrappers the * bench exposes. `overrides` win over every inherited value. */ export declare function createBenchEngine(bench: EngineScope & { now: Clock; advance: (ms: number) => void; assertedCaller?: { client: TestClient; access: WorkflowAccess; }; }, overrides?: Partial): Engine; /** Default workflow resource for benches that don't pass one. */ export declare const DEFAULT_WORKFLOW_RESOURCE: WorkflowResource; /** Default engine-scope partition for benches that don't pass one. */ export declare const BENCH_PARTITION = "bench"; /** * The default actor used when tests don't specify one. Its `"*"` role is an * inert placeholder, NOT a wildcard: role matching is literal membership, so * this actor satisfies no `Action.roles` gate or `{kind: "role"}` assignee on * its own — a test that exercises a role gate passes an actor carrying the * real role (and the definition's `roleAliases` decide what fulfills it). The * bench's all-access default is really {@link WILDCARD_GRANTS}, which feeds * `$can`. Production code should never see this id. */ export declare const ALL_ACCESS_USER: Actor; /** * The default grants used when tests don't specify any. A single * permissive grant matches every document and confers all permissions. */ export declare const WILDCARD_GRANTS: Grant[]; /** * The bench's default identity — wildcard user + wildcard grants, * registered as the default token on the bench's fake client. The engine * resolves it from that token (`/users/me` + the ACL path) exactly like * production, or receives it as `access` on a bench with a committer. * * Production code never sees this; pass `createBench({ access })` to * test denial paths. */ export declare const ALL_ACCESS: WorkflowAccess; /** * A workflow-scope `subject`-KIND entry value, keyed by a bare doc id in the * bench's default resource — what a definition declaring the first-class * `subject` kind expects at start (applicability and document pickers key on * that kind). `type` defaults to `'document'`; pass the subject's schema * type when a filter or projection reads it. For a plain `doc.ref` input, * use {@link docRefField}. */ export declare function subjectField(documentId: string, opts?: { name?: string; type?: string; }): InitialFieldValue; /** * A plain `doc.ref` entry value in the bench's default resource — for * document-reference inputs that are NOT the workflow's subject (the * `subject` kind is what marks THE subject; see {@link subjectField}). */ export declare function docRefField(documentId: string, opts: { name: string; type?: string; }): InitialFieldValue; /** * A `release.ref` entry pointing at `_.releases.` in the bench's * default resource — what a release-targeting workflow's `release` field * expects at start. */ export declare function releaseField(releaseName: string, opts?: { name?: string; }): InitialFieldValue; /** Bench operations required by the instance fixtures in this module. */ interface FixtureBench { deployDefinitions: (args: { expectedMinReaderModel: number; definitions: WorkflowDefinition[]; }) => Promise; startInstance: (args: { definition: string; instanceId?: string; initialFields?: InitialFieldValue[]; perspective?: WorkflowPerspective; }) => Promise<{ instance: WorkflowInstance; }>; } /** * Shared missing-reference scenario for workspace integration tests. * Unsupported outside this workspace. * @internal */ export declare function _referenceInstanceFixture(bench: FixtureBench, options?: { documentId?: string; requiresSource?: boolean; perspective?: WorkflowPerspective; }): Promise; /** * A REAL, minimal started instance — deployed and started through the bench's * actual verbs, parked forever on its first stage. The fixture for consumers * (adapter tests, validation tests) that need a persisted-shape-valid * instance document without caring about its workflow: hand-crafted instance * stubs do not pass the engine's read parse. */ export declare function startedInstanceFixture(bench: FixtureBench, opts?: { instanceId?: string; }): Promise; export interface CreateBenchOptions { /** Subject documents seeded into the store. */ documents?: StoreDocument[]; /** * The bench's default identity (actor + grants + optional attributes), * registered as the default token on the fake client. Each wrapped call * acts as it unless the call names another identity; see * {@link CreateBenchOptions.committer} for which identity commits. Defaults to `ALL_ACCESS` — * wildcard user + wildcard grants. Pass a restrictive value to test * denial paths. * * Mutually exclusive with the `currentUser` / `grants` / `attributes` * shortcuts (which compose into the same shape internally). */ access?: WorkflowAccess; /** Shortcut for `access.actor`. Composed with `grants` / `attributes`. */ currentUser?: Actor; /** Shortcut for `access.grants`. Composed with `currentUser` / `attributes`. */ grants?: Grant[]; /** Shortcut for `access.attributes` — advisory `$attributes` bag for soft gates. */ attributes?: UserAttributes; /** * A separate write-capable identity that commits every wrapped engine call, * like a service writing instances for the person who asked. The * committer's omitted grants default to wildcard. * * Without it, each call commits with its own identity's token and the * engine resolves the caller from that token. With it, each call commits * with this identity's token, and the call's identity (the bench default or * a per-call `actor:` / `grants:` / `attributes:` / `access:` shortcut) * reaches the engine as `createEngine`'s `access`. History then names the * call's identity, and `$actor`, `roles`, `$can`, and `$attributes` judge * it, so the same test runs unchanged on both paths. A call identity * without `grants` is judged with wildcard grants on both paths. The * Content Lake checks writes against the committer's grants. */ committer?: WorkflowAccess; /** * Serve a Workflows service on the bench's API host, writing instances as * this identity, like a project whose instance ACL editors cannot write. The * service's omitted grants default to wildcard. * * Each wrapped `startInstance`, `fireAction`, `editField`, `abortInstance`, * and `tick`, and each `session` commit, decides where its write goes from * the grants of the token it commits with: directly when that token can * create and update instances, or as an operation to this service when it * cannot. The service runs the operation with its own token and asserts * the call's identity as `access`. Pass call identities whose `grants` * cannot write instances to run a test on the routed path; the same test * runs on the direct path without this option. With `committer`, every * wrapped call asserts `access` and writes directly, so it never reaches * this service. */ service?: WorkflowAccess; /** * Engine-scope environment partition. Defaults to {@link BENCH_PARTITION}. Pass * different partitions to two benches sharing a `client` to assert partition * isolation; pass the same partition to assert visibility through a shared * partition. * * The partition must be ASCII lowercase + digits + dashes, no leading dash, * no dots — validated at construction. */ partition?: string; /** * Shared store client. Omit to create an isolated store. To retain simulated * guard rejection when sharing, pass another bench's `client`; the bench * does not add guard simulation to a supplied client. Use * {@link CreateBenchOptions.partition} to test partition visibility in the shared store. */ client?: TestClient; /** * Workflow resource the bench's engine operates against. Mirrors * `@sanity/client`'s `ClientConfigResource`. Defaults to * `{ type: "dataset", id: "test.test" }` so all bench-minted GDR * URIs read as `dataset:test:test:`. */ workflowResource?: WorkflowResource; /** * Sibling datasets the bench serves (and thereby declares) from its own * store — the common cross-resource case. Each listed resource routes to * a `withConfig`-derived handle over the bench's store, so reads reach it * and runtime-supplied refs into it are admitted. Only `dataset` * resources can be siblings of the bench's store; anything else needs * {@link CreateBenchOptions.resourceClients}. */ serveResources?: WorkflowResource[]; /** * Cross-resource read routing for the bench engine scope — a served * resource is also part of the declared surface for written refs. The * escape hatch for resolver logic beyond same-store siblings; prefer * {@link CreateBenchOptions.serveResources}, which is consulted first * when both are given. Omit for single-resource benches. */ resourceClients?: ResourceClientResolver; /** * Freeze the bench clock at this ISO instant from construction, so * `$now` and every engine timestamp are deterministic. Equivalent to * calling {@link BenchState.setNow} immediately after `createBench`. Omit to * start on the wall clock (`advance` / `setNow` can freeze it later). */ now?: string; /** * Declared execution context stamped (with the inferred runtime) on every * history entry the bench's engine calls append. Defaults to * `{ kind: "test" }`; override to exercise provenance rendering. */ executionContext?: DeclaredExecutionContext; /** * Model the Content Lake's query index lag. A commit at visibility `async` * or `deferred` (the engine's default) stays invisible to GROQ queries * until {@link QueryIndexControls.advanceQueryIndex}; a `sync` commit is * visible at once. Document reads by id and the documents a commit returns * are always current. Use it to prove a path never reads its own write back * through GROQ. GROQ queries then run as an all-access identity. Applies * only to the bench's own store; combining it with * {@link CreateBenchOptions.client} throws. */ laggingQueryIndex?: boolean; } export interface BenchState extends EngineScope { /** The bench's default identity as passed to {@link createBench}. */ access: WorkflowAccess; currentUser: Actor; /** The default identity's grants as passed, or `[]` when it carries none; verdicts judge an identity without grants with wildcard grants. */ grants: Grant[]; /** Set on a bench with a {@link CreateBenchOptions.committer}: the committer's client and the default identity it asserts, which {@link createBenchEngine} inherits. */ assertedCaller?: { client: TestClient; access: WorkflowAccess; }; /** A token-bound sibling client acting as `access` — the bench's ONE identity seam, cached per identity with omitted grants defaulting to wildcard; bind it to {@link createBenchEngine} instead of hand-rolling `addIdentity` + `withConfig`. */ clientFor: (access: WorkflowAccess) => TestClient; seedDocuments: (documents: StoreDocument[]) => void; /** Current bench clock reading (ISO); wall-clock until {@link BenchState.setNow} or {@link BenchState.advance} freezes it. */ now: () => string; /** Freezes the bench clock at an explicit ISO instant; every subsequent engine call sees this as `$now` and stamps it on history. */ setNow: (iso: string) => void; /** Moves the bench clock forward by `ms`; call {@link Bench.tick} after to re-evaluate — `advance` itself never writes. */ advance: (ms: number) => void; } export interface ComposedHelpers { /** Completes the pending effect named `effect` (looked up by name), throwing loud when none is pending. */ completePendingEffect: (args: Omit & { effect: string; }) => Promise; } export type Bench = BenchState & EngineWrappers & ReadHelpers & GuardHelpers & QueryHelpers & ComposedHelpers & QueryIndexControls; /** * Create a fresh bench. By default the bench is fully isolated — two * `createBench()` calls have no shared state. Pass `client` + `partition` to two * benches to share a store and exercise partition scoping. Each identity is * registered as a token on the client. Without * {@link CreateBenchOptions.committer}, the call's identity commits and the * engine resolves it from its token, exactly like production; with it, the * committer commits and the call's identity is asserted as `access`. * Without {@link CreateBenchOptions.service}, the bench client answers * `/workflow/capabilities` with HTTP 404, so the bench has no Workflows * service; pass `service` to test against one. */ export declare function createBench(options?: CreateBenchOptions): Bench; export { type BenchAbortInstanceArgs, type BenchCompleteEffectArgs, type BenchDeleteDefinitionArgs, type BenchEditFieldArgs, type BenchEvaluateArgs, type BenchFireActionArgs, type BenchResetActivityArgs, type BenchSessionArgs, type BenchStartInstanceArgs, type BenchTickArgs, type EditDocumentAction, type EditDocumentPatch, type EngineScope, type EngineWrappers, type FixtureBench, GuardDeniedError, type GuardHelpers, type QueryHelpers, type QueryIndexControls, type ReadHelpers, type StoreDocument, WriteAccessDeniedError };