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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1056,7 +1056,11 @@ export declare interface TestClient {
1056
1056
  * handle is bound to a registered identity.
1057
1057
  */
1058
1058
  config: () => {
1059
- projectId: string;
1059
+ /**
1060
+ * Absent on a handle created global-hosted (`useProjectHostname: false`)
1061
+ * without a `projectId`, as in `@sanity/client`.
1062
+ */
1063
+ projectId?: string;
1060
1064
  dataset: string;
1061
1065
  /** Present iff the handle is `resource`-configured. */
1062
1066
  resource?: TestClientResource;
@@ -1170,6 +1174,15 @@ export declare interface TestClient {
1170
1174
  addIdentity: (token: string, identity: TestClientIdentity) => void;
1171
1175
  /** Snapshot of the registered token→identity entries. */
1172
1176
  identities: () => Record<string, TestClientIdentity>;
1177
+ /**
1178
+ * Revoke a registered token, as when it expires or is deleted: it stays
1179
+ * registered and still binds, but from the next request on every Content
1180
+ * Lake and platform request made with it (on any handle) rejects with the
1181
+ * platform's 401 `Session not found`, and nothing is written. Revocation
1182
+ * is permanent for the family; `addIdentity` does not restore it. Unknown
1183
+ * tokens throw.
1184
+ */
1185
+ revokeIdentity: (token: string) => void;
1173
1186
  /**
1174
1187
  * Every mutation committed through this client's registry, flattened
1175
1188
  * and in order — `create` / `createOrReplace` / `createIfNotExists` /
package/dist/index.d.ts CHANGED
@@ -1056,7 +1056,11 @@ export declare interface TestClient {
1056
1056
  * handle is bound to a registered identity.
1057
1057
  */
1058
1058
  config: () => {
1059
- projectId: string;
1059
+ /**
1060
+ * Absent on a handle created global-hosted (`useProjectHostname: false`)
1061
+ * without a `projectId`, as in `@sanity/client`.
1062
+ */
1063
+ projectId?: string;
1060
1064
  dataset: string;
1061
1065
  /** Present iff the handle is `resource`-configured. */
1062
1066
  resource?: TestClientResource;
@@ -1170,6 +1174,15 @@ export declare interface TestClient {
1170
1174
  addIdentity: (token: string, identity: TestClientIdentity) => void;
1171
1175
  /** Snapshot of the registered token→identity entries. */
1172
1176
  identities: () => Record<string, TestClientIdentity>;
1177
+ /**
1178
+ * Revoke a registered token, as when it expires or is deleted: it stays
1179
+ * registered and still binds, but from the next request on every Content
1180
+ * Lake and platform request made with it (on any handle) rejects with the
1181
+ * platform's 401 `Session not found`, and nothing is written. Revocation
1182
+ * is permanent for the family; `addIdentity` does not restore it. Unknown
1183
+ * tokens throw.
1184
+ */
1185
+ revokeIdentity: (token: string) => void;
1173
1186
  /**
1174
1187
  * Every mutation committed through this client's registry, flattened
1175
1188
  * and in order — `create` / `createOrReplace` / `createIfNotExists` /
package/dist/index.js CHANGED
@@ -22,8 +22,12 @@ function clientErrorMessage(args) {
22
22
  const { body } = args;
23
23
  if (isRecord(body)) {
24
24
  const { error, message } = body;
25
- if (isRecord(error) && typeof error.description == "string") return error.description;
26
- if (typeof message == "string") return message;
25
+ if (typeof error == "string" && typeof message == "string") return `${error} - ${message}`;
26
+ if (typeof error == "string") return error;
27
+ if (isRecord(error)) {
28
+ if (typeof error.description == "string") return error.description;
29
+ } else if (typeof message == "string")
30
+ return message;
27
31
  }
28
32
  const details = typeof body == "string" ? ` (${body.length > 100 ? `${body.slice(0, 100)}\u2026` : body})` : "";
29
33
  return `${args.method}-request to ${args.path} resulted in HTTP ${args.statusCode} ${args.statusMessage}${details}`;
@@ -44,7 +48,17 @@ function accessApiError(args) {
44
48
  body: { statusCode, error: statusMessage, message }
45
49
  });
46
50
  }
47
- const noPermission = (request) => accessApiError({
51
+ const sessionNotFound = (request) => new PlatformHttpError({
52
+ ...request,
53
+ statusCode: 401,
54
+ statusMessage: "Unauthorized",
55
+ body: {
56
+ error: "Unauthorized",
57
+ errorCode: "SIO-401-ANF",
58
+ message: "Session not found",
59
+ statusCode: 401
60
+ }
61
+ }), noPermission = (request) => accessApiError({
48
62
  request,
49
63
  statusCode: 403,
50
64
  statusMessage: "Forbidden",
@@ -1277,7 +1291,7 @@ function requireActive(release) {
1277
1291
  `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.`
1278
1292
  );
1279
1293
  }
1280
- async function applyAction(store, action, hooks) {
1294
+ async function applyAction(store, action) {
1281
1295
  switch (action.actionType) {
1282
1296
  case "sanity.action.release.create": {
1283
1297
  if (maybeRelease(store, action.releaseId) !== void 0)
@@ -1381,7 +1395,7 @@ async function applyAction(store, action, hooks) {
1381
1395
  return store.remove(release._id), { transactionId: cryptoRandomKey() };
1382
1396
  }
1383
1397
  case "sanity.action.document.version.create": {
1384
- if ("baseId" in action) return createVersionFromBase(store, action, hooks);
1398
+ if ("baseId" in action) return createVersionFromBase(store, action);
1385
1399
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
1386
1400
  if (releaseId === void 0)
1387
1401
  throw fakeError(
@@ -1393,7 +1407,7 @@ async function applyAction(store, action, hooks) {
1393
1407
  ...action.document,
1394
1408
  _id: vid
1395
1409
  }, existing = store.get(vid), promoted = promote(doc);
1396
- return existing !== void 0 && (promoted._createdAt = existing._createdAt), await hooks?.gate?.(existing ?? promoted, existing === void 0 ? "create" : "update"), store.put(promoted), { transactionId: cryptoRandomKey() };
1410
+ return existing !== void 0 && (promoted._createdAt = existing._createdAt), store.put(promoted), { transactionId: cryptoRandomKey() };
1397
1411
  }
1398
1412
  case "sanity.action.document.version.replace": {
1399
1413
  const id = action.document._id;
@@ -1430,7 +1444,7 @@ async function applyAction(store, action, hooks) {
1430
1444
  const published = store.get(action.publishedId);
1431
1445
  requireRevisionMatch(action.draftId, draft._rev, action.ifDraftRevisionId), requireRevisionMatch(action.publishedId, published?._rev, action.ifPublishedRevisionId);
1432
1446
  const promoted = promote({ ...draft, _id: action.publishedId });
1433
- 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() };
1447
+ return published !== void 0 && (promoted._createdAt = published._createdAt), store.put(promoted), store.remove(action.draftId), { transactionId: cryptoRandomKey() };
1434
1448
  }
1435
1449
  case "sanity.action.document.unpublish": {
1436
1450
  requireDraftOf(action);
@@ -1439,7 +1453,7 @@ async function applyAction(store, action, hooks) {
1439
1453
  throw fakeError(
1440
1454
  `Cannot unpublish "${action.publishedId}": no published document with that _id exists. document.unpublish retracts a live published document into "${action.draftId}".`
1441
1455
  );
1442
- if (await hooks?.gate?.(published, "update"), store.get(action.draftId) === void 0) {
1456
+ if (store.get(action.draftId) === void 0) {
1443
1457
  const draft = promote({ ...published, _id: action.draftId });
1444
1458
  draft._createdAt = published._createdAt, store.put(draft);
1445
1459
  }
@@ -1453,7 +1467,7 @@ function requireDraftOf(action) {
1453
1467
  `${action.actionType}: draftId "${action.draftId}" is not the draft of publishedId "${action.publishedId}" \u2014 expected draftId "drafts.${action.publishedId}".`
1454
1468
  );
1455
1469
  }
1456
- async function createVersionFromBase(store, action, hooks) {
1470
+ async function createVersionFromBase(store, action) {
1457
1471
  const { releaseId, publishedId } = parseVersionId(action.versionId);
1458
1472
  if (publishedId !== action.publishedId)
1459
1473
  throw fakeError(
@@ -1472,7 +1486,7 @@ async function createVersionFromBase(store, action, hooks) {
1472
1486
  _createdAt: existing?._createdAt ?? nowIso(),
1473
1487
  _system: { base: { id: base._id, rev: base._rev } }
1474
1488
  }, promoted = promote(copy);
1475
- return await hooks?.gate?.(existing ?? promoted, existing === void 0 ? "create" : "update"), store.put(promoted), { transactionId: cryptoRandomKey() };
1489
+ return store.put(promoted), { transactionId: cryptoRandomKey() };
1476
1490
  }
1477
1491
  function requireRevisionMatch(documentId, actualRev, expectedRev) {
1478
1492
  if (!(expectedRev === void 0 || actualRev === expectedRev))
@@ -1484,7 +1498,7 @@ function requireRevisionMatch(documentId, actualRev, expectedRev) {
1484
1498
  );
1485
1499
  }
1486
1500
  async function applyActions(store, actions, hooks) {
1487
- const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), remember = (id) => {
1501
+ const list = Array.isArray(actions) ? actions : [actions], snapshot = /* @__PURE__ */ new Map(), guardedIds = /* @__PURE__ */ new Set(), gatedIds = /* @__PURE__ */ new Set(), remember = (id) => {
1488
1502
  snapshot.has(id) || snapshot.set(id, store.get(id));
1489
1503
  };
1490
1504
  try {
@@ -1497,9 +1511,15 @@ async function applyActions(store, actions, hooks) {
1497
1511
  case "sanity.action.release.unschedule":
1498
1512
  case "sanity.action.release.archive":
1499
1513
  case "sanity.action.release.unarchive":
1500
- case "sanity.action.release.delete":
1501
1514
  remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
1502
1515
  break;
1516
+ case "sanity.action.release.delete": {
1517
+ remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
1518
+ const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;
1519
+ for (const d of store.all())
1520
+ d._id.startsWith(prefix) && remember(d._id);
1521
+ break;
1522
+ }
1503
1523
  case "sanity.action.release.publish": {
1504
1524
  remember(`${RELEASE_DOC_PREFIX}${a.releaseId}`);
1505
1525
  const prefix = `${VERSIONS_PREFIX}${a.releaseId}.`;
@@ -1509,11 +1529,11 @@ async function applyActions(store, actions, hooks) {
1509
1529
  }
1510
1530
  case "sanity.action.document.version.create": {
1511
1531
  if ("baseId" in a) {
1512
- remember(a.versionId);
1532
+ remember(a.versionId), gatedIds.add(a.versionId);
1513
1533
  break;
1514
1534
  }
1515
1535
  const releaseId = a.releaseId ?? (typeof a.document._id == "string" ? parseVersionId(a.document._id).releaseId : void 0);
1516
- releaseId !== void 0 && remember(versionDocId(releaseId, a.publishedId));
1536
+ releaseId !== void 0 && (remember(versionDocId(releaseId, a.publishedId)), gatedIds.add(versionDocId(releaseId, a.publishedId)));
1517
1537
  break;
1518
1538
  }
1519
1539
  case "sanity.action.document.version.replace":
@@ -1524,13 +1544,17 @@ async function applyActions(store, actions, hooks) {
1524
1544
  remember(a.versionId);
1525
1545
  break;
1526
1546
  case "sanity.action.document.publish":
1527
- remember(a.draftId), remember(a.publishedId), guardedIds.add(a.publishedId), guardedIds.add(a.draftId);
1547
+ remember(a.draftId), remember(a.publishedId), guardedIds.add(a.publishedId), guardedIds.add(a.draftId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
1528
1548
  break;
1529
1549
  case "sanity.action.document.unpublish":
1530
- remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId);
1550
+ remember(a.draftId), remember(a.publishedId), guardedIds.add(a.draftId), guardedIds.add(a.publishedId), gatedIds.add(a.publishedId), gatedIds.add(a.draftId);
1531
1551
  break;
1532
1552
  }
1533
- last = await applyAction(store, a, hooks);
1553
+ last = await applyAction(store, a);
1554
+ }
1555
+ for (const id of gatedIds) {
1556
+ const before = snapshot.get(id), after = store.get(id);
1557
+ before !== after && await hooks?.gate?.(before, after);
1534
1558
  }
1535
1559
  const contexts = mutationContexts(
1536
1560
  [...guardedIds].map((id) => ({ before: snapshot.get(id), after: store.get(id) }))
@@ -1824,6 +1848,7 @@ function createTestClient(options = {}) {
1824
1848
  calls: [],
1825
1849
  concurrentEdits: /* @__PURE__ */ new Map(),
1826
1850
  identities: new Map(Object.entries(options.identities ?? {})),
1851
+ revoked: /* @__PURE__ */ new Set(),
1827
1852
  writeChain: Promise.resolve()
1828
1853
  }, registry = backend.registry;
1829
1854
  if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
@@ -1848,7 +1873,8 @@ function createTestClient(options = {}) {
1848
1873
  requestTagPrefix: options.requestTagPrefix,
1849
1874
  mutationGuard: options.mutationGuard,
1850
1875
  token: options.token,
1851
- useProjectHostname: options.useProjectHostname ?? !0
1876
+ useProjectHostname: options.useProjectHostname ?? !0,
1877
+ hasProjectId: options.projectId !== void 0
1852
1878
  });
1853
1879
  }
1854
1880
  function dedupeIds(results) {
@@ -1911,7 +1937,7 @@ function makeHandle(handleArgs) {
1911
1937
  mutationGuard,
1912
1938
  token,
1913
1939
  useProjectHostname
1914
- } = handleArgs, { registry } = backend, { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
1940
+ } = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
1915
1941
  if (token === void 0) return accessControl;
1916
1942
  const identity = backend.identities.get(token);
1917
1943
  if (identity === void 0)
@@ -1928,7 +1954,10 @@ function makeHandle(handleArgs) {
1928
1954
  if (access === void 0)
1929
1955
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
1930
1956
  return access;
1931
- }, admitToLake = (request) => {
1957
+ }, refuseRevoked = (request) => {
1958
+ if (token !== void 0 && backend.revoked.has(token)) throw sessionNotFound(request);
1959
+ }, withSession = (request) => async (opts) => (refuseRevoked({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
1960
+ refuseRevoked(request);
1932
1961
  const access = activeAccess();
1933
1962
  if (access === void 0) return;
1934
1963
  const refusal = refusedToken(request, access.grants);
@@ -2008,14 +2037,21 @@ function makeHandle(handleArgs) {
2008
2037
  throw fakeError(
2009
2038
  `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.)`
2010
2039
  );
2011
- }, gate = async (document, permission) => {
2040
+ }, gate = async (prev, next) => {
2012
2041
  const access = activeAccess();
2013
- access !== void 0 && await enforceWriteAccess({
2014
- document,
2015
- grants: access.grants,
2016
- permission: document._id !== void 0 && isSystemId(document._id) ? "manage" : permission,
2017
- userId: actorId()
2018
- });
2042
+ if (access === void 0) return;
2043
+ const id = (prev ?? next)?._id;
2044
+ if (id === void 0) return;
2045
+ const required = isSystemId(id) ? ["manage"] : [];
2046
+ required.push(prev === void 0 ? "create" : "update");
2047
+ for (const permission of required)
2048
+ for (const document of [prev, next])
2049
+ document !== void 0 && await enforceWriteAccess({
2050
+ document,
2051
+ grants: access.grants,
2052
+ permission,
2053
+ userId: actorId()
2054
+ });
2019
2055
  }, guardGate = async (contexts) => {
2020
2056
  const identity = actorId();
2021
2057
  await enforceMutationGuards(
@@ -2038,13 +2074,13 @@ function makeHandle(handleArgs) {
2038
2074
  throw fakeError(
2039
2075
  `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.`
2040
2076
  );
2041
- checkRevision(documentId, ifRev), await gate(existing, "update");
2077
+ checkRevision(documentId, ifRev);
2042
2078
  const patched = applyPatchOps(existing, ops), now = (/* @__PURE__ */ new Date()).toISOString(), next = {
2043
2079
  ...patched,
2044
2080
  _rev: cryptoRandomKey(),
2045
2081
  _updatedAt: now
2046
2082
  };
2047
- return options.evaluateGuard !== !1 && await guardOne("update", existing, next), store.put(next), next;
2083
+ return options.inTransaction !== !0 && (await gate(existing, next), await guardOne("update", existing, next)), store.put(next), next;
2048
2084
  }, applyTransaction = async (mutations, txnOptions) => {
2049
2085
  const transactionId = txnOptions?.transactionId ?? cryptoRandomKey(), snapshot = /* @__PURE__ */ new Map(), touchedIds = [], operations = [], remember = (id) => {
2050
2086
  snapshot.has(id) || snapshot.set(id, store.get(id));
@@ -2059,39 +2095,35 @@ function makeHandle(handleArgs) {
2059
2095
  throw fakeError(
2060
2096
  `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.`
2061
2097
  );
2062
- await gate(promoted, "create"), store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2098
+ store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2063
2099
  break;
2064
2100
  }
2065
2101
  case "createOrReplace": {
2066
2102
  remember(mut.doc._id);
2067
- const promoted = promote2(mut.doc), existing = store.get(promoted._id);
2068
- await gate(existing ?? promoted, existing !== void 0 ? "update" : "create");
2069
- const wasPresent = existing !== void 0;
2103
+ const promoted = promote2(mut.doc), wasPresent = store.get(promoted._id) !== void 0;
2070
2104
  store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: wasPresent ? "update" : "create" });
2071
2105
  break;
2072
2106
  }
2073
2107
  case "createIfNotExists": {
2074
2108
  if (remember(mut.doc._id), store.get(mut.doc._id) === void 0) {
2075
2109
  const promoted = promote2(mut.doc);
2076
- await gate(promoted, "create"), store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2110
+ store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
2077
2111
  }
2078
2112
  break;
2079
2113
  }
2080
2114
  case "delete": {
2081
- remember(mut.id);
2082
- const existing = store.get(mut.id);
2083
- existing !== void 0 && await gate(existing, "update"), store.remove(mut.id) && (touchedIds.push(mut.id), operations.push({ id: mut.id, operation: "delete" }));
2115
+ remember(mut.id), store.remove(mut.id) && (touchedIds.push(mut.id), operations.push({ id: mut.id, operation: "delete" }));
2084
2116
  break;
2085
2117
  }
2086
2118
  case "patch": {
2087
- remember(mut.documentId), await applyPatch(mut.documentId, mut.ops, mut.ifRev, { evaluateGuard: !1 }), touchedIds.push(mut.documentId), operations.push({ id: mut.documentId, operation: "update" });
2119
+ remember(mut.documentId), await applyPatch(mut.documentId, mut.ops, mut.ifRev, { inTransaction: !0 }), touchedIds.push(mut.documentId), operations.push({ id: mut.documentId, operation: "update" });
2088
2120
  break;
2089
2121
  }
2090
2122
  }
2091
- const contexts = mutationContexts(
2092
- [...snapshot].map(([id, before]) => ({ before, after: store.get(id) }))
2093
- );
2094
- await guardGate(contexts);
2123
+ const images = [...snapshot].map(([id, before]) => ({ before, after: store.get(id) }));
2124
+ for (const { before, after } of images)
2125
+ before !== after && await gate(before, after);
2126
+ await guardGate(mutationContexts(images));
2095
2127
  } catch (error) {
2096
2128
  for (const [id, doc] of snapshot)
2097
2129
  doc === void 0 ? store.remove(id) : store.put(doc);
@@ -2111,7 +2143,7 @@ function makeHandle(handleArgs) {
2111
2143
  method: "POST",
2112
2144
  path: `${capabilities.dataBase(target.id)}/actions`
2113
2145
  };
2114
- if (capabilities.actions !== "served") throw capabilities.actions(request);
2146
+ if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
2115
2147
  return write(async () => {
2116
2148
  for (const action of Array.isArray(actions) ? actions : [actions]) {
2117
2149
  const refused = capabilities.refusedActions[action.actionType];
@@ -2174,7 +2206,7 @@ function makeHandle(handleArgs) {
2174
2206
  `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.`
2175
2207
  );
2176
2208
  const promoted = promote2(doc);
2177
- await gate(promoted, "create"), await guardOne("create", null, promoted);
2209
+ await gate(void 0, promoted), await guardOne("create", null, promoted);
2178
2210
  const transactionId = opts?.transactionId ?? cryptoRandomKey();
2179
2211
  return opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "create", doc }], opts?.tag)), writeResult(
2180
2212
  [promoted],
@@ -2186,7 +2218,7 @@ function makeHandle(handleArgs) {
2186
2218
  createOrReplace: (doc, opts) => write(async () => {
2187
2219
  checkRevision(doc._id, opts?.ifRevisionId);
2188
2220
  const promoted = promote2(doc), existing = store.get(doc._id);
2189
- await gate(existing ?? promoted, existing !== void 0 ? "update" : "create"), await guardOne(existing !== void 0 ? "update" : "create", existing ?? null, promoted);
2221
+ await gate(existing, promoted), await guardOne(existing !== void 0 ? "update" : "create", existing ?? null, promoted);
2190
2222
  const transactionId = opts?.transactionId ?? cryptoRandomKey();
2191
2223
  opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createOrReplace", doc }], opts?.tag));
2192
2224
  const operation = existing !== void 0 ? "update" : "create";
@@ -2208,7 +2240,7 @@ function makeHandle(handleArgs) {
2208
2240
  opts
2209
2241
  );
2210
2242
  const promoted = promote2(doc);
2211
- return await gate(promoted, "create"), await guardOne("create", null, promoted), opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createIfNotExists", doc }], opts?.tag)), writeResult(
2243
+ 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(
2212
2244
  [promoted],
2213
2245
  [{ id: promoted._id, operation: "create" }],
2214
2246
  transactionId,
@@ -2218,7 +2250,7 @@ function makeHandle(handleArgs) {
2218
2250
  delete: (id, opts) => write(async () => {
2219
2251
  checkRevision(id, opts?.ifRevisionId);
2220
2252
  const existing = store.get(id);
2221
- existing !== void 0 && await gate(existing, "update"), existing !== void 0 && await guardOne("delete", existing, null);
2253
+ existing !== void 0 && await gate(existing, void 0), existing !== void 0 && await guardOne("delete", existing, null);
2222
2254
  const transactionId = opts?.transactionId ?? cryptoRandomKey();
2223
2255
  let removed = existing;
2224
2256
  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(
@@ -2315,36 +2347,38 @@ function makeHandle(handleArgs) {
2315
2347
  publishedId
2316
2348
  }),
2317
2349
  ...token !== void 0 || accessControl !== void 0 ? {
2318
- request: makeRequestImpl({
2319
- getAccess: requireActiveAccess,
2320
- // `@sanity/client` sends every request of a `resource`-configured
2321
- // client to the global API host.
2322
- useProjectHostname: useProjectHostname && resource === void 0,
2323
- organizationId: backend.organizationId,
2324
- listIdentities: members,
2325
- platform: {
2326
- projectId,
2350
+ request: withSession(
2351
+ makeRequestImpl({
2352
+ getAccess: requireActiveAccess,
2353
+ // `@sanity/client` sends every request of a `resource`-configured
2354
+ // client to the global API host.
2355
+ useProjectHostname: useProjectHostname && resource === void 0,
2327
2356
  organizationId: backend.organizationId,
2328
- projectFeatures: backend.projectFeatures,
2329
- own: (asked) => registryKey(asked) === registryKey(target) ? {
2330
- grants: requireActiveAccess().grants,
2331
- documents: () => store.all(),
2332
- history,
2333
- canRead,
2334
- admitToLake
2335
- } : void 0,
2336
- actorUser: () => {
2337
- const access = requireActiveAccess();
2338
- return access.globalUser ?? access.currentUser;
2339
- },
2340
- actorAccess: () => requireActiveAccess().access,
2341
- identities: members,
2342
- resources: () => [...registry.values()].map((entry) => entry.resource)
2343
- }
2344
- })
2357
+ listIdentities: members,
2358
+ platform: {
2359
+ projectId,
2360
+ organizationId: backend.organizationId,
2361
+ projectFeatures: backend.projectFeatures,
2362
+ own: (asked) => registryKey(asked) === registryKey(target) ? {
2363
+ grants: requireActiveAccess().grants,
2364
+ documents: () => store.all(),
2365
+ history,
2366
+ canRead,
2367
+ admitToLake
2368
+ } : void 0,
2369
+ actorUser: () => {
2370
+ const access = requireActiveAccess();
2371
+ return access.globalUser ?? access.currentUser;
2372
+ },
2373
+ actorAccess: () => requireActiveAccess().access,
2374
+ identities: members,
2375
+ resources: () => [...registry.values()].map((entry) => entry.resource)
2376
+ }
2377
+ })
2378
+ )
2345
2379
  } : {},
2346
2380
  config: () => ({
2347
- projectId,
2381
+ ...hasProjectId || resource !== void 0 ? { projectId } : {},
2348
2382
  dataset,
2349
2383
  ...resource !== void 0 ? { resource } : {},
2350
2384
  perspective,
@@ -2365,7 +2399,8 @@ function makeHandle(handleArgs) {
2365
2399
  requestTagPrefix: config.requestTagPrefix ?? requestTagPrefix,
2366
2400
  mutationGuard,
2367
2401
  token: rebinds ? config.token : token,
2368
- useProjectHostname: config.useProjectHostname ?? useProjectHostname
2402
+ useProjectHostname: config.useProjectHostname ?? useProjectHostname,
2403
+ hasProjectId: hasProjectId || config.projectId !== void 0
2369
2404
  });
2370
2405
  },
2371
2406
  seed: (documents) => store.seed(documents),
@@ -2387,6 +2422,9 @@ function makeHandle(handleArgs) {
2387
2422
  backend.identities.set(identityToken, identity);
2388
2423
  },
2389
2424
  identities: () => Object.fromEntries(backend.identities),
2425
+ revokeIdentity: (revokedToken) => {
2426
+ requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
2427
+ },
2390
2428
  mutations: () => backend.log.flatMap((entry) => entry.mutations),
2391
2429
  transactions: () => [...backend.log],
2392
2430
  clearLog: () => {