@sanity-labs/client-fake-for-test 0.15.0 → 0.16.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/dist/index.d.cts CHANGED
@@ -1004,12 +1004,25 @@ export declare interface TestClient {
1004
1004
  ) => Promise<ActionResult>;
1005
1005
  /** Helpers mirroring `@sanity/client`'s `client.releases.*` surface. */
1006
1006
  releases: ReleasesHandle;
1007
- /** Helper for `sanity.action.document.version.create`. */
1008
- createVersion: (params: {
1009
- releaseId: string;
1010
- publishedId: string;
1011
- document: DocumentBody;
1012
- }) => Promise<ActionResult>;
1007
+ /**
1008
+ * Helper for `sanity.action.document.version.create`: writes `document`, or,
1009
+ * given `baseId` (as `@sanity/client` takes it), copies that document into
1010
+ * `versions.<releaseId>.<publishedId>`.
1011
+ */
1012
+ createVersion: (
1013
+ params:
1014
+ | {
1015
+ releaseId: string;
1016
+ publishedId: string;
1017
+ document: DocumentBody;
1018
+ }
1019
+ | {
1020
+ releaseId: string;
1021
+ publishedId: string;
1022
+ baseId: string;
1023
+ ifBaseRevisionId?: string;
1024
+ },
1025
+ ) => Promise<ActionResult>;
1013
1026
  /** Helper for `sanity.action.document.version.unpublish`. */
1014
1027
  unpublishVersion: (params: {
1015
1028
  releaseId: string;
@@ -1401,6 +1414,14 @@ export declare type VersionAction =
1401
1414
  document: DocumentBody;
1402
1415
  releaseId?: string;
1403
1416
  }
1417
+ | {
1418
+ /** Copy the document at `baseId` into `versionId`, as `@sanity/client` sends `createVersion({ baseId })`. */
1419
+ actionType: "sanity.action.document.version.create";
1420
+ publishedId: string;
1421
+ baseId: string;
1422
+ versionId: string;
1423
+ ifBaseRevisionId?: string;
1424
+ }
1404
1425
  | {
1405
1426
  actionType: "sanity.action.document.version.replace";
1406
1427
  document: SanityDocumentLike;
package/dist/index.d.ts CHANGED
@@ -1004,12 +1004,25 @@ export declare interface TestClient {
1004
1004
  ) => Promise<ActionResult>;
1005
1005
  /** Helpers mirroring `@sanity/client`'s `client.releases.*` surface. */
1006
1006
  releases: ReleasesHandle;
1007
- /** Helper for `sanity.action.document.version.create`. */
1008
- createVersion: (params: {
1009
- releaseId: string;
1010
- publishedId: string;
1011
- document: DocumentBody;
1012
- }) => Promise<ActionResult>;
1007
+ /**
1008
+ * Helper for `sanity.action.document.version.create`: writes `document`, or,
1009
+ * given `baseId` (as `@sanity/client` takes it), copies that document into
1010
+ * `versions.<releaseId>.<publishedId>`.
1011
+ */
1012
+ createVersion: (
1013
+ params:
1014
+ | {
1015
+ releaseId: string;
1016
+ publishedId: string;
1017
+ document: DocumentBody;
1018
+ }
1019
+ | {
1020
+ releaseId: string;
1021
+ publishedId: string;
1022
+ baseId: string;
1023
+ ifBaseRevisionId?: string;
1024
+ },
1025
+ ) => Promise<ActionResult>;
1013
1026
  /** Helper for `sanity.action.document.version.unpublish`. */
1014
1027
  unpublishVersion: (params: {
1015
1028
  releaseId: string;
@@ -1401,6 +1414,14 @@ export declare type VersionAction =
1401
1414
  document: DocumentBody;
1402
1415
  releaseId?: string;
1403
1416
  }
1417
+ | {
1418
+ /** Copy the document at `baseId` into `versionId`, as `@sanity/client` sends `createVersion({ baseId })`. */
1419
+ actionType: "sanity.action.document.version.create";
1420
+ publishedId: string;
1421
+ baseId: string;
1422
+ versionId: string;
1423
+ ifBaseRevisionId?: string;
1424
+ }
1404
1425
  | {
1405
1426
  actionType: "sanity.action.document.version.replace";
1406
1427
  document: SanityDocumentLike;
package/dist/index.js CHANGED
@@ -282,6 +282,8 @@ const ACCESS_CAPABILITIES = {
282
282
  },
283
283
  project: {
284
284
  roles: "served",
285
+ // Also gates `GET /projects/<id>/roles`; the stock user roles all hold it on staging.
286
+ rolesPermission: "sanity.project.roles.read",
285
287
  users: "served",
286
288
  // Single-user reads are served only where the fake checks members read (the
287
289
  // organization); elsewhere they refuse rather than answer unchecked.
@@ -331,7 +333,7 @@ function dataUrl(args) {
331
333
  const base = `/${operation}/${dataset}`;
332
334
  return `/data${path !== void 0 ? `${base}/${path}` : base}`.replace(/\/($|\?)/, "$1");
333
335
  }
334
- const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/;
336
+ const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/;
335
337
  function page(data) {
336
338
  return { data, nextCursor: null };
337
339
  }
@@ -345,6 +347,11 @@ async function servePlatformRequest(ctx, url) {
345
347
  const organizationId = decodeURIComponent(myAttributes[1]);
346
348
  return serveMyAttributes({ ctx, request, organizationId, query });
347
349
  }
350
+ const projectRoles = path.match(PROJECT_ROLES_PATH);
351
+ if (projectRoles !== null) {
352
+ const projectId = decodeURIComponent(projectRoles[1]);
353
+ return serveProjectRoles({ ctx, request, projectId });
354
+ }
348
355
  const access = path.match(ACCESS_PATH);
349
356
  if (access !== null) {
350
357
  const [, type, id, rest2] = access;
@@ -412,6 +419,35 @@ async function readHistory(args) {
412
419
  }
413
420
  };
414
421
  }
422
+ function serveGated(args) {
423
+ const { capability, permission, held, request, serve } = args;
424
+ return serveCapability(capability, request, () => {
425
+ if (permission !== void 0 && !held.includes(permission)) throw noPermission(request);
426
+ return serve();
427
+ });
428
+ }
429
+ function serveProjectRoles(args) {
430
+ const { ctx, request, projectId } = args, row = ACCESS_CAPABILITIES.project;
431
+ return serveGated({
432
+ capability: row.roles,
433
+ permission: row.rolesPermission,
434
+ held: ctx.actorAccess()?.[accessKey("project", projectId)]?.permissions ?? [],
435
+ request,
436
+ serve: () => ({
437
+ value: rolesOn({
438
+ resource: { type: "project", id: projectId },
439
+ identities: ctx.identities()
440
+ }).map((role) => ({
441
+ name: role.name,
442
+ title: role.title,
443
+ ...role.description !== void 0 ? { description: role.description } : {},
444
+ projectId,
445
+ appliesToUsers: role.appliesToUsers,
446
+ appliesToRobots: role.appliesToRobots
447
+ }))
448
+ })
449
+ });
450
+ }
415
451
  function serveAccess(args) {
416
452
  const { ctx, request, type, id, rest, query } = args, row = accessCapabilitiesOf(type);
417
453
  if (row === void 0) throw invalidAccessType(request, type);
@@ -427,11 +463,7 @@ function serveAccess(args) {
427
463
  }
428
464
  if (row.unknown !== void 0 && !row.unknown.holds(registry, id))
429
465
  throw row.unknown.refusal(request);
430
- const gated = (capability, permission, serve) => serveCapability(capability, request, () => {
431
- if (permission !== void 0 && !permissions.includes(permission))
432
- throw noPermission(request);
433
- return serve();
434
- }), users = (capability, serve) => gated(capability, row.usersPermission, serve), roles = () => rolesOn({ resource, identities: ctx.identities() }), user = rest.match(ACCESS_USER_PATH);
466
+ const gated = (capability, permission, serve) => serveGated({ capability, permission, held: permissions, request, serve }), users = (capability, serve) => gated(capability, row.usersPermission, serve), roles = () => rolesOn({ resource, identities: ctx.identities() }), user = rest.match(ACCESS_USER_PATH);
435
467
  if (user !== null)
436
468
  return users(row.user, () => {
437
469
  const sanityUserId = decodeURIComponent(user[1]), record = usersOn({ resource, registry, identities: ctx.identities() }).find(
@@ -713,7 +745,7 @@ function makeRequestImpl(ctx) {
713
745
  const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
714
746
  if (served !== void 0) return served.value;
715
747
  throw fakeError(
716
- `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>", 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.`
748
+ `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", 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.`
717
749
  );
718
750
  };
719
751
  }
@@ -1259,6 +1291,7 @@ async function applyAction(store, action, hooks) {
1259
1291
  return store.remove(release._id), { transactionId: cryptoRandomKey() };
1260
1292
  }
1261
1293
  case "sanity.action.document.version.create": {
1294
+ if ("baseId" in action) return createVersionFromBase(store, action);
1262
1295
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
1263
1296
  if (releaseId === void 0)
1264
1297
  throw fakeError(
@@ -1330,10 +1363,33 @@ function requireDraftOf(action) {
1330
1363
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1331
1364
  );
1332
1365
  }
1366
+ function createVersionFromBase(store, action) {
1367
+ const { releaseId, publishedId } = parseVersionId(action.versionId);
1368
+ if (publishedId !== action.publishedId)
1369
+ throw fakeError(
1370
+ `version.create: versionId "${action.versionId}" is not a version of publishedId "${action.publishedId}" (expected "${versionDocId(releaseId, action.publishedId)}").`
1371
+ );
1372
+ requireActive(getRelease(store, releaseId));
1373
+ const base = store.get(action.baseId);
1374
+ if (base === void 0)
1375
+ throw fakeError(
1376
+ `Cannot create version "${action.versionId}": base document "${action.baseId}" not found. version.create with \`baseId\` copies an existing document; pass \`document\` instead when there is nothing to copy.`
1377
+ );
1378
+ requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
1379
+ const existing = store.get(action.versionId), promoted = promote({
1380
+ ...base,
1381
+ _id: action.versionId,
1382
+ _createdAt: existing?._createdAt ?? nowIso()
1383
+ });
1384
+ return store.put(promoted), { transactionId: cryptoRandomKey() };
1385
+ }
1333
1386
  function requireRevisionMatch(documentId, actualRev, expectedRev) {
1334
1387
  if (!(expectedRev === void 0 || actualRev === expectedRev))
1335
- throw fakeError(
1336
- `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1388
+ throw Object.assign(
1389
+ fakeError(
1390
+ `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1391
+ ),
1392
+ { statusCode: 409 }
1337
1393
  );
1338
1394
  }
1339
1395
  async function applyActions(store, actions, hooks) {
@@ -1361,6 +1417,10 @@ async function applyActions(store, actions, hooks) {
1361
1417
  break;
1362
1418
  }
1363
1419
  case "sanity.action.document.version.create": {
1420
+ if ("baseId" in a) {
1421
+ remember(a.versionId);
1422
+ break;
1423
+ }
1364
1424
  const releaseId = a.releaseId ?? (typeof a.document._id == "string" ? parseVersionId(a.document._id).releaseId : void 0);
1365
1425
  releaseId !== void 0 && remember(versionDocId(releaseId, a.publishedId));
1366
1426
  break;
@@ -2124,12 +2184,25 @@ function makeHandle(handleArgs) {
2124
2184
  unarchive: ({ releaseId }) => runAction({ actionType: "sanity.action.release.unarchive", releaseId }),
2125
2185
  delete: ({ releaseId }) => runAction({ actionType: "sanity.action.release.delete", releaseId })
2126
2186
  },
2127
- createVersion: ({ releaseId, publishedId, document }) => runAction({
2128
- actionType: "sanity.action.document.version.create",
2129
- releaseId,
2130
- publishedId,
2131
- document
2132
- }),
2187
+ createVersion: (params) => {
2188
+ const { releaseId, publishedId, document, baseId, ifBaseRevisionId } = params;
2189
+ if (document)
2190
+ return runAction({
2191
+ actionType: "sanity.action.document.version.create",
2192
+ releaseId,
2193
+ publishedId,
2194
+ document
2195
+ });
2196
+ if (baseId === void 0)
2197
+ throw fakeError("createVersion() requires `baseId` when no `document` is provided.");
2198
+ return runAction({
2199
+ actionType: "sanity.action.document.version.create",
2200
+ publishedId,
2201
+ baseId,
2202
+ versionId: `versions.${releaseId}.${publishedId}`,
2203
+ ...ifBaseRevisionId !== void 0 ? { ifBaseRevisionId } : {}
2204
+ });
2205
+ },
2133
2206
  unpublishVersion: ({ releaseId, publishedId }) => runAction({
2134
2207
  actionType: "sanity.action.document.version.unpublish",
2135
2208
  versionId: `versions.${releaseId}.${publishedId}`,