import type { BoundNodeFor } from '@astrale-os/sdk/client' import type { SessionRequestOptions } from '@astrale-os/sdk/client/session' import type { NodeId } from '@astrale-os/sdk/graph/node' import type { QueryAST } from '@astrale-os/sdk/query' import type { CallableInputOf, CallableResultOf, MethodOwnerKeyOf, MethodInheritance, ResolvedFunction, ResolvedMethod, } from '@astrale-os/sdk/schema' import { reference } from '@astrale-os/sdk/client/session' import { Path } from '@astrale-os/sdk/graph/path' import { useCallback, useMemo, useRef } from 'react' import type { Action as AsyncAction } from '../graph/action.js' import { useSessionKernel } from '../auth/session-kernel.js' import { useAction as useAsyncAction } from '../graph/action.js' import { useGraphStore } from '../graph/store.js' import { bindingFor } from './domain.hook.js' type ExecutableInheritance = Exclude type InstanceMethod = ResolvedMethod type StaticMethod = ResolvedMethod type Callable = ResolvedFunction | InstanceMethod | StaticMethod type Receiver = { readonly id: NodeId } type MethodReceiver = BoundNodeFor> const QUERY_REFRESH = Symbol('shell-react.query-refresh') export interface QueryRefresh { readonly id: string readonly [QUERY_REFRESH]: () => { readonly ast: QueryAST readonly page: Readonly<{ readonly size: number }> } } type RefreshableQuery = { readonly id: string readonly page: Readonly<{ readonly size: number }> prepare?(input: Input): Input build(input: Input): Query } /** Pair one exact named Query definition with its admitted input for targeted invalidation. */ export function queryRefresh( definition: RefreshableQuery, input: Input, ): QueryRefresh { return Object.freeze({ id: definition.id, [QUERY_REFRESH]: () => { const prepared = definition.prepare?.(input) ?? input return Object.freeze({ ast: definition.build(prepared), page: definition.page }) }, }) } export type ActionRefresh = | 'all' | 'none' | { readonly queries: readonly QueryRefresh[] } export interface ActionOptions extends SessionRequestOptions { readonly refresh?: ActionRefresh readonly onError?: (error: unknown) => void } type ActionArgs = C extends InstanceMethod ? [receiver: MethodReceiver, input: CallableInputOf] : [input: CallableInputOf] export interface DomainAction { run(...args: Args): Promise readonly pending: boolean readonly error: unknown readonly result: Result | undefined reset(): void } /** Invoke one schema-declared Function or Method and invalidate Store by explicit policy. */ export function useAction( callable: C, options: ActionOptions = {}, ): DomainAction, CallableResultOf> { const binding = bindingFor(callable) const kernel = useSessionKernel() const store = useGraphStore() const callableRef = useRef(callable) callableRef.current = callable const bindingRef = useRef(binding) bindingRef.current = binding const optionsRef = useRef(options) optionsRef.current = options const invoke = useCallback( async (...args: ActionArgs): Promise> => { const current = callableRef.current const policy = optionsRef.current const { refresh: _refresh, onError: _onError, ...request } = policy try { const result = isInstanceMethod(current) ? await kernel.session.invoke( reference(bindingRef.current.domain, current)(receiverPath(args[0] as Receiver)), args[1] as never, request, ) : await kernel.session.invoke( reference(bindingRef.current.domain, current), args[0] as never, request, ) const refresh = policy.refresh ?? 'all' if (refresh === 'all') store.invalidate() else if (refresh !== 'none') { refresh.queries.forEach((query) => { const target = query[QUERY_REFRESH]() store.invalidate(target.ast, { page: target.page }) }) } return result as CallableResultOf } catch (error) { policy.onError?.(error) throw error } }, [kernel, store], ) const action = useAsyncAction(invoke) return useMemo(() => projectAction(action), [action]) } function projectAction( action: AsyncAction, ): DomainAction { return { run: (...args) => action(...args), get pending() { return action.pending }, get error() { return action.error }, get result() { return action.result }, reset: action.reset, } } function isInstanceMethod(callable: Callable): callable is InstanceMethod { return 'owner' in callable && callable.static === false } function receiverPath(receiver: Receiver): Path { return Path.id(receiver.id) }