import type { Mutation } from '@astrale-os/sdk/mutation' import { executeMutation } from '@astrale-os/sdk/mutation' import { useCallback, useMemo, useRef } from 'react' import type { Action as AsyncAction } from '../graph/action.js' import type { DomainAction } from './action.hook.js' import { useAction as useAsyncAction } from '../graph/action.js' import { useGraphStore } from '../graph/store.js' export interface MutationOptions { readonly optimistic?: boolean readonly onError?: (error: unknown) => void } /** Execute one named SDK Mutation definition through GraphStore optimism/invalidation. */ export function useMutation( definition: Mutation, options: MutationOptions = {}, ): DomainAction<[Input], Output> { const store = useGraphStore() const definitionRef = useRef(definition) definitionRef.current = definition const optionsRef = useRef(options) optionsRef.current = options const run = useCallback( async (input: Input): Promise => { try { return await executeMutation( { mutate: (ast) => store.mutate(ast, { optimistic: optionsRef.current.optimistic ?? true, }), }, definitionRef.current, input, ) } catch (error) { optionsRef.current.onError?.(error) throw error } }, [store], ) const action = useAsyncAction(run) return useMemo(() => project(action), [action]) } function project( action: AsyncAction<[Input], Output>, ): DomainAction<[Input], Output> { return { run: (input) => action(input), get pending() { return action.pending }, get error() { return action.error }, get result() { return action.result }, reset: action.reset, } }