@sanity-labs/client-fake-for-test 0.28.0 → 0.30.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 +96 -3
- package/dist/index.cjs +532 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +101 -6
- package/dist/index.d.ts +101 -6
- package/dist/index.js +533 -18
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
|
|
|
83
83
|
| Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
|
|
84
84
|
| 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 |
|
|
85
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 | `request({ url? \| uri? })` | 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)). Calling it without one throws a guidance error. |
|
|
86
|
+
| 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
87
|
|
|
88
88
|
#### Mutation return shapes
|
|
89
89
|
|
|
@@ -200,11 +200,11 @@ The Content Lake refuses the token on every request it serves (queries, document
|
|
|
200
200
|
| `i` that is not a string | 400, `token field "i" must be a string` |
|
|
201
201
|
| `x` at or before now | 403 `{ error: { type: "permissionDeniedError", description: "Token has expired (at 2026-11-20 12:00:30 +0000 UTC)" } }` |
|
|
202
202
|
|
|
203
|
-
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
|
|
203
|
+
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
204
|
|
|
205
205
|
#### Platform outages
|
|
206
206
|
|
|
207
|
-
`client.simulateOutage("project-api")` takes the project API (populus) down, as in an outage. From the next request on, every `request()` it serves throws a `PlatformServerError`, on every handle of the family, siblings made before and after the call alike: `/users/me`, `/projects/<projectId>` and everything under it (members, users, roles, features, the dataset ACL), `/organizations/<id>/users/me/attributes`, the Access API, resource lookup (`/canvases/<id>`, …) and a Media Library's or Canvas's ACL. `PlatformServerError` extends `@sanity/client`'s `ServerError`, which the client throws for a status of 500 or more, not `ClientError`, and the client does not retry it:
|
|
207
|
+
`client.simulateOutage("project-api")` takes the project API (populus) down, as in an outage. From the next request on, every `request()` it serves throws a `PlatformServerError`, on every handle of the family, siblings made before and after the call alike: `/users/me`, `/projects/<projectId>` and everything under it (members, users, roles, features, the dataset ACL), `/organizations/<id>/users/me/attributes`, the organization store lookup, the Access API, resource lookup (`/canvases/<id>`, …) and a Media Library's or Canvas's ACL. `PlatformServerError` extends `@sanity/client`'s `ServerError`, which the client throws for a status of 500 or more, not `ClientError`, and the client does not retry it:
|
|
208
208
|
|
|
209
209
|
```ts
|
|
210
210
|
{
|
|
@@ -222,6 +222,96 @@ A JWT that does not verify still binds, as production clients accept any string;
|
|
|
222
222
|
|
|
223
223
|
That is the body populus sends for an unexpected error: its error handler sends Boom's payload, and Boom hides the error's own message behind a fixed one. The Content Lake keeps answering (queries, documents, mutations, actions, the History API), as does a route a resource does not mount (Express's 404). A token without a session is still refused with its 401 first, as the gateway checks the session before it routes. The call is recorded in `client.calls()` with its error. `"project-api"` is the only component so far, and an outage lasts for the rest of the family's life; create a new client for a healthy platform.
|
|
224
224
|
|
|
225
|
+
#### Organization stores
|
|
226
|
+
|
|
227
|
+
Populus keeps one document store per organization, which a service looks up with `GET /internal/organization-stores?organizationId=<id>`. Give the client its organization, and `request()` answers the lookup as populus does (`src/controllers/internal/organizationStores.ts`):
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
const client = createTestClient({
|
|
231
|
+
useProjectHostname: false,
|
|
232
|
+
organizationId: "oAbc",
|
|
233
|
+
internalTokenKeys: [publicKeyPem],
|
|
234
|
+
token: serviceToken, // an RS256 JWT with tokenType: "service"
|
|
235
|
+
organizationStores: { oAbc: "active" }, // optional: a store that already exists
|
|
236
|
+
});
|
|
237
|
+
await client.request({ uri: "/internal/organization-stores", query: { organizationId: "oAbc" } });
|
|
238
|
+
// { id: "os…", organizationId: "oAbc", status: "active" }
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
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
|
+
| Request | Answer |
|
|
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` | 401, `jwt signature is required` / `invalid signature` / `Session expired` |
|
|
247
|
+
| 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' } } }` |
|
|
248
|
+
| An organization other than `organizationId` | 404, `Organization <id> not found` |
|
|
249
|
+
| While `simulateOutage("project-api")` is in effect | 500 (see [Platform outages](#platform-outages)); no store is created |
|
|
250
|
+
|
|
251
|
+
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
|
+
#### Functions
|
|
254
|
+
|
|
255
|
+
`createTestClient({ functions })` deploys functions as the Functions API (sanity-io/functions) holds them, and `request()` invokes them as `POST /v<apiVersion>/functions/<idOrName>/invoke` does:
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
const client = createTestClient({
|
|
259
|
+
projectId: "p1",
|
|
260
|
+
apiVersion: "2025-07-30", // the Functions API serves vX and dated versions only
|
|
261
|
+
organizationId: "oAbc",
|
|
262
|
+
identities: {
|
|
263
|
+
"t-editor": {
|
|
264
|
+
user: { id: "p-editor" },
|
|
265
|
+
globalUser: { id: "gEditor" },
|
|
266
|
+
grants: [],
|
|
267
|
+
access: { "project:p1": { roles: [], permissions: ["sanity.project.functions.invoke"] } },
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
token: "t-editor",
|
|
271
|
+
functions: [
|
|
272
|
+
{
|
|
273
|
+
id: "fn0123456789",
|
|
274
|
+
name: "advance",
|
|
275
|
+
type: "sanity.function.pubsub",
|
|
276
|
+
blueprintStackId: "ST-0123456789",
|
|
277
|
+
resourceType: "project",
|
|
278
|
+
resourceId: "p1",
|
|
279
|
+
},
|
|
280
|
+
],
|
|
281
|
+
});
|
|
282
|
+
await client.request({
|
|
283
|
+
uri: "/functions/advance/invoke",
|
|
284
|
+
method: "POST",
|
|
285
|
+
query: { blueprintStackId: "ST-0123456789" }, // by name; omit to invoke by id
|
|
286
|
+
headers: { "X-Sanity-Scope-Type": "project", "X-Sanity-Scope-Id": "p1" },
|
|
287
|
+
body: { event: { data: { instanceId: "wf-1" } } },
|
|
288
|
+
});
|
|
289
|
+
// undefined: the API's 202 has an empty body
|
|
290
|
+
client.functionInvocations();
|
|
291
|
+
// [{ functionId: "fn0123456789", name: "advance", blueprintStackId: "ST-0123456789",
|
|
292
|
+
// scopeType: "project", scopeId: "p1", sync: false,
|
|
293
|
+
// event: { data: { instanceId: "wf-1" } }, invokedBy: { userId: "gEditor" } }]
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
`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:
|
|
297
|
+
|
|
298
|
+
| Request | Answer |
|
|
299
|
+
| --- | --- |
|
|
300
|
+
| `apiVersion` `1` (the default) | 400 `BAD_REQUEST`, `Invalid API version in path`, `details.errors: { version: "v1" }` |
|
|
301
|
+
| An internal token (a service-minted JWT has no `guid` claim) | 401 `INVALID_TOKEN`, `Missing required claim: guid` |
|
|
302
|
+
| No `X-Sanity-Scope-Type` or `X-Sanity-Scope-Id` header | 400 `MISSING_SCOPE` |
|
|
303
|
+
| A scope type other than `project` or `organization` | 400 `INVALID_SCOPE_TYPE` |
|
|
304
|
+
| 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: [...] }` |
|
|
305
|
+
| While `simulateOutage("project-api")` is in effect | 500 `ACCESS_ERROR`, `Failed to validate project access` |
|
|
306
|
+
| A body that is not `{ event: { data: {} } }`, a `blueprintStackId` under 10 characters, a `sync` other than `true` / `false` | 400 `INVALID_INPUT`, `Validation error: …` |
|
|
307
|
+
| Without `blueprintStackId`, an id under 10 characters | 400 `BAD_REQUEST`, `Invalid functionId` |
|
|
308
|
+
| With `blueprintStackId`, a name the stack does not hold | 404 `FUNCTION_NOT_FOUND`, `Function "<name>" was not found in Blueprint Stack <stackId>` |
|
|
309
|
+
| An unknown id, or a function outside the scope | 404 `FUNCTION_NOT_FOUND`, `function not found` |
|
|
310
|
+
| A document, media-library-asset, sync-tag-invalidate or schedule function; a queue or durable function with `sync: "true"` | 400 `INVOKE_NOT_SUPPORTED` |
|
|
311
|
+
| An asynchronous payload of 256 KiB or more | 413 `CONTENT_TOO_LARGE` |
|
|
312
|
+
|
|
313
|
+
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.
|
|
314
|
+
|
|
225
315
|
#### Missing datasets
|
|
226
316
|
|
|
227
317
|
`createTestClient({ missingDatasets: ["p1:staged"] })` names datasets the platform does not have, as `"<projectId>:<dataset>"` keys. Every Content Lake request on one (queries, documents, mutations, actions, the History API) throws the `PlatformHttpError` the Content Lake answers for a missing dataset, on every handle of the family:
|
|
@@ -412,6 +502,9 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
|
|
|
412
502
|
| `client.identities()` | Snapshot of the registered token→identity entries |
|
|
413
503
|
| `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)) |
|
|
414
504
|
| `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
|
|
505
|
+
| `client.addFunction(fn)` / `client.removeFunction(id)` | Deploy or remove a function the Functions API invoke route serves (see [Functions](#functions)) |
|
|
506
|
+
| `client.functionInvocations()` | Every invocation the Functions API accepted, in order (see [Functions](#functions)) |
|
|
507
|
+
| `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
|
|
415
508
|
| `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
|
|
416
509
|
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
417
510
|
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|