@sanity-labs/client-fake-for-test 0.16.0 → 0.17.1

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. `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 |
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 and records it in `_system.base` (`{ id, rev }`); a missing base fails. With access control, `version.create` in either form needs `create` on the resulting version, or `update` on the version it replaces (as `createOrReplace` does), as the Content Lake does; the base is not access-checked. 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`), `/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. |
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), `/projects/<projectId>/features` (the project's feature names, seeded with `projectFeatures`), 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
 
@@ -144,6 +144,40 @@ const bob = alice.withConfig({ token: "t-bob" });
144
144
 
145
145
  Register more identities after creation with `client.addIdentity(token, { user, grants })` — an upsert into the family-shared registry; already-bound siblings resolve lazily and pick the change up immediately. For a one-off identity without a registry, `withConfig({ accessControl })` still works (mutually exclusive with `token` in the same call).
146
146
 
147
+ #### Token grants: filters and paths
148
+
149
+ A grant is either a GROQ `filter`, as a project's ACL serves it, or a `path` glob, as a token carries it (an internal token's `{ s, p }` grant is `{ path: s, permissions: p }`). The Content Lake holds a grant as one or the other and evaluates a path grant as `_id in path("<path>")` (gradient `pkg/security/models.go`): the id's dot-separated elements compare literally, `*` matches one element and a trailing `**` one or more. The fake matches `{ path }` grants the same way. A `path()` call inside a GROQ query or a `{ filter }` grant still runs through groq-js, which matches `.` there as any character:
150
+
151
+ ```ts
152
+ const client = createTestClient({
153
+ identities: {
154
+ "t-service": {
155
+ user: { id: "p-service" },
156
+ grants: [
157
+ { path: "prod.wf-instance.*", permissions: ["read", "create", "update"] },
158
+ { path: "temp.system.guard.prod.wf-instance.**", permissions: ["read", "create", "update"] },
159
+ ],
160
+ },
161
+ },
162
+ token: "t-service",
163
+ });
164
+ ```
165
+
166
+ The Content Lake parses a token's path grants on every request it serves and refuses the whole request when one does not parse — whatever the request asks. The fake does the same for every handle acting as that identity, token-bound or inline `accessControl`: `fetch`, `getDocument(s)`, `releases.get` / `releases.fetchDocuments`, every mutation and action, and the History API throw a `PlatformHttpError` with `statusCode: 400` and body `{ error: { description, type: "httpBadRequest" } }`, where `description` is the Content Lake's message for the first grant it cannot parse. A route the resource does not mount still answers its 404 first (a Canvas's `/actions`), as the request never reaches the Content Lake.
167
+
168
+ | Grant | `description` |
169
+ | --- | --- |
170
+ | `path: ""` | `path must contain at least one element` |
171
+ | `path` starting with `.` | `path cannot begin with delimiter "."` |
172
+ | `path` with an empty element (`a..b`, `a.`) | `path contains empty element` |
173
+ | `path` over 128 UTF-8 bytes | `path exceeds maximum length of 128` |
174
+ | `*` before the last element (`*.wf-instance.*`) | `wildcard must be last component` |
175
+ | `**` before the last element | `descendant wildcard must be last component` |
176
+ | an element outside `[A-Za-z0-9_-]`, or starting with `-` (an element with several lines passes when any one line is valid, a quirk the Content Lake keeps for old ids) | `invalid element "<element>"`, Go-quoted |
177
+ | a permission other than `read`, `update`, `create`, `manage`, `history`, `editHistory` (e.g. `delete`) | `invalid permission "<permission>"`, Go-quoted |
178
+
179
+ Filter grants come from the ACL, not the token, and are not checked. `/users/me`, the project API (`/projects/…`), the Access API and the ACL are not the Content Lake's and do not read a token's grants, so they keep answering.
180
+
147
181
  #### System-document grants
148
182
 
149
183
  User-issued writes to system document IDs beginning with `_.` require the `manage` permission. Ordinary `create` and `update` grants do not authorize these writes; add `manage` to identities whose tests intentionally create, replace, patch, delete, transact, mutate, publish, or unpublish system documents. The fake's internal release/version bookkeeping remains outside access-control interception.
@@ -211,6 +245,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
211
245
  - **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`.
212
246
  - **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.
213
247
  - **Org lookup.** `createTestClient({ organizationId })` names the organization every resource of the client belongs to.
248
+ - **Project features.** `GET /projects/<projectId>/features` answers the project's feature names as a bare array, sorted and once each, as the project API does. Seed them with `createTestClient({ projectFeatures: { "<projectId>": ["advancedRolesManagement"] } })`; a project without an entry has no features and answers `[]`. Like `/projects/<projectId>`, it answers any project id to any acting identity: the platform lets any project member read it, and every identity is a member of every project.
214
249
  - **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
215
250
 
216
251
  ### Test-only helpers (not on real `SanityClient`)
package/dist/index.cjs CHANGED
@@ -5,67 +5,6 @@ const ERR_PREFIX = "[client-fake-for-test]";
5
5
  function fakeError(message) {
6
6
  return new Error(`${ERR_PREFIX} ${message}`);
7
7
  }
8
- function createDocumentHistory() {
9
- const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
10
- return {
11
- commit: ({ transactionId, author, before, after }) => {
12
- const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
13
- for (const id of ids) {
14
- const previous = before.get(id), next = afterById.get(id);
15
- 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({
16
- documentId: id,
17
- after: next === void 0 ? void 0 : structuredClone(next),
18
- existed: previous !== void 0
19
- }));
20
- }
21
- effects.length !== 0 && transactions.push({
22
- id: transactionId,
23
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
24
- author,
25
- effects
26
- });
27
- },
28
- documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
29
- const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
30
- return image === void 0 ? [] : [structuredClone(image)];
31
- }),
32
- lastImage: (id) => deleted.get(id),
33
- documentIds: () => [
34
- ...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
35
- ],
36
- 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) => ({
37
- id: txn.id,
38
- timestamp: txn.timestamp,
39
- ...txn.author !== void 0 ? { author: txn.author } : {},
40
- mutations: txn.effects.map((effect) => {
41
- if (effect.after === void 0) return { delete: { id: effect.documentId } };
42
- const after = structuredClone(effect.after);
43
- return effect.existed ? { createOrReplace: after } : { create: after };
44
- }),
45
- documentIDs: txn.effects.map((effect) => effect.documentId)
46
- })),
47
- events: (ids) => Object.fromEntries(
48
- ids.map((id) => [
49
- id,
50
- transactions.flatMap(
51
- (txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
52
- (effect) => ({
53
- type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
54
- id: txn.id,
55
- documentId: id,
56
- revisionId: effect.after._rev,
57
- timestamp: txn.timestamp,
58
- ...txn.author !== void 0 ? { author: txn.author } : {}
59
- })
60
- )
61
- ).toReversed()
62
- ])
63
- )
64
- };
65
- }
66
- function historyIds(list) {
67
- return list.split(",").map((id) => decodeURIComponent(id));
68
- }
69
8
  class PlatformHttpError extends Error {
70
9
  statusCode;
71
10
  response;
@@ -335,7 +274,148 @@ function dataUrl(args) {
335
274
  const base = `/${operation}/${dataset}`;
336
275
  return `/data${path !== void 0 ? `${base}/${path}` : base}`.replace(/\/($|\?)/, "$1");
337
276
  }
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\/([^/]+)(\/.*)$/;
277
+ const MAX_PATH_BYTES = 128, PERMISSIONS = /* @__PURE__ */ new Set(["read", "update", "create", "manage", "history", "editHistory"]), MISPLACED_WILDCARD = /* @__PURE__ */ new Map([
278
+ ["*", "wildcard must be last component"],
279
+ ["**", "descendant wildcard must be last component"]
280
+ ]), ELEMENT_LINE = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
281
+ function validElement(element) {
282
+ return element.split(`
283
+ `).some((line) => ELEMENT_LINE.test(line));
284
+ }
285
+ const GO_ESCAPES = {
286
+ "\x07": "\\a",
287
+ "\b": "\\b",
288
+ "\f": "\\f",
289
+ "\n": "\\n",
290
+ "\r": "\\r",
291
+ " ": "\\t",
292
+ "\v": "\\v",
293
+ '"': '\\"',
294
+ "\\": "\\\\"
295
+ }, GO_PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S} ]$/u;
296
+ function quoted(value) {
297
+ let out = '"';
298
+ for (const char of value) {
299
+ const escape = GO_ESCAPES[char];
300
+ if (escape !== void 0) {
301
+ out += escape;
302
+ continue;
303
+ }
304
+ if (GO_PRINTABLE.test(char)) {
305
+ out += char;
306
+ continue;
307
+ }
308
+ const code = char.codePointAt(0);
309
+ 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")}`;
310
+ }
311
+ return `${out}"`;
312
+ }
313
+ function pathError(path) {
314
+ if (path === "") return "path must contain at least one element";
315
+ if (path.startsWith(".")) return 'path cannot begin with delimiter "."';
316
+ const elements = path.split(".");
317
+ if (elements.includes("")) return "path contains empty element";
318
+ if (new TextEncoder().encode(path).length > MAX_PATH_BYTES)
319
+ return `path exceeds maximum length of ${MAX_PATH_BYTES}`;
320
+ const last = elements.length - 1;
321
+ for (const [index, element] of elements.entries()) {
322
+ const misplaced = MISPLACED_WILDCARD.get(element);
323
+ if (misplaced !== void 0) {
324
+ if (index < last) return misplaced;
325
+ } else if (!validElement(element))
326
+ return `invalid element ${quoted(element)}`;
327
+ }
328
+ }
329
+ function pathIncludes(path, id) {
330
+ const pattern = path.split("."), elements = id.split(".");
331
+ for (const [index, element] of pattern.entries()) {
332
+ if (index >= elements.length) return !1;
333
+ if (element === "**") return !0;
334
+ if (element === "*" ? elements[index] === "**" : element !== elements[index]) return !1;
335
+ }
336
+ return pattern.length === elements.length;
337
+ }
338
+ function grantsError(grants) {
339
+ for (const grant of grants) {
340
+ if (!("path" in grant)) continue;
341
+ const error = pathError(grant.path);
342
+ if (error !== void 0) return error;
343
+ const invalid = grant.permissions.find((permission) => !PERMISSIONS.has(permission));
344
+ if (invalid !== void 0) return `invalid permission ${quoted(invalid)}`;
345
+ }
346
+ }
347
+ function refusedToken(request, grants) {
348
+ const description = grantsError(grants);
349
+ if (description !== void 0)
350
+ return new PlatformHttpError({
351
+ ...request,
352
+ statusCode: 400,
353
+ statusMessage: "Bad Request",
354
+ body: { error: { description, type: "httpBadRequest" } }
355
+ });
356
+ }
357
+ function createDocumentHistory() {
358
+ const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
359
+ return {
360
+ commit: ({ transactionId, author, before, after }) => {
361
+ const afterById = new Map(after.map((doc) => [doc._id, doc])), ids = /* @__PURE__ */ new Set([...before.keys(), ...afterById.keys()]), effects = [];
362
+ for (const id of ids) {
363
+ const previous = before.get(id), next = afterById.get(id);
364
+ 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({
365
+ documentId: id,
366
+ after: next === void 0 ? void 0 : structuredClone(next),
367
+ existed: previous !== void 0
368
+ }));
369
+ }
370
+ effects.length !== 0 && transactions.push({
371
+ id: transactionId,
372
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
373
+ author,
374
+ effects
375
+ });
376
+ },
377
+ documentsAt: ({ ids, revision, current }) => ids.flatMap((id) => {
378
+ const image = revisions.get(`${id} ${revision}`) ?? current.find((doc) => doc._id === id && doc._rev === revision);
379
+ return image === void 0 ? [] : [structuredClone(image)];
380
+ }),
381
+ lastImage: (id) => deleted.get(id),
382
+ documentIds: () => [
383
+ ...new Set(transactions.flatMap((txn) => txn.effects.map((effect) => effect.documentId)))
384
+ ],
385
+ 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) => ({
386
+ id: txn.id,
387
+ timestamp: txn.timestamp,
388
+ ...txn.author !== void 0 ? { author: txn.author } : {},
389
+ mutations: txn.effects.map((effect) => {
390
+ if (effect.after === void 0) return { delete: { id: effect.documentId } };
391
+ const after = structuredClone(effect.after);
392
+ return effect.existed ? { createOrReplace: after } : { create: after };
393
+ }),
394
+ documentIDs: txn.effects.map((effect) => effect.documentId)
395
+ })),
396
+ events: (ids) => Object.fromEntries(
397
+ ids.map((id) => [
398
+ id,
399
+ transactions.flatMap(
400
+ (txn) => txn.effects.filter((effect) => effect.documentId === id && effect.after !== void 0).map(
401
+ (effect) => ({
402
+ type: effect.existed ? "updateLiveDocument" : "createLiveDocument",
403
+ id: txn.id,
404
+ documentId: id,
405
+ revisionId: effect.after._rev,
406
+ timestamp: txn.timestamp,
407
+ ...txn.author !== void 0 ? { author: txn.author } : {}
408
+ })
409
+ )
410
+ ).toReversed()
411
+ ])
412
+ )
413
+ };
414
+ }
415
+ function historyIds(list) {
416
+ return list.split(",").map((id) => decodeURIComponent(id));
417
+ }
418
+ 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\/([^/]+)(\/.*)$/;
339
419
  function page(data) {
340
420
  return { data, nextCursor: null };
341
421
  }
@@ -354,6 +434,11 @@ async function servePlatformRequest(ctx, url) {
354
434
  const projectId = decodeURIComponent(projectRoles[1]);
355
435
  return serveProjectRoles({ ctx, request, projectId });
356
436
  }
437
+ const projectFeatures = path.match(PROJECT_FEATURES_PATH);
438
+ if (projectFeatures !== null) {
439
+ const projectId = decodeURIComponent(projectFeatures[1]);
440
+ return { value: featuresOf(ctx, projectId) };
441
+ }
357
442
  const access = path.match(ACCESS_PATH);
358
443
  if (access !== null) {
359
444
  const [, type, id, rest2] = access;
@@ -376,6 +461,10 @@ async function servePlatformRequest(ctx, url) {
376
461
  if (rest.startsWith("/history/"))
377
462
  return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
378
463
  }
464
+ function featuresOf(ctx, projectId) {
465
+ const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
466
+ return [...new Set(features)].toSorted();
467
+ }
379
468
  function serveLookup(ctx, resource) {
380
469
  if (ctx.organizationId === void 0)
381
470
  throw fakeError(
@@ -387,7 +476,8 @@ function serveHistory(args) {
387
476
  const { ctx, request, resource, rest, query } = args;
388
477
  return serveCapability(capabilitiesOf(resource.type).history, request, () => {
389
478
  const own = ctx.own(resource);
390
- return own === void 0 ? void 0 : readHistory({ own, request, rest, query });
479
+ if (own !== void 0)
480
+ return own.admitToLake(request), readHistory({ own, request, rest, query });
391
481
  });
392
482
  }
393
483
  async function readHistory(args) {
@@ -614,15 +704,15 @@ async function matchesFilter(args) {
614
704
  })).get();
615
705
  return Array.isArray(data) && data.length === 1;
616
706
  }
707
+ async function grantMatches(args) {
708
+ const { document, grant, userId } = args;
709
+ return "path" in grant ? typeof document._id == "string" && pathIncludes(grant.path, document._id) : matchesFilter({ document, filter: grant.filter, userId });
710
+ }
617
711
  async function evaluateWriteAccess(args) {
618
712
  const { document, grants, permission, userId } = args;
619
713
  let matching = 0;
620
714
  for (const grant of grants)
621
- if (await matchesFilter({
622
- document,
623
- filter: grant.filter,
624
- userId
625
- }) && (matching++, grant.permissions.includes(permission)))
715
+ if (await grantMatches({ document, grant, userId }) && (matching++, grant.permissions.includes(permission)))
626
716
  return { allowed: !0, matchingGrants: matching };
627
717
  return { allowed: !1, matchingGrants: matching };
628
718
  }
@@ -747,7 +837,7 @@ function makeRequestImpl(ctx) {
747
837
  const served = path === void 0 ? void 0 : await servePlatformRequest(platform, path);
748
838
  if (served !== void 0) return served.value;
749
839
  throw fakeError(
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.`
840
+ `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.`
751
841
  );
752
842
  };
753
843
  }
@@ -1293,7 +1383,7 @@ async function applyAction(store, action, hooks) {
1293
1383
  return store.remove(release._id), { transactionId: cryptoRandomKey() };
1294
1384
  }
1295
1385
  case "sanity.action.document.version.create": {
1296
- if ("baseId" in action) return createVersionFromBase(store, action);
1386
+ if ("baseId" in action) return createVersionFromBase(store, action, hooks);
1297
1387
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
1298
1388
  if (releaseId === void 0)
1299
1389
  throw fakeError(
@@ -1305,7 +1395,7 @@ async function applyAction(store, action, hooks) {
1305
1395
  ...action.document,
1306
1396
  _id: vid
1307
1397
  }, existing = store.get(vid), promoted = promote(doc);
1308
- return existing !== void 0 && (promoted._createdAt = existing._createdAt), store.put(promoted), { transactionId: cryptoRandomKey() };
1398
+ return existing !== void 0 && (promoted._createdAt = existing._createdAt), await hooks?.gate?.(existing ?? promoted, existing === void 0 ? "create" : "update"), store.put(promoted), { transactionId: cryptoRandomKey() };
1309
1399
  }
1310
1400
  case "sanity.action.document.version.replace": {
1311
1401
  const id = action.document._id;
@@ -1365,7 +1455,7 @@ function requireDraftOf(action) {
1365
1455
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1366
1456
  );
1367
1457
  }
1368
- function createVersionFromBase(store, action) {
1458
+ async function createVersionFromBase(store, action, hooks) {
1369
1459
  const { releaseId, publishedId } = parseVersionId(action.versionId);
1370
1460
  if (publishedId !== action.publishedId)
1371
1461
  throw fakeError(
@@ -1378,12 +1468,13 @@ function createVersionFromBase(store, action) {
1378
1468
  `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
1469
  );
1380
1470
  requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
1381
- const existing = store.get(action.versionId), promoted = promote({
1471
+ const existing = store.get(action.versionId), copy = {
1382
1472
  ...base,
1383
1473
  _id: action.versionId,
1384
- _createdAt: existing?._createdAt ?? nowIso()
1385
- });
1386
- return store.put(promoted), { transactionId: cryptoRandomKey() };
1474
+ _createdAt: existing?._createdAt ?? nowIso(),
1475
+ _system: { base: { id: base._id, rev: base._rev } }
1476
+ }, promoted = promote(copy);
1477
+ return await hooks?.gate?.(existing ?? promoted, existing === void 0 ? "create" : "update"), store.put(promoted), { transactionId: cryptoRandomKey() };
1387
1478
  }
1388
1479
  function requireRevisionMatch(documentId, actualRev, expectedRev) {
1389
1480
  if (!(expectedRev === void 0 || actualRev === expectedRev))
@@ -1545,7 +1636,7 @@ const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues",
1545
1636
  },
1546
1637
  request: {
1547
1638
  what: "generic HTTP request hook \u2014 only wired up when the handle has an acting identity",
1548
- 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."
1639
+ 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."
1549
1640
  },
1550
1641
  dryRun: {
1551
1642
  what: "not a method \u2014 did you mean the `{ dryRun }` mutation option?",
@@ -1729,6 +1820,7 @@ function createTestClient(options = {}) {
1729
1820
  const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
1730
1821
  registry: /* @__PURE__ */ new Map(),
1731
1822
  organizationId: options.organizationId,
1823
+ projectFeatures: options.projectFeatures ?? {},
1732
1824
  log: [],
1733
1825
  stubs: /* @__PURE__ */ new Map(),
1734
1826
  calls: [],
@@ -1838,7 +1930,12 @@ function makeHandle(handleArgs) {
1838
1930
  if (access === void 0)
1839
1931
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
1840
1932
  return access;
1841
- }, members = () => [
1933
+ }, admitToLake = (request) => {
1934
+ const access = activeAccess();
1935
+ if (access === void 0) return;
1936
+ const refusal = refusedToken(request, access.grants);
1937
+ if (refusal !== void 0) throw refusal;
1938
+ }, lakeRequest = (method, operation, path) => ({ method, path: dataUrl({ resource, dataset, operation, path }) }), members = () => [
1842
1939
  ...backend.identities.values(),
1843
1940
  ...token === void 0 && accessControl !== void 0 ? [
1844
1941
  {
@@ -1854,8 +1951,8 @@ function makeHandle(handleArgs) {
1854
1951
  return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
1855
1952
  };
1856
1953
  let beforeWrite;
1857
- const write = (run) => serializeWrite(backend, async () => {
1858
- beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
1954
+ const write = (run, request = lakeRequest("POST", "mutate")) => serializeWrite(backend, async () => {
1955
+ admitToLake(request), beforeWrite = new Map(store.all().map((doc) => [doc._id, doc]));
1859
1956
  try {
1860
1957
  return await run();
1861
1958
  } finally {
@@ -2017,14 +2114,14 @@ function makeHandle(handleArgs) {
2017
2114
  path: `${capabilities.dataBase(target.id)}/actions`
2018
2115
  };
2019
2116
  if (capabilities.actions !== "served") throw capabilities.actions(request);
2020
- for (const action of Array.isArray(actions) ? actions : [actions]) {
2021
- const refused = capabilities.refusedActions[action.actionType];
2022
- if (refused !== void 0) throw refused(request);
2023
- }
2024
2117
  return write(async () => {
2118
+ for (const action of Array.isArray(actions) ? actions : [actions]) {
2119
+ const refused = capabilities.refusedActions[action.actionType];
2120
+ if (refused !== void 0) throw refused(request);
2121
+ }
2025
2122
  const result = await applyActions(store, actions, { gate, guard: guardGate });
2026
2123
  return commitHistory(result.transactionId), result;
2027
- });
2124
+ }, request);
2028
2125
  }, accessVisibleDocs = async () => {
2029
2126
  const all = store.all();
2030
2127
  if (activeAccess() === void 0) return all;
@@ -2037,6 +2134,7 @@ function makeHandle(handleArgs) {
2037
2134
  return applyPerspective(accessible, override ?? perspective);
2038
2135
  }, client = {
2039
2136
  fetch: async (query, params, opts) => {
2137
+ admitToLake(lakeRequest("GET", "query"));
2040
2138
  const start = Date.now(), tree = groqJs.parse(query, params ? { params } : void 0), result = await (await groqJs.evaluate(tree, {
2041
2139
  dataset: await visibleDocs(opts?.perspective),
2042
2140
  ...params !== void 0 ? { params } : {}
@@ -2048,6 +2146,7 @@ function makeHandle(handleArgs) {
2048
2146
  return result;
2049
2147
  },
2050
2148
  getDocument: async (id, opts) => {
2149
+ admitToLake(lakeRequest("GET", "doc", id));
2051
2150
  const effective = opts?.perspective ?? perspective;
2052
2151
  if (effective === "raw") {
2053
2152
  const doc = store.get(id);
@@ -2057,6 +2156,7 @@ function makeHandle(handleArgs) {
2057
2156
  return resolveDocument(view, id, effective) ?? void 0;
2058
2157
  },
2059
2158
  getDocuments: async (ids, opts) => {
2159
+ admitToLake(lakeRequest("GET", "doc", ids.join(",")));
2060
2160
  const effective = opts?.perspective ?? perspective;
2061
2161
  if (effective === "raw") {
2062
2162
  const result = [];
@@ -2170,10 +2270,16 @@ function makeHandle(handleArgs) {
2170
2270
  };
2171
2271
  },
2172
2272
  edit: ({ releaseId, patch }) => runAction({ actionType: "sanity.action.release.edit", releaseId, patch }),
2173
- get: async ({ releaseId }) => store.get(`_.releases.${releaseId}`),
2273
+ // `@sanity/client` reads a release by id and its documents by query.
2274
+ get: async ({ releaseId }) => {
2275
+ admitToLake(lakeRequest("GET", "doc", `_.releases.${releaseId}`));
2276
+ const doc = store.get(`_.releases.${releaseId}`);
2277
+ return doc !== void 0 && await canRead(doc) ? doc : void 0;
2278
+ },
2174
2279
  fetchDocuments: async ({ releaseId }) => {
2280
+ admitToLake(lakeRequest("GET", "query"));
2175
2281
  const prefix = `versions.${releaseId}.`;
2176
- return store.all().filter((d) => d._id.startsWith(prefix));
2282
+ return (await accessVisibleDocs()).filter((d) => d._id.startsWith(prefix));
2177
2283
  },
2178
2284
  schedule: ({ releaseId, publishAt }) => runAction({
2179
2285
  actionType: "sanity.action.release.schedule",
@@ -2221,11 +2327,13 @@ function makeHandle(handleArgs) {
2221
2327
  platform: {
2222
2328
  projectId,
2223
2329
  organizationId: backend.organizationId,
2330
+ projectFeatures: backend.projectFeatures,
2224
2331
  own: (asked) => registryKey(asked) === registryKey(target) ? {
2225
2332
  grants: requireActiveAccess().grants,
2226
2333
  documents: () => store.all(),
2227
2334
  history,
2228
- canRead
2335
+ canRead,
2336
+ admitToLake
2229
2337
  } : void 0,
2230
2338
  actorUser: () => {
2231
2339
  const access = requireActiveAccess();