import type { QueryPageRequest } from '@astrale-os/sdk/client' import type { GraphStore, StoreQueryResponse, StoreSnapshot } from '@astrale-os/sdk/client/store' import type { QueryAST, QueryDefinition } from '@astrale-os/sdk/query' import { executeQuery } from '@astrale-os/sdk/query' import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react' import type { GraphResource, GraphResourceState } from './resource.js' import { retainRefreshScheduler } from './resource.js' import { useGraphStore } from './store.js' export interface QueryResourceOptions { readonly keepPrevious?: boolean readonly refreshInterval?: number readonly refreshWhen?: 'always' | 'visible' } interface TouchedShape { readonly ast: QueryAST readonly options: { readonly page: QueryPageRequest } } interface DefinitionSnapshot { readonly state: GraphResourceState readonly data?: Output readonly error?: unknown } class DefinitionObserver { private readonly listeners = new Set<() => void>() private subscriptions: readonly (() => void)[] = Object.freeze([]) private touched: readonly TouchedShape[] = Object.freeze([]) private current: DefinitionSnapshot = Object.freeze({ state: 'loading' }) private generation = 0 private pending: Promise | null = null private started = false private rerunQueued = false constructor( private readonly store: GraphStore, private readonly definition: QueryDefinition, private readonly input: Input, ) {} subscribe = (listener: () => void): (() => void) => { this.listeners.add(listener) return () => this.listeners.delete(listener) } getSnapshot = (): DefinitionSnapshot => this.current start(): () => void { this.started = true void this.run('cached') return () => { this.started = false this.generation += 1 this.subscriptions.forEach((unsubscribe) => unsubscribe()) this.subscriptions = Object.freeze([]) } } refresh = async (): Promise => { await this.run('refresh') } private run(freshness: 'cached' | 'refresh'): Promise { if (this.pending !== null && freshness === 'cached') return this.pending const generation = ++this.generation const touched: TouchedShape[] = [] this.update({ state: this.current.data === undefined ? 'loading' : 'refreshing', ...(this.current.data === undefined ? {} : { data: this.current.data }), }) const execute = async ( ast: Ast, options: { readonly page: QueryPageRequest }, ): Promise> => { touched.push(Object.freeze({ ast, options })) return this.store.read(ast, { ...options, freshness }) } const running = executeQuery({ query: execute }, this.definition, this.input) .then((data) => { if (!this.started || generation !== this.generation) return this.touched = dedupeShapes(touched) this.bindShapes() this.update({ state: this.storeState(), data }) }) .catch((error: unknown) => { if (!this.started || generation !== this.generation) return this.touched = dedupeShapes(touched) this.bindShapes() this.update({ state: 'failed', ...(this.current.data === undefined ? {} : { data: this.current.data }), error, }) }) .finally(() => { if (this.pending === running) this.pending = null }) this.pending = running return running } private bindShapes(): void { this.subscriptions.forEach((unsubscribe) => unsubscribe()) this.subscriptions = Object.freeze( this.touched.map(({ ast, options }) => this.store.subscribe(ast, this.onStoreChange, options), ), ) } private onStoreChange = (): void => { const state = this.storeState() this.update({ state, ...(this.current.data === undefined ? {} : { data: this.current.data }), ...(this.current.error === undefined ? {} : { error: this.current.error }), }) if ((state === 'ready' || state === 'optimistic') && !this.rerunQueued) { this.rerunQueued = true queueMicrotask(() => { this.rerunQueued = false if (this.started) void this.run('cached') }) } } private storeState(): GraphResourceState { const snapshots = this.touched.map(({ ast, options }) => this.store.getSnapshot(ast, options)) if (snapshots.length === 0) return this.current.state return combine(snapshots) } private update(next: DefinitionSnapshot): void { if ( next.state === this.current.state && next.data === this.current.data && next.error === this.current.error ) return this.current = Object.freeze(next) this.listeners.forEach((listener) => listener()) } } /** Execute one named SDK Query definition exclusively through the current GraphStore. */ export function useQuery( definition: QueryDefinition | null, input: Input, options: QueryResourceOptions = {}, ): GraphResource { const store = useGraphStore() const inputIdentity = stableIdentity(input) const observer = useMemo( () => (definition === null ? null : new DefinitionObserver(store, definition, input)), [store, definition, inputIdentity], ) const idle = useMemo>(() => Object.freeze({ state: 'idle' }), []) const subscribe = useCallback( (listener: () => void) => observer?.subscribe(listener) ?? (() => {}), [observer], ) const snapshot = useCallback(() => observer?.getSnapshot() ?? idle, [observer, idle]) const current = useSyncExternalStore(subscribe, snapshot, snapshot) useEffect(() => observer?.start(), [observer]) const identity = definition === null ? 'idle' : `${definition.id}\u0000${inputIdentity}` useEffect(() => { if (observer === null || options.refreshInterval === undefined) return return retainRefreshScheduler( store, identity, observer.refresh, options.refreshInterval, options.refreshWhen ?? 'visible', ) }, [store, observer, identity, options.refreshInterval, options.refreshWhen]) const previousRef = useRef<{ readonly identity: string; readonly data: Output } | undefined>( undefined, ) const previous = options.keepPrevious && previousRef.current?.identity !== identity ? previousRef.current : undefined useEffect(() => { if (current.data !== undefined) { previousRef.current = Object.freeze({ identity, data: current.data }) } }, [identity, current.data]) return useMemo( () => Object.freeze({ state: current.state, data: current.data, error: current.error, ...(previous === undefined ? {} : { previous }), transitioning: current.state === 'loading' || current.state === 'refreshing', live: false as const, sequence: 0 as const, refresh: observer?.refresh ?? (() => Promise.resolve()), more: Object.freeze({ has: false, pending: false, load: () => Promise.resolve() }), }), [current, previous, observer], ) } function dedupeShapes(input: readonly TouchedShape[]): readonly TouchedShape[] { const seen = new Set() return Object.freeze( input.filter(({ ast, options }) => { const key = `${JSON.stringify(ast)}\u0000${JSON.stringify(options.page)}` if (seen.has(key)) return false seen.add(key) return true }), ) } function combine(snapshots: readonly StoreSnapshot[]): GraphResourceState { if (snapshots.some((snapshot) => snapshot.state === 'cold')) return 'loading' for (const state of ['failed', 'loading', 'refreshing', 'optimistic', 'stale'] as const) { if (snapshots.some((snapshot) => snapshot.state === state)) return state } return 'ready' } function stableIdentity(value: unknown): string { const seen = new WeakSet() const encode = (input: unknown): unknown => { if (input === null) return ['null'] if (typeof input !== 'object') { if (typeof input === 'function' || typeof input === 'symbol' || typeof input === 'bigint') { throw new TypeError('Query input must be portable and serializable.') } if (input === undefined) return ['undefined'] if (typeof input === 'number' && !Number.isFinite(input)) { throw new TypeError('Query input numbers must be finite.') } return [typeof input, input] } if (seen.has(input)) throw new TypeError('Query input cannot contain cycles.') seen.add(input) if (Array.isArray(input)) return ['array', input.map(encode)] return [ 'object', Object.fromEntries( Object.keys(input as Record) .sort() .map((key) => [key, encode((input as Record)[key])]), ), ] } return JSON.stringify(encode(value)) }