@collective-intelligence/external-apps-client-sdk-react 0.2.11 → 0.2.13
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 +3 -0
- package/README.md +49 -0
- package/dist/effect.d.ts +42 -1
- package/dist/effect.js +1 -1
- package/dist/index.js +1 -1
- package/dist/resources.js +1 -1
- package/docs/effect.md +38 -0
- package/package.json +2 -2
- package/dist/index-6ra894v2.js +0 -2
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{
|
|
2
|
+
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};export{EffectRuntimeProvider,QueryCache,effectTask,fromEffect,makeTestQueryCache,useEffectRuntime};
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{EntityRuntimeProvider,createDelegatedEntitySource2,defineEntity2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-zbq0t81c.js";import{__export}from"./index-6ra894v2.js";var exports_src={};__export(exports_src,{AgentPrompt:()=>AgentPrompt,AgentPromptPrimitive:()=>AgentPromptPrimitive,CollectiveIntelligenceLoginProvider:()=>CollectiveIntelligenceLoginProvider,CollectiveIntelligenceProvider:()=>CollectiveIntelligenceProvider,EntityForm:()=>EntityForm2,EntityList:()=>EntityList2,EntityTable:()=>EntityTable2,LoginButton:()=>LoginButton,LoginCallback:()=>LoginCallback,LoginCallbackPrimitive:()=>LoginCallbackPrimitive,RealtimeProvider:()=>RealtimeProvider,SessionGate:()=>SessionGate,clientSdkReactEntrypoint:()=>clientSdkReactEntrypoint,createDelegatedEntitySource:()=>createDelegatedEntitySource2,createPromptKeyHandler:()=>createPromptKeyHandler,defineEntity:()=>defineEntity2,useAgentInvocation:()=>useAgentInvocation,useAgents:()=>useAgents,useAttachments:()=>useAttachments,useClientContext:()=>useClientContext,useCollectiveIntelligenceAuth:()=>useCollectiveIntelligenceAuth,useCollectiveIntelligenceClient:()=>useCollectiveIntelligenceClient,useEntityViewState:()=>useEntityViewState2,useKnowledge:()=>useKnowledge,useMemoryEntityViewState:()=>useMemoryEntityViewState2,useOrganizationClient:()=>useOrganizationClient,useRealtimeClient:()=>useRealtimeClient,useRealtimeTopic:()=>useRealtimeTopic,useRuns:()=>useRuns,useSession:()=>useSession,useSkills:()=>useSkills,useWorkflows:()=>useWorkflows});import{useCallback,useId,useState as useState2}from"react";import{QueryClient,QueryClientProvider}from"@tanstack/react-query";import{createContext,useContext,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";var ClientContext=createContext(null);var CollectiveIntelligenceProvider=(props)=>{const{clientFactory}=props;const[ownedQueryClient]=useState(()=>new QueryClient({defaultOptions:{mutations:{retry:false},queries:{retry:false}}}));const ownedClient=useMemo(()=>clientFactory===undefined?undefined:clientFactory(),[clientFactory]);const client=props.client??ownedClient;const queryClient=props.queryClient??ownedQueryClient;if(client===undefined){throw new TypeError("A client or clientFactory is required")}return jsx(ClientContext.Provider,{value:client,children:jsx(QueryClientProvider,{client:queryClient,children:props.entitySource===undefined?props.children:jsx(EntityRuntimeProvider,{onWriteFailed:props.onWriteFailed,source:props.entitySource,children:props.children})})})};var useCollectiveIntelligenceClient=()=>{const client=useContext(ClientContext);if(client===null){throw new Error("CollectiveIntelligenceProvider must wrap Collective Intelligence hooks")}return client};var useOrganizationClient=(organizationId)=>{const client=useCollectiveIntelligenceClient();return useMemo(()=>client.forOrganization(organizationId),[client,organizationId])};var useKnowledge=(organizationId)=>useOrganizationClient(organizationId).knowledge;var useAgents=(organizationId)=>useOrganizationClient(organizationId).agents;var useSkills=(organizationId)=>useOrganizationClient(organizationId).skills;var useWorkflows=(organizationId)=>useOrganizationClient(organizationId).workflows;var useRuns=(organizationId)=>useOrganizationClient(organizationId).runs;var useAttachments=(organizationId)=>useOrganizationClient(organizationId).attachments;var useClientContext=(organizationId)=>useOrganizationClient(organizationId).context;import{jsx as jsx2,jsxs}from"react/jsx-runtime";var ignoreSubmit=()=>false;var createPromptKeyHandler=(onSubmit)=>(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing){event.preventDefault();onSubmit()}};var AgentPromptPrimitive=({autoFocus=false,className,components,id,label,onChange,onSubmit,pending,status,style,submitLabel="Send",value})=>{const Form=components?.Form??"form";const Label=components?.Label??"label";const Textarea=components?.Textarea??"textarea";const Button=components?.Button??"button";const Status=components?.Status??"div";const statusId=`${id}-status`;const submit=(event)=>{event.preventDefault();if(!pending){onSubmit()}};const onKeyDown=(event)=>{createPromptKeyHandler(pending?ignoreSubmit:onSubmit)({isComposing:event.nativeEvent.isComposing,key:event.key,preventDefault:()=>{event.preventDefault()},shiftKey:event.shiftKey})};return jsxs(Form,{className:["ci-agent-prompt",className].filter(Boolean).join(" "),onSubmit:submit,style,children:[jsx2(Label,{className:"ci-agent-prompt__label",htmlFor:id,children:label}),jsx2(Textarea,{"aria-describedby":statusId,autoFocus,className:"ci-agent-prompt__input",disabled:pending,id,onChange:(event)=>{onChange(event.currentTarget.value)},onKeyDown,value}),jsx2(Button,{className:"ci-agent-prompt__submit",disabled:pending||value.trim().length===0,type:"submit",children:submitLabel}),jsx2(Status,{"aria-live":"polite",className:"ci-agent-prompt__status",id:statusId,children:status})]})};var useAgentInvocation=(organizationId)=>{const{agents}=useOrganizationClient(organizationId);const[state,setState]=useState2({status:"idle"});const invoke=useCallback(async(input)=>{setState({status:"submitting"});try{const result=await agents.invoke(input);setState(result.ok?{result,status:"success"}:{result,status:"failure"});return result}catch(error){setState({error,status:"error"});throw error}},[agents]);return{invoke,reset:()=>{setState({status:"idle"})},state}};var invocationStatus=(state)=>{switch(state.status){case"submitting":{return"Sending"}case"success":{return"Request started"}case"failure":{return state.result.error.message}case"error":{return"Request failed"}case"idle":{return null}default:{return null}}};var EMPTY_AGENT_PROMPT_COMPONENTS={};var EMPTY_AGENT_PROMPT_STYLE={};var createDefaultIdempotencyKey=()=>globalThis.crypto.randomUUID();var AgentPrompt=({agentId,autoFocus=false,className="",components=EMPTY_AGENT_PROMPT_COMPONENTS,createIdempotencyKey=createDefaultIdempotencyKey,label="Message",onResult,organizationId,style=EMPTY_AGENT_PROMPT_STYLE,submitLabel="Send"})=>{const id=`ci-agent-prompt-${useId().replaceAll(":","")}`;const[value,setValue]=useState2("");const invocation=useAgentInvocation(organizationId);const submit=()=>{const prompt=value.trim();if(prompt.length===0||invocation.state.status==="submitting"){return}const submitInvocation=async()=>{try{const result=await invocation.invoke({agentId,idempotencyKey:createIdempotencyKey(),input:{prompt}});if(result.ok){setValue("")}onResult?.(result)}catch{}};submitInvocation()};return jsx2(AgentPromptPrimitive,{autoFocus,className,components,id,label,onChange:setValue,onSubmit:submit,pending:invocation.state.status==="submitting",status:invocationStatus(invocation.state),style,submitLabel,value})};import{FederatedAuthError}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext2,useCallback as useCallback2,useContext as useContext2,useEffect,useMemo as useMemo2,useSyncExternalStore}from"react";import{jsx as jsx3}from"react/jsx-runtime";var AuthContext=createContext2(null);var toFederatedAuthError=(error)=>new FederatedAuthError("authorization_failed",error.message);var unknownAuthError=()=>new FederatedAuthError("authorization_failed","Sign in failed");var CollectiveIntelligenceLoginProvider=(props)=>{const state=useSyncExternalStore(props.auth.subscribe,props.auth.getState,props.auth.getState);const contextValue=useMemo2(()=>({auth:props.auth,state}),[props.auth,state]);return jsx3(AuthContext.Provider,{value:contextValue,children:props.clientFactory===undefined?jsx3(CollectiveIntelligenceProvider,{client:props.client,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children}):jsx3(CollectiveIntelligenceProvider,{clientFactory:props.clientFactory,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children})})};var useCollectiveIntelligenceAuth=()=>{const value=useContext2(AuthContext);if(value===null){throw new Error("CollectiveIntelligenceLoginProvider must wrap authentication bindings")}return{...value,beginLogin:value.auth.beginLogin,completeLogin:value.auth.completeLogin,logout:value.auth.logout,reauthorize:value.auth.reauthorize}};var LoginButton=({children="Sign in with Collective Intelligence",className,components,disabled=false,onError,returnTo,style})=>{const{auth,state}=useCollectiveIntelligenceAuth();const Button=components?.Button??"button";const redirecting=state.status==="redirecting";const onClick=useCallback2((event)=>{event.preventDefault();const target=returnTo??globalThis.location.href;const begin=async()=>{try{await auth.beginLogin({returnTo:target})}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};begin()},[auth,onError,returnTo]);return jsx3(Button,{"aria-busy":redirecting,className:["ci-login-button",className].filter(Boolean).join(" "),disabled:disabled||redirecting,onClick,style,type:"button",children})};var callbackMessage=(state)=>{switch(state.status){case"authenticated":{return"Sign in complete"}case"error":{return state.error.message}case"expired":{return"Sign in expired"}case"anonymous":case"redirecting":{return"Completing sign in"}default:{return"Completing sign in"}}};var LoginCallbackPrimitive=({className,components,state,style})=>{const Status=components?.Status??"div";return jsx3(Status,{"aria-live":"polite",className:["ci-login-callback",className].filter(Boolean).join(" "),style,children:callbackMessage(state)})};var LoginCallback=({callbackUrl,onComplete,onError,...primitiveProps})=>{const{auth,state}=useCollectiveIntelligenceAuth();useEffect(()=>{const url=callbackUrl??globalThis.location.href;const complete=async()=>{try{const{returnTo}=await auth.completeLogin(url);onComplete?.(returnTo)}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};complete()},[auth,callbackUrl,onComplete,onError]);return jsx3(LoginCallbackPrimitive,{...primitiveProps,state})};var useSession=()=>{const{state}=useCollectiveIntelligenceAuth();return state};var SessionGate=({children,fallback=null})=>{const session=useSession();if(session.status!=="authenticated"){return fallback}return children};import{createRealtimeClient}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext3,useContext as useContext3,useEffect as useEffect2,useState as useState3}from"react";import{jsx as jsx4}from"react/jsx-runtime";var idle={connections:0,lastEventId:undefined,status:"idle",topics:[]};var hasOnReset=(options)=>options.onReset!==undefined;var shareClient=(initial)=>{let options=initial;let client;let holders=0;const subscriptions=new Set;const create=()=>createRealtimeClient({document:globalThis.document,window:globalThis.window,...options,onAccessChanged:()=>options.onAccessChanged?.(),...hasOnReset(options)&&{onReset:()=>options.onReset?.()}});const acquire=()=>{holders+=1;client??=create();return client};const release=()=>{holders-=1;queueMicrotask(()=>{if(holders===0){client?.close();client=undefined}})};const subscribe=(topic,onChanges)=>{const subscription={onChanges,topic,unsubscribe:acquire().subscribe(topic,onChanges)};subscriptions.add(subscription);return()=>{if(subscriptions.delete(subscription)){subscription.unsubscribe();release()}}};return{acquire,getState:()=>client?.getState()??idle,release,subscribe,update:(next)=>{const previous=options;options=next;if(client===undefined||hasOnReset(next)===hasOnReset(previous)){return}for(const subscription of subscriptions){subscription.unsubscribe()}client.close();client=create();for(const subscription of subscriptions){subscription.unsubscribe=client.subscribe(subscription.topic,subscription.onChanges)}}}};var RealtimeContext=createContext3(null);var RealtimeProvider=({children,...options})=>{const[shared]=useState3(()=>shareClient(options));useEffect2(()=>{shared.update(options)});useEffect2(()=>{shared.acquire();return shared.release},[shared]);return jsx4(RealtimeContext.Provider,{value:shared,children})};var useRealtimeClient=()=>{const client=useContext3(RealtimeContext);if(client===null){throw new Error("useRealtimeClient requires a RealtimeProvider")}return client};import{realtimeTopicKey}from"@collective-intelligence/external-apps-client-sdk";import{useEffect as useEffect3,useRef,useState as useState4}from"react";var useRealtimeTopic=(topic,onChanges)=>{const client=useRealtimeClient();const latest=useRef(onChanges);const key=topic===null?null:realtimeTopicKey(topic);const[subscribed,setSubscribed]=useState4({key,topic});if(subscribed.key!==key){setSubscribed({key,topic})}useEffect3(()=>{latest.current=onChanges});useEffect3(()=>subscribed.topic===null?undefined:client.subscribe(subscribed.topic,(changes)=>latest.current(changes)),[client,subscribed])};var clientSdkReactEntrypoint="react";var{AgentPrompt:AgentPrompt2,AgentPromptPrimitive:AgentPromptPrimitive2,CollectiveIntelligenceLoginProvider:CollectiveIntelligenceLoginProvider2,CollectiveIntelligenceProvider:CollectiveIntelligenceProvider2,EntityForm,EntityList,EntityTable,LoginButton:LoginButton2,LoginCallback:LoginCallback2,LoginCallbackPrimitive:LoginCallbackPrimitive2,RealtimeProvider:RealtimeProvider2,SessionGate:SessionGate2,clientSdkReactEntrypoint:clientSdkReactEntrypoint2,createDelegatedEntitySource,createPromptKeyHandler:createPromptKeyHandler2,defineEntity,useAgents:useAgents2,useAttachments:useAttachments2,useClientContext:useClientContext2,useCollectiveIntelligenceAuth:useCollectiveIntelligenceAuth2,useCollectiveIntelligenceClient:useCollectiveIntelligenceClient2,useEntityViewState,useKnowledge:useKnowledge2,useMemoryEntityViewState,useOrganizationClient:useOrganizationClient2,useRealtimeClient:useRealtimeClient2,useRealtimeTopic:useRealtimeTopic2,useRuns:useRuns2,useSession:useSession2,useSkills:useSkills2,useWorkflows:useWorkflows2,useAgentInvocation:useAgentInvocation2}=exports_src;export{AgentPrompt2 as AgentPrompt,AgentPromptPrimitive2 as AgentPromptPrimitive,CollectiveIntelligenceLoginProvider2 as CollectiveIntelligenceLoginProvider,CollectiveIntelligenceProvider2 as CollectiveIntelligenceProvider,EntityForm,EntityList,EntityTable,LoginButton2 as LoginButton,LoginCallback2 as LoginCallback,LoginCallbackPrimitive2 as LoginCallbackPrimitive,RealtimeProvider2 as RealtimeProvider,SessionGate2 as SessionGate,clientSdkReactEntrypoint2 as clientSdkReactEntrypoint,createDelegatedEntitySource,createPromptKeyHandler2 as createPromptKeyHandler,defineEntity,useAgentInvocation2 as useAgentInvocation,useAgents2 as useAgents,useAttachments2 as useAttachments,useClientContext2 as useClientContext,useCollectiveIntelligenceAuth2 as useCollectiveIntelligenceAuth,useCollectiveIntelligenceClient2 as useCollectiveIntelligenceClient,useEntityViewState,useKnowledge2 as useKnowledge,useMemoryEntityViewState,useOrganizationClient2 as useOrganizationClient,useRealtimeClient2 as useRealtimeClient,useRealtimeTopic2 as useRealtimeTopic,useRuns2 as useRuns,useSession2 as useSession,useSkills2 as useSkills,useWorkflows2 as useWorkflows};
|
|
2
|
+
import{EntityRuntimeProvider,createDelegatedEntitySource2,defineEntity2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-zbq0t81c.js";import{useCallback,useId,useState as useState2}from"react";import{QueryClient,QueryClientProvider}from"@tanstack/react-query";import{createContext,useContext,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";var ClientContext=createContext(null);var CollectiveIntelligenceProvider=(props)=>{const{clientFactory}=props;const[ownedQueryClient]=useState(()=>new QueryClient({defaultOptions:{mutations:{retry:false},queries:{retry:false}}}));const ownedClient=useMemo(()=>clientFactory===undefined?undefined:clientFactory(),[clientFactory]);const client=props.client??ownedClient;const queryClient=props.queryClient??ownedQueryClient;if(client===undefined){throw new TypeError("A client or clientFactory is required")}return jsx(ClientContext.Provider,{value:client,children:jsx(QueryClientProvider,{client:queryClient,children:props.entitySource===undefined?props.children:jsx(EntityRuntimeProvider,{onWriteFailed:props.onWriteFailed,source:props.entitySource,children:props.children})})})};var useCollectiveIntelligenceClient=()=>{const client=useContext(ClientContext);if(client===null){throw new Error("CollectiveIntelligenceProvider must wrap Collective Intelligence hooks")}return client};var useOrganizationClient=(organizationId)=>{const client=useCollectiveIntelligenceClient();return useMemo(()=>client.forOrganization(organizationId),[client,organizationId])};var useKnowledge=(organizationId)=>useOrganizationClient(organizationId).knowledge;var useAgents=(organizationId)=>useOrganizationClient(organizationId).agents;var useSkills=(organizationId)=>useOrganizationClient(organizationId).skills;var useWorkflows=(organizationId)=>useOrganizationClient(organizationId).workflows;var useRuns=(organizationId)=>useOrganizationClient(organizationId).runs;var useAttachments=(organizationId)=>useOrganizationClient(organizationId).attachments;var useClientContext=(organizationId)=>useOrganizationClient(organizationId).context;import{jsx as jsx2,jsxs}from"react/jsx-runtime";var ignoreSubmit=()=>false;var createPromptKeyHandler=(onSubmit)=>(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing){event.preventDefault();onSubmit()}};var AgentPromptPrimitive=({autoFocus=false,className,components,id,label,onChange,onSubmit,pending,status,style,submitLabel="Send",value})=>{const Form=components?.Form??"form";const Label=components?.Label??"label";const Textarea=components?.Textarea??"textarea";const Button=components?.Button??"button";const Status=components?.Status??"div";const statusId=`${id}-status`;const submit=(event)=>{event.preventDefault();if(!pending){onSubmit()}};const onKeyDown=(event)=>{createPromptKeyHandler(pending?ignoreSubmit:onSubmit)({isComposing:event.nativeEvent.isComposing,key:event.key,preventDefault:()=>{event.preventDefault()},shiftKey:event.shiftKey})};return jsxs(Form,{className:["ci-agent-prompt",className].filter(Boolean).join(" "),onSubmit:submit,style,children:[jsx2(Label,{className:"ci-agent-prompt__label",htmlFor:id,children:label}),jsx2(Textarea,{"aria-describedby":statusId,autoFocus,className:"ci-agent-prompt__input",disabled:pending,id,onChange:(event)=>{onChange(event.currentTarget.value)},onKeyDown,value}),jsx2(Button,{className:"ci-agent-prompt__submit",disabled:pending||value.trim().length===0,type:"submit",children:submitLabel}),jsx2(Status,{"aria-live":"polite",className:"ci-agent-prompt__status",id:statusId,children:status})]})};var useAgentInvocation=(organizationId)=>{const{agents}=useOrganizationClient(organizationId);const[state,setState]=useState2({status:"idle"});const invoke=useCallback(async(input)=>{setState({status:"submitting"});try{const result=await agents.invoke(input);setState(result.ok?{result,status:"success"}:{result,status:"failure"});return result}catch(error){setState({error,status:"error"});throw error}},[agents]);return{invoke,reset:()=>{setState({status:"idle"})},state}};var invocationStatus=(state)=>{switch(state.status){case"submitting":{return"Sending"}case"success":{return"Request started"}case"failure":{return state.result.error.message}case"error":{return"Request failed"}case"idle":{return null}default:{return null}}};var EMPTY_AGENT_PROMPT_COMPONENTS={};var EMPTY_AGENT_PROMPT_STYLE={};var createDefaultIdempotencyKey=()=>globalThis.crypto.randomUUID();var AgentPrompt=({agentId,autoFocus=false,className="",components=EMPTY_AGENT_PROMPT_COMPONENTS,createIdempotencyKey=createDefaultIdempotencyKey,label="Message",onResult,organizationId,style=EMPTY_AGENT_PROMPT_STYLE,submitLabel="Send"})=>{const id=`ci-agent-prompt-${useId().replaceAll(":","")}`;const[value,setValue]=useState2("");const invocation=useAgentInvocation(organizationId);const submit=()=>{const prompt=value.trim();if(prompt.length===0||invocation.state.status==="submitting"){return}const submitInvocation=async()=>{try{const result=await invocation.invoke({agentId,idempotencyKey:createIdempotencyKey(),input:{prompt}});if(result.ok){setValue("")}onResult?.(result)}catch{}};submitInvocation()};return jsx2(AgentPromptPrimitive,{autoFocus,className,components,id,label,onChange:setValue,onSubmit:submit,pending:invocation.state.status==="submitting",status:invocationStatus(invocation.state),style,submitLabel,value})};import{FederatedAuthError}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext2,useCallback as useCallback2,useContext as useContext2,useEffect,useMemo as useMemo2,useSyncExternalStore}from"react";import{jsx as jsx3}from"react/jsx-runtime";var AuthContext=createContext2(null);var toFederatedAuthError=(error)=>new FederatedAuthError("authorization_failed",error.message);var unknownAuthError=()=>new FederatedAuthError("authorization_failed","Sign in failed");var CollectiveIntelligenceLoginProvider=(props)=>{const state=useSyncExternalStore(props.auth.subscribe,props.auth.getState,props.auth.getState);const contextValue=useMemo2(()=>({auth:props.auth,state}),[props.auth,state]);return jsx3(AuthContext.Provider,{value:contextValue,children:props.clientFactory===undefined?jsx3(CollectiveIntelligenceProvider,{client:props.client,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children}):jsx3(CollectiveIntelligenceProvider,{clientFactory:props.clientFactory,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children})})};var useCollectiveIntelligenceAuth=()=>{const value=useContext2(AuthContext);if(value===null){throw new Error("CollectiveIntelligenceLoginProvider must wrap authentication bindings")}return{...value,beginLogin:value.auth.beginLogin,completeLogin:value.auth.completeLogin,logout:value.auth.logout,reauthorize:value.auth.reauthorize}};var LoginButton=({children="Sign in with Collective Intelligence",className,components,disabled=false,onError,returnTo,style})=>{const{auth,state}=useCollectiveIntelligenceAuth();const Button=components?.Button??"button";const redirecting=state.status==="redirecting";const onClick=useCallback2((event)=>{event.preventDefault();const target=returnTo??globalThis.location.href;const begin=async()=>{try{await auth.beginLogin({returnTo:target})}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};begin()},[auth,onError,returnTo]);return jsx3(Button,{"aria-busy":redirecting,className:["ci-login-button",className].filter(Boolean).join(" "),disabled:disabled||redirecting,onClick,style,type:"button",children})};var callbackMessage=(state)=>{switch(state.status){case"authenticated":{return"Sign in complete"}case"error":{return state.error.message}case"expired":{return"Sign in expired"}case"anonymous":case"redirecting":{return"Completing sign in"}default:{return"Completing sign in"}}};var LoginCallbackPrimitive=({className,components,state,style})=>{const Status=components?.Status??"div";return jsx3(Status,{"aria-live":"polite",className:["ci-login-callback",className].filter(Boolean).join(" "),style,children:callbackMessage(state)})};var LoginCallback=({callbackUrl,onComplete,onError,...primitiveProps})=>{const{auth,state}=useCollectiveIntelligenceAuth();useEffect(()=>{const url=callbackUrl??globalThis.location.href;const complete=async()=>{try{const{returnTo}=await auth.completeLogin(url);onComplete?.(returnTo)}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};complete()},[auth,callbackUrl,onComplete,onError]);return jsx3(LoginCallbackPrimitive,{...primitiveProps,state})};var useSession=()=>{const{state}=useCollectiveIntelligenceAuth();return state};var SessionGate=({children,fallback=null})=>{const session=useSession();if(session.status!=="authenticated"){return fallback}return children};import{createRealtimeClient}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext3,useContext as useContext3,useEffect as useEffect2,useState as useState3}from"react";import{jsx as jsx4}from"react/jsx-runtime";var idle={connections:0,lastEventId:undefined,status:"idle",topics:[]};var hasOnReset=(options)=>options.onReset!==undefined;var shareClient=(initial)=>{let options=initial;let client;let holders=0;const subscriptions=new Set;const create=()=>createRealtimeClient({document:globalThis.document,window:globalThis.window,...options,onAccessChanged:()=>options.onAccessChanged?.(),...hasOnReset(options)&&{onReset:()=>options.onReset?.()}});const acquire=()=>{holders+=1;client??=create();return client};const release=()=>{holders-=1;queueMicrotask(()=>{if(holders===0){client?.close();client=undefined}})};const subscribe=(topic,onChanges)=>{const subscription={onChanges,topic,unsubscribe:acquire().subscribe(topic,onChanges)};subscriptions.add(subscription);return()=>{if(subscriptions.delete(subscription)){subscription.unsubscribe();release()}}};return{acquire,getState:()=>client?.getState()??idle,release,subscribe,update:(next)=>{const previous=options;options=next;if(client===undefined||hasOnReset(next)===hasOnReset(previous)){return}for(const subscription of subscriptions){subscription.unsubscribe()}client.close();client=create();for(const subscription of subscriptions){subscription.unsubscribe=client.subscribe(subscription.topic,subscription.onChanges)}}}};var RealtimeContext=createContext3(null);var RealtimeProvider=({children,...options})=>{const[shared]=useState3(()=>shareClient(options));useEffect2(()=>{shared.update(options)});useEffect2(()=>{shared.acquire();return shared.release},[shared]);return jsx4(RealtimeContext.Provider,{value:shared,children})};var useRealtimeClient=()=>{const client=useContext3(RealtimeContext);if(client===null){throw new Error("useRealtimeClient requires a RealtimeProvider")}return client};import{realtimeTopicKey}from"@collective-intelligence/external-apps-client-sdk";import{useEffect as useEffect3,useRef,useState as useState4}from"react";var useRealtimeTopic=(topic,onChanges)=>{const client=useRealtimeClient();const latest=useRef(onChanges);const key=topic===null?null:realtimeTopicKey(topic);const[subscribed,setSubscribed]=useState4({key,topic});if(subscribed.key!==key){setSubscribed({key,topic})}useEffect3(()=>{latest.current=onChanges});useEffect3(()=>subscribed.topic===null?undefined:client.subscribe(subscribed.topic,(changes)=>latest.current(changes)),[client,subscribed])};var clientSdkReactEntrypoint="react";export{AgentPrompt,AgentPromptPrimitive,CollectiveIntelligenceLoginProvider,CollectiveIntelligenceProvider,EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,LoginButton,LoginCallback,LoginCallbackPrimitive,RealtimeProvider,SessionGate,clientSdkReactEntrypoint,createDelegatedEntitySource2 as createDelegatedEntitySource,createPromptKeyHandler,defineEntity2 as defineEntity,useAgentInvocation,useAgents,useAttachments,useClientContext,useCollectiveIntelligenceAuth,useCollectiveIntelligenceClient,useEntityViewState2 as useEntityViewState,useKnowledge,useMemoryEntityViewState2 as useMemoryEntityViewState,useOrganizationClient,useRealtimeClient,useRealtimeTopic,useRuns,useSession,useSkills,useWorkflows};
|
package/dist/resources.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-zbq0t81c.js";import{__export}from"./index-6ra894v2.js";var exports_resources={};__export(exports_resources,{EntityForm:()=>EntityForm2,EntityList:()=>EntityList2,EntityTable:()=>EntityTable2,ResourceCapabilityAction:()=>ResourceCapabilityAction,ResourceFilter:()=>ResourceFilter,ResourceLifecycleAction:()=>ResourceLifecycleAction,ResourceList:()=>ResourceList,ResourcePagination:()=>ResourcePagination,ResourceProvider:()=>ResourceProvider,ResourceQueryError:()=>ResourceQueryError2,ResourceTable:()=>ResourceTable,createDelegatedEntitySource:()=>createDelegatedEntitySource2,defineEntity:()=>defineEntity2,hasResourceCapability:()=>hasResourceCapability2,mapResourceAuthState:()=>mapResourceAuthState2,unwrapResourceResult:()=>unwrapResourceResult2,useEntityChanges:()=>useEntityChanges,useEntityCreate:()=>useEntityCreate2,useEntityDelete:()=>useEntityDelete2,useEntityList:()=>useEntityList2,useEntityRecord:()=>useEntityRecord2,useEntityUpdate:()=>useEntityUpdate2,useEntityViewState:()=>useEntityViewState2,useMemoryEntityViewState:()=>useMemoryEntityViewState2});import{useMutation,useQuery,useQueryClient as useQueryClient2}from"@tanstack/react-query";import{mutationOptions}from"@tanstack/react-query";var invalidateResource=async(options)=>{await options.queryClient.invalidateQueries({queryKey:resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version)})};var createResourceMutationOptions=(options)=>mutationOptions({mutationFn:async(input)=>{let result;switch(options.operation){case"hard_delete":{unwrapResourceResult2(await options.client.hardDelete(input));break}case"restore":{result=unwrapResourceResult2(await options.client.restore(input));break}case"soft_delete":{result=unwrapResourceResult2(await options.client.softDelete(input));break}default:{throw new TypeError(`Unknown resource operation: ${String(options.operation)}`)}}return result},mutationKey:[...resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version),"mutations",options.operation],onSuccess:async()=>{await invalidateResource(options)}});import{useQueryClient}from"@tanstack/react-query";import{createContext,useContext,useEffect,useMemo,useRef}from"react";import{jsx}from"react/jsx-runtime";var useResourceQueryCleanup=(queryClient,authStatus,organizationId)=>{const previousOrganizationId=useRef(null);const input=useMemo(()=>({authStatus,organizationId}),[authStatus,organizationId]);useEffect(()=>{const previous=previousOrganizationId.current;previousOrganizationId.current=input.organizationId;if(input.authStatus!=="authenticated"){clearProtectedResourceQueries(queryClient);return}if(previous!==null&&previous!==input.organizationId){clearProtectedResourceQueries(queryClient,previous)}},[input,queryClient])};var ResourceContext=createContext(null);var ResourceProvider=({authState,capabilities,children,organizationId})=>{const queryClient=useQueryClient();useResourceQueryCleanup(queryClient,authState.status,organizationId);const value=useMemo(()=>({authState,capabilities,organizationId}),[authState,capabilities,organizationId]);return jsx(ResourceContext.Provider,{value,children})};var useResourceContext=()=>{const value=useContext(ResourceContext);if(value===null){throw new Error("ResourceProvider must wrap resource bindings")}return value};var authStateForError=(error,fallback)=>error instanceof ResourceQueryError2?mapResourceAuthState2({correlationId:error.correlationId,error:error.resourceError,ok:false}):fallback;var useResourceList=(client,query)=>{const context=useResourceContext();const result=useQuery({...createResourceListQueryOptions({client,organizationId:context.organizationId,query}),enabled:context.authState.status==="authenticated"});return{...result,authState:authStateForError(result.error,context.authState)}};var useResourceLifecycleMutation=(client,operation)=>{const{capabilities,organizationId}=useResourceContext();const queryClient=useQueryClient2();const mutation=useMutation(createResourceMutationOptions({client,operation,organizationId,queryClient}));let capability;if(operation==="hard_delete"){capability="hardDelete"}else if(operation==="soft_delete"){capability="softDelete"}else{capability=operation}return{...mutation,available:capabilities[capability]===true}};import{jsx as jsx2,jsxs,Fragment}from"react/jsx-runtime";var nextQuery=(query,result)=>{if(result.pagination==="cursor"){return result.nextCursor===undefined?undefined:{...query,pagination:{cursor:result.nextCursor,limit:query.pagination.mode==="cursor"?query.pagination.limit:25,mode:"cursor"}}}return result.page>=result.totalPages?undefined:{...query,pagination:{mode:"page",page:result.page+1,pageSize:result.pageSize}}};var previousQuery=(query,result)=>result.pagination==="page"&&result.page>1?{...query,pagination:{mode:"page",page:result.page-1,pageSize:result.pageSize}}:undefined;var DefaultStatus=({authState,error,pending})=>{let message=authState.status;if(authState.status==="authenticated"){message=pending?"Loading resources":error?.message??""}return jsx2("output",{"aria-live":"polite",children:message})};var ResourceList=({client,components,onQueryChange,query,renderItem})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{List}=components;const{Pagination}=components;const result=resourceQuery.data;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsxs(Fragment,{children:[jsx2(List,{getItemKey:(item)=>item.id,items:result.items,renderItem}),Pagination===undefined?null:jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending:resourceQuery.isFetching,onNext:()=>{if(next!==undefined){onQueryChange?.(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange?.(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})]})};var ResourceCapabilityAction=({capability,children,components,unsupported="disable"})=>{const{capabilities}=useResourceContext();const supported=capabilities[capability]===true;if(!supported&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!supported,children})};var ResourceFilter=({components,label="Search resources",onQueryChange,query})=>{const{Filter}=components;const{textSearch:_textSearch,...queryWithoutTextSearch}=query;return jsx2(Filter,{label,onChange:(value)=>{onQueryChange(value===""?queryWithoutTextSearch:{...query,textSearch:value})},value:query.textSearch??""})};var ResourcePagination=({components,isPending=false,onQueryChange,query,result})=>{const{Pagination}=components;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending,onNext:()=>{if(next!==undefined){onQueryChange(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})};var ResourceTable=({caption,client,columns,components,query})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{Table}=components;return jsx2(Table,{caption,columns,getRowKey:(row)=>row.id,renderCell:(row,column)=>column.render(row),rows:resourceQuery.data.items})};var ResourceLifecycleAction=({children,client,components,input,operation,unsupported="disable"})=>{const mutation=useResourceLifecycleMutation(client,operation);if(!mutation.available&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!mutation.available,onClick:()=>{mutation.mutate(input)},pending:mutation.isPending,children})};import{useQueryClient as useQueryClient3}from"@tanstack/react-query";import{useCallback}from"react";var useEntityChanges=(contract)=>{const runtime=useEntityRuntime();const queryClient=useQueryClient3();return useCallback((changes)=>{if(changes.length===0||!runtime.current()){return}const resourceKey=["ci-entities",...runtime.key,contract.id,contract.version];for(const change of changes){const recordKey=[...resourceKey,"record",change.id];const record=queryClient.getQueryData(recordKey);if(record?.revision!==change.revision){queryClient.invalidateQueries({exact:true,queryKey:recordKey})}}queryClient.invalidateQueries({queryKey:[...resourceKey,"list"]})},[contract.id,contract.version,queryClient,runtime])};var{createDelegatedEntitySource,defineEntity,EntityForm,EntityList,EntityTable,ResourceCapabilityAction:ResourceCapabilityAction2,ResourceFilter:ResourceFilter2,ResourceLifecycleAction:ResourceLifecycleAction2,ResourceList:ResourceList2,ResourcePagination:ResourcePagination2,ResourceProvider:ResourceProvider2,ResourceQueryError,ResourceTable:ResourceTable2,hasResourceCapability,mapResourceAuthState,unwrapResourceResult,useEntityCreate,useEntityChanges:useEntityChanges2,useEntityDelete,useEntityList,useEntityRecord,useEntityUpdate,useEntityViewState,useMemoryEntityViewState}=exports_resources;export{EntityForm,EntityList,EntityTable,ResourceCapabilityAction2 as ResourceCapabilityAction,ResourceFilter2 as ResourceFilter,ResourceLifecycleAction2 as ResourceLifecycleAction,ResourceList2 as ResourceList,ResourcePagination2 as ResourcePagination,ResourceProvider2 as ResourceProvider,ResourceQueryError,ResourceTable2 as ResourceTable,createDelegatedEntitySource,defineEntity,hasResourceCapability,mapResourceAuthState,unwrapResourceResult,useEntityChanges2 as useEntityChanges,useEntityCreate,useEntityDelete,useEntityList,useEntityRecord,useEntityUpdate,useEntityViewState,useMemoryEntityViewState};
|
|
2
|
+
import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,useEntityRuntime,createDelegatedEntitySource2,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-zbq0t81c.js";import{useMutation,useQuery,useQueryClient as useQueryClient2}from"@tanstack/react-query";import{mutationOptions}from"@tanstack/react-query";var invalidateResource=async(options)=>{await options.queryClient.invalidateQueries({queryKey:resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version)})};var createResourceMutationOptions=(options)=>mutationOptions({mutationFn:async(input)=>{let result;switch(options.operation){case"hard_delete":{unwrapResourceResult2(await options.client.hardDelete(input));break}case"restore":{result=unwrapResourceResult2(await options.client.restore(input));break}case"soft_delete":{result=unwrapResourceResult2(await options.client.softDelete(input));break}default:{throw new TypeError(`Unknown resource operation: ${String(options.operation)}`)}}return result},mutationKey:[...resourceKeys.resource(options.organizationId,options.client.definition.id,options.client.definition.version),"mutations",options.operation],onSuccess:async()=>{await invalidateResource(options)}});import{useQueryClient}from"@tanstack/react-query";import{createContext,useContext,useEffect,useMemo,useRef}from"react";import{jsx}from"react/jsx-runtime";var useResourceQueryCleanup=(queryClient,authStatus,organizationId)=>{const previousOrganizationId=useRef(null);const input=useMemo(()=>({authStatus,organizationId}),[authStatus,organizationId]);useEffect(()=>{const previous=previousOrganizationId.current;previousOrganizationId.current=input.organizationId;if(input.authStatus!=="authenticated"){clearProtectedResourceQueries(queryClient);return}if(previous!==null&&previous!==input.organizationId){clearProtectedResourceQueries(queryClient,previous)}},[input,queryClient])};var ResourceContext=createContext(null);var ResourceProvider=({authState,capabilities,children,organizationId})=>{const queryClient=useQueryClient();useResourceQueryCleanup(queryClient,authState.status,organizationId);const value=useMemo(()=>({authState,capabilities,organizationId}),[authState,capabilities,organizationId]);return jsx(ResourceContext.Provider,{value,children})};var useResourceContext=()=>{const value=useContext(ResourceContext);if(value===null){throw new Error("ResourceProvider must wrap resource bindings")}return value};var authStateForError=(error,fallback)=>error instanceof ResourceQueryError2?mapResourceAuthState2({correlationId:error.correlationId,error:error.resourceError,ok:false}):fallback;var useResourceList=(client,query)=>{const context=useResourceContext();const result=useQuery({...createResourceListQueryOptions({client,organizationId:context.organizationId,query}),enabled:context.authState.status==="authenticated"});return{...result,authState:authStateForError(result.error,context.authState)}};var useResourceLifecycleMutation=(client,operation)=>{const{capabilities,organizationId}=useResourceContext();const queryClient=useQueryClient2();const mutation=useMutation(createResourceMutationOptions({client,operation,organizationId,queryClient}));let capability;if(operation==="hard_delete"){capability="hardDelete"}else if(operation==="soft_delete"){capability="softDelete"}else{capability=operation}return{...mutation,available:capabilities[capability]===true}};import{jsx as jsx2,jsxs,Fragment}from"react/jsx-runtime";var nextQuery=(query,result)=>{if(result.pagination==="cursor"){return result.nextCursor===undefined?undefined:{...query,pagination:{cursor:result.nextCursor,limit:query.pagination.mode==="cursor"?query.pagination.limit:25,mode:"cursor"}}}return result.page>=result.totalPages?undefined:{...query,pagination:{mode:"page",page:result.page+1,pageSize:result.pageSize}}};var previousQuery=(query,result)=>result.pagination==="page"&&result.page>1?{...query,pagination:{mode:"page",page:result.page-1,pageSize:result.pageSize}}:undefined;var DefaultStatus=({authState,error,pending})=>{let message=authState.status;if(authState.status==="authenticated"){message=pending?"Loading resources":error?.message??""}return jsx2("output",{"aria-live":"polite",children:message})};var ResourceList=({client,components,onQueryChange,query,renderItem})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{List}=components;const{Pagination}=components;const result=resourceQuery.data;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsxs(Fragment,{children:[jsx2(List,{getItemKey:(item)=>item.id,items:result.items,renderItem}),Pagination===undefined?null:jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending:resourceQuery.isFetching,onNext:()=>{if(next!==undefined){onQueryChange?.(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange?.(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})]})};var ResourceCapabilityAction=({capability,children,components,unsupported="disable"})=>{const{capabilities}=useResourceContext();const supported=capabilities[capability]===true;if(!supported&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!supported,children})};var ResourceFilter=({components,label="Search resources",onQueryChange,query})=>{const{Filter}=components;const{textSearch:_textSearch,...queryWithoutTextSearch}=query;return jsx2(Filter,{label,onChange:(value)=>{onQueryChange(value===""?queryWithoutTextSearch:{...query,textSearch:value})},value:query.textSearch??""})};var ResourcePagination=({components,isPending=false,onQueryChange,query,result})=>{const{Pagination}=components;const next=nextQuery(query,result);const previous=previousQuery(query,result);return jsx2(Pagination,{hasNextPage:next!==undefined,hasPreviousPage:previous!==undefined,isPending,onNext:()=>{if(next!==undefined){onQueryChange(next)}},onPrevious:()=>{if(previous!==undefined){onQueryChange(previous)}},...result.pagination==="page"?{currentPage:result.page}:{}})};var ResourceTable=({caption,client,columns,components,query})=>{const resourceQuery=useResourceList(client,query);const Status=components.Status??DefaultStatus;if(resourceQuery.authState.status!=="authenticated"||resourceQuery.isPending||resourceQuery.error!==null){return jsx2(Status,{authState:resourceQuery.authState,pending:resourceQuery.isPending,...resourceQuery.error===null?{}:{error:resourceQuery.error}})}const{Table}=components;return jsx2(Table,{caption,columns,getRowKey:(row)=>row.id,renderCell:(row,column)=>column.render(row),rows:resourceQuery.data.items})};var ResourceLifecycleAction=({children,client,components,input,operation,unsupported="disable"})=>{const mutation=useResourceLifecycleMutation(client,operation);if(!mutation.available&&unsupported==="hide"){return null}const{Action}=components;return jsx2(Action,{disabled:!mutation.available,onClick:()=>{mutation.mutate(input)},pending:mutation.isPending,children})};import{useQueryClient as useQueryClient3}from"@tanstack/react-query";import{useCallback}from"react";var useEntityChanges=(contract)=>{const runtime=useEntityRuntime();const queryClient=useQueryClient3();return useCallback((changes)=>{if(changes.length===0||!runtime.current()){return}const resourceKey=["ci-entities",...runtime.key,contract.id,contract.version];for(const change of changes){const recordKey=[...resourceKey,"record",change.id];const record=queryClient.getQueryData(recordKey);if(record?.revision!==change.revision){queryClient.invalidateQueries({exact:true,queryKey:recordKey})}}queryClient.invalidateQueries({queryKey:[...resourceKey,"list"]})},[contract.id,contract.version,queryClient,runtime])};export{EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,ResourceCapabilityAction,ResourceFilter,ResourceLifecycleAction,ResourceList,ResourcePagination,ResourceProvider,ResourceQueryError2 as ResourceQueryError,ResourceTable,createDelegatedEntitySource2 as createDelegatedEntitySource,defineEntity2 as defineEntity,hasResourceCapability2 as hasResourceCapability,mapResourceAuthState2 as mapResourceAuthState,unwrapResourceResult2 as unwrapResourceResult,useEntityChanges,useEntityCreate2 as useEntityCreate,useEntityDelete2 as useEntityDelete,useEntityList2 as useEntityList,useEntityRecord2 as useEntityRecord,useEntityUpdate2 as useEntityUpdate,useEntityViewState2 as useEntityViewState,useMemoryEntityViewState2 as useMemoryEntityViewState};
|
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.
|
|
3
|
+
"version": "0.2.13",
|
|
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": "
|
|
91
|
+
"gitHead": "5c6e6747e229d629d02380e62f0574c3e37d0090"
|
|
92
92
|
}
|
package/dist/index-6ra894v2.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};
|
|
2
|
-
export{__export};
|