@sanity-labs/client-fake-for-test 0.25.0 → 0.27.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 +1 -1
- package/dist/index.cjs +81 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +81 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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`. `…/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
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
|
@@ -117,6 +117,25 @@ function invalidAccessType(request, type) {
|
|
|
117
117
|
message: `Invalid resource type ${type}`
|
|
118
118
|
});
|
|
119
119
|
}
|
|
120
|
+
function robotsTypeRefused(request) {
|
|
121
|
+
return new PlatformHttpError({
|
|
122
|
+
...request,
|
|
123
|
+
statusCode: 400,
|
|
124
|
+
statusMessage: "Bad Request",
|
|
125
|
+
body: {
|
|
126
|
+
statusCode: 400,
|
|
127
|
+
error: "Bad Request",
|
|
128
|
+
message: "Validation failed",
|
|
129
|
+
validation: {
|
|
130
|
+
params: {
|
|
131
|
+
source: "params",
|
|
132
|
+
keys: ["resourceType"],
|
|
133
|
+
message: '"resourceType" must be one of [project, organization]'
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
}
|
|
120
139
|
function notFound(name) {
|
|
121
140
|
return (request) => accessApiError({
|
|
122
141
|
request,
|
|
@@ -482,7 +501,7 @@ function createDocumentHistory() {
|
|
|
482
501
|
function historyIds(list) {
|
|
483
502
|
return list.split(",").map((id) => decodeURIComponent(id));
|
|
484
503
|
}
|
|
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 = [
|
|
504
|
+
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
505
|
/^\/users\/me$/,
|
|
487
506
|
/^\/projects\/[^/]+$/,
|
|
488
507
|
/^\/projects\/[^/]+\/users\/[^/]+$/,
|
|
@@ -669,6 +688,17 @@ function serveAccess(args) {
|
|
|
669
688
|
if (record === void 0) throw notFound("User")(request);
|
|
670
689
|
return { value: record };
|
|
671
690
|
});
|
|
691
|
+
const robot = rest.match(ACCESS_ROBOT_PATH);
|
|
692
|
+
if (robot !== null) {
|
|
693
|
+
if (!ROBOT_RESOURCE_TYPES.has(resource.type)) throw robotsTypeRefused(request);
|
|
694
|
+
return gated("served", `sanity.${resource.type}.tokens.read`, () => {
|
|
695
|
+
if (robot[1] === void 0)
|
|
696
|
+
return { value: robotsPage({ resource, registry, query, identities: ctx.identities() }) };
|
|
697
|
+
const robotId = decodeURIComponent(robot[1]), record = robotOn({ resource, robotId, identities: ctx.identities() });
|
|
698
|
+
if (record === void 0) throw notFound("Robot")(request);
|
|
699
|
+
return { value: record };
|
|
700
|
+
});
|
|
701
|
+
}
|
|
672
702
|
const role = rest.match(ACCESS_ROLE_PATH);
|
|
673
703
|
if (role !== null)
|
|
674
704
|
return gated(row.roles, row.rolesPermission, () => {
|
|
@@ -728,11 +758,54 @@ function membershipOn(identity, resource) {
|
|
|
728
758
|
roleNames: roles.map((role) => role.name).toSorted()
|
|
729
759
|
};
|
|
730
760
|
}
|
|
761
|
+
function robotOn(args) {
|
|
762
|
+
const { resource, robotId, identities } = args, identity = identities.find(
|
|
763
|
+
(candidate) => candidate.robot && (candidate.globalUser ?? candidate.user).id === robotId
|
|
764
|
+
), membership = identity === void 0 ? void 0 : membershipOn(identity, resource);
|
|
765
|
+
if (identity === void 0 || membership === void 0 || membership.roleNames.length === 0)
|
|
766
|
+
return;
|
|
767
|
+
const user = identity.globalUser ?? identity.user;
|
|
768
|
+
return robotRecord({ id: robotId, label: user.name, memberships: [membership] });
|
|
769
|
+
}
|
|
770
|
+
const ROBOT_RESOURCE_TYPES = /* @__PURE__ */ new Set(["project", "organization"]), ROBOTS_LIMIT = { default: 100, max: 500 };
|
|
771
|
+
function robotsPage(args) {
|
|
772
|
+
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();
|
|
773
|
+
for (const identity of identities) {
|
|
774
|
+
if (!identity.robot) continue;
|
|
775
|
+
const user = identity.globalUser ?? identity.user, memberships = [resource, ...children].flatMap((target) => {
|
|
776
|
+
const membership = membershipOn(identity, target);
|
|
777
|
+
return membership === void 0 || membership.roleNames.length === 0 ? [] : [membership];
|
|
778
|
+
});
|
|
779
|
+
memberships.length !== 0 && byId.set(user.id, robotRecord({ id: user.id, label: user.name, memberships }));
|
|
780
|
+
}
|
|
781
|
+
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);
|
|
782
|
+
return { data, nextCursor: data.length === limit ? data.at(-1)?.id ?? null : null };
|
|
783
|
+
}
|
|
784
|
+
function robotsLimit(query) {
|
|
785
|
+
const raw = query.get("limit");
|
|
786
|
+
if (raw === null) return ROBOTS_LIMIT.default;
|
|
787
|
+
const limit = Number(raw);
|
|
788
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > ROBOTS_LIMIT.max)
|
|
789
|
+
throw fakeError(
|
|
790
|
+
`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).`
|
|
791
|
+
);
|
|
792
|
+
return limit;
|
|
793
|
+
}
|
|
794
|
+
function robotRecord(args) {
|
|
795
|
+
const { id, label, memberships } = args;
|
|
796
|
+
return {
|
|
797
|
+
id,
|
|
798
|
+
label: label ?? id,
|
|
799
|
+
createdAt: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
800
|
+
memberships,
|
|
801
|
+
networkPolicy: null
|
|
802
|
+
};
|
|
803
|
+
}
|
|
731
804
|
function usersOn(args) {
|
|
732
805
|
const { resource, registry, identities } = args, owned = ACCESS_CAPABILITIES[resource.type].owns?.(registry) ?? [], bySanityUserId = /* @__PURE__ */ new Map();
|
|
733
806
|
for (const identity of identities) {
|
|
734
807
|
const own = membershipOn(identity, resource);
|
|
735
|
-
if (own === void 0) continue;
|
|
808
|
+
if (own === void 0 || identity.robot) continue;
|
|
736
809
|
const user = identity.globalUser ?? identity.user, record = {
|
|
737
810
|
sanityUserId: user.id,
|
|
738
811
|
profile: {
|
|
@@ -923,8 +996,10 @@ function makeRequestImpl(ctx) {
|
|
|
923
996
|
const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
|
|
924
997
|
return async (opts) => {
|
|
925
998
|
const accessControl = getAccess(), path = opts.uri ?? opts.url;
|
|
926
|
-
if (path === "/users/me")
|
|
927
|
-
|
|
999
|
+
if (path === "/users/me") {
|
|
1000
|
+
const user = useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
|
|
1001
|
+
return accessControl.robot ? { ...user, provider: "sanity-token" } : user;
|
|
1002
|
+
}
|
|
928
1003
|
if (path !== void 0 && path === accessControl.aclPath)
|
|
929
1004
|
return refuseAclRequest(platform, requestFor(opts)), accessControl.grants;
|
|
930
1005
|
const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
|
|
@@ -944,7 +1019,7 @@ function makeRequestImpl(ctx) {
|
|
|
944
1019
|
const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path, requestFor(opts));
|
|
945
1020
|
if (served !== void 0) return served.value;
|
|
946
1021
|
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.`
|
|
1022
|
+
`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
1023
|
);
|
|
949
1024
|
};
|
|
950
1025
|
}
|
|
@@ -2301,6 +2376,7 @@ function makeHandle(handleArgs) {
|
|
|
2301
2376
|
// Per-project records apply only where the resource lives in a project.
|
|
2302
2377
|
currentUser: capabilitiesOf(target.type).identity === "project" ? projectUserOf(identity, projectId) : identity.user,
|
|
2303
2378
|
...identity.globalUser !== void 0 ? { globalUser: identity.globalUser } : {},
|
|
2379
|
+
...identity.robot ? { robot: !0 } : {},
|
|
2304
2380
|
grants: identity.grants,
|
|
2305
2381
|
...identity.access !== void 0 ? { access: identity.access } : {}
|
|
2306
2382
|
};
|