@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/README.md CHANGED
@@ -257,7 +257,7 @@ Workflows keeps its definitions and instances in the organization's store (see [
257
257
 
258
258
  | Route | Actions | Used by |
259
259
  | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------- |
260
- | `/vX/workflows/organizations/<organizationId>/<action>` (kong `config/common/kong.jsonnet`, `gradient-workflows`) | `query` (GET, or POST `{ query, params }`), `doc/<ids>` | the read route, for Studio, the SDK and engines |
260
+ | `/vX/workflows/organizations/<organizationId>/<action>` (kong `config/common/kong.jsonnet`, `gradient-workflows`) | `query` (GET, or POST `{ query, params }`), `doc/<ids>`, `listen` | the read route, for Studio, the SDK and engines |
261
261
  | `/v<X or date>/organization-stores/<storeId>/<action>` (kong `config/staging-internal/kong.jsonnet:326-345`, internal Kong) | `query`, `doc/<ids>`, `mutate` (POST `{ mutations }`) | the Workflows service, which reads and commits there |
262
262
 
263
263
  ```ts
@@ -295,7 +295,16 @@ Kong's answers, as staging gives them:
295
295
  | The read route on API version `1` or a date, or the store route on `1` | 404 `{ message: "no Route matched with those values" }` |
296
296
  | Any other `/vX/workflows…` path, such as `…/mutate` on the read route | Kong sends it to the Workflows service, which the fake does not serve: a fake error |
297
297
 
298
- The fake does not tell the two Kongs apart, so it serves the store route on any host; on the platform only internal Kong does. `listen`, and the store route's `export`, `references`, `actions` and `history`, throw a fake error.
298
+ The fake does not tell the two Kongs apart, so it serves the store route on any host; on the platform only internal Kong does. The store route's `export`, `references`, `actions` and `history`, throw a fake error.
299
+
300
+ The read route's `listen` is a server-sent event stream, which `@sanity/client` and the Workflows engine open with `fetch`, not with a request. `client.resolveFetch()` answers it: pass it as `resolveFetch` to a real `@sanity/client`, or call `client.resolveFetch()()` as the `fetch` of code that opens the stream itself. It answers as gradient serves a listener (sanity-io/gradient `pkg/server/httpapi/listen.go`):
301
+
302
+ - A revoked token, an organization without an `active` store, another API version than `X`, or an organization-scoped token on another organization's store get the same HTTP refusal as `query`, before the stream opens.
303
+ - The stream opens with `welcome` (`listen.go:342-349`). Each commit to the organization store then sends one `mutation` event per document it changes, in the order of its mutations, with `transition` `appear`, `update` or `disappear` as the listener's query matched the document before and after (`pkg/listening/transition.go:75-86`). A document the token may not read matches neither before nor after (`pkg/listening/listening.go:117-135`). Each event carries `eventId` (also its SSE `id`), `documentId`, `transactionId`, `identity`, `previousRev`, `resultRev`, `visibility` and its position in the transaction (`pkg/listening/notifications.go:276-291`, `distributor.go:697-698`); `result` only with `includeResult=true`, `previous` only with `includePreviousRevision=true`, and `mutations` (the document's net change as one `createOrReplace` or `delete`) unless `includeMutations=false`.
304
+ - An unknown query parameter, a `visibility` other than `transaction` or `query`, or a query gradient cannot run gets gradient's fatal error on the stream: `channelError` with `{ error: { type, description } }`, then `disconnect` with `{"reason": "error"}` (`listen.go:101-134`). `includeProjection`, `effectFormat`, `includeAllVersions` and `enableResume` throw a fake error.
305
+ - `client.failListeners(organizationId, error)` ends every open listener on the store with those two frames for `error`. `client.dropListeners(organizationId)` ends them without an event, as gradient ends a listener at shutdown or at the end of its lifetime so the client reconnects (`listen.go:504-514`).
306
+
307
+ `request()` of the `listen` path throws a fake error naming `resolveFetch()`.
299
308
 
300
309
  #### Functions
301
310
 
@@ -577,6 +586,8 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
577
586
  | `client.functionInvocations()` | Every invocation the Functions API accepted, in order (see [Functions](#functions)) |
578
587
  | `client.completeOrganizationStoreProvisioning(organizationId)` | Set the organization's `provisioning` store `active`, as populus's provisioning workflow does (see [Organization stores](#organization-stores)) |
579
588
  | `client.requestHandler()` | A `requestHandler` for a real `@sanity/client`: each request is answered as `request()` answers it on a sibling bound to the request's bearer token, API host and API version, so code that builds its own client runs against the fake |
589
+ | `client.resolveFetch()` | A `resolveFetch` for a real `@sanity/client` that answers the Workflows store read route's `listen` as gradient's event stream (see [Workflows store](#workflows-store)) |
590
+ | `client.failListeners(organizationId, error)` / `client.dropListeners(organizationId)` | End the open listeners on an organization's Workflows store with gradient's fatal error, or without an event (see [Workflows store](#workflows-store)) |
580
591
  | `client.organizationStore(organizationId)` | The documents of the organization's store, the Workflows store, to seed or inspect (see [Workflows store](#workflows-store)). Throws unless the organization has a store |
581
592
  | `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
582
593
  | `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
package/dist/index.cjs 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 = groqJs.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 groqJs.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 groqJs.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(client2.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(client2, {
4204
+ }, wrapped = wrapWithGuards(client2, {
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
  exports.ERR_PREFIX = ERR_PREFIX;
3970
4225
  exports.GuardDeniedError = GuardDeniedError;