@sanity-labs/client-fake-for-test 0.25.0 → 0.26.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
@@ -341,7 +341,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
341
341
  | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
342
342
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
343
343
 
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. `…/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" }`.
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" }`.
345
345
  - **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
346
  - **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
347
  - **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
@@ -482,7 +482,7 @@ function createDocumentHistory() {
482
482
  function historyIds(list) {
483
483
  return list.split(",").map((id) => decodeURIComponent(id));
484
484
  }
485
- const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, 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 = [
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 = [
486
486
  /^\/users\/me$/,
487
487
  /^\/projects\/[^/]+$/,
488
488
  /^\/projects\/[^/]+\/users\/[^/]+$/,
@@ -669,6 +669,13 @@ function serveAccess(args) {
669
669
  if (record === void 0) throw notFound("User")(request);
670
670
  return { value: record };
671
671
  });
672
+ const robot = rest.match(ACCESS_ROBOT_PATH);
673
+ if (robot !== null)
674
+ return gated("served", `sanity.${resource.type}.tokens.read`, () => {
675
+ const robotId = decodeURIComponent(robot[1]), record = robotOn({ resource, robotId, identities: ctx.identities() });
676
+ if (record === void 0) throw notFound("Robot")(request);
677
+ return { value: record };
678
+ });
672
679
  const role = rest.match(ACCESS_ROLE_PATH);
673
680
  if (role !== null)
674
681
  return gated(row.roles, row.rolesPermission, () => {
@@ -728,11 +735,26 @@ function membershipOn(identity, resource) {
728
735
  roleNames: roles.map((role) => role.name).toSorted()
729
736
  };
730
737
  }
738
+ function robotOn(args) {
739
+ const { resource, robotId, identities } = args, identity = identities.find(
740
+ (candidate) => candidate.robot && (candidate.globalUser ?? candidate.user).id === robotId
741
+ ), membership = identity === void 0 ? void 0 : membershipOn(identity, resource);
742
+ if (identity === void 0 || membership === void 0 || membership.roleNames.length === 0)
743
+ return;
744
+ const user = identity.globalUser ?? identity.user;
745
+ return {
746
+ id: robotId,
747
+ label: user.name ?? robotId,
748
+ createdAt: (/* @__PURE__ */ new Date(0)).toISOString(),
749
+ memberships: [membership],
750
+ networkPolicy: null
751
+ };
752
+ }
731
753
  function usersOn(args) {
732
754
  const { resource, registry, identities } = args, owned = ACCESS_CAPABILITIES[resource.type].owns?.(registry) ?? [], bySanityUserId = /* @__PURE__ */ new Map();
733
755
  for (const identity of identities) {
734
756
  const own = membershipOn(identity, resource);
735
- if (own === void 0) continue;
757
+ if (own === void 0 || identity.robot) continue;
736
758
  const user = identity.globalUser ?? identity.user, record = {
737
759
  sanityUserId: user.id,
738
760
  profile: {
@@ -923,8 +945,10 @@ function makeRequestImpl(ctx) {
923
945
  const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
924
946
  return async (opts) => {
925
947
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
926
- if (path === "/users/me")
927
- return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
948
+ if (path === "/users/me") {
949
+ const user = useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
950
+ return accessControl.robot ? { ...user, provider: "sanity-token" } : user;
951
+ }
928
952
  if (path !== void 0 && path === accessControl.aclPath)
929
953
  return refuseAclRequest(platform, requestFor(opts)), accessControl.grants;
930
954
  const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
@@ -944,7 +968,7 @@ function makeRequestImpl(ctx) {
944
968
  const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
945
969
  if (served !== void 0) return served.value;
946
970
  throw fakeError(
947
- `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>] | 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.`
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.`
948
972
  );
949
973
  };
950
974
  }
@@ -2301,6 +2325,7 @@ function makeHandle(handleArgs) {
2301
2325
  // Per-project records apply only where the resource lives in a project.
2302
2326
  currentUser: capabilitiesOf(target.type).identity === "project" ? projectUserOf(identity, projectId) : identity.user,
2303
2327
  ...identity.globalUser !== void 0 ? { globalUser: identity.globalUser } : {},
2328
+ ...identity.robot ? { robot: !0 } : {},
2304
2329
  grants: identity.grants,
2305
2330
  ...identity.access !== void 0 ? { access: identity.access } : {}
2306
2331
  };