@collective-intelligence/external-apps-client-sdk-react 0.2.11 → 0.2.12

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/AGENTS.md CHANGED
@@ -23,6 +23,9 @@ holds the full API.
23
23
  QueryClient in machine input. An optimistic write calls `cancel` on its keys
24
24
  before `update`, and `invalidate` when the write settles. A view renders: it calls no `fetch` and runs
25
25
  no Effect.
26
+ - Test machines with `makeTestQueryCache()` of `/effect`, never with a double
27
+ made with `QueryCache.of`: that double breaks when `QueryCache` gets a
28
+ member. Seed `queryClient`, then assert on its entries or on `calls`.
26
29
  - Show write failures with `onWriteFailed` on the provider, for example
27
30
  `ciWriteFailedToast()` of `@collective-intelligence/ui-react/ui`.
28
31
  - Give `RealtimeProvider` an `onReset` that refetches every realtime-driven
package/README.md CHANGED
@@ -325,6 +325,55 @@ const LeadEditor = ({ id }: { id: string }) => {
325
325
  }
326
326
  ```
327
327
 
328
+ ### Machine tests
329
+
330
+ Test a machine with `makeTestQueryCache(options?)`, never with a double made
331
+ with `QueryCache.of({ ... })`: that double breaks when `QueryCache` gets a new
332
+ member. `makeTestQueryCache` returns:
333
+
334
+ - `layer`: provides the `QueryCache` of `./effect`, the service that
335
+ `EffectRuntimeProvider` provides. Give it to `ManagedRuntime.make` for the
336
+ `runtime` of the machine input.
337
+ - `queryClient`: the real TanStack `QueryClient` under the cache. Each member
338
+ works on it as in the app, with the same key prefixes, `cancel` and
339
+ `remove`. Its entries stay until the test ends (`gcTime: Infinity`).
340
+ - `calls`: one `{ member, queryKey }` for each member call, in the order that
341
+ the calls ran. An effect that the machine only builds is no call.
342
+
343
+ Options, all optional: `seed` (`[queryKey, data]` entries that the
344
+ `QueryClient` holds first), `queryClient` (to use your own), and `overrides`
345
+ (a `Partial` of the members: each override replaces its member only, and the
346
+ call log records it too).
347
+
348
+ Assert on the entries, so a machine that skips a call fails the test:
349
+
350
+ ```ts
351
+ import {
352
+ QueryCache,
353
+ makeTestQueryCache
354
+ } from "@collective-intelligence/external-apps-client-sdk-react/effect"
355
+ import * as ManagedRuntime from "effect/ManagedRuntime"
356
+
357
+ const cache = makeTestQueryCache({
358
+ seed: [[["ci-entities", "lead", "7"], lead]]
359
+ })
360
+ const runtime = ManagedRuntime.make(cache.layer)
361
+ const actor = createActor(sessionMachine, { input: { runtime } }).start()
362
+ actor.send({ type: "session.signOut" })
363
+ await waitFor(actor, (snapshot) => snapshot.matches("idle"))
364
+
365
+ // Sign-out removed the reads of the user.
366
+ expect(
367
+ cache.queryClient.getQueryCache().findAll({ queryKey: ["ci-entities"] })
368
+ ).toEqual([])
369
+ expect(cache.calls).toEqual([{ member: "remove", queryKey: ["ci-entities"] }])
370
+ // After an invalidate: cache.queryClient.getQueryState(key)?.isInvalidated === true
371
+ await runtime.dispose()
372
+ ```
373
+
374
+ `makeTestQueryCache` adds no dependency, and a production bundle that does
375
+ not import it does not contain it (`sideEffects: false`).
376
+
328
377
  ## Workspace development
329
378
 
330
379
  See the repository's [Effect demo](../../../demo/external-app-effect/README.md)
package/dist/effect.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
3
  import { CiError, CiTransportError } from '@collective-intelligence/external-apps-client-sdk/effect';
4
- import { QueryKey } from '@tanstack/react-query';
4
+ import { QueryClient, QueryKey } from '@tanstack/react-query';
5
5
  import * as Context from 'effect/Context';
6
6
  import * as Effect from 'effect/Effect';
7
7
  import * as Layer from 'effect/Layer';
@@ -131,6 +131,47 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
131
131
  */
132
132
  export declare class QueryCache extends QueryCache_base {
133
133
  }
134
+ /** One call of a `QueryCache` member, as the test layer logs it when it runs. */
135
+ export type QueryCacheCall = Readonly<{
136
+ member: keyof QueryCache["Service"];
137
+ /** The key of the call; for `fetch`, the `queryKey` of its options. */
138
+ queryKey: QueryKey;
139
+ }>;
140
+ export type TestQueryCacheOptions = Readonly<{
141
+ /**
142
+ * Replaces these members only. Each other member works on the
143
+ * `QueryClient`, also members that a later SDK release adds.
144
+ */
145
+ overrides?: Partial<QueryCache["Service"]>;
146
+ /**
147
+ * The `QueryClient` under the cache. Without it, a new one that keeps its
148
+ * entries until the test ends (`gcTime: Infinity`); a `QueryClient` that
149
+ * the test passes keeps its own `gcTime`.
150
+ */
151
+ queryClient?: QueryClient;
152
+ /** Values that the `QueryClient` holds before the test runs. */
153
+ seed?: readonly (readonly [
154
+ queryKey: QueryKey,
155
+ data: unknown
156
+ ])[];
157
+ }>;
158
+ export type TestQueryCache = Readonly<{
159
+ /** The calls of the members, in the order that they ran. */
160
+ calls: readonly QueryCacheCall[];
161
+ /** Provides the `QueryCache` of `./effect`, as `EffectRuntimeProvider` does. */
162
+ layer: Layer.Layer<QueryCache>;
163
+ /** The `QueryClient` under the cache: seed it and read it in assertions. */
164
+ queryClient: QueryClient;
165
+ }>;
166
+ /**
167
+ * The `QueryCache` of a test, over a real `QueryClient`: each member works as
168
+ * in the app, including key prefixes, `cancel` and `remove`. Give the `layer`
169
+ * to `ManagedRuntime.make` for the `runtime` of a machine input, then assert
170
+ * on `queryClient` or on `calls`. A test overrides only the members that it
171
+ * must control, so a member that a later release adds does not break it, as
172
+ * it breaks a double made with `QueryCache.of`.
173
+ */
174
+ export declare const makeTestQueryCache: (options?: TestQueryCacheOptions) => TestQueryCache;
134
175
  /**
135
176
  * Gives its tree an Effect runtime with the `QueryCache` over the nearest
136
177
  * `QueryClient`. A view passes it to the machines it starts, in their input.
package/dist/effect.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import{__export}from"./index-6ra894v2.js";var exports_effect={};__export(exports_effect,{EffectRuntimeProvider:()=>EffectRuntimeProvider,QueryCache:()=>QueryCache,effectTask:()=>effectTask,fromEffect:()=>fromEffect,useEffectRuntime:()=>useEffectRuntime});import{assign,emit,setup}from"xstate";import{fromPromise}from"xstate";var unsettled=()=>Promise.race([]);var fromEffect=(run)=>fromPromise(async({input,signal})=>{try{const value=await input.runtime.runPromise(run(input),{signal});return signal.aborted?unsettled():value}catch(error){if(signal.aborted){return unsettled()}throw error}});var effectTask=(run)=>{const actors={run:fromEffect(({task})=>run(task))};return setup({actors}).createMachine({context:({input})=>({error:undefined,output:undefined,runtime:input.runtime}),id:"effectTask",initial:"idle",on:{RUN:{target:".running"}},states:{done:{},failed:{},idle:{},running:{entry:assign({error:undefined,output:undefined}),invoke:{input:({context,event})=>({runtime:context.runtime,task:event.input}),onDone:{actions:[assign({output:({event})=>event.output}),emit(({event})=>({output:event.output,type:"done"}))],target:"done"},onError:{actions:[assign({error:({event})=>event.error}),emit(({event})=>({error:event.error,type:"failed"}))],target:"failed"},src:"run"},on:{RUN:{}}}}})};import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{isCancelledError,QueryObserver}from"@tanstack/react-query";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Layer from"effect/Layer";class QueryCache extends Context.Service()("@collective-intelligence/external-apps-client-sdk-react/QueryCache"){}var make=(queryClient)=>{const fetchExit=async({query,...options},context)=>{try{return Exit.succeed(await queryClient.fetchQuery({...options,queryFn:({signal})=>Effect.runPromiseWith(context)(query,{signal}),retry:false}))}catch(error){if(isCancelledError(error)){return Exit.interrupt()}return error instanceof CiError||error instanceof CiTransportError?Exit.fail(error):Exit.die(error)}};const waitOn=(queryKey)=>Effect.sync(()=>new QueryObserver(queryClient,{enabled:false,queryKey}).subscribe(constVoid));return QueryCache.of({cancel:(queryKey)=>Effect.promise(()=>queryClient.cancelQueries({queryKey})),fetch:(options)=>Effect.flatMap(Effect.context(),(context)=>Effect.acquireUseRelease(waitOn(options.queryKey),()=>Effect.flatten(Effect.promise(()=>fetchExit(options,context))),(stopWaiting)=>Effect.sync(stopWaiting))),invalidate:(queryKey)=>Effect.promise(()=>queryClient.invalidateQueries({queryKey})),remove:(queryKey)=>Effect.sync(()=>{queryClient.removeQueries({queryKey})}),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)}),update:(queryKey,updater)=>Effect.sync(()=>{queryClient.setQueriesData({queryKey},updater)})})};var layer=(queryClient)=>Layer.succeed(QueryCache,make(queryClient));import{useQueryClient}from"@tanstack/react-query";import*as ManagedRuntime from"effect/ManagedRuntime";import{createContext,useContext,useMemo}from"react";import{jsx}from"react/jsx-runtime";var RuntimeContext=createContext(null);var EffectRuntimeProvider=({children})=>{const queryClient=useQueryClient();const runtime=useMemo(()=>ManagedRuntime.make(layer(queryClient)),[queryClient]);return jsx(RuntimeContext.Provider,{value:runtime,children})};var useEffectRuntime=()=>{const runtime=useContext(RuntimeContext);if(runtime===null){throw new Error("useEffectRuntime requires an EffectRuntimeProvider")}return runtime};var{EffectRuntimeProvider:EffectRuntimeProvider2,QueryCache:QueryCache2,effectTask:effectTask2,fromEffect:fromEffect2,useEffectRuntime:useEffectRuntime2}=exports_effect;export{EffectRuntimeProvider2 as EffectRuntimeProvider,QueryCache2 as QueryCache,effectTask2 as effectTask,fromEffect2 as fromEffect,useEffectRuntime2 as useEffectRuntime};
2
+ import{__export}from"./index-6ra894v2.js";var exports_effect={};__export(exports_effect,{EffectRuntimeProvider:()=>EffectRuntimeProvider,QueryCache:()=>QueryCache,effectTask:()=>effectTask,fromEffect:()=>fromEffect,makeTestQueryCache:()=>makeTestQueryCache,useEffectRuntime:()=>useEffectRuntime});import{assign,emit,setup}from"xstate";import{fromPromise}from"xstate";var unsettled=()=>Promise.race([]);var fromEffect=(run)=>fromPromise(async({input,signal})=>{try{const value=await input.runtime.runPromise(run(input),{signal});return signal.aborted?unsettled():value}catch(error){if(signal.aborted){return unsettled()}throw error}});var effectTask=(run)=>{const actors={run:fromEffect(({task})=>run(task))};return setup({actors}).createMachine({context:({input})=>({error:undefined,output:undefined,runtime:input.runtime}),id:"effectTask",initial:"idle",on:{RUN:{target:".running"}},states:{done:{},failed:{},idle:{},running:{entry:assign({error:undefined,output:undefined}),invoke:{input:({context,event})=>({runtime:context.runtime,task:event.input}),onDone:{actions:[assign({output:({event})=>event.output}),emit(({event})=>({output:event.output,type:"done"}))],target:"done"},onError:{actions:[assign({error:({event})=>event.error}),emit(({event})=>({error:event.error,type:"failed"}))],target:"failed"},src:"run"},on:{RUN:{}}}}})};import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{isCancelledError,QueryObserver}from"@tanstack/react-query";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Layer from"effect/Layer";class QueryCache extends Context.Service()("@collective-intelligence/external-apps-client-sdk-react/QueryCache"){}var make=(queryClient)=>{const fetchExit=async({query,...options},context)=>{try{return Exit.succeed(await queryClient.fetchQuery({...options,queryFn:({signal})=>Effect.runPromiseWith(context)(query,{signal}),retry:false}))}catch(error){if(isCancelledError(error)){return Exit.interrupt()}return error instanceof CiError||error instanceof CiTransportError?Exit.fail(error):Exit.die(error)}};const waitOn=(queryKey)=>Effect.sync(()=>new QueryObserver(queryClient,{enabled:false,queryKey}).subscribe(constVoid));return QueryCache.of({cancel:(queryKey)=>Effect.promise(()=>queryClient.cancelQueries({queryKey})),fetch:(options)=>Effect.flatMap(Effect.context(),(context)=>Effect.acquireUseRelease(waitOn(options.queryKey),()=>Effect.flatten(Effect.promise(()=>fetchExit(options,context))),(stopWaiting)=>Effect.sync(stopWaiting))),invalidate:(queryKey)=>Effect.promise(()=>queryClient.invalidateQueries({queryKey})),remove:(queryKey)=>Effect.sync(()=>{queryClient.removeQueries({queryKey})}),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)}),update:(queryKey,updater)=>Effect.sync(()=>{queryClient.setQueriesData({queryKey},updater)})})};var layer=(queryClient)=>Layer.succeed(QueryCache,make(queryClient));import{QueryClient}from"@tanstack/react-query";import*as Effect2 from"effect/Effect";import*as Layer2 from"effect/Layer";var makeTestQueryCache=(options={})=>{const queryClient=options.queryClient??new QueryClient({defaultOptions:{queries:{gcTime:Infinity}}});for(const[queryKey,data]of options.seed??[]){queryClient.setQueryData(queryKey,data)}const real=make(queryClient);const overrides=options.overrides??{};const calls=[];const logged=(member,queryKey,run)=>Effect2.suspend(()=>{calls.push({member,queryKey});return run()});return{calls,layer:Layer2.succeed(QueryCache,QueryCache.of({cancel:(queryKey)=>logged("cancel",queryKey,()=>(overrides.cancel??real.cancel)(queryKey)),fetch:(fetchOptions)=>logged("fetch",fetchOptions.queryKey,()=>(overrides.fetch??real.fetch)(fetchOptions)),invalidate:(queryKey)=>logged("invalidate",queryKey,()=>(overrides.invalidate??real.invalidate)(queryKey)),remove:(queryKey)=>logged("remove",queryKey,()=>(overrides.remove??real.remove)(queryKey)),setData:(queryKey,data)=>logged("setData",queryKey,()=>(overrides.setData??real.setData)(queryKey,data)),update:(queryKey,updater)=>logged("update",queryKey,()=>(overrides.update??real.update)(queryKey,updater))})),queryClient}};import{useQueryClient}from"@tanstack/react-query";import*as ManagedRuntime from"effect/ManagedRuntime";import{createContext,useContext,useMemo}from"react";import{jsx}from"react/jsx-runtime";var RuntimeContext=createContext(null);var EffectRuntimeProvider=({children})=>{const queryClient=useQueryClient();const runtime=useMemo(()=>ManagedRuntime.make(layer(queryClient)),[queryClient]);return jsx(RuntimeContext.Provider,{value:runtime,children})};var useEffectRuntime=()=>{const runtime=useContext(RuntimeContext);if(runtime===null){throw new Error("useEffectRuntime requires an EffectRuntimeProvider")}return runtime};var{EffectRuntimeProvider:EffectRuntimeProvider2,QueryCache:QueryCache2,effectTask:effectTask2,fromEffect:fromEffect2,makeTestQueryCache:makeTestQueryCache2,useEffectRuntime:useEffectRuntime2}=exports_effect;export{EffectRuntimeProvider2 as EffectRuntimeProvider,QueryCache2 as QueryCache,effectTask2 as effectTask,fromEffect2 as fromEffect,makeTestQueryCache2 as makeTestQueryCache,useEffectRuntime2 as useEffectRuntime};
package/docs/effect.md CHANGED
@@ -153,9 +153,47 @@ const saveFollowing = fromEffect(
153
153
  - UI feedback, such as a toast, is a machine action that the view provides
154
154
  with `machine.provide({ actions })`.
155
155
  - A test swaps an actor with `machine.provide({ actors })`.
156
+ - Test machines with `makeTestQueryCache`, never with `QueryCache.of`. See
157
+ [Machine tests](#machine-tests).
156
158
  - In Strict Mode, an actor that `useActorRef` starts again can run its `query`
157
159
  a second time: keep queries idempotent.
158
160
 
161
+ ## Machine tests
162
+
163
+ `makeTestQueryCache(options?)` gives a test the `QueryCache` of `/effect`
164
+ over a real TanStack `QueryClient`: each member works as in the app. Do not
165
+ make a double with `QueryCache.of({ ... })`: it breaks each time
166
+ `QueryCache` gets a member. The result has:
167
+
168
+ - `layer`: give it to `ManagedRuntime.make` for the machine input `runtime`.
169
+ - `queryClient`: seed it, and assert on its entries after the machine runs.
170
+ - `calls`: `{ member, queryKey }` for each call that ran, in order.
171
+
172
+ Options: `seed` (`[queryKey, data]` entries), `queryClient` (your own) and
173
+ `overrides` (replace some members only, for example to make one fail).
174
+
175
+ Assert on the entries, so that a machine that skips the call fails:
176
+
177
+ ```ts
178
+ const cache = makeTestQueryCache({
179
+ seed: [[["ci-entities", "lead", "7"], lead]]
180
+ })
181
+ const runtime = ManagedRuntime.make(cache.layer)
182
+ const actor = createActor(sessionMachine, { input: { runtime } }).start()
183
+ actor.send({ type: "session.signOut" })
184
+ await waitFor(actor, (snapshot) => snapshot.matches("idle"))
185
+
186
+ // Removed: no entry under the key is left.
187
+ expect(
188
+ cache.queryClient.getQueryCache().findAll({ queryKey: ["ci-entities"] })
189
+ ).toEqual([])
190
+ // Invalidated: the entry is stale.
191
+ // expect(cache.queryClient.getQueryState(key)?.isInvalidated).toBe(true)
192
+ // Or the call itself:
193
+ expect(cache.calls).toEqual([{ member: "remove", queryKey: ["ci-entities"] }])
194
+ await runtime.dispose()
195
+ ```
196
+
159
197
  ## Client SDK services
160
198
 
161
199
  The services of `external-apps-client-sdk/effect` (`CiClient`, `Resources`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk-react",
3
- "version": "0.2.11",
3
+ "version": "0.2.12",
4
4
  "description": "React bindings for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -88,5 +88,5 @@
88
88
  "vitest": "4.1.10",
89
89
  "xstate": "5.33.3"
90
90
  },
91
- "gitHead": "6eb615293703ba8e92c566d40ce637fcd6adf7d7"
91
+ "gitHead": "651f2a1a48f0c82cd24c832378da8a664172a970"
92
92
  }