@sanity-labs/client-fake-for-test 0.14.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/README.md CHANGED
@@ -76,12 +76,12 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
76
76
  | Patch | `patch(id)` chain → `.commit()` | Ops: `.set`, `.setIfMissing`, `.unset`, `.inc`, `.dec`, `.insert(position, anchor, items)`, `.ifRevisionId` |
77
77
  | Transaction | `transaction()` chain → `.commit()` | Mutations: `.create`, `.createOrReplace`, `.createIfNotExists`, `.delete`, `.patch(id, recipe)`. Atomic — any throw rolls back the whole batch. Default result is a `MultipleMutationResult` (`{ transactionId, documentIds, results }`) |
78
78
  | Actions | `action(action \| action[])` | Content Lake release / version actions, applied atomically |
79
- | Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish |
79
+ | Releases | `releases.*`, `createVersion`, `unpublishVersion` | Content Releases lifecycle — create / edit / schedule / publish / archive / delete, plus version create / replace / discard / unpublish. `createVersion({ baseId, publishedId, releaseId })` (or `version.create` with `baseId` + `versionId`) copies the base document, `_type` included, into the version; a missing base fails. A failed revision precondition (`ifDraftRevisionId`, `ifPublishedRevisionId`, `ifBaseRevisionId`) carries `statusCode: 409`, as the Actions API answers |
80
80
  | Config | `config()` | Returns `{ projectId, dataset, resource?, perspective, token?, useProjectHostname }` |
81
81
  | Config | `getDataUrl(operation, path?)` | The same URL `@sanity/client` builds: `<resource base>/<operation>/<path>` on a `resource` handle, `/data/<operation>/<dataset>/<path>` otherwise |
82
82
  | Config | `withConfig({ projectId?, dataset?, resource?, perspective?, accessControl?, token?, useProjectHostname? })` | 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 |
83
83
  | 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 |
84
- | 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`), 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. |
84
+ | 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), 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. |
85
85
 
86
86
  #### Mutation return shapes
87
87
 
@@ -199,11 +199,16 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
199
199
  | Access API `…/user-permissions/me`, `…/me/check` | ✅ | ✅ | ✅ | ✅ |
200
200
  | Access API `…/users` | ✅ | ✅ | 403 | 403 |
201
201
  | Access API `…/users/<sanityUserId>` (served on `organization`, below) | 403 | 403 | 403 | 403 |
202
- | Access API `…/roles` | ✅ | 403 | 403 | 403 |
202
+ | Access API `…/roles`, `…/roles/<roleName>` | ✅ with `sanity.project.roles.read`, else 403 | ✅ with `sanity.media-library.roles.read`, else 403 | 403 | 403 |
203
+ | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
203
204
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
204
205
 
205
206
  - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. 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 project member with its project roles. 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 the registry does not hold (never seeded, written or addressed) answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. `…/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" }`.
207
+ - **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.
208
+ - **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.
209
+ - **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.
206
210
  - **Organization.** `/access/organization/<organizationId>/users` and `…/users/<sanityUserId>` (one row, or 404 `User not found` for a non-member) serve the members of the client's `organizationId`: identities with roles in their `"organization:<id>"` entry. Each row lists the organization membership, then the member's roles on every resource the client holds (its libraries, canvases, dashboards and projects), as the platform's organization row does. Like the platform, it needs `sanity.organization.members.read` in the actor's `"organization:<id>"` `permissions` (the built-in `member` role grants it), else 403. Another organization id answers 404 `Organization not found`; `…/roles` answers 403.
211
+ - **User attributes.** `GET /organizations/<organizationId>/users/me/attributes` answers the caller's own attributes there: `{ sanityUserId, organizationId, attributes: [{ type, key, values: { saml?, sanity? }, activeSource, activeValue }] }`, ordered by key. Seed them as `attributes: [{ key, type, values }]` on the identity's `"organization:<id>"` entry; the Sanity value takes precedence over the SAML one for `activeSource` and `activeValue`, as on the platform. No permission is needed. `limit` (default 50) and `cursor` (the last key of the previous page) page the list. A member with no seeded attributes gets `attributes: []`; a caller without roles in the organization gets 404 `User not found`, and another organization id 404 `Organization not found`.
207
212
  - **History.** Every committed write since the client was created is recorded per resource, authored by the acting identity; seeded documents can be read at their seeded `_rev`. A handle answers for its own resource, and hides documents its grants cannot read, as reads do (a transaction that also touched such a document is served without it). Events model `createLiveDocument` / `updateLiveDocument` only.
208
213
  - **Org lookup.** `createTestClient({ organizationId })` names the organization every resource of the client belongs to.
209
214
  - **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
package/dist/index.cjs CHANGED
@@ -284,6 +284,8 @@ const ACCESS_CAPABILITIES = {
284
284
  },
285
285
  project: {
286
286
  roles: "served",
287
+ // Also gates `GET /projects/<id>/roles`; the stock user roles all hold it on staging.
288
+ rolesPermission: "sanity.project.roles.read",
287
289
  users: "served",
288
290
  // Single-user reads are served only where the fake checks members read (the
289
291
  // organization); elsewhere they refuse rather than answer unchecked.
@@ -292,8 +294,9 @@ const ACCESS_CAPABILITIES = {
292
294
  memberRoles: ({ identity, id }) => (identity.usersByProject?.[id] ?? identity.user).roles ?? []
293
295
  },
294
296
  "media-library": {
295
- // Unproven on staging (no token held roles read): refused like a missing permission.
296
- roles: noPermission,
297
+ // Staging refuses it only because no probe token held roles read.
298
+ roles: "served",
299
+ rolesPermission: "sanity.media-library.roles.read",
297
300
  users: "served",
298
301
  // Unproven on staging (only the listing was probed); refused as on `project`.
299
302
  user: noPermission,
@@ -332,7 +335,7 @@ function dataUrl(args) {
332
335
  const base = `/${operation}/${dataset}`;
333
336
  return `/data${path !== void 0 ? `${base}/${path}` : base}`.replace(/\/($|\?)/, "$1");
334
337
  }
335
- const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/;
338
+ 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\/([^/]+)(\/.*)$/;
336
339
  function page(data) {
337
340
  return { data, nextCursor: null };
338
341
  }
@@ -341,7 +344,17 @@ function usersPage(data) {
341
344
  }
342
345
  const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
343
346
  async function servePlatformRequest(ctx, url) {
344
- const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), query = new URLSearchParams(queryStart === -1 ? "" : url.slice(queryStart + 1)), request = { method: "GET", path }, access = path.match(ACCESS_PATH);
347
+ const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), query = new URLSearchParams(queryStart === -1 ? "" : url.slice(queryStart + 1)), request = { method: "GET", path }, myAttributes = path.match(MY_ATTRIBUTES_PATH);
348
+ if (myAttributes !== null) {
349
+ const organizationId = decodeURIComponent(myAttributes[1]);
350
+ return serveMyAttributes({ ctx, request, organizationId, query });
351
+ }
352
+ const projectRoles = path.match(PROJECT_ROLES_PATH);
353
+ if (projectRoles !== null) {
354
+ const projectId = decodeURIComponent(projectRoles[1]);
355
+ return serveProjectRoles({ ctx, request, projectId });
356
+ }
357
+ const access = path.match(ACCESS_PATH);
345
358
  if (access !== null) {
346
359
  const [, type, id, rest2] = access;
347
360
  return serveAccess({ ctx, request, type, id: decodeURIComponent(id), rest: rest2 ?? "", query });
@@ -408,6 +421,35 @@ async function readHistory(args) {
408
421
  }
409
422
  };
410
423
  }
424
+ function serveGated(args) {
425
+ const { capability, permission, held, request, serve } = args;
426
+ return serveCapability(capability, request, () => {
427
+ if (permission !== void 0 && !held.includes(permission)) throw noPermission(request);
428
+ return serve();
429
+ });
430
+ }
431
+ function serveProjectRoles(args) {
432
+ const { ctx, request, projectId } = args, row = ACCESS_CAPABILITIES.project;
433
+ return serveGated({
434
+ capability: row.roles,
435
+ permission: row.rolesPermission,
436
+ held: ctx.actorAccess()?.[accessKey("project", projectId)]?.permissions ?? [],
437
+ request,
438
+ serve: () => ({
439
+ value: rolesOn({
440
+ resource: { type: "project", id: projectId },
441
+ identities: ctx.identities()
442
+ }).map((role) => ({
443
+ name: role.name,
444
+ title: role.title,
445
+ ...role.description !== void 0 ? { description: role.description } : {},
446
+ projectId,
447
+ appliesToUsers: role.appliesToUsers,
448
+ appliesToRobots: role.appliesToRobots
449
+ }))
450
+ })
451
+ });
452
+ }
411
453
  function serveAccess(args) {
412
454
  const { ctx, request, type, id, rest, query } = args, row = accessCapabilitiesOf(type);
413
455
  if (row === void 0) throw invalidAccessType(request, type);
@@ -423,11 +465,7 @@ function serveAccess(args) {
423
465
  }
424
466
  if (row.unknown !== void 0 && !row.unknown.holds(registry, id))
425
467
  throw row.unknown.refusal(request);
426
- const users = (capability, serve) => serveCapability(capability, request, () => {
427
- if (row.usersPermission !== void 0 && !permissions.includes(row.usersPermission))
428
- throw noPermission(request);
429
- return serve();
430
- }), user = rest.match(ACCESS_USER_PATH);
468
+ 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);
431
469
  if (user !== null)
432
470
  return users(row.user, () => {
433
471
  const sanityUserId = decodeURIComponent(user[1]), record = usersOn({ resource, registry, identities: ctx.identities() }).find(
@@ -436,11 +474,16 @@ function serveAccess(args) {
436
474
  if (record === void 0) throw notFound("User")(request);
437
475
  return { value: record };
438
476
  });
477
+ const role = rest.match(ACCESS_ROLE_PATH);
478
+ if (role !== null)
479
+ return gated(row.roles, row.rolesPermission, () => {
480
+ const name = decodeURIComponent(role[1]), record = roles().find((candidate) => candidate.name === name);
481
+ if (record === void 0) throw notFound("Role")(request);
482
+ return { value: record };
483
+ });
439
484
  switch (rest) {
440
485
  case "/roles":
441
- return serveCapability(row.roles, request, () => ({
442
- value: page(rolesOn({ resource, identities: ctx.identities() }))
443
- }));
486
+ return gated(row.roles, row.rolesPermission, () => ({ value: page(roles()) }));
444
487
  case "/users":
445
488
  return users(row.users, () => ({
446
489
  value: usersPage(usersOn({ resource, registry, identities: ctx.identities() }))
@@ -463,6 +506,7 @@ function serveAccess(args) {
463
506
  return;
464
507
  }
465
508
  }
509
+ const UNMODELLED_ROLE = { appliesToUsers: !0, appliesToRobots: !0 };
466
510
  function rolesOn(args) {
467
511
  const { resource } = args, byName = /* @__PURE__ */ new Map();
468
512
  for (const identity of args.identities) {
@@ -470,8 +514,12 @@ function rolesOn(args) {
470
514
  for (const role of roles ?? [])
471
515
  byName.set(role.name, {
472
516
  name: role.name,
473
- ...role.title !== void 0 ? { title: role.title } : {},
474
- ...role.description !== void 0 ? { description: role.description } : {}
517
+ title: role.title ?? role.name,
518
+ ...role.description !== void 0 ? { description: role.description } : {},
519
+ resourceType: resource.type,
520
+ resourceId: resource.id,
521
+ ...UNMODELLED_ROLE,
522
+ permissions: []
475
523
  });
476
524
  }
477
525
  return [...byName.values()].toSorted((a, b) => a.name.localeCompare(b.name));
@@ -509,12 +557,40 @@ function usersOn(args) {
509
557
  }, existing = bySanityUserId.get(record.sanityUserId);
510
558
  if (existing !== void 0 && JSON.stringify(existing) !== JSON.stringify(record))
511
559
  throw fakeError(
512
- `request(): two registered identities resolve to user "${record.sanityUserId}" on ${resource.type} "${resource.id}" with different records. Fix the identity registrations so duplicate ids carry identical records.`
560
+ `request(): two identities (registered, or the handle's inline accessControl) resolve to user "${record.sanityUserId}" on ${resource.type} "${resource.id}" with different records. Fix the identities so duplicate ids carry identical records.`
513
561
  );
514
562
  bySanityUserId.set(record.sanityUserId, record);
515
563
  }
516
564
  return [...bySanityUserId.values()];
517
565
  }
566
+ const DEFAULT_ATTRIBUTES_LIMIT = 50;
567
+ function serveMyAttributes(args) {
568
+ const { ctx, request, organizationId, query } = args, organization = ACCESS_CAPABILITIES.organization, registry = { organizationId: ctx.organizationId, resources: ctx.resources };
569
+ if (organization.unknown !== void 0 && !organization.unknown.holds(registry, organizationId))
570
+ throw organization.unknown.refusal(request);
571
+ const entry = ctx.actorAccess()?.[accessKey("organization", organizationId)];
572
+ if (entry?.roles === void 0) throw notFound("User")(request);
573
+ const limit = attributesLimit(query), cursor = query.get("cursor"), attributes = (entry.attributes ?? []).map(attributeRecord).toSorted((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0).filter((attribute) => cursor === null || attribute.key > cursor).slice(0, limit);
574
+ return { value: { sanityUserId: ctx.actorUser().id, organizationId, attributes } };
575
+ }
576
+ function attributesLimit(query) {
577
+ const raw = query.get("limit");
578
+ if (raw === null) return DEFAULT_ATTRIBUTES_LIMIT;
579
+ const limit = Number(raw);
580
+ if (!Number.isInteger(limit) || limit < 1)
581
+ throw fakeError(
582
+ `request(): users/me/attributes got limit=${JSON.stringify(raw)}; the fake serves positive integer limits only (the platform's answer to others is not simulated).`
583
+ );
584
+ return limit;
585
+ }
586
+ function attributeRecord(attribute) {
587
+ const { key, type, values } = attribute, activeSource = values.sanity !== void 0 ? "sanity" : "saml", activeValue = values[activeSource];
588
+ if (activeValue === void 0)
589
+ throw fakeError(
590
+ `request(): user attribute "${key}" is seeded with no value; give it a \`saml\` or \`sanity\` value.`
591
+ );
592
+ return { type, key, values: { ...values }, activeSource, activeValue };
593
+ }
518
594
  class WriteAccessDeniedError extends Error {
519
595
  documentId;
520
596
  permission;
@@ -586,7 +662,7 @@ function consistentProjectRecords(args) {
586
662
  const existing = byId.get(record.id);
587
663
  if (existing !== void 0 && JSON.stringify(existing) !== JSON.stringify(record))
588
664
  throw fakeError(
589
- `request(): two registered identities resolve to project user "${record.id}" in project "${args.projectId}" with different records. The project records cannot be served unambiguously \u2014 fix the identity registrations so duplicate ids carry identical records.`
665
+ `request(): two identities (registered, or the handle's inline accessControl) resolve to project user "${record.id}" in project "${args.projectId}" with different records. The project records cannot be served unambiguously \u2014 fix the identities so duplicate ids carry identical records.`
590
666
  );
591
667
  byId.set(record.id, record);
592
668
  }
@@ -671,7 +747,7 @@ function makeRequestImpl(ctx) {
671
747
  const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
672
748
  if (served !== void 0) return served.value;
673
749
  throw fakeError(
674
- `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 | users[/<id>] | user-permissions/me[/check]"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
750
+ `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.`
675
751
  );
676
752
  };
677
753
  }
@@ -1217,6 +1293,7 @@ async function applyAction(store, action, hooks) {
1217
1293
  return store.remove(release._id), { transactionId: cryptoRandomKey() };
1218
1294
  }
1219
1295
  case "sanity.action.document.version.create": {
1296
+ if ("baseId" in action) return createVersionFromBase(store, action);
1220
1297
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
1221
1298
  if (releaseId === void 0)
1222
1299
  throw fakeError(
@@ -1288,10 +1365,33 @@ function requireDraftOf(action) {
1288
1365
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1289
1366
  );
1290
1367
  }
1368
+ function createVersionFromBase(store, action) {
1369
+ const { releaseId, publishedId } = parseVersionId(action.versionId);
1370
+ if (publishedId !== action.publishedId)
1371
+ throw fakeError(
1372
+ `version.create: versionId "${action.versionId}" is not a version of publishedId "${action.publishedId}" (expected "${versionDocId(releaseId, action.publishedId)}").`
1373
+ );
1374
+ requireActive(getRelease(store, releaseId));
1375
+ const base = store.get(action.baseId);
1376
+ if (base === void 0)
1377
+ throw fakeError(
1378
+ `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.`
1379
+ );
1380
+ requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
1381
+ const existing = store.get(action.versionId), promoted = promote({
1382
+ ...base,
1383
+ _id: action.versionId,
1384
+ _createdAt: existing?._createdAt ?? nowIso()
1385
+ });
1386
+ return store.put(promoted), { transactionId: cryptoRandomKey() };
1387
+ }
1291
1388
  function requireRevisionMatch(documentId, actualRev, expectedRev) {
1292
1389
  if (!(expectedRev === void 0 || actualRev === expectedRev))
1293
- throw fakeError(
1294
- `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1390
+ throw Object.assign(
1391
+ fakeError(
1392
+ `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1393
+ ),
1394
+ { statusCode: 409 }
1295
1395
  );
1296
1396
  }
1297
1397
  async function applyActions(store, actions, hooks) {
@@ -1319,6 +1419,10 @@ async function applyActions(store, actions, hooks) {
1319
1419
  break;
1320
1420
  }
1321
1421
  case "sanity.action.document.version.create": {
1422
+ if ("baseId" in a) {
1423
+ remember(a.versionId);
1424
+ break;
1425
+ }
1322
1426
  const releaseId = a.releaseId ?? (typeof a.document._id == "string" ? parseVersionId(a.document._id).releaseId : void 0);
1323
1427
  releaseId !== void 0 && remember(versionDocId(releaseId, a.publishedId));
1324
1428
  break;
@@ -1734,7 +1838,17 @@ function makeHandle(handleArgs) {
1734
1838
  if (access === void 0)
1735
1839
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
1736
1840
  return access;
1737
- }, capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), { store, history } = ensureEntry(registry, target), concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
1841
+ }, members = () => [
1842
+ ...backend.identities.values(),
1843
+ ...token === void 0 && accessControl !== void 0 ? [
1844
+ {
1845
+ user: accessControl.currentUser,
1846
+ ...accessControl.globalUser !== void 0 ? { globalUser: accessControl.globalUser } : {},
1847
+ grants: accessControl.grants,
1848
+ ...accessControl.access !== void 0 ? { access: accessControl.access } : {}
1849
+ }
1850
+ ] : []
1851
+ ], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), { store, history } = ensureEntry(registry, target), concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
1738
1852
  const access = activeAccess();
1739
1853
  if (access !== void 0)
1740
1854
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
@@ -2072,12 +2186,25 @@ function makeHandle(handleArgs) {
2072
2186
  unarchive: ({ releaseId }) => runAction({ actionType: "sanity.action.release.unarchive", releaseId }),
2073
2187
  delete: ({ releaseId }) => runAction({ actionType: "sanity.action.release.delete", releaseId })
2074
2188
  },
2075
- createVersion: ({ releaseId, publishedId, document }) => runAction({
2076
- actionType: "sanity.action.document.version.create",
2077
- releaseId,
2078
- publishedId,
2079
- document
2080
- }),
2189
+ createVersion: (params) => {
2190
+ const { releaseId, publishedId, document, baseId, ifBaseRevisionId } = params;
2191
+ if (document)
2192
+ return runAction({
2193
+ actionType: "sanity.action.document.version.create",
2194
+ releaseId,
2195
+ publishedId,
2196
+ document
2197
+ });
2198
+ if (baseId === void 0)
2199
+ throw fakeError("createVersion() requires `baseId` when no `document` is provided.");
2200
+ return runAction({
2201
+ actionType: "sanity.action.document.version.create",
2202
+ publishedId,
2203
+ baseId,
2204
+ versionId: `versions.${releaseId}.${publishedId}`,
2205
+ ...ifBaseRevisionId !== void 0 ? { ifBaseRevisionId } : {}
2206
+ });
2207
+ },
2081
2208
  unpublishVersion: ({ releaseId, publishedId }) => runAction({
2082
2209
  actionType: "sanity.action.document.version.unpublish",
2083
2210
  versionId: `versions.${releaseId}.${publishedId}`,
@@ -2090,7 +2217,7 @@ function makeHandle(handleArgs) {
2090
2217
  // client to the global API host.
2091
2218
  useProjectHostname: useProjectHostname && resource === void 0,
2092
2219
  organizationId: backend.organizationId,
2093
- listIdentities: () => [...backend.identities.values()],
2220
+ listIdentities: members,
2094
2221
  platform: {
2095
2222
  projectId,
2096
2223
  organizationId: backend.organizationId,
@@ -2100,8 +2227,12 @@ function makeHandle(handleArgs) {
2100
2227
  history,
2101
2228
  canRead
2102
2229
  } : void 0,
2230
+ actorUser: () => {
2231
+ const access = requireActiveAccess();
2232
+ return access.globalUser ?? access.currentUser;
2233
+ },
2103
2234
  actorAccess: () => requireActiveAccess().access,
2104
- identities: () => [...backend.identities.values()],
2235
+ identities: members,
2105
2236
  resources: () => [...registry.values()].map((entry) => entry.resource)
2106
2237
  }
2107
2238
  })