@sanity-labs/client-fake-for-test 0.15.0 → 0.17.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.js CHANGED
@@ -3,67 +3,6 @@ const ERR_PREFIX = "[client-fake-for-test]";
3
3
  function fakeError(message) {
4
4
  return new Error(`${ERR_PREFIX} ${message}`);
5
5
  }
6
- function createDocumentHistory() {
7
- const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
8
- return {
9
- commit: ({ transactionId, author, before, after }) => {
10
- const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
11
- for (const id of ids) {
12
- const previous = before.get(id), next = afterById.get(id);
13
- previous !== next && (previous !== void 0 && keep(previous), next !== void 0 && keep(next), next === void 0 && previous !== void 0 ? deleted.set(id, structuredClone(previous)) : deleted.delete(id), effects.push({
14
- documentId: id,
15
- after: next === void 0 ? void 0 : structuredClone(next),
16
- existed: previous !== void 0
17
- }));
18
- }
19
- effects.length !== 0 && transactions.push({
20
- id: transactionId,
21
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
22
- author,
23
- effects
24
- });
25
- },
26
- documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
27
- const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
28
- return image === void 0 ? [] : [structuredClone(image)];
29
- }),
30
- lastImage: (id) => deleted.get(id),
31
- documentIds: () => [
32
- ...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
33
- ],
34
- transactions: (ids, visible) => transactions.filter((txn) => txn.effects.some((effect) => ids.includes(effect.documentId))).map((txn) => ({ ...txn, effects: txn.effects.filter((e) => visible(e.documentId)) })).map((txn) => ({
35
- id: txn.id,
36
- timestamp: txn.timestamp,
37
- ...txn.author !== void 0 ? { author: txn.author } : {},
38
- mutations: txn.effects.map((effect) => {
39
- if (effect.after === void 0) return { delete: { id: effect.documentId } };
40
- const after = structuredClone(effect.after);
41
- return effect.existed ? { createOrReplace: after } : { create: after };
42
- }),
43
- documentIDs: txn.effects.map((effect) => effect.documentId)
44
- })),
45
- events: (ids) => Object.fromEntries(
46
- ids.map((id) => [
47
- id,
48
- transactions.flatMap(
49
- (txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
50
- (effect) => ({
51
- type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
52
- id: txn.id,
53
- documentId: id,
54
- revisionId: effect.after._rev,
55
- timestamp: txn.timestamp,
56
- ...txn.author !== void 0 ? { author: txn.author } : {}
57
- })
58
- )
59
- ).toReversed()
60
- ])
61
- )
62
- };
63
- }
64
- function historyIds(list) {
65
- return list.split(",").map((id) => decodeURIComponent(id));
66
- }
67
6
  class PlatformHttpError extends Error {
68
7
  statusCode;
69
8
  response;
@@ -282,6 +221,8 @@ const ACCESS_CAPABILITIES = {
282
221
  },
283
222
  project: {
284
223
  roles: "served",
224
+ // Also gates `GET /projects/<id>/roles`; the stock user roles all hold it on staging.
225
+ rolesPermission: "sanity.project.roles.read",
285
226
  users: "served",
286
227
  // Single-user reads are served only where the fake checks members read (the
287
228
  // organization); elsewhere they refuse rather than answer unchecked.
@@ -331,7 +272,148 @@ function dataUrl(args) {
331
272
  const base = `/${operation}/${dataset}`;
332
273
  return `/data${path !== void 0 ? `${base}/${path}` : base}`.replace(/\/($|\?)/, "$1");
333
274
  }
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\/([^/]+)(\/.*)$/;
275
+ const MAX_PATH_BYTES = 128, PERMISSIONS = /* @__PURE__ */ new Set(["read", "update", "create", "manage", "history", "editHistory"]), MISPLACED_WILDCARD = /* @__PURE__ */ new Map([
276
+ ["*", "wildcard must be last component"],
277
+ ["**", "descendant wildcard must be last component"]
278
+ ]), ELEMENT_LINE = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
279
+ function validElement(element) {
280
+ return element.split(`
281
+ `).some((line) => ELEMENT_LINE.test(line));
282
+ }
283
+ const GO_ESCAPES = {
284
+ "\x07": "\\a",
285
+ "\b": "\\b",
286
+ "\f": "\\f",
287
+ "\n": "\\n",
288
+ "\r": "\\r",
289
+ " ": "\\t",
290
+ "\v": "\\v",
291
+ '"': '\\"',
292
+ "\\": "\\\\"
293
+ }, GO_PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S} ]$/u;
294
+ function quoted(value) {
295
+ let out = '"';
296
+ for (const char of value) {
297
+ const escape = GO_ESCAPES[char];
298
+ if (escape !== void 0) {
299
+ out += escape;
300
+ continue;
301
+ }
302
+ if (GO_PRINTABLE.test(char)) {
303
+ out += char;
304
+ continue;
305
+ }
306
+ const code = char.codePointAt(0);
307
+ out += code < 128 ? `\\x${code.toString(16).padStart(2, "0")}` : code <= 65535 ? `\\u${code.toString(16).padStart(4, "0")}` : `\\U${code.toString(16).padStart(8, "0")}`;
308
+ }
309
+ return `${out}"`;
310
+ }
311
+ function pathError(path) {
312
+ if (path === "") return "path must contain at least one element";
313
+ if (path.startsWith(".")) return 'path cannot begin with delimiter "."';
314
+ const elements = path.split(".");
315
+ if (elements.includes("")) return "path contains empty element";
316
+ if (new TextEncoder().encode(path).length > MAX_PATH_BYTES)
317
+ return `path exceeds maximum length of ${MAX_PATH_BYTES}`;
318
+ const last = elements.length - 1;
319
+ for (const [index, element] of elements.entries()) {
320
+ const misplaced = MISPLACED_WILDCARD.get(element);
321
+ if (misplaced !== void 0) {
322
+ if (index < last) return misplaced;
323
+ } else if (!validElement(element))
324
+ return `invalid element ${quoted(element)}`;
325
+ }
326
+ }
327
+ function pathIncludes(path, id) {
328
+ const pattern = path.split("."), elements = id.split(".");
329
+ for (const [index, element] of pattern.entries()) {
330
+ if (index >= elements.length) return !1;
331
+ if (element === "**") return !0;
332
+ if (element === "*" ? elements[index] === "**" : element !== elements[index]) return !1;
333
+ }
334
+ return pattern.length === elements.length;
335
+ }
336
+ function grantsError(grants) {
337
+ for (const grant of grants) {
338
+ if (!("path" in grant)) continue;
339
+ const error = pathError(grant.path);
340
+ if (error !== void 0) return error;
341
+ const invalid = grant.permissions.find((permission) => !PERMISSIONS.has(permission));
342
+ if (invalid !== void 0) return `invalid permission ${quoted(invalid)}`;
343
+ }
344
+ }
345
+ function refusedToken(request, grants) {
346
+ const description = grantsError(grants);
347
+ if (description !== void 0)
348
+ return new PlatformHttpError({
349
+ ...request,
350
+ statusCode: 400,
351
+ statusMessage: "Bad Request",
352
+ body: { error: { description, type: "httpBadRequest" } }
353
+ });
354
+ }
355
+ function createDocumentHistory() {
356
+ const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
357
+ return {
358
+ commit: ({ transactionId, author, before, after }) => {
359
+ const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
360
+ for (const id of ids) {
361
+ const previous = before.get(id), next = afterById.get(id);
362
+ previous !== next && (previous !== void 0 && keep(previous), next !== void 0 && keep(next), next === void 0 && previous !== void 0 ? deleted.set(id, structuredClone(previous)) : deleted.delete(id), effects.push({
363
+ documentId: id,
364
+ after: next === void 0 ? void 0 : structuredClone(next),
365
+ existed: previous !== void 0
366
+ }));
367
+ }
368
+ effects.length !== 0 && transactions.push({
369
+ id: transactionId,
370
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
371
+ author,
372
+ effects
373
+ });
374
+ },
375
+ documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
376
+ const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
377
+ return image === void 0 ? [] : [structuredClone(image)];
378
+ }),
379
+ lastImage: (id) => deleted.get(id),
380
+ documentIds: () => [
381
+ ...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
382
+ ],
383
+ transactions: (ids, visible) => transactions.filter((txn) => txn.effects.some((effect) => ids.includes(effect.documentId))).map((txn) => ({ ...txn, effects: txn.effects.filter((e) => visible(e.documentId)) })).map((txn) => ({
384
+ id: txn.id,
385
+ timestamp: txn.timestamp,
386
+ ...txn.author !== void 0 ? { author: txn.author } : {},
387
+ mutations: txn.effects.map((effect) => {
388
+ if (effect.after === void 0) return { delete: { id: effect.documentId } };
389
+ const after = structuredClone(effect.after);
390
+ return effect.existed ? { createOrReplace: after } : { create: after };
391
+ }),
392
+ documentIDs: txn.effects.map((effect) => effect.documentId)
393
+ })),
394
+ events: (ids) => Object.fromEntries(
395
+ ids.map((id) => [
396
+ id,
397
+ transactions.flatMap(
398
+ (txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
399
+ (effect) => ({
400
+ type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
401
+ id: txn.id,
402
+ documentId: id,
403
+ revisionId: effect.after._rev,
404
+ timestamp: txn.timestamp,
405
+ ...txn.author !== void 0 ? { author: txn.author } : {}
406
+ })
407
+ )
408
+ ).toReversed()
409
+ ])
410
+ )
411
+ };
412
+ }
413
+ function historyIds(list) {
414
+ return list.split(",").map((id) => decodeURIComponent(id));
415
+ }
416
+ 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\/([^/]+)(\/.*)$/;
335
417
  function page(data) {
336
418
  return { data, nextCursor: null };
337
419
  }
@@ -345,6 +427,16 @@ async function servePlatformRequest(ctx, url) {
345
427
  const organizationId = decodeURIComponent(myAttributes[1]);
346
428
  return serveMyAttributes({ ctx, request, organizationId, query });
347
429
  }
430
+ const projectRoles = path.match(PROJECT_ROLES_PATH);
431
+ if (projectRoles !== null) {
432
+ const projectId = decodeURIComponent(projectRoles[1]);
433
+ return serveProjectRoles({ ctx, request, projectId });
434
+ }
435
+ const projectFeatures = path.match(PROJECT_FEATURES_PATH);
436
+ if (projectFeatures !== null) {
437
+ const projectId = decodeURIComponent(projectFeatures[1]);
438
+ return { value: featuresOf(ctx, projectId) };
439
+ }
348
440
  const access = path.match(ACCESS_PATH);
349
441
  if (access !== null) {
350
442
  const [, type, id, rest2] = access;
@@ -367,6 +459,10 @@ async function servePlatformRequest(ctx, url) {
367
459
  if (rest.startsWith("/history/"))
368
460
  return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
369
461
  }
462
+ function featuresOf(ctx, projectId) {
463
+ const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
464
+ return [...new Set(features)].toSorted();
465
+ }
370
466
  function serveLookup(ctx, resource) {
371
467
  if (ctx.organizationId === void 0)
372
468
  throw fakeError(
@@ -378,7 +474,8 @@ function serveHistory(args) {
378
474
  const { ctx, request, resource, rest, query } = args;
379
475
  return serveCapability(capabilitiesOf(resource.type).history, request, () => {
380
476
  const own = ctx.own(resource);
381
- return own === void 0 ? void 0 : readHistory({ own, request, rest, query });
477
+ if (own !== void 0)
478
+ return own.admitToLake(request), readHistory({ own, request, rest, query });
382
479
  });
383
480
  }
384
481
  async function readHistory(args) {
@@ -412,6 +509,35 @@ async function readHistory(args) {
412
509
  }
413
510
  };
414
511
  }
512
+ function serveGated(args) {
513
+ const { capability, permission, held, request, serve } = args;
514
+ return serveCapability(capability, request, () => {
515
+ if (permission !== void 0 && !held.includes(permission)) throw noPermission(request);
516
+ return serve();
517
+ });
518
+ }
519
+ function serveProjectRoles(args) {
520
+ const { ctx, request, projectId } = args, row = ACCESS_CAPABILITIES.project;
521
+ return serveGated({
522
+ capability: row.roles,
523
+ permission: row.rolesPermission,
524
+ held: ctx.actorAccess()?.[accessKey("project", projectId)]?.permissions ?? [],
525
+ request,
526
+ serve: () => ({
527
+ value: rolesOn({
528
+ resource: { type: "project", id: projectId },
529
+ identities: ctx.identities()
530
+ }).map((role) => ({
531
+ name: role.name,
532
+ title: role.title,
533
+ ...role.description !== void 0 ? { description: role.description } : {},
534
+ projectId,
535
+ appliesToUsers: role.appliesToUsers,
536
+ appliesToRobots: role.appliesToRobots
537
+ }))
538
+ })
539
+ });
540
+ }
415
541
  function serveAccess(args) {
416
542
  const { ctx, request, type, id, rest, query } = args, row = accessCapabilitiesOf(type);
417
543
  if (row === void 0) throw invalidAccessType(request, type);
@@ -427,11 +553,7 @@ function serveAccess(args) {
427
553
  }
428
554
  if (row.unknown !== void 0 && !row.unknown.holds(registry, id))
429
555
  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);
556
+ 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
557
  if (user !== null)
436
558
  return users(row.user, () => {
437
559
  const sanityUserId = decodeURIComponent(user[1]), record = usersOn({ resource, registry, identities: ctx.identities() }).find(
@@ -580,15 +702,15 @@ async function matchesFilter(args) {
580
702
  })).get();
581
703
  return Array.isArray(data) && data.length === 1;
582
704
  }
705
+ async function grantMatches(args) {
706
+ const { document, grant, userId } = args;
707
+ return "path" in grant ? typeof document._id == "string" && pathIncludes(grant.path, document._id) : matchesFilter({ document, filter: grant.filter, userId });
708
+ }
583
709
  async function evaluateWriteAccess(args) {
584
710
  const { document, grants, permission, userId } = args;
585
711
  let matching = 0;
586
712
  for (const grant of grants)
587
- if (await matchesFilter({
588
- document,
589
- filter: grant.filter,
590
- userId
591
- }) && (matching++, grant.permissions.includes(permission)))
713
+ if (await grantMatches({ document, grant, userId }) && (matching++, grant.permissions.includes(permission)))
592
714
  return { allowed: !0, matchingGrants: matching };
593
715
  return { allowed: !1, matchingGrants: matching };
594
716
  }
@@ -713,7 +835,7 @@ function makeRequestImpl(ctx) {
713
835
  const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
714
836
  if (served !== void 0) return served.value;
715
837
  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.`
838
+ `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.`
717
839
  );
718
840
  };
719
841
  }
@@ -1259,6 +1381,7 @@ async function applyAction(store, action, hooks) {
1259
1381
  return store.remove(release._id), { transactionId: cryptoRandomKey() };
1260
1382
  }
1261
1383
  case "sanity.action.document.version.create": {
1384
+ if ("baseId" in action) return createVersionFromBase(store, action);
1262
1385
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
1263
1386
  if (releaseId === void 0)
1264
1387
  throw fakeError(
@@ -1330,10 +1453,33 @@ function requireDraftOf(action) {
1330
1453
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1331
1454
  );
1332
1455
  }
1456
+ function createVersionFromBase(store, action) {
1457
+ const { releaseId, publishedId } = parseVersionId(action.versionId);
1458
+ if (publishedId !== action.publishedId)
1459
+ throw fakeError(
1460
+ `version.create: versionId "${action.versionId}" is not a version of publishedId "${action.publishedId}" (expected "${versionDocId(releaseId, action.publishedId)}").`
1461
+ );
1462
+ requireActive(getRelease(store, releaseId));
1463
+ const base = store.get(action.baseId);
1464
+ if (base === void 0)
1465
+ throw fakeError(
1466
+ `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.`
1467
+ );
1468
+ requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
1469
+ const existing = store.get(action.versionId), promoted = promote({
1470
+ ...base,
1471
+ _id: action.versionId,
1472
+ _createdAt: existing?._createdAt ?? nowIso()
1473
+ });
1474
+ return store.put(promoted), { transactionId: cryptoRandomKey() };
1475
+ }
1333
1476
  function requireRevisionMatch(documentId, actualRev, expectedRev) {
1334
1477
  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}"`}.`
1478
+ throw Object.assign(
1479
+ fakeError(
1480
+ `Revision precondition failed for "${documentId}": expected _rev "${expectedRev}" but the document is at ${actualRev === void 0 ? "no revision (missing)" : `"${actualRev}"`}.`
1481
+ ),
1482
+ { statusCode: 409 }
1337
1483
  );
1338
1484
  }
1339
1485
  async function applyActions(store, actions, hooks) {
@@ -1361,6 +1507,10 @@ async function applyActions(store, actions, hooks) {
1361
1507
  break;
1362
1508
  }
1363
1509
  case "sanity.action.document.version.create": {
1510
+ if ("baseId" in a) {
1511
+ remember(a.versionId);
1512
+ break;
1513
+ }
1364
1514
  const releaseId = a.releaseId ?? (typeof a.document._id == "string" ? parseVersionId(a.document._id).releaseId : void 0);
1365
1515
  releaseId !== void 0 && remember(versionDocId(releaseId, a.publishedId));
1366
1516
  break;
@@ -1483,7 +1633,7 @@ const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues",
1483
1633
  },
1484
1634
  request: {
1485
1635
  what: "generic HTTP request hook \u2014 only wired up when the handle has an acting identity",
1486
- workaround: "Create the client with `accessControl`, or bind a registered token (`identities` + `token` / `withConfig({ token })`), to enable request() (it serves /users/me, the ACL path, /projects/<projectId>, /projects/<projectId>/users/<ids>, the History API, resource lookup and the Access API). Or register a stub."
1636
+ workaround: "Create the client with `accessControl`, or bind a registered token (`identities` + `token` / `withConfig({ token })`), to enable request() (it serves /users/me, the ACL path, /projects/<projectId>, /projects/<projectId>/users/<ids>, /projects/<projectId>/features, the History API, resource lookup and the Access API). Or register a stub."
1487
1637
  },
1488
1638
  dryRun: {
1489
1639
  what: "not a method \u2014 did you mean the `{ dryRun }` mutation option?",
@@ -1667,6 +1817,7 @@ function createTestClient(options = {}) {
1667
1817
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
1668
1818
  registry: /* @__PURE__ */ new Map(),
1669
1819
  organizationId: options.organizationId,
1820
+ projectFeatures: options.projectFeatures ?? {},
1670
1821
  log: [],
1671
1822
  stubs: /* @__PURE__ */ new Map(),
1672
1823
  calls: [],
@@ -1776,7 +1927,12 @@ function makeHandle(handleArgs) {
1776
1927
  if (access === void 0)
1777
1928
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
1778
1929
  return access;
1779
- }, members = () => [
1930
+ }, admitToLake = (request) => {
1931
+ const access = activeAccess();
1932
+ if (access === void 0) return;
1933
+ const refusal = refusedToken(request, access.grants);
1934
+ if (refusal !== void 0) throw refusal;
1935
+ }, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
1780
1936
  ...backend.identities.values(),
1781
1937
  ...token === void 0 && accessControl !== void 0 ? [
1782
1938
  {
@@ -1792,8 +1948,8 @@ function makeHandle(handleArgs) {
1792
1948
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
1793
1949
  };
1794
1950
  let beforeWrite;
1795
- const write = (run) => serializeWrite(backend, async () => {
1796
- beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
1951
+ const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
1952
+ admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
1797
1953
  try {
1798
1954
  return await run();
1799
1955
  } finally {
@@ -1955,14 +2111,14 @@ function makeHandle(handleArgs) {
1955
2111
  path: `${capabilities.dataBase(target.id)}/actions`
1956
2112
  };
1957
2113
  if (capabilities.actions !== "served") throw capabilities.actions(request);
1958
- for (const action of Array.isArray(actions) ? actions : [actions]) {
1959
- const refused = capabilities.refusedActions[action.actionType];
1960
- if (refused !== void 0) throw refused(request);
1961
- }
1962
2114
  return write(async () => {
2115
+ for (const action of Array.isArray(actions) ? actions : [actions]) {
2116
+ const refused = capabilities.refusedActions[action.actionType];
2117
+ if (refused !== void 0) throw refused(request);
2118
+ }
1963
2119
  const result = await applyActions(store, actions, { gate, guard: guardGate });
1964
2120
  return commitHistory(result.transactionId), result;
1965
- });
2121
+ }, request);
1966
2122
  }, accessVisibleDocs = async () => {
1967
2123
  const all = store.all();
1968
2124
  if (activeAccess() === void 0) return all;
@@ -1975,6 +2131,7 @@ function makeHandle(handleArgs) {
1975
2131
  return applyPerspective(accessible, override ?? perspective);
1976
2132
  }, client = {
1977
2133
  fetch: async (query, params, opts) => {
2134
+ admitToLake(lakeRequest("GET", "query"));
1978
2135
  const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
1979
2136
  dataset: await visibleDocs(opts?.perspective),
1980
2137
  ...params !== void 0 ? { params } : {}
@@ -1986,6 +2143,7 @@ function makeHandle(handleArgs) {
1986
2143
  return result;
1987
2144
  },
1988
2145
  getDocument: async (id, opts) => {
2146
+ admitToLake(lakeRequest("GET", "doc", id));
1989
2147
  const effective = opts?.perspective ?? perspective;
1990
2148
  if (effective === "raw") {
1991
2149
  const doc = store.get(id);
@@ -1995,6 +2153,7 @@ function makeHandle(handleArgs) {
1995
2153
  return resolveDocument(view, id, effective) ?? void 0;
1996
2154
  },
1997
2155
  getDocuments: async (ids, opts) => {
2156
+ admitToLake(lakeRequest("GET", "doc", ids.join(",")));
1998
2157
  const effective = opts?.perspective ?? perspective;
1999
2158
  if (effective === "raw") {
2000
2159
  const result = [];
@@ -2108,10 +2267,16 @@ function makeHandle(handleArgs) {
2108
2267
  };
2109
2268
  },
2110
2269
  edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
2111
- get: async ({ releaseId }) => store.get(`_.releases.${releaseId}`),
2270
+ // `@sanity/client` reads a release by id and its documents by query.
2271
+ get: async ({ releaseId }) => {
2272
+ admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
2273
+ const doc = store.get(`_.releases.${releaseId}`);
2274
+ return doc !== void 0 && await canRead(doc) ? doc : void 0;
2275
+ },
2112
2276
  fetchDocuments: async ({ releaseId }) => {
2277
+ admitToLake(lakeRequest("GET", "query"));
2113
2278
  const prefix = `versions.${releaseId}.`;
2114
- return store.all().filter((d) => d._id.startsWith(prefix));
2279
+ return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
2115
2280
  },
2116
2281
  schedule: ({ releaseId, publishAt }) => runAction({
2117
2282
  actionType: "sanity.action.release.schedule",
@@ -2124,12 +2289,25 @@ function makeHandle(handleArgs) {
2124
2289
  unarchive: ({ releaseId }) => runAction({ actionType: "sanity.action.release.unarchive", releaseId }),
2125
2290
  delete: ({ releaseId }) => runAction({ actionType: "sanity.action.release.delete", releaseId })
2126
2291
  },
2127
- createVersion: ({ releaseId, publishedId, document }) => runAction({
2128
- actionType: "sanity.action.document.version.create",
2129
- releaseId,
2130
- publishedId,
2131
- document
2132
- }),
2292
+ createVersion: (params) => {
2293
+ const { releaseId, publishedId, document, baseId, ifBaseRevisionId } = params;
2294
+ if (document)
2295
+ return runAction({
2296
+ actionType: "sanity.action.document.version.create",
2297
+ releaseId,
2298
+ publishedId,
2299
+ document
2300
+ });
2301
+ if (baseId === void 0)
2302
+ throw fakeError("createVersion() requires `baseId` when no `document` is provided.");
2303
+ return runAction({
2304
+ actionType: "sanity.action.document.version.create",
2305
+ publishedId,
2306
+ baseId,
2307
+ versionId: `versions.${releaseId}.${publishedId}`,
2308
+ ...ifBaseRevisionId !== void 0 ? { ifBaseRevisionId } : {}
2309
+ });
2310
+ },
2133
2311
  unpublishVersion: ({ releaseId, publishedId }) => runAction({
2134
2312
  actionType: "sanity.action.document.version.unpublish",
2135
2313
  versionId: `versions.${releaseId}.${publishedId}`,
@@ -2146,11 +2324,13 @@ function makeHandle(handleArgs) {
2146
2324
  platform: {
2147
2325
  projectId,
2148
2326
  organizationId: backend.organizationId,
2327
+ projectFeatures: backend.projectFeatures,
2149
2328
  own: (asked) => registryKey(asked) === registryKey(target) ? {
2150
2329
  grants: requireActiveAccess().grants,
2151
2330
  documents: () => store.all(),
2152
2331
  history,
2153
- canRead
2332
+ canRead,
2333
+ admitToLake
2154
2334
  } : void 0,
2155
2335
  actorUser: () => {
2156
2336
  const access = requireActiveAccess();