@sanity-labs/client-fake-for-test 0.32.0 → 0.33.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.d.cts CHANGED
@@ -1374,6 +1374,37 @@ export declare interface TestClient {
1374
1374
  * own methods instead.
1375
1375
  */
1376
1376
  requestHandler: () => (options: HandledRequestOptions) => Promise<unknown>;
1377
+ /**
1378
+ * A `resolveFetch` for a real `@sanity/client`, or a `fetch` for any
1379
+ * code that opens a server-sent event stream itself: `createClient({
1380
+ * ...config, resolveFetch: fake.resolveFetch() })`. It answers the
1381
+ * Workflows store read route's `listen`, as the stream gradient sends
1382
+ * (see [Workflows store](#workflows-store) in the README), and throws a
1383
+ * fake error for any other URL.
1384
+ */
1385
+ resolveFetch: () => () => (
1386
+ input: string | URL,
1387
+ init?: RequestInit,
1388
+ ) => Promise<Response>;
1389
+ /**
1390
+ * End every open listener on `organizationId`'s Workflows store with
1391
+ * gradient's fatal error: a `channelError` event carrying `error`, then a
1392
+ * `disconnect` with reason `error`. `@sanity/client` raises the
1393
+ * `channelError`'s `description`.
1394
+ */
1395
+ failListeners: (
1396
+ organizationId: string,
1397
+ error: {
1398
+ type: string;
1399
+ description: string;
1400
+ },
1401
+ ) => void;
1402
+ /**
1403
+ * End every open listener on `organizationId`'s Workflows store without an
1404
+ * event, as gradient ends one on shutdown or at its lifetime, so the client
1405
+ * reconnects.
1406
+ */
1407
+ dropListeners: (organizationId: string) => void;
1377
1408
  /**
1378
1409
  * Deploy a function, or replace the one with its id, for every handle of
1379
1410
  * the family. Throws for an id shorter than 10 characters, an unknown
package/dist/index.d.ts CHANGED
@@ -1374,6 +1374,37 @@ export declare interface TestClient {
1374
1374
  * own methods instead.
1375
1375
  */
1376
1376
  requestHandler: () => (options: HandledRequestOptions) => Promise<unknown>;
1377
+ /**
1378
+ * A `resolveFetch` for a real `@sanity/client`, or a `fetch` for any
1379
+ * code that opens a server-sent event stream itself: `createClient({
1380
+ * ...config, resolveFetch: fake.resolveFetch() })`. It answers the
1381
+ * Workflows store read route's `listen`, as the stream gradient sends
1382
+ * (see [Workflows store](#workflows-store) in the README), and throws a
1383
+ * fake error for any other URL.
1384
+ */
1385
+ resolveFetch: () => () => (
1386
+ input: string | URL,
1387
+ init?: RequestInit,
1388
+ ) => Promise<Response>;
1389
+ /**
1390
+ * End every open listener on `organizationId`'s Workflows store with
1391
+ * gradient's fatal error: a `channelError` event carrying `error`, then a
1392
+ * `disconnect` with reason `error`. `@sanity/client` raises the
1393
+ * `channelError`'s `description`.
1394
+ */
1395
+ failListeners: (
1396
+ organizationId: string,
1397
+ error: {
1398
+ type: string;
1399
+ description: string;
1400
+ },
1401
+ ) => void;
1402
+ /**
1403
+ * End every open listener on `organizationId`'s Workflows store without an
1404
+ * event, as gradient ends one on shutdown or at its lifetime, so the client
1405
+ * reconnects.
1406
+ */
1407
+ dropListeners: (organizationId: string) => void;
1377
1408
  /**
1378
1409
  * Deploy a function, or replace the one with its id, for every handle of
1379
1410
  * the family. Throws for an id shorter than 10 characters, an unknown
package/dist/index.js CHANGED
@@ -2221,6 +2221,179 @@ async function applyActions(store, actions, hooks) {
2221
2221
  throw err;
2222
2222
  }
2223
2223
  }
2224
+ function openListener(args) {
2225
+ const { organizationId, spec, readable, open, signal } = args, tree = parse(spec.query, { params: spec.params }), encoder = new TextEncoder();
2226
+ let listener;
2227
+ const close = () => {
2228
+ listener !== void 0 && open.delete(listener);
2229
+ }, body = new ReadableStream({
2230
+ start: (controller) => {
2231
+ let ended = !1;
2232
+ const write = (text) => {
2233
+ ended || controller.enqueue(encoder.encode(text));
2234
+ }, end = () => {
2235
+ ended || (ended = !0, close(), controller.close());
2236
+ }, sees = async (document) => {
2237
+ if (document === void 0 || !await readable(document)) return !1;
2238
+ const result = await (await evaluate(tree, { dataset: [document], params: spec.params })).get();
2239
+ return Array.isArray(result) ? result.length > 0 : result !== null && result !== !1;
2240
+ };
2241
+ listener = {
2242
+ organizationId,
2243
+ deliver: async (commit) => {
2244
+ const events = [];
2245
+ for (const change of commit.changes) {
2246
+ const transition = transitionOf(await sees(change.before), await sees(change.after));
2247
+ transition !== void 0 && events.push({ change, transition });
2248
+ }
2249
+ events.forEach(
2250
+ ({ change, transition }, index) => write(
2251
+ mutationFrame({
2252
+ spec,
2253
+ commit,
2254
+ change,
2255
+ transition,
2256
+ position: { current: index + 1, total: events.length }
2257
+ })
2258
+ )
2259
+ );
2260
+ },
2261
+ fail: (error) => {
2262
+ write(`event: channelError
2263
+ data: ${JSON.stringify({ error })}
2264
+
2265
+ `), write(`event: disconnect
2266
+ data: {"reason": "error"}
2267
+
2268
+ `), end();
2269
+ },
2270
+ drop: end
2271
+ }, open.add(listener), write(`:
2272
+
2273
+ `), write(`event: welcome
2274
+ data: ${JSON.stringify({ listenerName: listenerName() })}
2275
+
2276
+ `), signal?.addEventListener("abort", close);
2277
+ },
2278
+ cancel: close
2279
+ });
2280
+ return new Response(body, {
2281
+ status: 200,
2282
+ headers: { "content-type": "text/event-stream", "cache-control": "no-cache" }
2283
+ });
2284
+ }
2285
+ function transitionOf(before, after) {
2286
+ return before ? after ? "update" : "disappear" : after ? "appear" : void 0;
2287
+ }
2288
+ function mutationFrame(args) {
2289
+ const { spec, commit, change, transition, position } = args, eventId = `${commit.transactionId}#${change.id}`, now = (/* @__PURE__ */ new Date()).toISOString(), data = {
2290
+ eventId,
2291
+ documentId: change.id,
2292
+ transactionId: commit.transactionId,
2293
+ transition,
2294
+ ...commit.identity !== void 0 ? { identity: commit.identity } : {},
2295
+ ...spec.includeMutations ? { mutations: mutationsOf(change) } : {},
2296
+ ...spec.includePreviousRevision && change.before !== void 0 ? { previous: change.before } : {},
2297
+ ...spec.includeResult && change.after !== void 0 ? { result: change.after } : {},
2298
+ ...change.before !== void 0 ? { previousRev: change.before._rev } : {},
2299
+ ...change.after !== void 0 ? { resultRev: change.after._rev } : {},
2300
+ timestamp: now,
2301
+ visibility: spec.visibility,
2302
+ transactionCurrentEvent: position.current,
2303
+ transactionTotalEvents: position.total,
2304
+ messageDispatchedAt: now
2305
+ };
2306
+ return `event: mutation
2307
+ id: ${eventId}
2308
+ data: ${JSON.stringify(data)}
2309
+
2310
+ `;
2311
+ }
2312
+ function mutationsOf(change) {
2313
+ return change.after === void 0 ? [{ delete: { id: change.id } }] : [{ createOrReplace: change.after }];
2314
+ }
2315
+ let listenerCount = 0;
2316
+ function listenerName() {
2317
+ return listenerCount += 1, `listener-${listenerCount}`;
2318
+ }
2319
+ class ListenerRefusal extends Error {
2320
+ error;
2321
+ constructor(error) {
2322
+ super(error.description), this.error = error;
2323
+ }
2324
+ }
2325
+ const KNOWN_PARAMETERS = /* @__PURE__ */ new Set([
2326
+ "query",
2327
+ "visibility",
2328
+ "includeResult",
2329
+ "includeMutations",
2330
+ "includeProjection",
2331
+ "includePreviousRevision",
2332
+ "effectFormat",
2333
+ "includeAllVersions",
2334
+ "lastEventId",
2335
+ "enableResume",
2336
+ "evs_preamble",
2337
+ "evs_buffer_size_limit",
2338
+ "evs_last_event_id",
2339
+ "tag",
2340
+ "access_token",
2341
+ "debug"
2342
+ ]), UNMODELLED = ["includeProjection", "effectFormat", "includeAllVersions", "enableResume"];
2343
+ function listenerSpec(search) {
2344
+ const unknown = [...new Set(search.keys())].filter(
2345
+ (name) => !name.startsWith("$") && !KNOWN_PARAMETERS.has(name)
2346
+ );
2347
+ if (unknown.length > 0)
2348
+ throw new ListenerRefusal({
2349
+ type: "httpUnknownQueryStringParameters",
2350
+ description: unknown.length === 1 ? `Unknown query parameter ${JSON.stringify(unknown[0])}` : `Unknown query parameters: ${unknown.map((name) => JSON.stringify(name)).join(", ")}`,
2351
+ names: unknown
2352
+ });
2353
+ const unmodelled = UNMODELLED.find((name) => search.has(name));
2354
+ if (unmodelled !== void 0)
2355
+ throw fakeError(`resolveFetch(): the listener option \`${unmodelled}\` is not modelled.`);
2356
+ const query = search.getAll("query");
2357
+ if (query.length > 1)
2358
+ throw new ListenerRefusal({
2359
+ type: "validationError",
2360
+ description: "query can only occur once"
2361
+ });
2362
+ if (query[0] === void 0)
2363
+ throw fakeError("resolveFetch(): a listener needs a `query` parameter.");
2364
+ const visibility = search.get("visibility") ?? "transaction";
2365
+ if (visibility !== "transaction" && visibility !== "query")
2366
+ throw new ListenerRefusal({
2367
+ type: "validationError",
2368
+ description: `invalid listener visibility ${JSON.stringify(visibility)}`
2369
+ });
2370
+ const flag = (name) => search.has(name) && search.get(name) !== "false";
2371
+ return {
2372
+ query: query[0],
2373
+ params: Object.fromEntries(
2374
+ [...search].filter(([name]) => name.startsWith("$")).map(([name, value]) => [name.slice(1), JSON.parse(value)])
2375
+ ),
2376
+ includeResult: flag("includeResult"),
2377
+ includePreviousRevision: flag("includePreviousRevision"),
2378
+ includeMutations: !search.has("includeMutations") || flag("includeMutations"),
2379
+ visibility
2380
+ };
2381
+ }
2382
+ function refusedListener(error) {
2383
+ return new Response(fatalFrames(error), {
2384
+ status: 200,
2385
+ headers: { "content-type": "text/event-stream" }
2386
+ });
2387
+ }
2388
+ function fatalFrames(error) {
2389
+ return `event: channelError
2390
+ data: ${JSON.stringify({ error })}
2391
+
2392
+ event: disconnect
2393
+ data: {"reason": "error"}
2394
+
2395
+ `;
2396
+ }
2224
2397
  function createTransaction(executor) {
2225
2398
  const mutations = [], handle = {
2226
2399
  create: (doc) => (mutations.push({ kind: "create", doc }), handle),
@@ -2891,7 +3064,10 @@ function tagFromArgs(method, args) {
2891
3064
  if (!(typeof options != "object" || options === null || !("tag" in options)))
2892
3065
  return options.tag;
2893
3066
  }
2894
- const RECORDED_METHODS = /* @__PURE__ */ new Set([
3067
+ function mutatedId(mutation) {
3068
+ return mutation.kind === "delete" ? mutation.id : mutation.kind === "patch" ? mutation.documentId : String(mutation.doc._id);
3069
+ }
3070
+ const handleListeners = /* @__PURE__ */ new WeakMap(), RECORDED_METHODS = /* @__PURE__ */ new Set([
2895
3071
  "fetch",
2896
3072
  "getDocument",
2897
3073
  "getDocuments",
@@ -3095,6 +3271,7 @@ function createTestClient(options = {}) {
3095
3271
  internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
3096
3272
  internalTokens: /* @__PURE__ */ new Map(),
3097
3273
  outages: /* @__PURE__ */ new Set(),
3274
+ listeners: /* @__PURE__ */ new Set(),
3098
3275
  missingDatasets: new Set(options.missingDatasets ?? []),
3099
3276
  writeChain: Promise.resolve()
3100
3277
  }, registry = backend.registry;
@@ -3265,6 +3442,10 @@ function makeHandle(handleArgs) {
3265
3442
  sent,
3266
3443
  routed.route === "read" ? `org:${routed.organizationId}` : routed.storeId
3267
3444
  );
3445
+ if (routed.route === "read" && routed.action === "listen")
3446
+ throw fakeError(
3447
+ `request(): "${sent.path}" is a listener, which \`request()\` does not open. Open it through \`resolveFetch()\`, as \`@sanity/client\` opens a listener.`
3448
+ );
3268
3449
  const servedActions = routed.route === "read" ? ["query", "doc"] : ["query", "doc", "mutate"];
3269
3450
  if (!servedActions.includes(routed.action))
3270
3451
  throw fakeError(
@@ -3292,6 +3473,61 @@ function makeHandle(handleArgs) {
3292
3473
  sent,
3293
3474
  opts
3294
3475
  });
3476
+ }, listen = (url, init) => {
3477
+ const sent = { method: "GET", path: url.pathname, url: url.href };
3478
+ try {
3479
+ if (handleArgs.internalStore !== void 0) return streamListener(sent, url, init);
3480
+ refuseSession2(sent);
3481
+ const [, version = "", ...rest] = url.pathname.split("/"), path = `/${rest.join("/")}`, routed = matchWorkflowsStoreRoute({ path, apiVersion: version.slice(1) });
3482
+ if (routed === "unrouted") throw noRouteMatched({ ...sent, path });
3483
+ if (typeof routed != "object" || routed.route !== "read" || routed.action !== "listen")
3484
+ throw fakeError(
3485
+ `resolveFetch(): "${url.href}" is not the Workflows store read route's listen, the only URL it serves.`
3486
+ );
3487
+ const store2 = activeStoreOf(routed.organizationId);
3488
+ if (store2 === void 0) throw storeNotFound(sent, `org:${routed.organizationId}`);
3489
+ const scope = token === void 0 ? void 0 : backend.identities.get(token)?.organizationScope;
3490
+ if (scope !== void 0 && scope !== store2.organizationId)
3491
+ throw unauthorizedOrganization(sent);
3492
+ const onStore = makeHandle({
3493
+ ...handleArgs,
3494
+ resource: void 0,
3495
+ useProjectHostname: !1,
3496
+ perspective: "raw",
3497
+ configuredPerspective: void 0,
3498
+ internalStore: {
3499
+ resource: { type: "organization-store", id: store2.id },
3500
+ store: { id: store2.id, organizationId: store2.organizationId }
3501
+ }
3502
+ });
3503
+ return handleListeners.get(onStore)(url, init);
3504
+ } catch (error) {
3505
+ if (!(error instanceof PlatformHttpError)) throw error;
3506
+ return new Response(JSON.stringify(error.response.body), {
3507
+ status: error.response.statusCode,
3508
+ headers: { "content-type": "application/json; charset=utf-8" }
3509
+ });
3510
+ }
3511
+ }, streamListener = (sent, url, init) => {
3512
+ admitToLake(sent);
3513
+ let spec;
3514
+ try {
3515
+ spec = listenerSpec(url.searchParams), parseQuery(sent, spec.query, spec.params);
3516
+ } catch (error) {
3517
+ if (error instanceof ListenerRefusal) return refusedListener(error.error);
3518
+ if (error instanceof PlatformHttpError)
3519
+ return refusedListener(error.response.body.error);
3520
+ if (error instanceof GroqSyntaxError)
3521
+ return refusedListener({ type: "queryParseError", description: error.message });
3522
+ throw error;
3523
+ }
3524
+ return openListener({
3525
+ organizationId: handleArgs.internalStore.store.organizationId,
3526
+ spec,
3527
+ readable: canRead,
3528
+ open: backend.listeners,
3529
+ signal: init?.signal
3530
+ });
3295
3531
  }, activeStoreOf = (organizationId) => {
3296
3532
  const store2 = backend.organizationStores.get(organizationId);
3297
3533
  return store2?.status === "active" ? store2 : void 0;
@@ -3404,11 +3640,18 @@ function makeHandle(handleArgs) {
3404
3640
  } finally {
3405
3641
  beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
3406
3642
  }
3407
- }), commitHistory = (transactionId) => {
3408
- beforeWrite !== void 0 && (targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() }));
3643
+ }), commitHistory = (transactionId, touched = []) => {
3644
+ if (beforeWrite === void 0) return;
3645
+ targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
3646
+ const organizationId = handleArgs.internalStore?.store.organizationId;
3647
+ organizationId !== void 0 && notifyListeners({ organizationId, transactionId, touched, before: beforeWrite });
3648
+ }, notifyListeners = (args) => {
3649
+ const after = new Map(store.all().map((doc) => [doc._id, doc])), changes = [.../* @__PURE__ */ new Set([...args.touched, ...args.before.keys(), ...after.keys()])].filter((id) => args.before.get(id) !== after.get(id)).map((id) => ({ id, before: args.before.get(id), after: after.get(id) })), commit = { transactionId: args.transactionId, identity: actorId(), changes };
3650
+ for (const listener of backend.listeners)
3651
+ listener.organizationId === args.organizationId && listener.deliver(commit);
3409
3652
  }, record = (transactionId, mutations, tag) => {
3410
3653
  const effectiveTag = effectiveRequestTag(tag);
3411
- commitHistory(transactionId), backend.log.push({
3654
+ commitHistory(transactionId, mutations.map(mutatedId)), backend.log.push({
3412
3655
  transactionId,
3413
3656
  projectId,
3414
3657
  dataset,
@@ -3933,6 +4176,18 @@ function makeHandle(handleArgs) {
3933
4176
  ...sent.tag !== void 0 ? { tag: sent.tag } : {}
3934
4177
  });
3935
4178
  },
4179
+ resolveFetch: () => () => async (input, init) => {
4180
+ const url = new URL(String(input)), bearer = new Headers(init?.headers).get("authorization")?.replace(/^Bearer /, "");
4181
+ return bearer === void 0 ? listen(url, init) : handleListeners.get(client.withConfig({ token: bearer }))(url, init);
4182
+ },
4183
+ failListeners: (organizationId, error) => {
4184
+ for (const listener of backend.listeners)
4185
+ listener.organizationId === organizationId && listener.fail(error);
4186
+ },
4187
+ dropListeners: (organizationId) => {
4188
+ for (const listener of backend.listeners)
4189
+ listener.organizationId === organizationId && listener.drop();
4190
+ },
3936
4191
  addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
3937
4192
  removeFunction: (id) => unregisterFunction(backend.functions, id),
3938
4193
  functionInvocations: () => structuredClone(backend.functions.invocations),
@@ -3946,8 +4201,7 @@ function makeHandle(handleArgs) {
3946
4201
  clearCalls: () => {
3947
4202
  backend.calls.length = 0;
3948
4203
  }
3949
- };
3950
- return wrapWithGuards(client, {
4204
+ }, wrapped = wrapWithGuards(client, {
3951
4205
  getStub: (name) => backend.stubs.get(name),
3952
4206
  onCall: (method, args) => {
3953
4207
  const rec = {
@@ -3965,6 +4219,7 @@ function makeHandle(handleArgs) {
3965
4219
  },
3966
4220
  recorded: handleArgs.internalStore === void 0 ? RECORDED_METHODS : /* @__PURE__ */ new Set()
3967
4221
  });
4222
+ return handleListeners.set(wrapped, listen), wrapped;
3968
4223
  }
3969
4224
  export {
3970
4225
  ERR_PREFIX,