@sanity-labs/client-fake-for-test 0.31.0 → 0.33.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 +163 -142
- package/dist/index.cjs +395 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +70 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.js +395 -19
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -48,7 +48,8 @@ const approved = await client.fetch<{ _id: string }[]>(
|
|
|
48
48
|
await client.patch("article-1").set({ state: "approved" }).commit();
|
|
49
49
|
|
|
50
50
|
// transaction — atomic batch
|
|
51
|
-
await client
|
|
51
|
+
await client
|
|
52
|
+
.transaction()
|
|
52
53
|
.patch("article-1", (p) => p.set({ reviewedBy: "alice" }))
|
|
53
54
|
.patch("article-2", (p) => p.set({ reviewedBy: "alice" }))
|
|
54
55
|
.commit();
|
|
@@ -65,36 +66,36 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
65
66
|
|
|
66
67
|
### Supported
|
|
67
68
|
|
|
68
|
-
| Area
|
|
69
|
-
|
|
|
70
|
-
| Read
|
|
71
|
-
| Read
|
|
72
|
-
| Read
|
|
73
|
-
| Write
|
|
74
|
-
| Write
|
|
75
|
-
| Write
|
|
76
|
-
| Write
|
|
77
|
-
| Mutate
|
|
78
|
-
| Patch
|
|
79
|
-
| Transaction
|
|
80
|
-
| Actions
|
|
81
|
-
| Releases
|
|
82
|
-
| Config
|
|
83
|
-
| Config
|
|
84
|
-
| Config
|
|
85
|
-
| Perspectives | `raw` / `published` / `drafts` / release stacks / a single release name or comma-joined stack (`"rA"`, `"drafts,rA"`), as `@sanity/client` sends them | Per-client default or per-`fetch` override; draft/version layering with `_originalId` projection
|
|
86
|
-
| HTTP
|
|
69
|
+
| Area | Method | Notes |
|
|
70
|
+
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
71
|
+
| Read | `fetch<T>(query, params?, { filterResponse?, returnQuery? })` | GROQ via groq-js. `filterResponse: false` → `{ result, ms, query }` (`RawQueryResponse`), like the real client |
|
|
72
|
+
| Read | `getDocument<T>(id)` | Returns `undefined` if missing (or hidden by ACL) — matches `@sanity/client` |
|
|
73
|
+
| Read | `getDocuments<T>(ids)` | Element-wise `null` for missing |
|
|
74
|
+
| Write | `create(doc, options?)` | Throws if `_id` already exists |
|
|
75
|
+
| Write | `createOrReplace(doc, options?)` | Upsert |
|
|
76
|
+
| Write | `createIfNotExists(doc, options?)` | No-op if `_id` exists |
|
|
77
|
+
| Write | `delete(id, options?)` | Default `{ _id }` or `null`; id/array shapes via options |
|
|
78
|
+
| Mutate | `mutate(operations, options?)` | Raw mutation array (`{create}`/`{patch}`/`{delete}`/…), or a `patch()` / `transaction()` builder. Atomic |
|
|
79
|
+
| Patch | `patch(id)` chain → `.commit()` | Ops: `.set`, `.setIfMissing`, `.unset`, `.inc`, `.dec`, `.insert(position, anchor, items)`, `.ifRevisionId` |
|
|
80
|
+
| Transaction | `transaction()` chain → `.commit()` | Mutations: `.create`, `.createOrReplace`, `.createIfNotExists`, `.delete`, `.patch(id, recipe)`. Atomic — any throw rolls back the whole batch. Default result is a `MultipleMutationResult` (`{ transactionId, documentIds, results }`) |
|
|
81
|
+
| Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
|
|
82
|
+
| Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish. `createVersion({ baseId, publishedId, releaseId })` (or `version.create` with `baseId` + `versionId`) copies the base document, `_type` included, into the version and records it in `_system.base` (`{ id, rev }`); a missing base fails. With access control, `version.create` in either form needs `create` on the resulting version, or `update` on the version it replaces (as `createOrReplace` does), as the Content Lake does; the base is not access-checked. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
|
|
83
|
+
| Config | `config()` | Returns `{ projectId?, dataset, resource?, perspective, token?, useProjectHostname, apiHost, apiVersion, useCdn }`. `apiHost` (default `https://api.sanity.io`), `apiVersion` (default `"1"`, a leading `v` dropped) and `useCdn` (default `true`) are taken as `createTestClient` and `withConfig` options and only decide the URL an error names (see [Errors are `ClientError`s](#errors-are-clienterrors)). `projectId` defaults to `"test"`, and is absent on a client created with `useProjectHostname: false` and no `projectId`, as `@sanity/client` leaves it unset there (its siblings too, until one names a project) |
|
|
84
|
+
| Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
|
|
85
|
+
| Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname?, apiHost?, apiVersion?, useCdn? })` | Sibling handle into the same multi-resource registry; `resource` points it at a Media Library, Canvas, dashboard or dataset (see [Resource types](#resource-types-media-library-canvas-dashboard)); `token` binds a registered identity (see the token→identity registry below), `accessControl` rebinds it inline — the two are mutually exclusive; `useProjectHostname: false` mints a global-hosted sibling |
|
|
86
|
+
| Perspectives | `raw` / `published` / `drafts` / release stacks / a single release name or comma-joined stack (`"rA"`, `"drafts,rA"`), as `@sanity/client` sends them | Per-client default or per-`fetch` override; draft/version layering with `_originalId` projection |
|
|
87
|
+
| HTTP | `request({ url? \| uri?, method?, body?, headers?, query? })` | Present **only** when the handle has an acting identity (`accessControl`, or a bound `token`). Serves `/users/me` (host-aware: project-scoped record on the project host, `globalUser` on a global-hosted or `resource` handle), the handle's ACL (`<data base>/acl`, or an explicit `aclPath`), `/projects/<projectId>` (the project's members: `{ id, isRobot?, roles? }` rows, one per distinct resolved project user, plus `organizationId` when configured), `/projects/<projectId>/users/<ids>` (project-user records with `id` + `sanityUserId`), `/projects/<projectId>/roles` (the project role catalog), `/projects/<projectId>/features` (the project's feature names, seeded with `projectFeatures`), the History API, resource lookup and the Access API (see [Resource types](#resource-types-media-library-canvas-dashboard)), and `POST /functions/<idOrName>/invoke` (see [Functions](#functions)). Calling it without one throws a guidance error. |
|
|
87
88
|
|
|
88
89
|
#### Mutation return shapes
|
|
89
90
|
|
|
90
91
|
`create` / `createOrReplace` / `createIfNotExists` / `delete` / `mutate` / `transaction().commit()` honor `returnDocuments` / `returnFirst`, mirroring `@sanity/client`:
|
|
91
92
|
|
|
92
|
-
| `returnDocuments`
|
|
93
|
-
|
|
|
94
|
-
| (default for create-family) |
|
|
95
|
-
| `true`
|
|
96
|
-
| `false`
|
|
97
|
-
| `false`
|
|
93
|
+
| `returnDocuments` | `returnFirst` | Resolves to |
|
|
94
|
+
| --------------------------- | ---------------------------------------------- | ------------------------------------------------------------------ |
|
|
95
|
+
| (default for create-family) | | the mutated document |
|
|
96
|
+
| `true` | `false` | `SanityDocument[]` |
|
|
97
|
+
| `false` | `true` (or default) | `SingleMutationResult` `{ transactionId, documentId, results }` |
|
|
98
|
+
| `false` | `false` (default for `transaction` / `mutate`) | `MultipleMutationResult` `{ transactionId, documentIds, results }` |
|
|
98
99
|
|
|
99
100
|
> [!NOTE]
|
|
100
101
|
> The static return type of `create` / `delete` reflects the **default** shape (the document / `{ _id } | null`). When you pass `returnDocuments: false` to get an id-shaped result, supply a type argument or cast — the runtime value is correct either way.
|
|
@@ -190,15 +191,15 @@ A bearer that is not a registered identity, has a JWT's three segments and verif
|
|
|
190
191
|
|
|
191
192
|
The Content Lake refuses the token on every request it serves (queries, documents, mutations, actions, the History API), as gradient does (`pkg/server/httpapi/middlewares/sessions/session.go`), each as a `PlatformHttpError`:
|
|
192
193
|
|
|
193
|
-
| Token
|
|
194
|
-
|
|
|
195
|
-
| Signed by another key
|
|
196
|
-
| `alg` other than `RS256`
|
|
197
|
-
| A segment that is not base64url
|
|
198
|
-
| A grant the Content Lake cannot parse
|
|
194
|
+
| Token | Answer |
|
|
195
|
+
| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
|
196
|
+
| Signed by another key | 400 `{ error: { type: "httpBadRequest", description: 'invalid JWT token "<token>": crypto/rsa: verification error' } }` |
|
|
197
|
+
| `alg` other than `RS256` | 400, `invalid JWT token "<token>": token uses algorithm "<alg>", expected "RS256"` |
|
|
198
|
+
| A segment that is not base64url | 400, `invalid JWT token "<token>": illegal base64 data at input byte <n>` |
|
|
199
|
+
| A grant the Content Lake cannot parse | 400, the grant's own `description` (no `invalid JWT token` prefix) |
|
|
199
200
|
| `x` that is not an int64 (`1.0`, `4.1e9`, over 2^63 - 1) | 400, `invalid expiry: expected int64: strconv.ParseInt: parsing "<x>": <reason>` (`invalid syntax` / `value out of range`) |
|
|
200
|
-
| `i` that is not a string
|
|
201
|
-
| `x` at or before now
|
|
201
|
+
| `i` that is not a string | 400, `token field "i" must be a string` |
|
|
202
|
+
| `x` at or before now | 403 `{ error: { type: "permissionDeniedError", description: "Token has expired (at 2026-11-20 12:00:30 +0000 UTC)" } }` |
|
|
202
203
|
|
|
203
204
|
A JWT that does not verify still binds, as production clients accept any string; the refusal comes on the first request. Without `internalTokenKeys` a JWT is an unknown token, as before. An internal token has no session, so `revokeIdentity` throws for one: mint one whose `x` has passed instead. The project API (populus) verifies internal tokens with its own key and answers differently; the fake models that only for the [organization store lookup](#organization-stores), so `request()` of `/users/me`, `/projects/…`, the Access API or an ACL throws a fake error with an internal token. A token with claims the Content Lake reads but the fake does not model (`tokenType`, `guid`, `s`, `z`, `audit`, `act`) binds, and throws a fake error on a Content Lake request instead of a guessed answer; `exp`, `iat`, `nbf` or a claims segment that is not a JSON object throw when the token binds. A missing `i`, or a `g…` global user id other than `god` (which gradient maps to a project user), throws its fake error on a request, after the 400 and 403 checks above.
|
|
204
205
|
|
|
@@ -240,13 +241,13 @@ await client.request({ uri: "/internal/organization-stores", query: { organizati
|
|
|
240
241
|
|
|
241
242
|
The first lookup for an organization without a store creates one `provisioning`, as populus does, and every later lookup answers the same store. In populus a background workflow then sets it `active`; in the fake `client.completeOrganizationStoreProvisioning("oAbc")` stands for that workflow finishing, and the next lookup answers `active`. A store whose provisioning never completes stays `provisioning`. The id is `os` and ten characters, derived from the organization id, so the same organization always gets the same id. Stores are shared by the whole `withConfig` family.
|
|
242
243
|
|
|
243
|
-
| Request
|
|
244
|
-
|
|
|
245
|
-
| A registered identity's token (a user or robot session), or an internal token that is not a service token | 401 `{ statusCode: 401, error: "Unauthorized", message: "A service session is required for this endpoint" }`
|
|
246
|
-
| An internal token without a signature, signed by another key, or past its `x`
|
|
247
|
-
| A missing, empty, repeated or unknown query parameter
|
|
248
|
-
| An organization other than `organizationId`
|
|
249
|
-
| While `simulateOutage("project-api")` is in effect
|
|
244
|
+
| Request | Answer |
|
|
245
|
+
| --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
246
|
+
| A registered identity's token (a user or robot session), or an internal token that is not a service token | 401 `{ statusCode: 401, error: "Unauthorized", message: "A service session is required for this endpoint" }` |
|
|
247
|
+
| An internal token without a signature, signed by another key, or past its `x` | 401, `jwt signature is required` / `invalid signature` / `Session expired` |
|
|
248
|
+
| A missing, empty, repeated or unknown query parameter | 400 `{ statusCode: 400, error: "Bad Request", message: "Validation failed", validation: { query: { source: "query", keys: [<key>], message: '"organizationId" is required' } } }` |
|
|
249
|
+
| An organization other than `organizationId` | 404, `Organization <id> not found` |
|
|
250
|
+
| While `simulateOutage("project-api")` is in effect | 500 (see [Platform outages](#platform-outages)); no store is created |
|
|
250
251
|
|
|
251
252
|
Populus answers only `provisioning` and `active` stores, so the lookup never answers another status, and seeding another status throws. `request()` takes a `query` object as `@sanity/client` does, appended to the URL after the request tag; every route reads its parameters from that URL. A `tag` in `query`, and bracketed query keys such as `organizationId[]` (which Express parses into nested values), throw a fake error.
|
|
252
253
|
|
|
@@ -254,10 +255,10 @@ Populus answers only `provisioning` and `active` stores, so the lookup never ans
|
|
|
254
255
|
|
|
255
256
|
Workflows keeps its definitions and instances in the organization's store (see [Organization stores](#organization-stores)). Kong serves that store on two routes, and `request()` answers both on a handle with an acting identity, so code that reads and writes a Workflows store runs against the fake as against the platform:
|
|
256
257
|
|
|
257
|
-
| Route
|
|
258
|
-
|
|
|
259
|
-
| `/vX/workflows/organizations/<organizationId>/<action>` (kong `config/common/kong.jsonnet`, `gradient-workflows`)
|
|
260
|
-
| `/v<X or date>/organization-stores/<storeId>/<action>` (kong `config/staging-internal/kong.jsonnet:326-345`, internal Kong) | `query`, `doc/<ids>`, `mutate` (POST `{ mutations }`)
|
|
258
|
+
| Route | Actions | Used by |
|
|
259
|
+
| --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
|
|
260
|
+
| `/vX/workflows/organizations/<organizationId>/<action>` (kong `config/common/kong.jsonnet`, `gradient-workflows`) | `query` (GET, or POST `{ query, params }`), `doc/<ids>`, `listen` | the read route, for Studio, the SDK and engines |
|
|
261
|
+
| `/v<X or date>/organization-stores/<storeId>/<action>` (kong `config/staging-internal/kong.jsonnet:326-345`, internal Kong) | `query`, `doc/<ids>`, `mutate` (POST `{ mutations }`) | the Workflows service, which reads and commits there |
|
|
261
262
|
|
|
262
263
|
```ts
|
|
263
264
|
const client = createTestClient({
|
|
@@ -276,23 +277,34 @@ await client.request({ url: "/workflows/organizations/oAbc/doc/wf.def,wf.none" }
|
|
|
276
277
|
// { documents: [{ _id: "wf.def", … }], omitted: [{ id: "wf.none", reason: "existence" }] }
|
|
277
278
|
```
|
|
278
279
|
|
|
279
|
-
The store is the organization's store from `organizationStores` or the lookup, and `client.organizationStore(organizationId)` hands out its documents to seed or inspect. Reads and writes act as the handle's token, with its grants, mutation guards, mutation log and history, as on any resource:
|
|
280
|
+
The store is the organization's store from `organizationStores` or the lookup, and `client.organizationStore(organizationId)` hands out its documents to seed or inspect. `organizationStoreId(organizationId)` is the id the lookup answers, for a test that addresses the store route without looking it up. Reads and writes act as the handle's token, with its grants, mutation guards, mutation log and history, as on any resource:
|
|
280
281
|
|
|
281
282
|
- A query sees only the documents the token may read. `doc` omits a missing id with reason `existence` and one the token may not read with reason `permission` (gradient `pkg/server/httpapi/get_documents.go:25-33,140-162`).
|
|
282
283
|
- `mutate` applies its mutations atomically and answers `{ transactionId, results: [{ id, operation, document? }] }`, `document` only with `returnDocuments=true` (gradient `pkg/server/httpapi/mutate_test.go:66-98`). A write the grants do not allow is refused with `WriteAccessDeniedError`.
|
|
284
|
+
- An identity with `organizationScope`, an organization-scoped token, is refused on another organization's store on both routes with 403 `{ error: { type: "permissionDeniedError", description: "Unauthorized organization access" } }` (gradient `pkg/system/session.go:71-94`).
|
|
285
|
+
- `mutate` refuses a body gradient cannot apply with gradient's answer, and writes nothing (`pkg/documents/mutation/patch.go:15-26,80-92`, `pkg/documents/errors.go:14-30`, `pkg/server/httpapi/error_test.go:208-265`): a `create` on an id the store holds is 409 `documentAlreadyExistsError` (`Document by ID "<id>" already exists`), a `patch` of an id it does not hold is 404 `documentNotFoundError` (`The document with the ID "<id>" was not found`), and a `patch` whose `ifRevisionID` is not the document's `_rev` is 409 `documentRevisionIDDoesNotMatchError` with `expectedRevisionID` and `currentRevisionID`. An `ifRevisionID` on a document an earlier mutation of the same body wrote throws a fake error.
|
|
283
286
|
- A query that references a parameter it does not send answers the Content Lake's 400 (see [Unsent query parameters](#unsent-query-parameters)), and a revoked token its 401.
|
|
284
287
|
- A request carries no perspective, so reads are raw whatever the calling handle's `perspective` is. A write is logged in `client.transactions()` with `organizationStore: { id, organizationId }`; `projectId` and `dataset` there are the calling handle's. `client.calls()` records the `request()` call only.
|
|
285
288
|
|
|
286
289
|
Kong's answers, as staging gives them:
|
|
287
290
|
|
|
288
|
-
| Request
|
|
289
|
-
|
|
|
290
|
-
| An organization without a store, or with one still `provisioning`
|
|
291
|
-
| A store id that is not an `active` store
|
|
292
|
-
| The read route on API version `1` or a date, or the store route on `1` | 404 `{ message: "no Route matched with those values" }`
|
|
293
|
-
| Any other `/vX/workflows…` path, such as `…/mutate` on the read route
|
|
291
|
+
| Request | Answer |
|
|
292
|
+
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
293
|
+
| An organization without a store, or with one still `provisioning` | 404 `{ statusCode: 404, error: "Dataset not found", message: 'Dataset for id "org:<organizationId>" not found' }` (kong `kong/sanity-utils/sanity_namespace_routing_key.lua:47-56`; populus makes a store routable before it sets it `active`) |
|
|
294
|
+
| A store id that is not an `active` store | the same 404, naming the store id |
|
|
295
|
+
| The read route on API version `1` or a date, or the store route on `1` | 404 `{ message: "no Route matched with those values" }` |
|
|
296
|
+
| Any other `/vX/workflows…` path, such as `…/mutate` on the read route | Kong sends it to the Workflows service, which the fake does not serve: a fake error |
|
|
294
297
|
|
|
295
|
-
The fake does not tell the two Kongs apart, so it serves the store route on any host; on the platform only internal Kong does.
|
|
298
|
+
The fake does not tell the two Kongs apart, so it serves the store route on any host; on the platform only internal Kong does. The store route's `export`, `references`, `actions` and `history`, throw a fake error.
|
|
299
|
+
|
|
300
|
+
The read route's `listen` is a server-sent event stream, which `@sanity/client` and the Workflows engine open with `fetch`, not with a request. `client.resolveFetch()` answers it: pass it as `resolveFetch` to a real `@sanity/client`, or call `client.resolveFetch()()` as the `fetch` of code that opens the stream itself. It answers as gradient serves a listener (sanity-io/gradient `pkg/server/httpapi/listen.go`):
|
|
301
|
+
|
|
302
|
+
- A revoked token, an organization without an `active` store, another API version than `X`, or an organization-scoped token on another organization's store get the same HTTP refusal as `query`, before the stream opens.
|
|
303
|
+
- The stream opens with `welcome` (`listen.go:342-349`). Each commit to the organization store then sends one `mutation` event per document it changes, in the order of its mutations, with `transition` `appear`, `update` or `disappear` as the listener's query matched the document before and after (`pkg/listening/transition.go:75-86`). A document the token may not read matches neither before nor after (`pkg/listening/listening.go:117-135`). Each event carries `eventId` (also its SSE `id`), `documentId`, `transactionId`, `identity`, `previousRev`, `resultRev`, `visibility` and its position in the transaction (`pkg/listening/notifications.go:276-291`, `distributor.go:697-698`); `result` only with `includeResult=true`, `previous` only with `includePreviousRevision=true`, and `mutations` (the document's net change as one `createOrReplace` or `delete`) unless `includeMutations=false`.
|
|
304
|
+
- An unknown query parameter, a `visibility` other than `transaction` or `query`, or a query gradient cannot run gets gradient's fatal error on the stream: `channelError` with `{ error: { type, description } }`, then `disconnect` with `{"reason": "error"}` (`listen.go:101-134`). `includeProjection`, `effectFormat`, `includeAllVersions` and `enableResume` throw a fake error.
|
|
305
|
+
- `client.failListeners(organizationId, error)` ends every open listener on the store with those two frames for `error`. `client.dropListeners(organizationId)` ends them without an event, as gradient ends a listener at shutdown or at the end of its lifetime so the client reconnects (`listen.go:504-514`).
|
|
306
|
+
|
|
307
|
+
`request()` of the `listen` path throws a fake error naming `resolveFetch()`.
|
|
296
308
|
|
|
297
309
|
#### Functions
|
|
298
310
|
|
|
@@ -339,20 +351,20 @@ client.functionInvocations();
|
|
|
339
351
|
|
|
340
352
|
`client.addFunction(fn)` deploys (or replaces) one more and `client.removeFunction(id)` removes one, for every handle of the family. `functionInvocations()` lists every accepted invocation, in order; a refused one is not recorded. The caller's permissions are read from its `access["<scopeType>:<scopeId>"].permissions`. Header names are case-insensitive, and `blueprintStackId` may also be in the `uri`'s own query string. A `POST` to any other path throws the fake's no-handler error. Refusals are `PlatformHttpError`s whose `response.body` is the Functions API's `{ error, message, details: { errors } }`, checked in the service's order:
|
|
341
353
|
|
|
342
|
-
| Request
|
|
343
|
-
|
|
|
344
|
-
| `apiVersion` `1` (the default)
|
|
345
|
-
| An internal token (a service-minted JWT has no `guid` claim)
|
|
346
|
-
| No `X-Sanity-Scope-Type` or `X-Sanity-Scope-Id` header
|
|
347
|
-
| A scope type other than `project` or `organization`
|
|
354
|
+
| Request | Answer |
|
|
355
|
+
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
|
|
356
|
+
| `apiVersion` `1` (the default) | 400 `BAD_REQUEST`, `Invalid API version in path`, `details.errors: { version: "v1" }` |
|
|
357
|
+
| An internal token (a service-minted JWT has no `guid` claim) | 401 `INVALID_TOKEN`, `Missing required claim: guid` |
|
|
358
|
+
| No `X-Sanity-Scope-Type` or `X-Sanity-Scope-Id` header | 400 `MISSING_SCOPE` |
|
|
359
|
+
| A scope type other than `project` or `organization` | 400 `INVALID_SCOPE_TYPE` |
|
|
348
360
|
| A caller holding none of `sanity.project.functions.invoke`, `sanity.project.blueprints.deploy`, `sanity.project.deployStudio` on a project scope (organization: `sanity.organization.functions.invoke`, `sanity.blueprints.deploy`, `sanity.organization.tokens.create`) | 403 `FORBIDDEN`, `You do not have invoke access to project p1`, `details.errors: { required: [...] }` |
|
|
349
|
-
| While `simulateOutage("project-api")` is in effect
|
|
350
|
-
| A body that is not `{ event: { data: {} } }`, a `blueprintStackId` under 10 characters, a `sync` other than `true` / `false`
|
|
351
|
-
| Without `blueprintStackId`, an id under 10 characters
|
|
352
|
-
| With `blueprintStackId`, a name the stack does not hold
|
|
353
|
-
| An unknown id, or a function outside the scope
|
|
354
|
-
| A document, media-library-asset, sync-tag-invalidate or schedule function; a queue or durable function with `sync: "true"`
|
|
355
|
-
| An asynchronous payload of 256 KiB or more
|
|
361
|
+
| While `simulateOutage("project-api")` is in effect | 500 `ACCESS_ERROR`, `Failed to validate project access` |
|
|
362
|
+
| A body that is not `{ event: { data: {} } }`, a `blueprintStackId` under 10 characters, a `sync` other than `true` / `false` | 400 `INVALID_INPUT`, `Validation error: …` |
|
|
363
|
+
| Without `blueprintStackId`, an id under 10 characters | 400 `BAD_REQUEST`, `Invalid functionId` |
|
|
364
|
+
| With `blueprintStackId`, a name the stack does not hold | 404 `FUNCTION_NOT_FOUND`, `Function "<name>" was not found in Blueprint Stack <stackId>` |
|
|
365
|
+
| An unknown id, or a function outside the scope | 404 `FUNCTION_NOT_FOUND`, `function not found` |
|
|
366
|
+
| A document, media-library-asset, sync-tag-invalidate or schedule function; a queue or durable function with `sync: "true"` | 400 `INVOKE_NOT_SUPPORTED` |
|
|
367
|
+
| An asynchronous payload of 256 KiB or more | 413 `CONTENT_TOO_LARGE` |
|
|
356
368
|
|
|
357
369
|
A function is in scope when the scope owns it, or when an organization scope invokes a project's function and that organization is the client's `organizationId` (every project of the family belongs to it); a project scope never reaches an organization's function. Invocations are asynchronous only: a synchronous one that passes every check throws a fake error, as does an `x-sanity-lineage` header (the recursion limit is not modelled). The payload size is measured on `{ data, invokedBySanityUserId, lineage }`, slightly smaller than the Lambda payload the service measures. The service's quota check is not modelled.
|
|
358
370
|
|
|
@@ -406,11 +418,11 @@ createTestClient({
|
|
|
406
418
|
|
|
407
419
|
Such an identity is a member of `p1` only. Without `projectId` (the default, and how the fake behaved before) an identity is a member of every project and accepted on every host. A project-scoped identity is refused the way staging refuses an Editor robot of another project (EDEX-3204), each as a `PlatformHttpError`:
|
|
408
420
|
|
|
409
|
-
| Request
|
|
410
|
-
|
|
|
411
|
-
| Any request on another project's host: a handle with `projectId: "p2"`, project-hosted (queries, documents, writes, actions, `request()`) | 401 `{ statusCode: 401, errorCode: "SIO-401-AWH", error: "Unauthorized", message: "Session does not match project host" }`
|
|
412
|
-
| `GET /projects/<other or unknown project>/features` (global host)
|
|
413
|
-
| `/projects/<other project>` and `/projects/<other project>/users/<ids>`
|
|
421
|
+
| Request | Answer |
|
|
422
|
+
| ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
|
423
|
+
| Any request on another project's host: a handle with `projectId: "p2"`, project-hosted (queries, documents, writes, actions, `request()`) | 401 `{ statusCode: 401, errorCode: "SIO-401-AWH", error: "Unauthorized", message: "Session does not match project host" }` |
|
|
424
|
+
| `GET /projects/<other or unknown project>/features` (global host) | 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be a member of this project to perform this operation" }` |
|
|
425
|
+
| `/projects/<other project>` and `/projects/<other project>/users/<ids>` | The identity is not listed among the members |
|
|
414
426
|
|
|
415
427
|
Membership of a Media Library or Canvas is not a project matter; their ACLs answer as in [Resource types](#resource-types-media-library-canvas-dashboard).
|
|
416
428
|
|
|
@@ -425,7 +437,10 @@ const client = createTestClient({
|
|
|
425
437
|
user: { id: "p-service" },
|
|
426
438
|
grants: [
|
|
427
439
|
{ path: "prod.wf-instance.*", permissions: ["read", "create", "update"] },
|
|
428
|
-
{
|
|
440
|
+
{
|
|
441
|
+
path: "temp.system.guard.prod.wf-instance.**",
|
|
442
|
+
permissions: ["read", "create", "update"],
|
|
443
|
+
},
|
|
429
444
|
],
|
|
430
445
|
},
|
|
431
446
|
},
|
|
@@ -435,16 +450,16 @@ const client = createTestClient({
|
|
|
435
450
|
|
|
436
451
|
The Content Lake parses a token's path grants on every request it serves and refuses the whole request when one does not parse — whatever the request asks. The fake does the same for every handle acting as that identity, token-bound or inline `accessControl`: `fetch`, `getDocument(s)`, `releases.get` / `releases.fetchDocuments`, every mutation and action, and the History API throw a `PlatformHttpError` with `statusCode: 400` and body `{ error: { description, type: "httpBadRequest" } }`, where `description` is the Content Lake's message for the first grant it cannot parse. A route the resource does not mount still answers its 404 first (a Canvas's `/actions`), as the request never reaches the Content Lake.
|
|
437
452
|
|
|
438
|
-
| Grant
|
|
439
|
-
|
|
|
440
|
-
| `path: ""`
|
|
441
|
-
| `path` starting with `.`
|
|
442
|
-
| `path` with an empty element (`a..b`, `a.`)
|
|
443
|
-
| `path` over 128 UTF-8 bytes
|
|
444
|
-
| `*` before the last element (`*.wf-instance.*`)
|
|
445
|
-
| `**` before the last element
|
|
446
|
-
| an element outside `[A-Za-z0-9_-]`, or starting with `-` (an element with several lines passes when any one line is valid, a quirk the Content Lake keeps for old ids) | `invalid element "<element>"`, Go-quoted
|
|
447
|
-
| a permission other than `read`, `update`, `create`, `manage`, `history`, `editHistory` (e.g. `delete`)
|
|
453
|
+
| Grant | `description` |
|
|
454
|
+
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
|
|
455
|
+
| `path: ""` | `path must contain at least one element` |
|
|
456
|
+
| `path` starting with `.` | `path cannot begin with delimiter "."` |
|
|
457
|
+
| `path` with an empty element (`a..b`, `a.`) | `path contains empty element` |
|
|
458
|
+
| `path` over 128 UTF-8 bytes | `path exceeds maximum length of 128` |
|
|
459
|
+
| `*` before the last element (`*.wf-instance.*`) | `wildcard must be last component` |
|
|
460
|
+
| `**` before the last element | `descendant wildcard must be last component` |
|
|
461
|
+
| an element outside `[A-Za-z0-9_-]`, or starting with `-` (an element with several lines passes when any one line is valid, a quirk the Content Lake keeps for old ids) | `invalid element "<element>"`, Go-quoted |
|
|
462
|
+
| a permission other than `read`, `update`, `create`, `manage`, `history`, `editHistory` (e.g. `delete`) | `invalid permission "<permission>"`, Go-quoted |
|
|
448
463
|
|
|
449
464
|
Filter grants come from the ACL, not the token, and are not checked. `/users/me`, the project API (`/projects/…`), the Access API and the ACL are not the Content Lake's and do not read a token's grants, so they keep answering.
|
|
450
465
|
|
|
@@ -500,23 +515,24 @@ await client.request({ url: client.getDataUrl("history", `documents/a?revision=$
|
|
|
500
515
|
await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/c1/actions
|
|
501
516
|
```
|
|
502
517
|
|
|
503
|
-
| Capability
|
|
504
|
-
|
|
|
505
|
-
| `drafts.` / `versions.` ids, perspectives
|
|
506
|
-
| `/actions` (releases, version and document actions)
|
|
507
|
-
| History: `documents/<ids>?revision=`, `transactions/<ids>` (NDJSON), `events/documents/<ids>` | ✅
|
|
508
|
-
| ACL `<data base>/acl`
|
|
509
|
-
| Access API `…/user-permissions/me`, `…/me/check`
|
|
510
|
-
| Access API `…/users`
|
|
511
|
-
| Access API `…/users/<sanityUserId>` (served on `organization`, below)
|
|
512
|
-
| Access API `…/roles`, `…/roles/<roleName>`
|
|
513
|
-
| Project role catalog `/projects/<projectId>/roles`
|
|
514
|
-
| Org lookup
|
|
518
|
+
| Capability | dataset | media-library | canvas | dashboard |
|
|
519
|
+
| --------------------------------------------------------------------------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------- |
|
|
520
|
+
| `drafts.` / `versions.` ids, perspectives | ✅ | ✅ | ✅ | ✅ |
|
|
521
|
+
| `/actions` (releases, version and document actions) | ✅ | ✅, except `release.create` → 403 `releaseLimitExceededError` | 404 `Cannot POST …/actions` | 404 `Cannot POST …/actions` |
|
|
522
|
+
| History: `documents/<ids>?revision=`, `transactions/<ids>` (NDJSON), `events/documents/<ids>` | ✅ | ✅ | ✅ | 404 `Cannot GET …` |
|
|
523
|
+
| ACL `<data base>/acl` | ✅ | ✅ with `sanity.media-library.read`, else 401; unknown id 404 `Media library not found` | ✅; unknown id 404 `Resource not found` | 404 `Cannot GET …` |
|
|
524
|
+
| Access API `…/user-permissions/me`, `…/me/check` | ✅ | ✅ | ✅ | ✅ |
|
|
525
|
+
| Access API `…/users` | ✅ | ✅ | 403 | 403 |
|
|
526
|
+
| Access API `…/users/<sanityUserId>` (served on `organization`, below) | 403 | 403 | 403 | 403 |
|
|
527
|
+
| Access API `…/roles`, `…/roles/<roleName>` | ✅ with `sanity.project.roles.read`, else 403 | ✅ with `sanity.media-library.roles.read`, else 403 | 403 | 403 |
|
|
528
|
+
| Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
|
|
529
|
+
| Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
|
|
515
530
|
|
|
516
531
|
- **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. Populus mounts the Access API from API version `2025-07-11`, so a handle on an earlier `apiVersion`, the default `"1"` included, gets the 404 Express answers for a route that is not mounted (`Cannot GET /access/…`), as on the platform; `X` reaches it. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id that does not exist answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. A Media Library, Canvas or dashboard exists once it is seeded (`resources`, `documents`, or `seed()` / `add()` on its handle or its `store()`) or written to through the fake; pointing a client at it (`withConfig({ resource })`) does not create it, as on the platform. An identity registered with `robot: true` is a robot, as populus flags an API token's principal: `/users/me` reports it with `provider: "sanity-token"`, users listings leave it out, and `…/robots/<id>` (keyed by its account-global id) answers `{ id, label, createdAt, memberships, networkPolicy: null }` with only its membership on the addressed resource, as populus's `getRobot` does. That read needs `sanity.<type>.tokens.read` on the actor's entry for the resource, else 403; an id with no robot holding a role there answers 404 `Robot not found`. `…/robots` lists every robot with a membership on the resource as `{ data, nextCursor }`, ordered by id, `limit` per page (default 100, at most 500) after the `nextCursor` id, with `nextCursor` the last id of a full page, else `null`, as populus's `listRobots` does. On an organization, `includeChildren=true` also lists the memberships each robot holds on the organization's Media Libraries, Canvases and dashboards, and the robots that hold only those. Populus serves robots only on `project` and `organization`, so both robots routes on any other type answer 400 `{ statusCode: 400, error: "Bad Request", message: "Validation failed", validation: { params: { source: "params", keys: ["resourceType"], message: '"resourceType" must be one of [project, organization]' } } }`, before the permission check. The fake does not model tokens, so `tokenId`, `expiresAt`, `managedBy` and `lastSeenAt` are absent, `label` is the robot's name (else its id) and `createdAt` is the epoch. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
|
|
517
532
|
- **Members.** Every member listing (`/projects/<projectId>`, `…/users`, `…/roles`) sees the registered identities plus, on a handle created with inline `accessControl`, that handle's own actor. Inline config belongs to its handle: a token sibling does not see it.
|
|
518
533
|
- **Roles.** `…/roles` answers `{ data: [role], nextCursor: null }` and `…/roles/<roleName>` one role (404 `Role not found` for a name no member holds). A role is `{ name, title, description?, resourceType, resourceId, appliesToUsers, appliesToRobots, permissions }`, collected from the roles the members hold on the resource. The fake does not model role definitions, so `title` is the name where the seed gives none, both `appliesTo…` flags are `true` and `permissions` is `[]`. A media library serves its roles only to an actor whose `"media-library:<id>"` entry holds `sanity.media-library.roles.read` in `permissions`, else 403, as the reference requires. Likewise a project serves its roles only to an actor whose `"project:<id>"` entry holds `sanity.project.roles.read` (on staging every stock user role holds it), else 403.
|
|
519
534
|
- **Project role catalog.** `GET /projects/<projectId>/roles` answers the older projects API's bare array, one row per role the project's members hold: `{ name, title, description?, projectId, appliesToUsers, appliesToRobots }`, with the same unmodelled defaults as the Access API rows. The platform also sends `isCustom` and a `grants` tree per role; the fake does not model role definitions, so it omits both. It needs `sanity.project.roles.read` on the actor's `"project:<projectId>"` entry, else 403 with the Access API's permission body.
|
|
535
|
+
- **Organization permissions.** `/access/organization/<organizationId>/user-permissions/me` on the client's `organizationId` lists the permissions of every `access` entry the actor holds, the organization's and those on its projects, libraries, canvases and dashboards, each row naming its own resource, as populus selects grants by the role's `ownerOrganizationId` there (`src/services/access/permissions.ts:462-472`). A project robot whose only access in the organization is its project role lists that role's grants.
|
|
520
536
|
- **Organization.** `/access/organization/<organizationId>/users` and `…/users/<sanityUserId>` (one row, or 404 `User not found` for a non-member) serve the members of the client's `organizationId`: identities with roles in their `"organization:<id>"` entry. Each row lists the organization membership, then the member's roles on every resource the client holds (its libraries, canvases, dashboards and projects), as the platform's organization row does. Like the platform, it needs `sanity.organization.members.read` in the actor's `"organization:<id>"` `permissions` (the built-in `member` role grants it), else 403. Another organization id answers 404 `Organization not found`; `…/roles` answers 403.
|
|
521
537
|
- **User attributes.** `GET /organizations/<organizationId>/users/me/attributes` answers the caller's own attributes there: `{ sanityUserId, organizationId, attributes: [{ type, key, values: { saml?, sanity? }, activeSource, activeValue }] }`, ordered by key. Seed them as `attributes: [{ key, type, values }]` on the identity's `"organization:<id>"` entry; the Sanity value takes precedence over the SAML one for `activeSource` and `activeValue`, as on the platform. No permission is needed. `limit` (default 50) and `cursor` (the last key of the previous page) page the list. A member with no seeded attributes gets `attributes: []`; a caller without roles in the organization gets 404 `User not found`, and another organization id 404 `Organization not found`.
|
|
522
538
|
- **History.** Every committed write since the client was created is recorded per resource, authored by the acting identity; seeded documents can be read at their seeded `_rev`. A handle answers for its own resource, and hides documents its grants cannot read, as reads do (a transaction that also touched such a document is served without it). Events model `createLiveDocument` / `updateLiveDocument` only.
|
|
@@ -529,11 +545,11 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
|
|
|
529
545
|
|
|
530
546
|
Every error the fake throws for an HTTP answer of the platform is an instance of `@sanity/client`'s `ClientError`, so code that branches on `error instanceof ClientError` handles it as it handles production's:
|
|
531
547
|
|
|
532
|
-
| Class
|
|
533
|
-
|
|
|
534
|
-
| `PlatformHttpError`
|
|
535
|
-
| `WriteAccessDeniedError` | a write the grants do not permit (403)
|
|
536
|
-
| `GuardDeniedError`
|
|
548
|
+
| Class | Answer |
|
|
549
|
+
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
550
|
+
| `PlatformHttpError` | the platform's refusals: a revoked token's 401, a token grant the Content Lake cannot parse (400), the Access API's 400/403/404, a route a resource does not mount (404), a Media Library release (403), an action's failed `if…RevisionId` precondition (409 `documentRevisionIDDoesNotMatchError`, or 404 `documentNotFoundError` when the document is missing) |
|
|
551
|
+
| `WriteAccessDeniedError` | a write the grants do not permit (403) |
|
|
552
|
+
| `GuardDeniedError` | a write a mutation guard denies (403) |
|
|
537
553
|
|
|
538
554
|
A project API outage (see [Platform outages](#platform-outages)) throws `PlatformServerError` instead, an instance of `@sanity/client`'s `ServerError`, as the client raises a 500.
|
|
539
555
|
|
|
@@ -545,38 +561,41 @@ The fake hands `ClientError` the response the platform sends, and `ClientError`
|
|
|
545
561
|
|
|
546
562
|
Useful in test bodies, but a giveaway that the code under test isn't using the real client. Keep them in the test file, not in the code being tested.
|
|
547
563
|
|
|
548
|
-
| Method
|
|
549
|
-
|
|
|
550
|
-
| `client.snapshot()`
|
|
551
|
-
| `client.seed(documents)`
|
|
552
|
-
| `client.add(documents)`
|
|
553
|
-
| `client.reset()`
|
|
554
|
-
| `client.store()`
|
|
555
|
-
| `client.datasets()`
|
|
556
|
-
| `client.resources()`
|
|
557
|
-
| `client.mutations()`
|
|
558
|
-
| `client.transactions()`
|
|
559
|
-
| `client.clearLog()`
|
|
560
|
-
| `client.calls(method?)`
|
|
561
|
-
| `client.callCount(method?)`
|
|
562
|
-
| `client.clearCalls()`
|
|
563
|
-
| `client.stub(name, handler)`
|
|
564
|
-
| `client.stubs()`
|
|
565
|
-
| `client.addIdentity(token, identity)`
|
|
566
|
-
| `client.identities()`
|
|
567
|
-
| `client.revokeIdentity(token)`
|
|
568
|
-
| `createTestClient({ internalTokenKeys: [publicKeyPem] })`
|
|
569
|
-
| `client.addFunction(fn)` / `client.removeFunction(id)`
|
|
570
|
-
| `client.functionInvocations()`
|
|
571
|
-
| `client.completeOrganizationStoreProvisioning(organizationId)`
|
|
572
|
-
| `client.
|
|
573
|
-
| `client.
|
|
574
|
-
| `
|
|
575
|
-
| `
|
|
564
|
+
| Method | Use |
|
|
565
|
+
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
566
|
+
| `client.snapshot()` | Read-only `readonly SanityDocument[]` of the current dataset |
|
|
567
|
+
| `client.seed(documents)` | Replace the current dataset's contents |
|
|
568
|
+
| `client.add(documents)` | Merge documents in without resetting |
|
|
569
|
+
| `client.reset()` | Drop everything in the current dataset |
|
|
570
|
+
| `client.store()` | Direct access to the underlying `TestStore` |
|
|
571
|
+
| `client.datasets()` | `{ projectId, dataset }[]` known to the registry |
|
|
572
|
+
| `client.resources()` | Every resource known to the registry, `{ type, id }[]` (datasets as `id: "<projectId>.<dataset>"`) |
|
|
573
|
+
| `client.mutations()` | Every committed mutation, flattened and in order — assert exactly what writes your code submitted |
|
|
574
|
+
| `client.transactions()` | Every committed transaction (a direct mutation is a one-mutation transaction), each tagged with `transactionId` + `(projectId, dataset)` |
|
|
575
|
+
| `client.clearLog()` | Reset the mutation / transaction log |
|
|
576
|
+
| `client.calls(method?)` | Every recorded method call, with args + result — a framework-agnostic spy (like `vi.fn().mock.calls`) |
|
|
577
|
+
| `client.callCount(method?)` | Number of recorded calls, optionally filtered by method |
|
|
578
|
+
| `client.clearCalls()` | Reset the call log |
|
|
579
|
+
| `client.stub(name, handler)` | Register a handler for any unimplemented `@sanity/client` member (see below) |
|
|
580
|
+
| `client.stubs()` | The currently-registered stubs |
|
|
581
|
+
| `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
|
|
582
|
+
| `client.identities()` | Snapshot of the registered token→identity entries |
|
|
583
|
+
| `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
|
|
584
|
+
| `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
|
|
585
|
+
| `client.addFunction(fn)` / `client.removeFunction(id)` | Deploy or remove a function the Functions API invoke route serves (see [Functions](#functions)) |
|
|
586
|
+
| `client.functionInvocations()` | Every invocation the Functions API accepted, in order (see [Functions](#functions)) |
|
|
587
|
+
| `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
|
|
588
|
+
| `client.requestHandler()` | A `requestHandler` for a real `@sanity/client`: each request is answered as `request()` answers it on a sibling bound to the request's bearer token, API host and API version, so code that builds its own client runs against the fake |
|
|
589
|
+
| `client.resolveFetch()` | A `resolveFetch` for a real `@sanity/client` that answers the Workflows store read route's `listen` as gradient's event stream (see [Workflows store](#workflows-store)) |
|
|
590
|
+
| `client.failListeners(organizationId, error)` / `client.dropListeners(organizationId)` | End the open listeners on an organization's Workflows store with gradient's fatal error, or without an event (see [Workflows store](#workflows-store)) |
|
|
591
|
+
| `client.organizationStore(organizationId)` | The documents of the organization's store, the Workflows store, to seed or inspect (see [Workflows store](#workflows-store)). Throws unless the organization has a store |
|
|
592
|
+
| `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
|
|
593
|
+
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
594
|
+
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|
|
576
595
|
|
|
577
596
|
#### Two layers of observability
|
|
578
597
|
|
|
579
|
-
The fake records at two levels, so you can assert on either
|
|
598
|
+
The fake records at two levels, so you can assert on either _what your code did to the data_ or _how it called the client_:
|
|
580
599
|
|
|
581
600
|
- **Write effects** — `client.mutations()` / `client.transactions()`: the create/patch/delete/mutate operations that actually landed (rolled-back and `dryRun` writes excluded).
|
|
582
601
|
- **API calls** — `client.calls()` / `client.callCount()`: every invocation of a `@sanity/client`-surface method (`fetch`, `getDocument`, `create`, `patch`, `mutate`, `releases.*`, …) with its `args`, resolved `result`, or thrown `error`. This is the spy layer — reach for it to assert read patterns (`fetch` called once, with these params) that the write log can't show.
|
|
@@ -601,10 +620,12 @@ const client = createTestClient({
|
|
|
601
620
|
const serviceClient = client.withConfig({ token: "service-token" });
|
|
602
621
|
await loadAs(client, serviceClient); // code under test reads with one or the other
|
|
603
622
|
|
|
604
|
-
expect(client.calls("getDocument").map(({ token, apiVersion }) => ({ token, apiVersion }))).toEqual(
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
623
|
+
expect(client.calls("getDocument").map(({ token, apiVersion }) => ({ token, apiVersion }))).toEqual(
|
|
624
|
+
[
|
|
625
|
+
{ token: "caller-token", apiVersion: "2025-02-19" },
|
|
626
|
+
{ token: "service-token", apiVersion: "2025-02-19" },
|
|
627
|
+
],
|
|
628
|
+
);
|
|
608
629
|
```
|
|
609
630
|
|
|
610
631
|
> [!NOTE]
|
|
@@ -642,15 +663,15 @@ If this should be supported, open an issue: …
|
|
|
642
663
|
|
|
643
664
|
Nested access reports the full path (`client.assets.upload(...)` → `client.assets.upload`). If you type the test variable as `TestClient`, TypeScript also catches the misuse at compile time.
|
|
644
665
|
|
|
645
|
-
| Area
|
|
646
|
-
|
|
|
647
|
-
| `listen(...)` — real-time
|
|
648
|
-
| `clone()`
|
|
649
|
-
| `getUrl(uri)` — URL builder
|
|
650
|
-
| `request(...)` — generic HTTP
|
|
651
|
-
| `agent.*` / `assets.*` / `projects.*` / `users.*` / `live.*` / `mediaLibrary.*` | ❌ Guarded
|
|
652
|
-
| `observable.*` — RxJS API
|
|
653
|
-
| Patch ops: `.diffMatchPatch`, `.merge`, `.append`, `.prepend`, `.replace`
|
|
666
|
+
| Area | Status | Workaround |
|
|
667
|
+
| ------------------------------------------------------------------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
668
|
+
| `listen(...)` — real-time | ❌ Guarded | Test subscription logic separately, or `client.stub("listen", fn)` |
|
|
669
|
+
| `clone()` | ❌ Guarded | `withConfig({})` returns a sibling handle |
|
|
670
|
+
| `getUrl(uri)` — URL builder | ❌ Guarded | Hard-code in tests, or stub |
|
|
671
|
+
| `request(...)` — generic HTTP | ⚠️ Only with an acting identity | Configure `accessControl` or bind a registered `token`, stub it, or use [MSW](https://mswjs.io) |
|
|
672
|
+
| `agent.*` / `assets.*` / `projects.*` / `users.*` / `live.*` / `mediaLibrary.*` | ❌ Guarded | Seed docs directly, or `client.stub(name, fn)` |
|
|
673
|
+
| `observable.*` — RxJS API | ❌ Guarded | Wrap the Promise API with `from()` if needed |
|
|
674
|
+
| Patch ops: `.diffMatchPatch`, `.merge`, `.append`, `.prepend`, `.replace` | ❌ Absent | `.insert("after", "field[-1]", items)` for append; `.insert("before", "field[0]", items)` for prepend |
|
|
654
675
|
|
|
655
676
|
#### Registering stubs
|
|
656
677
|
|
|
@@ -666,7 +687,7 @@ Stubs fill gaps only — they don't shadow implemented methods like `fetch` or `
|
|
|
666
687
|
|
|
667
688
|
## Design constraints
|
|
668
689
|
|
|
669
|
-
- **Closure-scoped isolation.** `createTestClient({ documents })` returns a client whose store is local to that closure. Two clients in two tests do not see each other's writes. Pass the
|
|
690
|
+
- **Closure-scoped isolation.** `createTestClient({ documents })` returns a client whose store is local to that closure. Two clients in two tests do not see each other's writes. Pass the _same_ client to two consumers if they need to share a store.
|
|
670
691
|
- **Structural compatibility, not nominal.** Methods accept the same arg shapes as `@sanity/client`, so any code typed against `SanityClient` (or a narrow subset) can take a `TestClient` without an adapter.
|
|
671
692
|
- **groq-js directly.** Same GROQ evaluator the real client supports server-side, against the in-memory document set. What groq-js supports, this supports. What it doesn't (some `&&` short-circuit edge cases, custom functions), this doesn't either.
|
|
672
693
|
|