import type { Node, NodeId } from '@astrale-os/sdk/graph/node' import { useCallback, useEffect, useRef, useState } from 'react' import { useSessionKernel } from '../auth/session-kernel.js' export type SelectionNode = Node export type { NodeId } export interface ResolvedSelection { readonly aliveIds: readonly NodeId[] readonly nodes: readonly SelectionNode[] readonly pending: boolean readonly error: unknown refetch(): Promise } interface State { readonly key: string readonly aliveIds: readonly NodeId[] readonly nodes: readonly SelectionNode[] readonly pending: boolean readonly error: unknown } /** Resolve selected identities through the authenticated GraphApi; no fake live subscription. */ export function useResolvedNodes(orderedIds: readonly NodeId[]): ResolvedSelection { const graph = useSessionKernel().graph const key = orderedIds.join('\u0000') const idsRef = useRef(orderedIds) idsRef.current = orderedIds const generation = useRef(0) const alive = useRef(true) const [state, setState] = useState({ key, aliveIds: orderedIds, nodes: [], pending: orderedIds.length > 0, error: undefined, }) useEffect(() => { alive.current = true return () => { alive.current = false } }, []) const load = useCallback(async (): Promise => { const ids = idsRef.current const currentKey = ids.join('\u0000') const id = ++generation.current if (ids.length === 0) { if (alive.current) { setState({ key: currentKey, aliveIds: [], nodes: [], pending: false, error: undefined }) } return } setState({ key: currentKey, aliveIds: ids, nodes: [], pending: true, error: undefined }) try { const values = await Promise.all(ids.map((nodeId) => graph.get(nodeId))) if (!alive.current || id !== generation.current) return const aliveIds: NodeId[] = [] const nodes: Node[] = [] values.forEach((node, index) => { if (node === null) return aliveIds.push(ids[index]!) nodes.push(node) }) setState({ key: currentKey, aliveIds: Object.freeze(aliveIds), nodes: Object.freeze(nodes), pending: false, error: undefined, }) } catch (error) { if (alive.current && id === generation.current) { setState({ key: currentKey, aliveIds: ids, nodes: [], pending: false, error }) } } }, [graph]) useEffect(() => { void load() }, [key, load]) if (state.key !== key) { return { aliveIds: orderedIds, nodes: [], pending: true, error: undefined, refetch: load } } return { ...state, refetch: load } }