/** * vapor-chamber/router - the loader SPI. * * The router core knows WHEN data loads (on navigation, abort-on-supersede, * two-phase committed onto the snapshot; on query-only changes, refetch of * affected loaders only). It does NOT know HOW: that's a preset's job, * resolved from the route row's `load` string - * * registered prefix wins: "rows:products" -> handlers.prefixes['rows:'] * otherwise a URL template: "/api/x?page={page}" -> handlers.url * * In-box preset: `vapor-chamber/router-fetch` (plain JSON backends). Any other * backend convention is a preset returning LoaderHandlers. A load with no * matching handler is a coded `router:missing:loader`. */ import type { HttpClient } from '../http'; import { isRouterError, routerError } from './errors'; import type { QueryParamDef, RouteLocation, TableRecord } from './types'; import { encodeSplat } from './table'; import { decodeQueryParam } from './url'; /** * Per-record channel handed to a loader handler, bound to the record and * location of this run - so it cannot be misattributed when a navigation and * a query refetch overlap. Optional, and appended last: handlers written * against the four-argument signature keep working untouched. */ export type LoaderContext = { /** * Report a background refresh behind stale data you are returning now. * The engine flips `router.isRevalidating` and patches `snapshot.data` when * the promise resolves - dropping it if the location has since changed, and * leaving the stale data in place if it rejects. Without this a * stale-while-revalidate response would refresh the HTTP cache but never the * page. */ revalidate: (fresh: Promise) => void; /** * True when this run refreshes data the page already shows because it is * known to be out of date (`revalidateRoutes` after a mapped command); false * on a navigation or a query refetch. A loader that caches reads past its * cache when it is true, or it hands back the copy from before the change. */ refresh: boolean; /** * The router's client (its `http` option), or undefined when it has none. A * loader that makes requests reads through it, so the app's reads, commands * and route data share one cache. tests/router/one-client.test.ts. */ http?: HttpClient; /** * Name the groups this record's data belongs to: the read's `Cache-Groups` * (RFC 9875). When the router's client invalidates one of them, the router * refreshes the record (fetchLoaders reports them). tests/router/cache-groups.test.ts. */ cacheGroups: (groups: readonly string[]) => void; }; /** * @internal - each router's client, recorded by `createRouter`: a refresh that * runs loaders outside a navigation (`revalidateRoutes`) reads through the * client the navigations read through. */ export const _routerClients = new WeakMap(); /** Handles `load` values under a registered prefix * ('rows:products' -> ref 'products'). */ export type PrefixHandler = ( ref: string, location: RouteLocation, record: TableRecord, signal: AbortSignal, ctx: LoaderContext, ) => unknown | Promise; /** Handles plain URL-template `load` values. Receives the RAW template - * interpolation (interpolateLoad) is the handler's choice. */ export type UrlHandler = ( template: string, location: RouteLocation, record: TableRecord, signal: AbortSignal, ctx: LoaderContext, ) => unknown | Promise; export type LoaderHandlers = { prefixes?: Record; url?: UrlHandler; /** Decide whether a query-only change in `changedKeys` requires this * record's loader to refetch. Default (`defaultAffects`): a prefix/row-source * loader depends on its declared query params plus `page`/`per_page`/`sort`; * a URL template depends only on the `{placeholders}` it mentions. Resolved * once at `createRouter` - override for a preset with different query * semantics. */ affects?: (record: TableRecord, changedKeys: readonly string[]) => boolean; }; /** Fill `{placeholders}` from path params first, then typed query params * (declared defaults apply - `{page}` is `1` when absent), else ''. */ export function interpolateLoad( template: string, location: RouteLocation, queryDefs: Record, ): string { return template.replace(/\{(\w+)\}/g, (_, key: string) => { const param = location.params[key]; if (param !== undefined) return key === 'pathMatch' ? encodeSplat(String(param)) : encodeURIComponent(String(param)); const typed = decodeQueryParam(location.query[key], queryDefs[key] ?? {}); if (typed === undefined || typed === null) return ''; return Array.isArray(typed) ? typed.map((v) => encodeURIComponent(String(v))).join(',') : encodeURIComponent(String(typed)); }); } /** * LONGEST prefix wins, not the first one registered. * * The first match would resolve overlapping prefixes by object key order: * with `'rows:'` and `'rows:archived:'` registered, a `rows:archived:...` load * would reach the general handler or not depending on which key was written * first. The specific handler is what a longer prefix asks for. * * One pass, no sort: prefix maps hold a handful of entries and this runs per * record per navigation. */ function matchPrefix(template: string, handlers: LoaderHandlers): [string, PrefixHandler] | null { const prefixes = handlers.prefixes; if (!prefixes) return null; let best: [string, PrefixHandler] | null = null; for (const prefix of Object.keys(prefixes)) { if (template.startsWith(prefix) && (best === null || prefix.length > best[0].length)) { best = [prefix, prefixes[prefix] as PrefixHandler]; } } return best; } /** Run every loader in a record chain. Results keyed by record name; * failures throw coded RouterErrors (cause attached, abort -> `aborted:navigation`). */ export async function runLoaders( handlers: LoaderHandlers, records: readonly TableRecord[], location: RouteLocation, signal: AbortSignal, /** Wired by createRouter - see LoaderContext.revalidate. */ onRevalidate?: (recordName: string, revalidation: Promise, location: RouteLocation) => void, /** See LoaderContext.refresh. */ refresh = false, /** See LoaderContext.http. */ http?: HttpClient, /** See LoaderContext.cacheGroups: the record's name and its groups. */ onGroups?: (recordName: string, groups: readonly string[]) => void, ): Promise> { const results = new Map(); await Promise.all( records.map(async (record) => { const template = record.load as string; const prefixed = matchPrefix(template, handlers); const ctx: LoaderContext = { revalidate: (fresh) => onRevalidate?.(record.name, fresh, location), refresh, http, cacheGroups: (groups) => onGroups?.(record.name, groups), }; try { if (prefixed) { results.set(record.name, await prefixed[1](template.slice(prefixed[0].length), location, record, signal, ctx)); } else if (handlers.url) { results.set(record.name, await handlers.url(template, location, record, signal, ctx)); } else { throw routerError('missing:loader', `no loader handler for "${template}" - register a preset`, { to: location, }); } } catch (cause) { if (signal.aborted) throw routerError('aborted:navigation', `load aborted for "${record.name}"`, { to: location }); throw isRouterError(cause) ? cause : routerError('failed:loader', `loader failed for "${record.name}" (${template})`, { to: location, cause }); } }), ); return results; } /** Default affect policy: does a change in `keys` require this record's loader * to refetch? Prefix-handled (row-source) loaders receive the whole location, * so they depend on every declared query param plus `page`/`per_page`/`sort`; * URL templates depend only on the placeholders they mention. Override via * `LoaderHandlers.affects`. */ export function defaultAffects(record: TableRecord, keys: readonly string[], handlers: LoaderHandlers): boolean { const template = record.load as string; if (matchPrefix(template, handlers)) { // `Object.hasOwn`, not `in`: query keys come from the URL, and `in` walks // the prototype chain - `?toString=` would read as DECLARED and refetch // this record's loader. See `../dict`. return keys.some( (key) => Object.hasOwn(record.queryDefs, key) || key === 'page' || key === 'per_page' || key === 'sort', ); } return keys.some((key) => template.includes(`{${key}}`)); }