@collective-intelligence/external-apps-client-sdk-react 0.2.4 → 0.2.6
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 +4 -2
- package/README.md +16 -2
- package/dist/effect.d.ts +17 -0
- package/dist/effect.js +1 -1
- package/dist/index.js +1 -1
- package/dist/resources.js +1 -1
- package/docs/effect.md +19 -0
- package/package.json +3 -3
- package/skills/client-sdk-react-move-to-effect/SKILL.md +5 -3
package/AGENTS.md
CHANGED
|
@@ -18,8 +18,10 @@ holds the full API.
|
|
|
18
18
|
- To share one cache, pass the app's QueryClient to
|
|
19
19
|
`CollectiveIntelligenceProvider` as `queryClient`.
|
|
20
20
|
- Run each side effect of a machine in a `fromEffect` actor. Keep remote data
|
|
21
|
-
in `QueryCache`, never in machine context.
|
|
22
|
-
`
|
|
21
|
+
in `QueryCache`, never in machine context. After a write, refresh reads with
|
|
22
|
+
`QueryCache` (`invalidate`, `setData`, `update`, `remove`); do not put the
|
|
23
|
+
QueryClient in machine input. A view renders: it calls no `fetch` and runs
|
|
24
|
+
no Effect.
|
|
23
25
|
- Show write failures with `onWriteFailed` on the provider, for example
|
|
24
26
|
`ciWriteFailedToast()` of `@collective-intelligence/ui-react/ui`.
|
|
25
27
|
- Give `RealtimeProvider` an `onReset` that refetches every realtime-driven
|
package/README.md
CHANGED
|
@@ -257,8 +257,22 @@ QueryClient. It has no Effect Atom bindings.
|
|
|
257
257
|
`query`. A `fetch` that waits then returns the value from before the fetch,
|
|
258
258
|
or is interrupted when the key has no value. `invalidate(queryKey)` marks
|
|
259
259
|
values stale and refetches the ones that views show.
|
|
260
|
-
`setData(queryKey, value)` writes a value that views show at once.
|
|
261
|
-
|
|
260
|
+
`setData(queryKey, value)` writes a value that views show at once.
|
|
261
|
+
`update(queryKey, (current) => next)` replaces each cached value with the
|
|
262
|
+
result of the function for its current value, without a refetch, for
|
|
263
|
+
example an optimistic toggle or a changed row; views show the new values at
|
|
264
|
+
once. Each key under `queryKey` must hold a value of the type that the
|
|
265
|
+
function takes. `current` is `undefined` for an entry without a value, an
|
|
266
|
+
`undefined` result keeps the value, and a key that the cache does not hold
|
|
267
|
+
stays absent. `update` does not cancel a running fetch, which can replace
|
|
268
|
+
the new value when it ends.
|
|
269
|
+
`remove(queryKey)` removes the cached entries without a refetch, for example
|
|
270
|
+
at sign-out; it cancels a running fetch of a removed key, and the next
|
|
271
|
+
`fetch` runs its query. A mounted view of a removed key keeps its last
|
|
272
|
+
result until it renders again. `invalidate`,
|
|
273
|
+
`update` and `remove` apply to `queryKey` and to each key below it
|
|
274
|
+
(`["crm", "lead"]` matches `["crm", "lead", "7"]`, not `["crm", "leads"]`);
|
|
275
|
+
`setData` writes `queryKey` only. Views read the same keys with `useQuery`.
|
|
262
276
|
|
|
263
277
|
```tsx
|
|
264
278
|
import type { EffectRunner } from "@collective-intelligence/external-apps-client-sdk-react/effect"
|
package/dist/effect.d.ts
CHANGED
|
@@ -38,6 +38,23 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
|
|
|
38
38
|
invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
|
|
39
39
|
/** Caches `data` as the value of `queryKey`; views show it at once. */
|
|
40
40
|
setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Replaces the cached value of `queryKey` and of each cached key below it
|
|
43
|
+
* with the result of `updater` for its current value, without a refetch;
|
|
44
|
+
* views show the new values at once. `updater` gets `undefined` for an entry
|
|
45
|
+
* without a value, and its `undefined` result keeps the value. Keys that the
|
|
46
|
+
* cache does not hold stay absent. Each key below `queryKey` must hold a
|
|
47
|
+
* `Data` value. A running fetch is not cancelled, and its value replaces the
|
|
48
|
+
* new value when it ends.
|
|
49
|
+
*/
|
|
50
|
+
update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Removes the entries of `queryKey` and of the keys below it from the cache,
|
|
53
|
+
* without a refetch, and cancels a running fetch of a removed key. The next
|
|
54
|
+
* fetch of a removed key runs its query. A mounted view of a removed key
|
|
55
|
+
* keeps its last result until it renders again.
|
|
56
|
+
*/
|
|
57
|
+
remove: (queryKey: QueryKey) => Effect.Effect<void>;
|
|
41
58
|
}>>;
|
|
42
59
|
/**
|
|
43
60
|
* The remote data of the app's `QueryClient`, as machine actors read and
|
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,fromEffect:()=>fromEffect,useEffectRuntime:()=>useEffectRuntime});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}});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({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})),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)})})};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};
|
|
2
|
+
import{__export}from"./index-6ra894v2.js";var exports_effect={};__export(exports_effect,{EffectRuntimeProvider:()=>EffectRuntimeProvider,QueryCache:()=>QueryCache,fromEffect:()=>fromEffect,useEffectRuntime:()=>useEffectRuntime});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}});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({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,fromEffect:fromEffect2,useEffectRuntime:useEffectRuntime2}=exports_effect;export{EffectRuntimeProvider2 as EffectRuntimeProvider,QueryCache2 as QueryCache,fromEffect2 as fromEffect,useEffectRuntime2 as 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-qkm3tz5f.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])};"use client";var clientSdkReactEntrypoint="react";"use client";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-qkm3tz5f.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};
|
package/dist/resources.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,createDelegatedEntitySource2,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-qkm3tz5f.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,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})};
|
|
2
|
+
import{resourceKeys,ResourceQueryError2,unwrapResourceResult2,createResourceListQueryOptions,mapResourceAuthState2,hasResourceCapability2,clearProtectedResourceQueries,createDelegatedEntitySource2,defineEntity2,useEntityUpdate2,useEntityCreate2,useEntityDelete2,useEntityList2,useEntityRecord2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-qkm3tz5f.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,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})};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,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,useEntityCreate,useEntityDelete,useEntityList,useEntityRecord,useEntityUpdate,useEntityViewState,useMemoryEntityViewState};
|
package/docs/effect.md
CHANGED
|
@@ -22,8 +22,27 @@ is an actor; each actor is a `fromEffect` actor.
|
|
|
22
22
|
- `invalidate(queryKey)` marks values stale and refetches the ones that
|
|
23
23
|
views show.
|
|
24
24
|
- `setData(queryKey, value)` writes a value that views show at once.
|
|
25
|
+
- `update(queryKey, (current) => next)` replaces each cached value with the
|
|
26
|
+
result of the function for its current value, without a refetch, for example
|
|
27
|
+
for an optimistic toggle or a changed row. `current` is `undefined` for
|
|
28
|
+
an entry without a value; an `undefined` result keeps the value. A key
|
|
29
|
+
that the cache does not hold stays absent. Each key under `queryKey`
|
|
30
|
+
must hold a value of the type that the function takes. A running fetch
|
|
31
|
+
is not cancelled and can replace the new value when it ends.
|
|
32
|
+
- `remove(queryKey)` removes the cached entries without a refetch, for
|
|
33
|
+
example at sign-out. It cancels a running fetch of a removed key; the
|
|
34
|
+
next `fetch` runs its query. A mounted view of a removed key keeps its
|
|
35
|
+
last result until it renders again, so remove at sign-out before or as
|
|
36
|
+
the views of the user unmount.
|
|
37
|
+
- `invalidate`, `update` and `remove` apply to `queryKey` and to each key
|
|
38
|
+
below it: `["crm", "lead"]` matches `["crm", "lead", "7"]`, not
|
|
39
|
+
`["crm", "leads"]` or `["crm"]`. `setData` writes `queryKey` only.
|
|
25
40
|
- Views read the same keys with `useQuery`.
|
|
26
41
|
|
|
42
|
+
A write refreshes the reads through `QueryCache`: `invalidate` to read again
|
|
43
|
+
from CI, `setData` or `update` to show a known value, `remove` to drop values
|
|
44
|
+
that the next user must not get. Machine input holds no QueryClient.
|
|
45
|
+
|
|
27
46
|
```tsx
|
|
28
47
|
import type { EffectRunner } from "@collective-intelligence/external-apps-client-sdk-react/effect"
|
|
29
48
|
import {
|
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.6",
|
|
4
4
|
"description": "React bindings for Collective Intelligence external applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"type-check": "bun check"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@collective-intelligence/external-apps-client-sdk": "0.2.
|
|
51
|
+
"@collective-intelligence/external-apps-client-sdk": "0.2.3",
|
|
52
52
|
"nuqs": "2.10.1"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
@@ -88,5 +88,5 @@
|
|
|
88
88
|
"vitest": "4.1.10",
|
|
89
89
|
"xstate": "5.33.3"
|
|
90
90
|
},
|
|
91
|
-
"gitHead": "
|
|
91
|
+
"gitHead": "1718b80bc8d0ba696d78ac8f5f905c8dc46fe0c5"
|
|
92
92
|
}
|
|
@@ -23,9 +23,11 @@ Reference: [effect.md](../../docs/effect.md), [errors.md](../../docs/errors.md).
|
|
|
23
23
|
input. Map the typed failure in `onError`. Done when step 1 finds no
|
|
24
24
|
side-effect actor of XState.
|
|
25
25
|
4. **Move API data to `QueryCache`.** Read with `cache.fetch({ queryKey, query })`;
|
|
26
|
-
after a write, `cache.invalidate(queryKey)
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
after a write, `cache.invalidate(queryKey)`, `cache.setData`,
|
|
27
|
+
`cache.update(queryKey, updater)` for a change from the current value, or
|
|
28
|
+
`cache.remove(queryKey)` at sign-out. Views read the same keys with
|
|
29
|
+
`useQuery`. Remove the API data and the QueryClient from machine context
|
|
30
|
+
and input. Done when machine context holds flow state only.
|
|
29
31
|
5. **Empty the views.** Move each `fetch` and Effect run of a view into an
|
|
30
32
|
actor; a view starts the machine and renders. Done when oxlint reports no
|
|
31
33
|
`ci-solution/no-run-in-view` finding.
|