import type { GraphStore } from '@astrale-os/sdk/client/store' import type { Node } from '@astrale-os/sdk/graph/node' import type { NodePath, PathLike } from '@astrale-os/sdk/graph/path' import type { Key } from '@astrale-os/sdk/schema' import type { Shell } from '@astrale-os/shell' import { Path } from '@astrale-os/sdk/graph/path' import { Query } from '@astrale-os/sdk/query' import type { NavHistory, SerializedLocation } from './history.js' import { viewKey } from './view-key.js' /** Canonical navigation inputs; there is no implicit slash-tree or bare-id grammar. */ export type NavTarget = | PathLike | Node | { readonly node: PathLike | Node readonly view?: Key.View readonly params?: Record } function isNode(value: PathLike | Node): value is Node { return typeof value === 'object' && value !== null && 'id' in value && 'class' in value } function nodePath(value: PathLike | Node): NodePath { return isNode(value) ? Path.id(value.id).raw : Path.from(value).raw } function isComposite( value: NavTarget, ): value is Extract { return typeof value === 'object' && value !== null && 'node' in value } /** Normalize every target to canonical astrale-node-path-v1 text. */ export function serializeTarget(target: NavTarget): SerializedLocation { if (!isComposite(target)) return { node: nodePath(target) } return { node: nodePath(target.node), ...(target.view === undefined ? {} : { view: viewKey(target.view) }), ...(target.params === undefined ? {} : { params: { ...target.params } }), } } /** Drop restored entries that no longer resolve under the authenticated Graph capability. */ export async function revalidateAndPrune( history: NavHistory, store: GraphStore, shell: Shell, ): Promise { const { entries, cursor } = history.snapshot() const alive = await Promise.all(entries.map((entry) => resolves(store, shell, entry))) if (alive.every(Boolean)) return false const survivors: SerializedLocation[] = [] let newCursor = -1 let fallback = -1 entries.forEach((entry, index) => { if (!alive[index]) return survivors.push(entry) const next = survivors.length - 1 if (index === cursor) newCursor = next else if (index < cursor) fallback = next }) if (newCursor === -1) newCursor = fallback !== -1 ? fallback : survivors.length > 0 ? 0 : -1 history.reset(survivors, newCursor) return true } async function resolves( store: GraphStore, shell: Shell, entry: SerializedLocation, ): Promise { try { const query = Query.from({ nodes: [entry.node] }).select({ kind: 'graph' }) const response = await store.read(query, { page: { size: 1 } }) if ( response.result.kind !== 'graph' || response.result.selection.kind !== 'node' || response.result.selection.ids.length === 0 ) return false if (entry.view === undefined) return true const routes = await shell.views.resolve(entry.node) return routes.some((candidate) => candidate.route.key === entry.view) } catch { return false } }