import { NodePath } from '@astrale-os/sdk/graph/path' /** * urlAdapter (API ยง8.1) โ€” the History-API adapter: mirrors the location into the * query string (URL form โ†’ ``), owning the nav query keys (`param`, * `view`, the location's `params`). */ import type { SerializedLocation } from '../history.js' import type { NavAdapter } from './adapter.js' import { viewKey } from '../view-key.js' const VIEW_KEY = 'astrale.view' const PARAM_PREFIX = 'astrale.param.' /** History-API adapter โ€” the location lives in the query string. */ export function urlAdapter(opts?: { param?: string }): NavAdapter { const param = opts?.param ?? 'astrale.node' const hasWindow = (): boolean => typeof window !== 'undefined' const build = (loc: SerializedLocation): string => { const url = new URL(window.location.href) const sp = url.searchParams sp.set(param, loc.node) if (loc.view !== undefined) sp.set(VIEW_KEY, loc.view) else sp.delete(VIEW_KEY) for (const key of sp.keys()) if (key.startsWith(PARAM_PREFIX)) sp.delete(key) for (const [k, v] of Object.entries(loc.params ?? {})) { if (isSensitive(k)) throw new TypeError(`Navigation param '${k}' is sensitive.`) sp.set(`${PARAM_PREFIX}${k}`, v) } url.search = sp.toString() return `${url.pathname}${url.search}${url.hash}` } const clear = (): string => { const url = new URL(window.location.href) const sp = url.searchParams sp.delete(param) sp.delete(VIEW_KEY) for (const key of sp.keys()) if (key.startsWith(PARAM_PREFIX)) sp.delete(key) url.search = sp.toString() return `${url.pathname}${url.search}${url.hash}` } return { kind: 'browser', read() { if (!hasWindow()) return null const sp = new URL(window.location.href).searchParams const rawNode = sp.get(param) if (rawNode === null) return null let node let view try { node = NodePath(rawNode) const rawView = sp.get(VIEW_KEY) if (rawView !== null) { view = viewKey(rawView) } } catch { return null } const params: Record = {} for (const [k, v] of sp) { if (k.startsWith(PARAM_PREFIX)) params[k.slice(PARAM_PREFIX.length)] = v } return { node, ...(view !== undefined ? { view } : {}), ...(Object.keys(params).length > 0 ? { params } : {}), } }, write(loc, { replace }) { if (!hasWindow()) return const href = build(loc) if (replace) window.history.replaceState(null, '', href) else window.history.pushState(null, '', href) }, clear({ replace }) { if (!hasWindow()) return const href = clear() if (replace) window.history.replaceState(null, '', href) else window.history.pushState(null, '', href) }, subscribe(cb) { if (!hasWindow()) return () => undefined const handler = (): void => cb() window.addEventListener('popstate', handler) return () => window.removeEventListener('popstate', handler) }, href(loc) { return hasWindow() ? build(loc) : loc.node }, } } function isSensitive(key: string): boolean { return /token|credential|authorization|secret/i.test(key) }