@sanity-labs/client-fake-for-test 0.2.0 → 0.3.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
@@ -1,4 +1,8 @@
1
1
  import { parse, evaluate } from "groq-js";
2
+ const ERR_PREFIX = "[client-fake-for-test]";
3
+ function fakeError(message) {
4
+ return new Error(`${ERR_PREFIX} ${message}`);
5
+ }
2
6
  class WriteAccessDeniedError extends Error {
3
7
  documentId;
4
8
  permission;
@@ -63,17 +67,21 @@ function makeRequestImpl(accessControl, projectId, dataset) {
63
67
  return accessControl.currentUser;
64
68
  if (path === aclPath)
65
69
  return accessControl.grants;
66
- throw new Error(
67
- `TestClient.request: no handler for path "${path}". The TestClient only serves "/users/me" and "${aclPath}". Configure additional endpoints via createTestClient({ accessControl }).`
70
+ throw fakeError(
71
+ `request(): no handler for path "${path}". With accessControl configured, the fake only serves "/users/me" and "${aclPath}". For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
68
72
  );
69
73
  };
70
74
  }
71
75
  function createTestStore(initial) {
72
76
  const docs = /* @__PURE__ */ new Map(), promote2 = (doc) => {
73
77
  if (typeof doc._id != "string" || doc._id.length === 0)
74
- throw new Error(`document is missing _id: ${JSON.stringify(doc)}`);
78
+ throw fakeError(
79
+ `Cannot seed/store a document without a non-empty string \`_id\` (got ${JSON.stringify(doc._id)}). This fake never auto-generates ids \u2014 give every document an explicit _id. Document: ${JSON.stringify(doc)}`
80
+ );
75
81
  if (typeof doc._type != "string" || doc._type.length === 0)
76
- throw new Error(`document ${doc._id} is missing _type`);
82
+ throw fakeError(
83
+ `Document "${doc._id}" is missing a non-empty string \`_type\` (got ${JSON.stringify(doc._type)}). Every Sanity document needs a _type.`
84
+ );
77
85
  const now = (/* @__PURE__ */ new Date()).toISOString();
78
86
  return {
79
87
  ...doc,
@@ -115,6 +123,9 @@ function cryptoRandomKey(length = 12) {
115
123
  const bytes = new Uint8Array(length);
116
124
  return globalThis.crypto.getRandomValues(bytes), [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, length);
117
125
  }
126
+ function describeType(value) {
127
+ return value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`;
128
+ }
118
129
  function createPatch(documentId, executor) {
119
130
  const ops = [];
120
131
  let ifRev;
@@ -175,7 +186,10 @@ function parsePath(path) {
175
186
  const segments = [];
176
187
  for (const raw of path.split(".")) {
177
188
  const match = /^([A-Za-z_$][\w$]*)(?:\[(.+)\])?$/.exec(raw);
178
- if (!match) throw new Error(`Unsupported patch path segment: ${raw}`);
189
+ if (!match)
190
+ throw fakeError(
191
+ `Unsupported patch path segment "${raw}" (in path "${path}"). This fake supports dotted field access ("a.b.c"), array index ("items[0]"), and keyed lookup (\`items[_key=="x"]\`). Recursive descent ("..") and GROQ filter expressions are not supported.`
192
+ );
179
193
  const key = match[1], selectorRaw = match[2];
180
194
  if (selectorRaw === void 0) {
181
195
  segments.push({ key });
@@ -194,7 +208,9 @@ function parsePath(path) {
194
208
  });
195
209
  continue;
196
210
  }
197
- throw new Error(`Unsupported array selector in patch path: ${selectorRaw}`);
211
+ throw fakeError(
212
+ `Unsupported array selector "[${selectorRaw}]" in patch path "${path}". Supported selectors are a numeric index (e.g. "[0]") and a single keyed match (e.g. \`[_key=="abc"]\`). Multi-key matches and arbitrary GROQ filters are not supported.`
213
+ );
198
214
  }
199
215
  return segments;
200
216
  }
@@ -204,7 +220,9 @@ function resolveSelector(array, selector) {
204
220
  (entry) => typeof entry == "object" && entry !== null && entry[selector.field] === selector.value
205
221
  );
206
222
  if (idx === -1)
207
- throw new Error(`No array entry matched ${selector.field}=="${selector.value}" in patch path`);
223
+ throw fakeError(
224
+ `Patch path matched no array entry where ${selector.field}=="${selector.value}". The array has ${array.length} item(s); check the key exists (and that you're patching the right document).`
225
+ );
208
226
  return idx;
209
227
  }
210
228
  function getAtPath(doc, path) {
@@ -222,14 +240,17 @@ function getAtPath(doc, path) {
222
240
  }
223
241
  function setAtPath(doc, path, value) {
224
242
  const segments = parsePath(path);
225
- if (segments.length === 0) throw new Error("Empty patch path");
243
+ if (segments.length === 0)
244
+ throw fakeError("Empty patch path \u2014 a set/setIfMissing op needs a target field.");
226
245
  let cursor = doc;
227
246
  for (let i = 0; i < segments.length - 1; i++) {
228
247
  const seg = segments[i];
229
248
  let next = cursor[seg.key];
230
249
  if (next === void 0 && (next = seg.selector?.kind === "index" || seg.selector?.kind === "keyed" ? [] : {}, cursor[seg.key] = next), seg.selector !== void 0) {
231
250
  if (!Array.isArray(next))
232
- throw new Error(`Patch path crosses non-array at segment ${seg.key}`);
251
+ throw fakeError(
252
+ `Patch path "${path}" applies an array selector to field "${seg.key}", but that field holds ${describeType(next)}, not an array.`
253
+ );
233
254
  const idx = resolveSelector(next, seg.selector);
234
255
  cursor = next[idx];
235
256
  } else
@@ -239,7 +260,9 @@ function setAtPath(doc, path, value) {
239
260
  if (last.selector !== void 0) {
240
261
  const arr = cursor[last.key];
241
262
  if (!Array.isArray(arr))
242
- throw new Error(`Patch path crosses non-array at segment ${last.key}`);
263
+ throw fakeError(
264
+ `Patch path "${path}" applies an array selector to field "${last.key}", but that field holds ${describeType(arr)}, not an array.`
265
+ );
243
266
  const idx = resolveSelector(arr, last.selector);
244
267
  arr[idx] = value;
245
268
  } else
@@ -271,41 +294,56 @@ function unsetAtPath(doc, path) {
271
294
  }
272
295
  function insertIntoArray(doc, position, anchor, items) {
273
296
  const segments = parsePath(anchor);
274
- if (segments.length === 0) throw new Error("Empty insert anchor");
297
+ if (segments.length === 0)
298
+ throw fakeError("Empty insert anchor \u2014 insert() needs an array path to anchor against.");
275
299
  const last = segments[segments.length - 1];
276
300
  if (last.selector === void 0)
277
- throw new Error(`Insert anchor must end with an array selector: ${anchor}`);
301
+ throw fakeError(
302
+ `Insert anchor "${anchor}" must end with an array selector (an index like "[0]" or a keyed match like \`[_key=="x"]\`) so the fake knows where in the array to insert.`
303
+ );
278
304
  let cursor = doc;
279
305
  for (let i = 0; i < segments.length - 1; i++) {
280
306
  const seg = segments[i], next = cursor[seg.key];
281
307
  if (next == null)
282
- throw new Error(`Insert anchor traverses missing field: ${seg.key}`);
308
+ throw fakeError(
309
+ `Insert anchor "${anchor}" traverses field "${seg.key}", which is missing on the document. setIfMissing the parent first, or anchor against an existing array.`
310
+ );
283
311
  if (seg.selector !== void 0) {
284
312
  if (!Array.isArray(next))
285
- throw new Error(`Insert anchor traverses non-array at: ${seg.key}`);
313
+ throw fakeError(
314
+ `Insert anchor "${anchor}" applies an array selector to field "${seg.key}", but it holds ${describeType(next)}, not an array.`
315
+ );
286
316
  cursor = next[resolveSelector(next, seg.selector)];
287
317
  } else
288
318
  cursor = next;
289
319
  }
290
320
  const arr = cursor[last.key];
291
321
  if (!Array.isArray(arr))
292
- throw new Error(`Insert anchor target is not an array: ${last.key}`);
322
+ throw fakeError(
323
+ `Insert anchor "${anchor}" targets field "${last.key}", but it holds ${describeType(arr)}, not an array.`
324
+ );
293
325
  const idx = resolveSelector(arr, last.selector);
294
326
  position === "replace" ? arr.splice(idx, 1, ...items) : position === "before" ? arr.splice(idx, 0, ...items) : arr.splice(idx + 1, 0, ...items);
295
327
  }
296
328
  const RELEASE_DOC_PREFIX$1 = "_.releases.", VERSIONS_PREFIX$1 = "versions.", releaseDocId = (releaseId) => `${RELEASE_DOC_PREFIX$1}${releaseId}`, versionDocId = (releaseId, publishedId) => `${VERSIONS_PREFIX$1}${releaseId}.${publishedId}`;
297
329
  function parseVersionId(versionId) {
298
330
  if (!versionId.startsWith(VERSIONS_PREFIX$1))
299
- throw new Error(`Not a version id: ${versionId}`);
331
+ throw fakeError(
332
+ `"${versionId}" is not a version document id. Version ids look like "versions.<releaseId>.<publishedId>" (e.g. "versions.summer-drop.product-1").`
333
+ );
300
334
  const rest = versionId.slice(VERSIONS_PREFIX$1.length), dot = rest.indexOf(".");
301
335
  if (dot === -1)
302
- throw new Error(`Not a version id: ${versionId}`);
336
+ throw fakeError(
337
+ `"${versionId}" is not a version document id. Version ids look like "versions.<releaseId>.<publishedId>" (e.g. "versions.summer-drop.product-1").`
338
+ );
303
339
  return { releaseId: rest.slice(0, dot), publishedId: rest.slice(dot + 1) };
304
340
  }
305
341
  function getRelease(store, releaseId) {
306
342
  const doc = store.get(releaseDocId(releaseId));
307
343
  if (doc === void 0)
308
- throw new Error(`Release not found: ${releaseId}`);
344
+ throw fakeError(
345
+ `Release "${releaseId}" not found. Create it first with client.releases.create({ releaseId: "${releaseId}" }) (or a "sanity.action.release.create" action) before editing, scheduling, or adding versions to it.`
346
+ );
309
347
  return doc;
310
348
  }
311
349
  function maybeRelease(store, releaseId) {
@@ -335,15 +373,17 @@ function bumpRev(doc, patch) {
335
373
  }
336
374
  function requireActive(release) {
337
375
  if (release.state !== "active")
338
- throw new Error(
339
- `Release ${release.name} is ${release.state}; only active releases accept version writes`
376
+ throw fakeError(
377
+ `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.`
340
378
  );
341
379
  }
342
380
  function applyAction(store, action) {
343
381
  switch (action.actionType) {
344
382
  case "sanity.action.release.create": {
345
383
  if (maybeRelease(store, action.releaseId) !== void 0)
346
- throw new Error(`Release ${action.releaseId} already exists`);
384
+ throw fakeError(
385
+ `Release "${action.releaseId}" already exists. release.create expects a new releaseId; use release.edit to change its metadata, or pick a different releaseId.`
386
+ );
347
387
  const now = nowIso(), metadata = {
348
388
  releaseType: "undecided",
349
389
  ...action.metadata
@@ -368,7 +408,9 @@ function applyAction(store, action) {
368
408
  case "sanity.action.release.schedule": {
369
409
  const release = getRelease(store, action.releaseId);
370
410
  if (release.state !== "active")
371
- throw new Error(`Cannot schedule release in state ${release.state}`);
411
+ throw fakeError(
412
+ `Cannot schedule release "${action.releaseId}": it is "${release.state}", and only "active" releases can be scheduled.`
413
+ );
372
414
  return store.put(
373
415
  bumpRev(release, {
374
416
  state: "scheduled",
@@ -379,7 +421,9 @@ function applyAction(store, action) {
379
421
  case "sanity.action.release.unschedule": {
380
422
  const release = getRelease(store, action.releaseId);
381
423
  if (release.state !== "scheduled")
382
- throw new Error(`Cannot unschedule release in state ${release.state}`);
424
+ throw fakeError(
425
+ `Cannot unschedule release "${action.releaseId}": it is "${release.state}", and only "scheduled" releases can be unscheduled.`
426
+ );
383
427
  const next = { ...release, state: "active" };
384
428
  return delete next.publishAt, store.put(bumpRev(next, {})), { transactionId: cryptoRandomKey() };
385
429
  }
@@ -388,7 +432,9 @@ function applyAction(store, action) {
388
432
  if (release.state === "published")
389
433
  return { transactionId: cryptoRandomKey() };
390
434
  if (release.state !== "active" && release.state !== "scheduled")
391
- throw new Error(`Cannot publish release in state ${release.state}`);
435
+ throw fakeError(
436
+ `Cannot publish release "${action.releaseId}": it is "${release.state}", and only "active" or "scheduled" releases can be published.`
437
+ );
392
438
  const prefix = `${VERSIONS_PREFIX$1}${action.releaseId}.`, sources = store.all().filter((d) => d._id.startsWith(prefix));
393
439
  for (const v of sources) {
394
440
  const pubId = v._id.slice(prefix.length);
@@ -410,20 +456,24 @@ function applyAction(store, action) {
410
456
  case "sanity.action.release.archive": {
411
457
  const release = getRelease(store, action.releaseId);
412
458
  if (release.state !== "active" && release.state !== "scheduled")
413
- throw new Error(`Cannot archive release in state ${release.state}`);
459
+ throw fakeError(
460
+ `Cannot archive release "${action.releaseId}": it is "${release.state}", and only "active" or "scheduled" releases can be archived.`
461
+ );
414
462
  return store.put(bumpRev(release, { state: "archived" })), { transactionId: cryptoRandomKey() };
415
463
  }
416
464
  case "sanity.action.release.unarchive": {
417
465
  const release = getRelease(store, action.releaseId);
418
466
  if (release.state !== "archived")
419
- throw new Error(`Cannot unarchive release in state ${release.state}`);
467
+ throw fakeError(
468
+ `Cannot unarchive release "${action.releaseId}": it is "${release.state}", and only "archived" releases can be unarchived.`
469
+ );
420
470
  return store.put(bumpRev(release, { state: "active" })), { transactionId: cryptoRandomKey() };
421
471
  }
422
472
  case "sanity.action.release.delete": {
423
473
  const release = getRelease(store, action.releaseId);
424
474
  if (release.state !== "archived" && release.state !== "published")
425
- throw new Error(
426
- `Cannot delete release in state ${release.state}; archive or publish it first`
475
+ throw fakeError(
476
+ `Cannot delete release "${action.releaseId}": it is "${release.state}", and only "archived" or "published" releases can be deleted. Archive it first (sanity.action.release.archive) or publish it.`
427
477
  );
428
478
  const prefix = `${VERSIONS_PREFIX$1}${action.releaseId}.`;
429
479
  for (const v of store.all())
@@ -433,7 +483,9 @@ function applyAction(store, action) {
433
483
  case "sanity.action.document.version.create": {
434
484
  const releaseId = action.releaseId ?? (action.document._id !== void 0 ? parseVersionId(action.document._id).releaseId : void 0);
435
485
  if (releaseId === void 0)
436
- throw new Error("version.create needs releaseId or a document._id that encodes it");
486
+ throw fakeError(
487
+ 'version.create needs a release to attach to: pass `releaseId`, or a `document._id` shaped "versions.<releaseId>.<publishedId>" so the release can be inferred.'
488
+ );
437
489
  const release = getRelease(store, releaseId);
438
490
  requireActive(release);
439
491
  const vid = versionDocId(releaseId, action.publishedId), doc = {
@@ -445,7 +497,9 @@ function applyAction(store, action) {
445
497
  case "sanity.action.document.version.replace": {
446
498
  const id = action.document._id;
447
499
  if (typeof id != "string")
448
- throw new Error("version.replace needs document._id");
500
+ throw fakeError(
501
+ 'version.replace needs `document._id` (a version id like "versions.<releaseId>.<publishedId>") to identify which version document to replace.'
502
+ );
449
503
  const { releaseId } = parseVersionId(id), release = getRelease(store, releaseId);
450
504
  requireActive(release);
451
505
  const existing = store.get(id), promoted = promote(action.document);
@@ -619,12 +673,193 @@ function createTransaction(executor) {
619
673
  };
620
674
  return handle;
621
675
  }
622
- const DEFAULT_PROJECT_ID = "test", DEFAULT_DATASET = "test", registryKey = (projectId, dataset) => `${projectId}:${dataset}`, parseRegistryKey = (key) => {
676
+ const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
677
+ "fetch",
678
+ "getDocument",
679
+ "getDocuments",
680
+ "create",
681
+ "createOrReplace",
682
+ "createIfNotExists",
683
+ "delete",
684
+ "patch",
685
+ "transaction",
686
+ "mutate",
687
+ "action",
688
+ "releases",
689
+ "createVersion",
690
+ "unpublishVersion",
691
+ "request (only with accessControl)",
692
+ "config",
693
+ "withConfig"
694
+ ], UNSUPPORTED_MEMBERS = {
695
+ listen: {
696
+ what: "real-time listener (returns an RxJS Observable of mutation events)",
697
+ workaround: 'Test your subscription logic in isolation, or register a fake: client.stub("listen", () => myFakeObservable).'
698
+ },
699
+ observable: {
700
+ what: "the RxJS-flavoured mirror of the client API",
701
+ workaround: "Use the Promise-based methods and wrap them with `from()` if you need an Observable."
702
+ },
703
+ clone: {
704
+ what: "clone the client with the same config",
705
+ workaround: "Use `withConfig({})` \u2014 it returns a sibling handle into the same store."
706
+ },
707
+ getUrl: {
708
+ what: "build an absolute API URL for a path",
709
+ workaround: "Hard-code the expected URL in your test, or stub it."
710
+ },
711
+ getDataUrl: {
712
+ what: "build an absolute data-API URL",
713
+ workaround: "Hard-code the expected URL in your test, or stub it."
714
+ },
715
+ assets: {
716
+ what: "asset upload / metadata namespace",
717
+ workaround: "Seed asset documents into the store directly with `seed()` / `add()`."
718
+ },
719
+ agent: {
720
+ what: "Agent Actions namespace (generate / transform / \u2026)",
721
+ workaround: 'Stub the call site: client.stub("agent", myFakeAgent).'
722
+ },
723
+ projects: {
724
+ what: "project-management namespace",
725
+ workaround: "Out of scope for a data-plane fake \u2014 stub the call site."
726
+ },
727
+ users: {
728
+ what: "user-management namespace",
729
+ workaround: "Out of scope for a data-plane fake \u2014 stub the call site."
730
+ },
731
+ live: {
732
+ what: "Live Content API namespace",
733
+ workaround: "Out of scope \u2014 stub the call site or test the consumer separately."
734
+ },
735
+ mediaLibrary: {
736
+ what: "Media Library namespace",
737
+ workaround: "Out of scope \u2014 seed documents directly or stub the call site."
738
+ },
739
+ request: {
740
+ what: "generic HTTP request hook \u2014 only wired up when accessControl is configured",
741
+ workaround: "Create the client with `accessControl` to enable request() (it serves /users/me + the ACL path), or register a stub."
742
+ },
743
+ dryRun: {
744
+ what: "not a method \u2014 did you mean the `{ dryRun }` mutation option?",
745
+ workaround: "Pass `{ dryRun: true }` as the second arg to create / mutate / delete."
746
+ }
747
+ }, PROBE_NAMES = /* @__PURE__ */ new Set([
748
+ "then",
749
+ "catch",
750
+ "finally",
751
+ "toJSON",
752
+ "asymmetricMatch",
753
+ "$$typeof",
754
+ "nodeType",
755
+ "_isMockFunction"
756
+ ]);
757
+ function guardMessage(path, detail, workaround) {
758
+ return [
759
+ `[client-fake-for-test] \`client.${path}\` ${detail}`,
760
+ "",
761
+ "This is an in-memory fake of @sanity/client. It implements:",
762
+ ` ${SUPPORTED_SURFACE.join(", ")}.`,
763
+ "",
764
+ `\u2192 ${workaround}`,
765
+ "",
766
+ `Register a stub to fill any gap: client.stub(${JSON.stringify(path.split(".")[0])}, handler)`,
767
+ `If this should be supported, open an issue: ${ISSUES_URL}`
768
+ ].join(`
769
+ `);
770
+ }
771
+ function makeGuard(path, message) {
772
+ const thrower = () => {
773
+ throw new Error(message);
774
+ };
775
+ return new Proxy(thrower, {
776
+ apply: () => thrower(),
777
+ get: (_t, prop) => {
778
+ if (typeof prop == "symbol" || PROBE_NAMES.has(prop)) return;
779
+ const childPath = `${path}.${String(prop)}`, top = path.split(".")[0], entry = UNSUPPORTED_MEMBERS[top], detail = entry ? `is not implemented (${entry.what}).` : "is not implemented.", workaround = entry?.workaround ?? "Register a stub or use a different test strategy.";
780
+ return makeGuard(childPath, guardMessage(childPath, detail, workaround));
781
+ }
782
+ });
783
+ }
784
+ function wrapRecorded(method, fn, onCall) {
785
+ return (...args) => {
786
+ const settle = onCall(method, args);
787
+ try {
788
+ const out = fn(...args);
789
+ return out !== null && typeof out == "object" && typeof out.then == "function" ? out.then(
790
+ (result) => (settle({ result }), result),
791
+ (error) => {
792
+ throw settle({ error }), error;
793
+ }
794
+ ) : (settle({ result: out }), out);
795
+ } catch (error) {
796
+ throw settle({ error }), error;
797
+ }
798
+ };
799
+ }
800
+ function wrapNamespace(ns, prefix, onCall) {
801
+ return new Proxy(ns, {
802
+ get(target, prop, receiver) {
803
+ const value = Reflect.get(target, prop, receiver);
804
+ return typeof prop == "string" && typeof value == "function" ? wrapRecorded(`${prefix}.${prop}`, value, onCall) : value;
805
+ }
806
+ });
807
+ }
808
+ function wrapWithGuards(client, config) {
809
+ const { getStub, onCall, recorded } = config;
810
+ return new Proxy(client, {
811
+ get(target, prop, receiver) {
812
+ if (typeof prop == "symbol") return Reflect.get(target, prop, receiver);
813
+ if (prop in target) {
814
+ const value = Reflect.get(target, prop, receiver);
815
+ if (onCall !== void 0 && recorded?.has(prop) === !0) {
816
+ if (typeof value == "function")
817
+ return wrapRecorded(prop, value, onCall);
818
+ if (value !== null && typeof value == "object")
819
+ return wrapNamespace(value, prop, onCall);
820
+ }
821
+ return value;
822
+ }
823
+ if (PROBE_NAMES.has(prop)) return;
824
+ const stub = getStub(prop);
825
+ if (stub !== void 0) return stub;
826
+ const entry = UNSUPPORTED_MEMBERS[prop];
827
+ return entry !== void 0 ? makeGuard(
828
+ prop,
829
+ guardMessage(prop, `is not implemented (${entry.what}).`, entry.workaround)
830
+ ) : makeGuard(
831
+ prop,
832
+ guardMessage(
833
+ prop,
834
+ "is not a method on this fake (unknown member or unimplemented @sanity/client API).",
835
+ "Check for a typo, register a stub, or use a different test strategy."
836
+ )
837
+ );
838
+ }
839
+ });
840
+ }
841
+ const RECORDED_METHODS = /* @__PURE__ */ new Set([
842
+ "fetch",
843
+ "getDocument",
844
+ "getDocuments",
845
+ "create",
846
+ "createOrReplace",
847
+ "createIfNotExists",
848
+ "delete",
849
+ "patch",
850
+ "transaction",
851
+ "mutate",
852
+ "action",
853
+ "releases",
854
+ "createVersion",
855
+ "unpublishVersion",
856
+ "request"
857
+ ]), DEFAULT_PROJECT_ID = "test", DEFAULT_DATASET = "test", registryKey = (projectId, dataset) => `${projectId}:${dataset}`, parseRegistryKey = (key) => {
623
858
  const [projectId, dataset] = key.split(":");
624
859
  return { projectId, dataset };
625
860
  };
626
861
  function createTestClient(options = {}) {
627
- const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, registry = /* @__PURE__ */ new Map(), ensureStore = (projectId, dataset) => {
862
+ const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = { registry: /* @__PURE__ */ new Map(), log: [], stubs: /* @__PURE__ */ new Map(), calls: [] }, registry = backend.registry, ensureStore = (projectId, dataset) => {
628
863
  const key = registryKey(projectId, dataset);
629
864
  let store = registry.get(key);
630
865
  return store === void 0 && (store = createTestStore(), registry.set(key, store)), store;
@@ -635,24 +870,86 @@ function createTestClient(options = {}) {
635
870
  ensureStore(projectId, dataset).seed(docs);
636
871
  }
637
872
  return makeHandle(
638
- registry,
873
+ backend,
639
874
  defaultProjectId,
640
875
  defaultDataset,
641
876
  options.accessControl,
642
877
  options.perspective ?? "raw"
643
878
  );
644
879
  }
645
- function makeHandle(registry, projectId, dataset, accessControl, perspective) {
646
- const store = (() => {
880
+ function dedupeIds(results) {
881
+ const seen = /* @__PURE__ */ new Set(), out = [];
882
+ for (const r of results)
883
+ seen.has(r.id) || (seen.add(r.id), out.push(r.id));
884
+ return out;
885
+ }
886
+ function formatMutationResult(documents, results, transactionId, returnDocuments, returnFirst) {
887
+ return returnDocuments ? returnFirst ? documents[0] : documents : returnFirst ? {
888
+ transactionId,
889
+ documentId: results[0]?.id,
890
+ results
891
+ } : {
892
+ transactionId,
893
+ documentIds: dedupeIds(results),
894
+ results
895
+ };
896
+ }
897
+ function toSingleTxnMutation(op) {
898
+ if ("create" in op) return { kind: "create", doc: op.create };
899
+ if ("createOrReplace" in op) return { kind: "createOrReplace", doc: op.createOrReplace };
900
+ if ("createIfNotExists" in op) return { kind: "createIfNotExists", doc: op.createIfNotExists };
901
+ if ("delete" in op) return { kind: "delete", id: op.delete.id };
902
+ const p = op.patch, ops = [];
903
+ if (p.set !== void 0 && ops.push({ kind: "set", props: p.set }), p.setIfMissing !== void 0 && ops.push({ kind: "setIfMissing", props: p.setIfMissing }), p.unset !== void 0 && ops.push({ kind: "unset", paths: p.unset }), p.inc !== void 0 && ops.push({ kind: "inc", props: p.inc }), p.dec !== void 0 && ops.push({ kind: "dec", props: p.dec }), p.insert !== void 0) {
904
+ const { before, after, replace, items } = p.insert, position = before !== void 0 ? "before" : after !== void 0 ? "after" : "replace", anchor = before ?? after ?? replace;
905
+ if (anchor === void 0)
906
+ throw fakeError(
907
+ 'mutate(): a `patch.insert` operation must name exactly one anchor \u2014 `before`, `after`, or `replace` \u2014 pointing at an array path (e.g. "tags[-1]" or `tags[_key=="x"]`), alongside `items`. None was set.'
908
+ );
909
+ ops.push({ kind: "insert", position, anchor, items });
910
+ }
911
+ return {
912
+ kind: "patch",
913
+ documentId: p.id,
914
+ ops,
915
+ ...p.ifRevisionID !== void 0 ? { ifRev: p.ifRevisionID } : {}
916
+ };
917
+ }
918
+ function toTxnMutations(operations) {
919
+ if (Array.isArray(operations)) return operations.map(toSingleTxnMutation);
920
+ const json = operations.toJSON();
921
+ return Array.isArray(json) ? json : [
922
+ {
923
+ kind: "patch",
924
+ documentId: json.id,
925
+ ops: json.ops,
926
+ ...json.ifRev !== void 0 ? { ifRev: json.ifRev } : {}
927
+ }
928
+ ];
929
+ }
930
+ function makeHandle(backend, projectId, dataset, accessControl, perspective) {
931
+ const { registry } = backend, store = (() => {
647
932
  const key = registryKey(projectId, dataset);
648
933
  let s = registry.get(key);
649
934
  return s === void 0 && (s = createTestStore(), registry.set(key, s)), s;
650
- })(), promote2 = (doc) => {
935
+ })(), record = (transactionId, mutations) => {
936
+ backend.log.push({ transactionId, projectId, dataset, mutations });
937
+ }, writeResult = (documents, results, transactionId, opts) => formatMutationResult(
938
+ documents,
939
+ results,
940
+ transactionId,
941
+ opts?.returnDocuments ?? !0,
942
+ opts?.returnFirst ?? !0
943
+ ), promote2 = (doc) => {
651
944
  const now = (/* @__PURE__ */ new Date()).toISOString();
652
945
  if (typeof doc._id != "string" || doc._id.length === 0)
653
- throw new Error("document is missing _id");
946
+ throw fakeError(
947
+ `Cannot store a document without a non-empty string \`_id\` (got ${JSON.stringify(doc._id)}). Unlike @sanity/client, this fake never auto-generates ids \u2014 give every document an explicit _id.`
948
+ );
654
949
  if (typeof doc._type != "string" || doc._type.length === 0)
655
- throw new Error(`document ${doc._id} is missing _type`);
950
+ throw fakeError(
951
+ `Document "${doc._id}" is missing a non-empty string \`_type\` (got ${JSON.stringify(doc._type)}). Every Sanity document needs a _type.`
952
+ );
656
953
  return {
657
954
  ...doc,
658
955
  _id: doc._id,
@@ -665,10 +962,12 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
665
962
  if (ifRevisionId === void 0) return;
666
963
  const existing = store.get(id);
667
964
  if (existing === void 0)
668
- throw new Error(`ifRevisionId check failed: document ${id} does not exist`);
965
+ throw fakeError(
966
+ `ifRevisionId check failed: document "${id}" does not exist, so its revision cannot match the expected _rev="${ifRevisionId}". Drop ifRevisionId when creating a new document, or seed/create the document before guarding on its revision.`
967
+ );
669
968
  if (existing._rev !== ifRevisionId)
670
- throw new Error(
671
- `ifRevisionId check failed: document ${id} has _rev=${existing._rev}, expected ${ifRevisionId}`
969
+ throw fakeError(
970
+ `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.)`
672
971
  );
673
972
  }, gate = async (document, permission) => {
674
973
  accessControl !== void 0 && await enforceWriteAccess({
@@ -685,7 +984,9 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
685
984
  }), applyPatch = async (documentId, ops, ifRev) => {
686
985
  const existing = store.get(documentId);
687
986
  if (existing === void 0)
688
- throw new Error(`Cannot patch document ${documentId}: not found`);
987
+ throw fakeError(
988
+ `Cannot patch document "${documentId}": not found \u2014 no document with that _id exists in dataset "${projectId}:${dataset}". patch() requires the target to already exist; use createOrReplace() / createIfNotExists() to upsert, or seed the document first.`
989
+ );
689
990
  checkRevision(documentId, ifRev), await gate(existing, "update");
690
991
  const patched = applyPatchOps(existing, ops), now = (/* @__PURE__ */ new Date()).toISOString(), next = {
691
992
  ...patched,
@@ -694,7 +995,7 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
694
995
  };
695
996
  return store.put(next), next;
696
997
  }, applyTransaction = async (mutations, txnOptions) => {
697
- const snapshot = /* @__PURE__ */ new Map(), touchedIds = [], operations = [], remember = (id) => {
998
+ const transactionId = txnOptions?.transactionId ?? cryptoRandomKey(), snapshot = /* @__PURE__ */ new Map(), touchedIds = [], operations = [], remember = (id) => {
698
999
  snapshot.has(id) || snapshot.set(id, store.get(id));
699
1000
  };
700
1001
  try {
@@ -704,7 +1005,9 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
704
1005
  remember(mut.doc._id);
705
1006
  const promoted = promote2(mut.doc);
706
1007
  if (store.get(promoted._id) !== void 0)
707
- throw new Error(`create failed: document ${promoted._id} already exists`);
1008
+ throw fakeError(
1009
+ `create() failed: a document with _id "${promoted._id}" already exists in dataset "${projectId}:${dataset}". Use createOrReplace() to overwrite it, or createIfNotExists() to leave the existing one untouched.`
1010
+ );
708
1011
  await gate(promoted, "create"), store.put(promoted), touchedIds.push(promoted._id), operations.push({ id: promoted._id, operation: "create" });
709
1012
  break;
710
1013
  }
@@ -739,14 +1042,15 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
739
1042
  doc === void 0 ? store.remove(id) : store.put(doc);
740
1043
  throw error;
741
1044
  }
742
- if (txnOptions?.returnDocuments) {
743
- const docs = touchedIds.map((id) => store.get(id)).filter((d) => d !== void 0);
744
- return txnOptions.returnFirst ? docs[0] : docs;
745
- }
746
- return {
747
- transactionId: cryptoRandomKey(),
748
- results: operations
749
- };
1045
+ record(transactionId, mutations);
1046
+ const documents = touchedIds.map((id) => store.get(id)).filter((d) => d !== void 0);
1047
+ return formatMutationResult(
1048
+ documents,
1049
+ operations,
1050
+ transactionId,
1051
+ txnOptions?.returnDocuments ?? !1,
1052
+ txnOptions?.returnFirst ?? !1
1053
+ );
750
1054
  }, accessVisibleDocs = async () => {
751
1055
  const all = store.all();
752
1056
  if (accessControl === void 0) return all;
@@ -757,23 +1061,26 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
757
1061
  }, visibleDocs = async (override) => {
758
1062
  const accessible = await accessVisibleDocs();
759
1063
  return applyPerspective(accessible, override ?? perspective);
760
- };
761
- return {
1064
+ }, client = {
762
1065
  fetch: async (query, params, opts) => {
763
- const tree = parse(query, params ? { params } : void 0);
764
- return await (await evaluate(tree, {
1066
+ const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
765
1067
  dataset: await visibleDocs(opts?.perspective),
766
1068
  ...params !== void 0 ? { params } : {}
767
1069
  })).get();
1070
+ if (opts?.filterResponse === !1) {
1071
+ const ms = Date.now() - start;
1072
+ return opts.returnQuery === !1 ? { ms, result } : { query, ms, result };
1073
+ }
1074
+ return result;
768
1075
  },
769
1076
  getDocument: async (id, opts) => {
770
1077
  const effective = opts?.perspective ?? perspective;
771
1078
  if (effective === "raw") {
772
1079
  const doc = store.get(id);
773
- return doc === void 0 || !await canRead(doc) ? null : doc;
1080
+ return doc === void 0 || !await canRead(doc) ? void 0 : doc;
774
1081
  }
775
1082
  const view = await visibleDocs(effective);
776
- return resolveDocument(view, id, effective) ?? null;
1083
+ return resolveDocument(view, id, effective) ?? void 0;
777
1084
  },
778
1085
  getDocuments: async (ids, opts) => {
779
1086
  const effective = opts?.perspective ?? perspective;
@@ -790,29 +1097,75 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
790
1097
  },
791
1098
  create: async (doc, opts) => {
792
1099
  if (checkRevision(doc._id, opts?.ifRevisionId), store.get(doc._id) !== void 0)
793
- throw new Error(`create failed: document ${doc._id} already exists`);
1100
+ throw fakeError(
1101
+ `create() failed: a document with _id "${doc._id}" already exists in dataset "${projectId}:${dataset}". Use createOrReplace() to overwrite it, or createIfNotExists() to leave the existing one untouched.`
1102
+ );
794
1103
  const promoted = promote2(doc);
795
- return await gate(promoted, "create"), store.put(promoted), promoted;
1104
+ await gate(promoted, "create");
1105
+ const transactionId = opts?.transactionId ?? cryptoRandomKey();
1106
+ return opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "create", doc }])), writeResult(
1107
+ [promoted],
1108
+ [{ id: promoted._id, operation: "create" }],
1109
+ transactionId,
1110
+ opts
1111
+ );
796
1112
  },
797
1113
  createOrReplace: async (doc, opts) => {
798
1114
  checkRevision(doc._id, opts?.ifRevisionId);
799
1115
  const promoted = promote2(doc), existing = store.get(doc._id);
800
- return await gate(existing ?? promoted, existing !== void 0 ? "update" : "create"), store.put(promoted), promoted;
1116
+ await gate(existing ?? promoted, existing !== void 0 ? "update" : "create");
1117
+ const transactionId = opts?.transactionId ?? cryptoRandomKey();
1118
+ opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createOrReplace", doc }]));
1119
+ const operation = existing !== void 0 ? "update" : "create";
1120
+ return writeResult(
1121
+ [promoted],
1122
+ [{ id: promoted._id, operation }],
1123
+ transactionId,
1124
+ opts
1125
+ );
801
1126
  },
802
1127
  createIfNotExists: async (doc, opts) => {
803
1128
  checkRevision(doc._id, opts?.ifRevisionId);
804
- const existing = store.get(doc._id);
805
- if (existing !== void 0) return existing;
1129
+ const existing = store.get(doc._id), transactionId = opts?.transactionId ?? cryptoRandomKey();
1130
+ if (existing !== void 0)
1131
+ return writeResult(
1132
+ [existing],
1133
+ [{ id: existing._id, operation: "none" }],
1134
+ transactionId,
1135
+ opts
1136
+ );
806
1137
  const promoted = promote2(doc);
807
- return await gate(promoted, "create"), store.put(promoted), promoted;
1138
+ return await gate(promoted, "create"), opts?.dryRun !== !0 && (store.put(promoted), record(transactionId, [{ kind: "createIfNotExists", doc }])), writeResult(
1139
+ [promoted],
1140
+ [{ id: promoted._id, operation: "create" }],
1141
+ transactionId,
1142
+ opts
1143
+ );
808
1144
  },
809
1145
  delete: async (id, opts) => {
810
1146
  checkRevision(id, opts?.ifRevisionId);
811
1147
  const existing = store.get(id);
812
- return existing !== void 0 && await gate(existing, "update"), store.remove(id) ? { _id: id } : null;
1148
+ existing !== void 0 && await gate(existing, "update");
1149
+ const transactionId = opts?.transactionId ?? cryptoRandomKey();
1150
+ let removed = existing;
1151
+ return opts?.dryRun !== !0 && (removed = store.remove(id), removed !== void 0 && record(transactionId, [{ kind: "delete", id }])), opts?.returnDocuments === void 0 && opts?.returnFirst === void 0 ? removed !== void 0 ? { _id: id } : null : formatMutationResult(
1152
+ removed !== void 0 ? [removed] : [],
1153
+ removed !== void 0 ? [{ id, operation: "delete" }] : [],
1154
+ transactionId,
1155
+ opts.returnDocuments ?? !0,
1156
+ opts.returnFirst ?? !0
1157
+ );
813
1158
  },
814
- patch: (documentId) => createPatch(documentId, { apply: applyPatch }),
1159
+ patch: (documentId) => createPatch(documentId, {
1160
+ apply: async (docId, ops, ifRev) => {
1161
+ const doc = await applyPatch(docId, ops, ifRev);
1162
+ return record(cryptoRandomKey(), [
1163
+ { kind: "patch", documentId: docId, ops, ...ifRev !== void 0 ? { ifRev } : {} }
1164
+ ]), doc;
1165
+ }
1166
+ }),
815
1167
  transaction: () => createTransaction({ apply: applyTransaction }),
1168
+ mutate: async (operations, options) => applyTransaction(toTxnMutations(operations), options),
816
1169
  action: async (action) => applyActions(store, action),
817
1170
  releases: {
818
1171
  create: async ({ releaseId, metadata }) => {
@@ -858,7 +1211,7 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
858
1211
  ...accessControl !== void 0 ? { request: makeRequestImpl(accessControl, projectId, dataset) } : {},
859
1212
  config: () => ({ projectId, dataset, perspective }),
860
1213
  withConfig: (config) => makeHandle(
861
- registry,
1214
+ backend,
862
1215
  config.projectId ?? projectId,
863
1216
  config.dataset ?? dataset,
864
1217
  accessControl,
@@ -869,10 +1222,37 @@ function makeHandle(registry, projectId, dataset, accessControl, perspective) {
869
1222
  reset: () => store.reset(),
870
1223
  snapshot: () => store.snapshot(),
871
1224
  store: () => store,
872
- datasets: () => [...registry.keys()].map(parseRegistryKey)
1225
+ datasets: () => [...registry.keys()].map(parseRegistryKey),
1226
+ stub: (name, handler) => {
1227
+ backend.stubs.set(name, handler);
1228
+ },
1229
+ stubs: () => Object.fromEntries(backend.stubs),
1230
+ mutations: () => backend.log.flatMap((entry) => entry.mutations),
1231
+ transactions: () => [...backend.log],
1232
+ clearLog: () => {
1233
+ backend.log.length = 0;
1234
+ },
1235
+ calls: (method) => method === void 0 ? [...backend.calls] : backend.calls.filter((c) => c.method === method),
1236
+ callCount: (method) => method === void 0 ? backend.calls.length : backend.calls.filter((c) => c.method === method).length,
1237
+ clearCalls: () => {
1238
+ backend.calls.length = 0;
1239
+ }
873
1240
  };
1241
+ return wrapWithGuards(client, {
1242
+ getStub: (name) => backend.stubs.get(name),
1243
+ onCall: (method, args) => {
1244
+ const rec = { method, args, projectId, dataset };
1245
+ return backend.calls.push(rec), (outcome) => {
1246
+ "error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;
1247
+ };
1248
+ },
1249
+ recorded: RECORDED_METHODS
1250
+ });
874
1251
  }
875
1252
  export {
1253
+ ERR_PREFIX,
1254
+ SUPPORTED_SURFACE,
1255
+ UNSUPPORTED_MEMBERS,
876
1256
  WriteAccessDeniedError,
877
1257
  applyPatchOps,
878
1258
  applyPerspective,
@@ -882,11 +1262,13 @@ export {
882
1262
  createTransaction,
883
1263
  defaultAclPath,
884
1264
  evaluateWriteAccess,
1265
+ fakeError,
885
1266
  isDraftId,
886
1267
  isReleaseDocId,
887
1268
  isSystemId,
888
1269
  isVersionId,
889
1270
  publishedIdOf,
890
- releaseNameOf
1271
+ releaseNameOf,
1272
+ wrapWithGuards
891
1273
  };
892
1274
  //# sourceMappingURL=index.js.map