@sanity-labs/client-fake-for-test 0.26.0 → 0.28.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 CHANGED
@@ -222,6 +222,24 @@ 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
+ #### Missing datasets
226
+
227
+ `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:
228
+
229
+ ```ts
230
+ {
231
+ statusCode: 404,
232
+ message: 'Dataset not found - Dataset "staged" not found for project ID "p1"',
233
+ response: {
234
+ statusCode: 404,
235
+ body: { error: "Dataset not found", message: 'Dataset "staged" not found for project ID "p1"', statusCode: 404 },
236
+ // url, method, headers, statusMessage
237
+ },
238
+ }
239
+ ```
240
+
241
+ A token without a session is refused with its 401 first, as the gateway checks the session before it routes. The order is the session first, then the missing dataset: a listed dataset answers its 404 before an internal token's or a malformed grant's refusal. A dataset that is not listed answers as before: one the fake has never seen is an empty dataset. A key may not also be seeded, at construction or later through `client.seed()` / `client.add()` / `client.store()`'s `seed` / `add` / `put`.
242
+
225
243
  #### Project-scoped tokens: membership and refusals
226
244
 
227
245
  A robot token belongs to the project that issued it. Model one with `projectId` on the identity:
@@ -341,7 +359,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
341
359
  | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
342
360
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
343
361
 
344
- - **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`. 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" }`.
362
+ - **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" }`.
345
363
  - **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.
346
364
  - **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.
347
365
  - **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.
package/dist/index.cjs CHANGED
@@ -98,6 +98,18 @@ function projectApiDown(request) {
98
98
  }
99
99
  });
100
100
  }
101
+ function datasetNotFound(request, projectId, dataset) {
102
+ return new PlatformHttpError({
103
+ ...request,
104
+ statusCode: 404,
105
+ statusMessage: "Not Found",
106
+ body: {
107
+ error: "Dataset not found",
108
+ message: `Dataset "${dataset}" not found for project ID "${projectId}"`,
109
+ statusCode: 404
110
+ }
111
+ });
112
+ }
101
113
  const mediaLibraryReadRequired = (request) => accessApiError({
102
114
  request,
103
115
  statusCode: 401,
@@ -117,6 +129,25 @@ function invalidAccessType(request, type) {
117
129
  message: `Invalid resource type ${type}`
118
130
  });
119
131
  }
132
+ function robotsTypeRefused(request) {
133
+ return new PlatformHttpError({
134
+ ...request,
135
+ statusCode: 400,
136
+ statusMessage: "Bad Request",
137
+ body: {
138
+ statusCode: 400,
139
+ error: "Bad Request",
140
+ message: "Validation failed",
141
+ validation: {
142
+ params: {
143
+ source: "params",
144
+ keys: ["resourceType"],
145
+ message: '"resourceType" must be one of [project, organization]'
146
+ }
147
+ }
148
+ }
149
+ });
150
+ }
120
151
  function notFound(name) {
121
152
  return (request) => accessApiError({
122
153
  request,
@@ -482,7 +513,7 @@ function createDocumentHistory() {
482
513
  function historyIds(list) {
483
514
  return list.split(",").map((id) => decodeURIComponent(id));
484
515
  }
485
- const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, ACCESS_ROBOT_PATH = /^\/robots\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, ACCESS_API_SINCE = "2025-07-11", PROJECT_API_PATHS = [
516
+ const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, ACCESS_ROBOT_PATH = /^\/robots(?:\/([^/]+))?$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, ACCESS_API_SINCE = "2025-07-11", PROJECT_API_PATHS = [
486
517
  /^\/users\/me$/,
487
518
  /^\/projects\/[^/]+$/,
488
519
  /^\/projects\/[^/]+\/users\/[^/]+$/,
@@ -670,12 +701,16 @@ function serveAccess(args) {
670
701
  return { value: record };
671
702
  });
672
703
  const robot = rest.match(ACCESS_ROBOT_PATH);
673
- if (robot !== null)
704
+ if (robot !== null) {
705
+ if (!ROBOT_RESOURCE_TYPES.has(resource.type)) throw robotsTypeRefused(request);
674
706
  return gated("served", `sanity.${resource.type}.tokens.read`, () => {
707
+ if (robot[1] === void 0)
708
+ return { value: robotsPage({ resource, registry, query, identities: ctx.identities() }) };
675
709
  const robotId = decodeURIComponent(robot[1]), record = robotOn({ resource, robotId, identities: ctx.identities() });
676
710
  if (record === void 0) throw notFound("Robot")(request);
677
711
  return { value: record };
678
712
  });
713
+ }
679
714
  const role = rest.match(ACCESS_ROLE_PATH);
680
715
  if (role !== null)
681
716
  return gated(row.roles, row.rolesPermission, () => {
@@ -742,11 +777,39 @@ function robotOn(args) {
742
777
  if (identity === void 0 || membership === void 0 || membership.roleNames.length === 0)
743
778
  return;
744
779
  const user = identity.globalUser ?? identity.user;
780
+ return robotRecord({ id: robotId, label: user.name, memberships: [membership] });
781
+ }
782
+ const ROBOT_RESOURCE_TYPES = /* @__PURE__ */ new Set(["project", "organization"]), ROBOTS_LIMIT = { default: 100, max: 500 };
783
+ function robotsPage(args) {
784
+ const { resource, registry, query, identities } = args, limit = robotsLimit(query), cursor = query.get("nextCursor"), children = query.get("includeChildren") === "true" ? ACCESS_CAPABILITIES[resource.type].owns?.(registry) ?? [] : [], byId = /* @__PURE__ */ new Map();
785
+ for (const identity of identities) {
786
+ if (!identity.robot) continue;
787
+ const user = identity.globalUser ?? identity.user, memberships = [resource, ...children].flatMap((target) => {
788
+ const membership = membershipOn(identity, target);
789
+ return membership === void 0 || membership.roleNames.length === 0 ? [] : [membership];
790
+ });
791
+ memberships.length !== 0 && byId.set(user.id, robotRecord({ id: user.id, label: user.name, memberships }));
792
+ }
793
+ const data = [...byId.values()].toSorted((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).filter((robot) => cursor === null || robot.id > cursor).slice(0, limit);
794
+ return { data, nextCursor: data.length === limit ? data.at(-1)?.id ?? null : null };
795
+ }
796
+ function robotsLimit(query) {
797
+ const raw = query.get("limit");
798
+ if (raw === null) return ROBOTS_LIMIT.default;
799
+ const limit = Number(raw);
800
+ if (!Number.isInteger(limit) || limit < 1 || limit > ROBOTS_LIMIT.max)
801
+ throw fakeError(
802
+ `request(): robots got limit=${JSON.stringify(raw)}; the fake serves integer limits from 1 to ${ROBOTS_LIMIT.max} only (the platform's 400 for others is not simulated).`
803
+ );
804
+ return limit;
805
+ }
806
+ function robotRecord(args) {
807
+ const { id, label, memberships } = args;
745
808
  return {
746
- id: robotId,
747
- label: user.name ?? robotId,
809
+ id,
810
+ label: label ?? id,
748
811
  createdAt: (/* @__PURE__ */ new Date(0)).toISOString(),
749
- memberships: [membership],
812
+ memberships,
750
813
  networkPolicy: null
751
814
  };
752
815
  }
@@ -968,7 +1031,7 @@ function makeRequestImpl(ctx) {
968
1031
  const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
969
1032
  if (served !== void 0) return served.value;
970
1033
  throw fakeError(
971
- `request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", "/projects/<projectId>/features", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | robots/<id> | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
1034
+ `request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", "/projects/<projectId>/features", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | robots[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
972
1035
  );
973
1036
  };
974
1037
  }
@@ -2200,6 +2263,11 @@ function ensureEntry(registry, resource) {
2200
2263
  exists: !1
2201
2264
  }, registry.set(key, entry)), entry;
2202
2265
  }
2266
+ function seededMissingDataset(caller, key) {
2267
+ return fakeError(
2268
+ `${caller}: dataset "${key}" is both seeded and in \`missingDatasets\`; a dataset the platform does not have holds no documents.`
2269
+ );
2270
+ }
2203
2271
  function seedEntry(registry, resource, documents) {
2204
2272
  const entry = ensureEntry(registry, resource);
2205
2273
  entry.store.seed(documents), entry.exists = !0;
@@ -2218,6 +2286,7 @@ function createTestClient(options = {}) {
2218
2286
  internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
2219
2287
  internalTokens: /* @__PURE__ */ new Map(),
2220
2288
  outages: /* @__PURE__ */ new Set(),
2289
+ missingDatasets: new Set(options.missingDatasets ?? []),
2221
2290
  writeChain: Promise.resolve()
2222
2291
  }, registry = backend.registry;
2223
2292
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
@@ -2232,6 +2301,11 @@ function createTestClient(options = {}) {
2232
2301
  if (options.resources)
2233
2302
  for (const [key, docs] of Object.entries(options.resources))
2234
2303
  seedEntry(registry, parseResourceKey(key), docs);
2304
+ for (const key of backend.missingDatasets) {
2305
+ const { projectId, dataset } = parseDatasetKey(key);
2306
+ if (registry.get(registryKey(datasetResource(projectId, dataset)))?.exists)
2307
+ throw seededMissingDataset("createTestClient()", key);
2308
+ }
2235
2309
  return makeHandle({
2236
2310
  backend,
2237
2311
  projectId: defaultProjectId,
@@ -2355,7 +2429,11 @@ function makeHandle(handleArgs) {
2355
2429
  throw projectApiDown(sent);
2356
2430
  return request(opts);
2357
2431
  }, admitToLake = (request) => {
2358
- refuseSession(request), refuseInternalToken(request);
2432
+ if (refuseSession(request), missingKey !== void 0) {
2433
+ const parts = datasetParts(target.id);
2434
+ throw datasetNotFound(request, parts.projectId, parts.dataset);
2435
+ }
2436
+ refuseInternalToken(request);
2359
2437
  const access = activeAccess();
2360
2438
  if (access === void 0) return;
2361
2439
  const refusal = refusedToken(request, access.grants);
@@ -2418,16 +2496,22 @@ function makeHandle(handleArgs) {
2418
2496
  ...accessControl.access !== void 0 ? { access: accessControl.access } : {}
2419
2497
  }
2420
2498
  ] : []
2421
- ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, publicStore = {
2499
+ ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
2500
+ if (target.type !== "dataset") return;
2501
+ const parts = datasetParts(target.id), key = `${parts.projectId}:${parts.dataset}`;
2502
+ return backend.missingDatasets.has(key) ? key : void 0;
2503
+ })(), refuseSeedingMissing = (caller) => {
2504
+ if (missingKey !== void 0) throw seededMissingDataset(caller, missingKey);
2505
+ }, publicStore = {
2422
2506
  ...store,
2423
2507
  seed: (documents) => {
2424
- store.seed(documents), targetEntry.exists = !0;
2508
+ refuseSeedingMissing("seed()"), store.seed(documents), targetEntry.exists = !0;
2425
2509
  },
2426
2510
  add: (documents) => {
2427
- store.add(documents), targetEntry.exists = !0;
2511
+ refuseSeedingMissing("add()"), store.add(documents), targetEntry.exists = !0;
2428
2512
  },
2429
2513
  put: (doc) => {
2430
- store.put(doc), targetEntry.exists = !0;
2514
+ refuseSeedingMissing("put()"), store.put(doc), targetEntry.exists = !0;
2431
2515
  }
2432
2516
  }, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
2433
2517
  const access = activeAccess();