import type { BoundNode } from '@astrale-os/sdk/client' import type { StoreQueryResponse } from '@astrale-os/sdk/client/store' import type { NodeId } from '@astrale-os/sdk/graph/node' import type { ClassKey as ClassKeyValue, ClassRef, ResolvedClass } from '@astrale-os/sdk/schema' import { Path } from '@astrale-os/sdk/graph/path' import { Query } from '@astrale-os/sdk/query' import { ClassKey } from '@astrale-os/sdk/schema' import { useCallback, useMemo } from 'react' import type { GraphResource } from '../graph/resource.js' import { useStoreResource } from '../graph/resource.js' import { bindingFor } from './domain.hook.js' type EndpointRole = 'source' | 'target' type RelationCardinality = '1' | '0..1' | '0..*' | '1..*' type RuntimeEndpoint = { readonly accepts: readonly ClassRef[] readonly outgoing?: RelationCardinality readonly incoming?: RelationCardinality } type DefinitionOf = Relation extends ResolvedClass< 'edge', infer _Properties, infer _Methods, infer _StaticMethods, infer _SelfProperties, infer _SelfMethods, infer _SelfStaticMethods, infer Definition > ? Definition : never type EndpointsOf = DefinitionOf extends { readonly orientation: 'directed' readonly endpoints: infer Endpoints } ? Endpoints : never type Opposite = Role extends 'source' ? 'target' : 'source' type AcceptedAt = Role extends keyof EndpointsOf ? EndpointsOf[Role] extends { readonly accepts: readonly (infer Accepted)[] } ? Accepted : never : never type DeclaredCardinality = Role extends 'source' ? EndpointsOf extends { readonly source: { readonly outgoing: infer Count } } ? Extract : RelationCardinality : EndpointsOf extends { readonly target: { readonly incoming: infer Count } } ? Extract : RelationCardinality type CoversOpposite> = [ AcceptedAt>, ] extends [To['ref']] ? true : false type EffectiveCardinality> = DeclaredCardinality extends infer Count extends RelationCardinality ? CoversOpposite extends true ? Count : Count extends '1' ? '0..1' : Count extends '1..*' ? '0..*' : Count : RelationCardinality export interface RelationUnavailable { readonly kind: 'required-hidden-or-invalid' readonly cardinality: '1' | '1..*' } export class RelationUnavailableError extends Error { readonly code = 'SHELL_REACT_RELATION_UNAVAILABLE' as const constructor(readonly unavailable: RelationUnavailable) { super( `Required relation (${unavailable.cardinality}) is hidden or violates the installed schema.`, ) this.name = 'RelationUnavailableError' } } export type RelationResource = Cardinality extends | '1' | '0..1' ? GraphResource & { readonly cardinality: Cardinality readonly unavailable?: RelationUnavailable require(): T } : GraphResource & { readonly cardinality: Cardinality readonly unavailable?: RelationUnavailable require(): readonly T[] } export interface RelationOptions { readonly from: Role readonly to: To readonly page?: { readonly size: number } } /** Traverse one directed resolved Edge Class and bind the selected opposite Nodes. */ export function useRelation< Relation extends ResolvedClass<'edge'>, Role extends EndpointRole, To extends ResolvedClass<'node'>, Source extends ResolvedClass<'node'>, >( relation: Relation, source: BoundNode | null | undefined, options: RelationOptions, ): RelationResource, EffectiveCardinality> { const binding = bindingFor(relation) if (source !== null && source !== undefined) admitSource(binding, relation, options.from, source) admitRelatedDefinition(binding, relation, options.from, options.to) const path = source === null || source === undefined ? null : Path.id(source.id as NodeId) const query = useMemo(() => { if (path === null) return null const expanded = Query.from({ nodes: [path] }).expand({ via: [relation], direction: options.from === 'source' ? 'outgoing' : 'incoming', }) return expanded.filter({ class: options.to }).select({ kind: 'graph', binding: expanded.node }) }, [relation, options.from, options.to, path?.raw]) const cardinality = effectiveCardinality(binding, relation, options.from, options.to) const project = useCallback( (response: StoreQueryResponse>) => { const result = response.result if (result.kind !== 'graph' || result.selection.kind !== 'node') { return cardinality === '0..1' ? null : cardinality === '0..*' ? Object.freeze([]) : undefined } const byId = new Map(result.graph.nodes.map((node) => [node.id, node])) const values = result.selection.ids.flatMap((id) => { const node = byId.get(id) return node === undefined ? [] : [binding.wrapNode(options.to, node)] }) if (cardinality === '0..1') return values[0] ?? null if (cardinality === '1') return values[0] if (cardinality === '1..*' && values.length === 0) return undefined return Object.freeze(values) }, [binding, cardinality, options.to], ) const resource = useStoreResource(query, options.page?.size ?? 50, project) const unavailable = (cardinality === '1' || cardinality === '1..*') && resource.data === undefined && resource.state !== 'idle' && resource.state !== 'loading' ? Object.freeze({ kind: 'required-hidden-or-invalid' as const, cardinality }) : undefined const require = () => { if (unavailable !== undefined) throw new RelationUnavailableError(unavailable) if (resource.data === undefined || resource.data === null) { throw new Error('Relation resource is not settled with an available value.') } return resource.data } return Object.freeze({ ...resource, cardinality, ...(unavailable === undefined ? {} : { unavailable }), require, }) as RelationResource, EffectiveCardinality> } function admitSource( binding: ReturnType, relation: ResolvedClass<'edge'>, from: EndpointRole, source: { readonly id: NodeId; readonly class: ClassKeyValue }, ): void { const exact = binding.domain.definition(ClassKey.ref(ClassKey(source.class))) const matches = exact?.ref.kind === 'class' && exact.kind === 'node' && edgeEndpoints(relation)[from].accepts.some((ref) => { const accepted = binding.domain.definition(ref) return accepted?.ref.kind === 'class' && accepted.kind === 'node' && exact.satisfies(accepted) }) if (!matches) throw new TypeError('Relation source does not satisfy the selected endpoint.') } function admitRelatedDefinition( binding: ReturnType, relation: ResolvedClass<'edge'>, from: EndpointRole, to: ResolvedClass<'node'>, ): void { const opposite = from === 'source' ? 'target' : 'source' const matches = edgeEndpoints(relation)[opposite].accepts.some((ref) => { const accepted = binding.domain.definition(ref) return accepted?.ref.kind === 'class' && accepted.kind === 'node' && to.satisfies(accepted) }) if (!matches) { throw new TypeError('Relation target Class is not admitted by the opposite endpoint.') } } function effectiveCardinality( binding: ReturnType, relation: ResolvedClass<'edge'>, from: EndpointRole, to: ResolvedClass<'node'>, ): RelationCardinality { const endpoint = edgeEndpoints(relation)[from] const base = from === 'source' ? endpoint.outgoing : endpoint.incoming if (base === undefined) throw new TypeError(`Relation ${from} cardinality is absent.`) if (base !== '1' && base !== '1..*') return base const opposite = from === 'source' ? 'target' : 'source' const covers = edgeEndpoints(relation)[opposite].accepts.every((ref) => { const accepted = binding.domain.definition(ref) return accepted?.ref.kind === 'class' && accepted.kind === 'node' && accepted.satisfies(to) }) return covers ? base : base === '1' ? '0..1' : '0..*' } function edgeEndpoints( relation: ResolvedClass<'edge'>, ): Readonly> { const definition = relation.definition if (definition.orientation !== 'directed') { throw new TypeError('useRelation currently requires a directed Edge Class.') } return definition.endpoints }