@sanity-labs/client-fake-for-test 0.17.0 → 0.17.2

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,7 +76,7 @@ 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 |
@@ -178,9 +178,13 @@ The Content Lake parses a token's path grants on every request it serves and ref
178
178
 
179
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
180
 
181
+ #### Which permission a write needs
182
+
183
+ The fake checks every written document the way the Content Lake does (gradient `pkg/security/document_permission_checker.go`): a create needs `create` on the new document; an update, replace or patch needs `update` on the document before the write **and** on the document after it; a delete needs `update` on the document before. So a patch or `createOrReplace` that moves a document out of the identity's `update` grant (a filter it stops matching) is refused with `WriteAccessDeniedError`, and nothing is written. The same holds for `version.create` replacing a version and for the documents `document.publish` / `document.unpublish` write and delete. A transaction, `mutate` or action batch is checked per document on its net change once every mutation is staged, so a document patched out of the grant and back again in one transaction passes, and one created and deleted in it is not checked. Reads inside a write are not checked.
184
+
181
185
  #### System-document grants
182
186
 
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.
187
+ User-issued writes to system document IDs beginning with `_.` require the `manage` permission **in addition to** the `create` or `update` the write needs, each checked on the same documents (before and after the write), as the Content Lake's permission checker does. `create` and `update` alone do not authorize these writes, and neither does `manage` alone; grant `manage` alongside `create` / `update` 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.
184
188
 
185
189
  #### Dual-namespace identities: global vs project user ids
186
190
 
package/dist/index.cjs CHANGED
@@ -1279,7 +1279,7 @@ function requireActive(release) {
1279
1279
  `Release "${release.name}" is "${release.state}", but only "active" releases accept version writes (create / replace / discard / unpublish). Unschedule or unarchive it back to "active" first, or target a different release.`
1280
1280
  );
1281
1281
  }
1282
- async function applyAction(store, action, hooks) {
1282
+ async function applyAction(store, action) {
1283
1283
  switch (action.actionType) {
1284
1284
  case "sanity.action.release.create": {
1285
1285
  if (maybeRelease(store, action.releaseId) !== void 0)
@@ -1432,7 +1432,7 @@ async function applyAction(store, action, hooks) {
1432
1432
  const published = store.get(action.publishedId);
1433
1433
  requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(action.publishedId, published?._rev, action.ifPublishedRevisionId);
1434
1434
  const promoted = promote({ ...draft, _id: action.publishedId });
1435
- return published !== void 0 && (promoted._createdAt = published._createdAt), await hooks?.gate?.(promoted, published === void 0 ? "create" : "update"), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
1435
+ return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
1436
1436
  }
1437
1437
  case "sanity.action.document.unpublish": {
1438
1438
  requireDraftOf(action);
@@ -1441,7 +1441,7 @@ async function applyAction(store, action, hooks) {
1441
1441
  throw fakeError(
1442
1442
  `Cannot unpublish "${action.publishedId}": no published document with that _id exists. document.unpublish retracts a live published document into "${action.draftId}".`
1443
1443
  );
1444
- if (await hooks?.gate?.(published, "update"), store.get(action.draftId) === void 0) {
1444
+ if (store.get(action.draftId) === void 0) {
1445
1445
  const draft = promote({ ...published, _id: action.draftId });
1446
1446
  draft._createdAt = published._createdAt, store.put(draft);
1447
1447
  }
@@ -1455,7 +1455,7 @@ function requireDraftOf(action) {
1455
1455
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1456
1456
  );
1457
1457
  }
1458
- function createVersionFromBase(store, action) {
1458
+ async function createVersionFromBase(store, action) {
1459
1459
  const { releaseId, publishedId } = parseVersionId(action.versionId);
1460
1460
  if (publishedId !== action.publishedId)
1461
1461
  throw fakeError(
@@ -1468,11 +1468,12 @@ function createVersionFromBase(store, action) {
1468
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.`
1469
1469
  );
1470
1470
  requireRevisionMatch(action.baseId, base._rev, action.ifBaseRevisionId);
1471
- const existing = store.get(action.versionId), promoted = promote({
1471
+ const existing = store.get(action.versionId), copy = {
1472
1472
  ...base,
1473
1473
  _id: action.versionId,
1474
- _createdAt: existing?._createdAt ?? nowIso()
1475
- });
1474
+ _createdAt: existing?._createdAt ?? nowIso(),
1475
+ _system: { base: { id: base._id, rev: base._rev } }
1476
+ }, promoted = promote(copy);
1476
1477
  return store.put(promoted), { transactionId: cryptoRandomKey() };
1477
1478
  }
1478
1479
  function requireRevisionMatch(documentId, actualRev, expectedRev) {
@@ -1485,7 +1486,7 @@ function requireRevisionMatch(documentId, actualRev, expectedRev) {
1485
1486
  );
1486
1487
  }
1487
1488
  async function applyActions(store, actions, hooks) {
1488
- const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), remember = (id) => {
1489
+ const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
1489
1490
  snapshot.has(id) || snapshot.set(id, store.get(id));
1490
1491
  };
1491
1492
  try {
@@ -1498,9 +1499,15 @@ async function applyActions(store, actions, hooks) {
1498
1499
  case "sanity.action.release.unschedule":
1499
1500
  case "sanity.action.release.archive":
1500
1501
  case "sanity.action.release.unarchive":
1501
- case "sanity.action.release.delete":
1502
1502
  remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
1503
1503
  break;
1504
+ case "sanity.action.release.delete": {
1505
+ remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
1506
+ const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;
1507
+ for (const d of store.all())
1508
+ d._id.startsWith(prefix) && remember(d._id);
1509
+ break;
1510
+ }
1504
1511
  case "sanity.action.release.publish": {
1505
1512
  remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
1506
1513
  const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;
@@ -1510,11 +1517,11 @@ async function applyActions(store, actions, hooks) {
1510
1517
  }
1511
1518
  case "sanity.action.document.version.create": {
1512
1519
  if ("baseId" in a) {
1513
- remember(a.versionId);
1520
+ remember(a.versionId), gatedIds.add(a.versionId);
1514
1521
  break;
1515
1522
  }
1516
1523
  const releaseId = a.releaseId ?? (typeof a.document._id == "string" ? parseVersionId(a.document._id).releaseId : void 0);
1517
- releaseId !== void 0 && remember(versionDocId(releaseId, a.publishedId));
1524
+ releaseId !== void 0 && (remember(versionDocId(releaseId, a.publishedId)), gatedIds.add(versionDocId(releaseId, a.publishedId)));
1518
1525
  break;
1519
1526
  }
1520
1527
  case "sanity.action.document.version.replace":
@@ -1525,13 +1532,17 @@ async function applyActions(store, actions, hooks) {
1525
1532
  remember(a.versionId);
1526
1533
  break;
1527
1534
  case "sanity.action.document.publish":
1528
- remember(a.draftId), remember(a.publishedId), guardedIds.add(a.publishedId), guardedIds.add(a.draftId);
1535
+ remember(a.draftId), remember(a.publishedId), guardedIds.add(a.publishedId), guardedIds.add(a.draftId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
1529
1536
  break;
1530
1537
  case "sanity.action.document.unpublish":
1531
- remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId);
1538
+ remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
1532
1539
  break;
1533
1540
  }
1534
- last = await applyAction(store, a, hooks);
1541
+ last = await applyAction(store, a);
1542
+ }
1543
+ for (const id of gatedIds) {
1544
+ const before = snapshot.get(id), after = store.get(id);
1545
+ before !== after && await hooks?.gate?.(before, after);
1535
1546
  }
1536
1547
  const contexts = mutationContexts(
1537
1548
  [...guardedIds].map((id) => ({ before: snapshot.get(id), after: store.get(id) }))
@@ -2009,14 +2020,21 @@ function makeHandle(handleArgs) {
2009
2020
  throw fakeError(
2010
2021
  `ifRevisionId check failed: document "${id}" is at _rev="${existing._rev}" but the mutation required _rev="${ifRevisionId}". The document changed since you read it \u2014 re-read it and retry. (This mirrors Sanity's optimistic-locking 409.)`
2011
2022
  );
2012
- }, gate = async (document, permission) => {
2023
+ }, gate = async (prev, next) => {
2013
2024
  const access = activeAccess();
2014
- access !== void 0 && await enforceWriteAccess({
2015
- document,
2016
- grants: access.grants,
2017
- permission: document._id !== void 0 && isSystemId(document._id) ? "manage" : permission,
2018
- userId: actorId()
2019
- });
2025
+ if (access === void 0) return;
2026
+ const id = (prev ?? next)?._id;
2027
+ if (id === void 0) return;
2028
+ const required = isSystemId(id) ? ["manage"] : [];
2029
+ required.push(prev === void 0 ? "create" : "update");
2030
+ for (const permission of required)
2031
+ for (const document of [prev, next])
2032
+ document !== void 0 && await enforceWriteAccess({
2033
+ document,
2034
+ grants: access.grants,
2035
+ permission,
2036
+ userId: actorId()
2037
+ });
2020
2038
  }, guardGate = async (contexts) => {
2021
2039
  const identity = actorId();
2022
2040
  await enforceMutationGuards(
@@ -2039,13 +2057,13 @@ function makeHandle(handleArgs) {
2039
2057
  throw fakeError(
2040
2058
  `Cannot patch document "${documentId}": not found \u2014 no document with that _id exists in ${targetLabel}. patch() requires the target to already exist; use createOrReplace() / createIfNotExists() to upsert, or seed the document first.`
2041
2059
  );
2042
- checkRevision(documentId, ifRev), await gate(existing, "update");
2060
+ checkRevision(documentId, ifRev);
2043
2061
  const patched = applyPatchOps(existing, ops), now = (/* @__PURE__ */ new Date()).toISOString(), next = {
2044
2062
  ...patched,
2045
2063
  _rev: cryptoRandomKey(),
2046
2064
  _updatedAt: now
2047
2065
  };
2048
- return options.evaluateGuard !== !1 && await guardOne("update", existing, next), store.put(next), next;
2066
+ return options.inTransaction !== !0 && (await gate(existing, next), await guardOne("update", existing, next)), store.put(next), next;
2049
2067
  }, applyTransaction = async (mutations, txnOptions) => {
2050
2068
  const transactionId = txnOptions?.transactionId ?? cryptoRandomKey(), snapshot = /* @__PURE__ */ new Map(), touchedIds = [], operations = [], remember = (id) => {
2051
2069
  snapshot.has(id) || snapshot.set(id, store.get(id));
@@ -2060,39 +2078,35 @@ function makeHandle(handleArgs) {
2060
2078
  throw fakeError(
2061
2079
  `create() failed: a document with _id "${promoted._id}" already exists in ${targetLabel}. Use createOrReplace() to overwrite it, or createIfNotExists() to leave the existing one untouched.`
2062
2080
  );
2063
- await gate(promoted, "create"), store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2081
+ store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2064
2082
  break;
2065
2083
  }
2066
2084
  case "createOrReplace": {
2067
2085
  remember(mut.doc._id);
2068
- const promoted = promote2(mut.doc), existing = store.get(promoted._id);
2069
- await gate(existing ?? promoted, existing !== void 0 ? "update" : "create");
2070
- const wasPresent = existing !== void 0;
2086
+ const promoted = promote2(mut.doc), wasPresent = store.get(promoted._id) !== void 0;
2071
2087
  store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: wasPresent ? "update" : "create" });
2072
2088
  break;
2073
2089
  }
2074
2090
  case "createIfNotExists": {
2075
2091
  if (remember(mut.doc._id), store.get(mut.doc._id) === void 0) {
2076
2092
  const promoted = promote2(mut.doc);
2077
- await gate(promoted, "create"), store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2093
+ store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2078
2094
  }
2079
2095
  break;
2080
2096
  }
2081
2097
  case "delete": {
2082
- remember(mut.id);
2083
- const existing = store.get(mut.id);
2084
- existing !== void 0 && await gate(existing, "update"), store.remove(mut.id) && (touchedIds.push(mut.id), operations.push({ id: mut.id, operation: "delete" }));
2098
+ remember(mut.id), store.remove(mut.id) && (touchedIds.push(mut.id), operations.push({ id: mut.id, operation: "delete" }));
2085
2099
  break;
2086
2100
  }
2087
2101
  case "patch": {
2088
- remember(mut.documentId), await applyPatch(mut.documentId, mut.ops, mut.ifRev, { evaluateGuard: !1 }), touchedIds.push(mut.documentId), operations.push({ id: mut.documentId, operation: "update" });
2102
+ remember(mut.documentId), await applyPatch(mut.documentId, mut.ops, mut.ifRev, { inTransaction: !0 }), touchedIds.push(mut.documentId), operations.push({ id: mut.documentId, operation: "update" });
2089
2103
  break;
2090
2104
  }
2091
2105
  }
2092
- const contexts = mutationContexts(
2093
- [...snapshot].map(([id, before]) => ({ before, after: store.get(id) }))
2094
- );
2095
- await guardGate(contexts);
2106
+ const images = [...snapshot].map(([id, before]) => ({ before, after: store.get(id) }));
2107
+ for (const { before, after } of images)
2108
+ before !== after && await gate(before, after);
2109
+ await guardGate(mutationContexts(images));
2096
2110
  } catch (error) {
2097
2111
  for (const [id, doc] of snapshot)
2098
2112
  doc === void 0 ? store.remove(id) : store.put(doc);
@@ -2175,7 +2189,7 @@ function makeHandle(handleArgs) {
2175
2189
  `create() failed: a document with _id "${doc._id}" already exists in ${targetLabel}. Use createOrReplace() to overwrite it, or createIfNotExists() to leave the existing one untouched.`
2176
2190
  );
2177
2191
  const promoted = promote2(doc);
2178
- await gate(promoted, "create"), await guardOne("create", null, promoted);
2192
+ await gate(void 0, promoted), await guardOne("create", null, promoted);
2179
2193
  const transactionId = opts?.transactionId ?? cryptoRandomKey();
2180
2194
  return opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "create", doc }], opts?.tag)), writeResult(
2181
2195
  [promoted],
@@ -2187,7 +2201,7 @@ function makeHandle(handleArgs) {
2187
2201
  createOrReplace: (doc, opts) => write(async () => {
2188
2202
  checkRevision(doc._id, opts?.ifRevisionId);
2189
2203
  const promoted = promote2(doc), existing = store.get(doc._id);
2190
- await gate(existing ?? promoted, existing !== void 0 ? "update" : "create"), await guardOne(existing !== void 0 ? "update" : "create", existing ?? null, promoted);
2204
+ await gate(existing, promoted), await guardOne(existing !== void 0 ? "update" : "create", existing ?? null, promoted);
2191
2205
  const transactionId = opts?.transactionId ?? cryptoRandomKey();
2192
2206
  opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createOrReplace", doc }], opts?.tag));
2193
2207
  const operation = existing !== void 0 ? "update" : "create";
@@ -2209,7 +2223,7 @@ function makeHandle(handleArgs) {
2209
2223
  opts
2210
2224
  );
2211
2225
  const promoted = promote2(doc);
2212
- return await gate(promoted, "create"), await guardOne("create", null, promoted), opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createIfNotExists", doc }], opts?.tag)), writeResult(
2226
+ return await gate(void 0, promoted), await guardOne("create", null, promoted), opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createIfNotExists", doc }], opts?.tag)), writeResult(
2213
2227
  [promoted],
2214
2228
  [{ id: promoted._id, operation: "create" }],
2215
2229
  transactionId,
@@ -2219,7 +2233,7 @@ function makeHandle(handleArgs) {
2219
2233
  delete: (id, opts) => write(async () => {
2220
2234
  checkRevision(id, opts?.ifRevisionId);
2221
2235
  const existing = store.get(id);
2222
- existing !== void 0 && await gate(existing, "update"), existing !== void 0 && await guardOne("delete", existing, null);
2236
+ existing !== void 0 && await gate(existing, void 0), existing !== void 0 && await guardOne("delete", existing, null);
2223
2237
  const transactionId = opts?.transactionId ?? cryptoRandomKey();
2224
2238
  let removed = existing;
2225
2239
  return opts?.dryRun !== !0 && (removed = store.remove(id), removed !== void 0 && record(transactionId, [{ kind: "delete", id }], opts?.tag)), opts?.returnDocuments === void 0 && opts?.returnFirst === void 0 ? removed !== void 0 ? { _id: id } : null : formatMutationResult(