Skip to content

Private previewMost of the architecture is written. First public release in 2027.

hamur/adapter

What an adapter package implements. You only need these to write an adapter, as @hamur/adapter-react and the others do. An app does not import from here.

defineAdapter

Returns the adapter unchanged. Export the result as the default export of @hamur/adapter-<library>/adapter.

ts
function defineAdapter(adapter: Adapter): Adapter
ts
import { defineAdapter } from "hamur/adapter";
import type { Adapter } from "hamur/adapter";

const adapter: Adapter = {
  name: "demo",
  extensions: [".demo"],
  clientEntry: "@hamur/adapter-demo/runtime/client",
  serverEntry: "@hamur/adapter-demo/runtime/server",
  peers: ["demo-lib"],
  errorPage: "@hamur/adapter-demo/error-page",
};

export default defineAdapter(adapter);

Adapter

FieldType
namestringthe framework value
extensionsstring[]page file extensions the adapter owns
clientEntry, serverEntrystringmodule specifiers of the runtime entries
peersstring[]peer packages the app must install
plugins(ctx: AdapterBuildContext) => BunPlugin[]compile plugins, optional
jsx{ runtime: "automatic"; importSource: string; development?: boolean }optional
errorPagestringthe default error page, optional
svgComponent{ types: string; module(svg: SvgSource): { contents: string; extension: string } }./logo.svg?component, optional

SvgSource, SvgNode, SvgStyle, SvgValue

What svgComponent.module gets for one ?component import: the file after the core sanitised it. attrs are the root <svg>'s attributes, children its elements ({ tag, attrs, children }) and text (a SvgValue), decorative says the file has no aria-hidden, aria-label, aria-labelledby or <title> of its own, and file is the absolute path. Only SVG 2's elements and attributes are kept, matched case-sensitively and first copy first: <script>, <foreignObject>, <style>, class, every on* attribute and any DOM or framework name such as innerHTML, ref or on:click are gone. An href or xlink:href is #…, or http:/https: on <a>, or a PNG, JPEG, GIF or WebP data: URL on <image>. Every other CSS-valued attribute, and each declaration of a style attribute (SVG presentation properties only, without !important and without ;, given as the element's style list rather than an attribute), holds no <, &, escape, control character in a string, brace or at-rule and no function but url(#id) of an id the file defines, rgb/rgba/hsl/hsla and, on a transform, the transform functions. An animation changes only a visual attribute, and never the root's size or what the root lost (style, transform, transform-origin, overflow, filter, mask, clip-path). A reference to an id no kept element defines is dropped, and elements nest at most 256 deep. A SvgValue is a string, or an array whose { id } parts are ids the file defines and the references to them (id, href="#…", url(#…), aria-labelledby): the component writes each as <instance id>-<id>, the instance id coming from the library's SSR-stable id, so two copies on a page never share an id.

ts
interface SvgSource {
  attrs: Record<string, SvgValue>;
  children: SvgNode[];
  decorative: boolean;
  file: string;
}
type SvgNode = SvgValue | { tag: string; attrs: Record<string, SvgValue>; style?: SvgStyle; children: SvgNode[] };
type SvgStyle = Array<{ name: string; value: SvgValue }>;
type SvgValue = string | Array<string | { id: string }>;

types is the type typegen declares for *.svg?component. module(svg) returns contents, the module's source, whose default export is a component of the library rendering <svg> with the file's attributes, the props over them, title as the first child <title>, and, when decorative is true, aria-hidden="true" unless the props give title, aria-label or aria-labelledby; and extension, the module's file extension: .js, or one the library's compile plugin reads (svelte .svelte, solid .jsx). An adapter without svgComponent fails the import with @hamur/adapter-<library> has no svgComponent; import "./logo.svg" for its URL.

svgCode, SvgCode

svgCode(svg, { title, props }) gives the code every svgComponent.module writes alike, as JavaScript source text. value(v) is an expression for a SvgValue, with each { id } part as uid + "-<id>", so the module declares uid from its library's SSR-stable id. attrs(node) is the element's attributes with its style list written in as one name:value;… value, for a library that takes a style string; React builds its style object from node.style instead, so no adapter parses CSS. props(attrs, name?) is an object literal of the attributes, each name passed through name (React camel-cases them). hidden is the condition under which a decorative file gets aria-hidden="true", written with the module's variables named by title and props, or undefined when the file labels itself.

ts
import { svgCode } from "hamur/adapter";

const code = svgCode(svg, { title: "title", props: "props" });
const root = `h("svg", { ...${code.props(svg.attrs)}, ...(${code.hidden ?? "false"} ? { "aria-hidden": "true" } : {}), ...props })`;

AdapterBuildContext

Given to plugins. target is "client" or "server", dev is true under hamur dev, rootDir and buildDir are absolute, and components lists app/components/** by name and file when the components option is on.

ts
import { defineAdapter } from "hamur/adapter";
import type { AdapterBuildContext, ResolvedRoute } from "hamur/adapter";

const label = (ctx: AdapterBuildContext) => `${ctx.target}${ctx.dev ? " dev" : ""} ${ctx.components?.length ?? 0} components`;

export default defineAdapter({
  name: "demo",
  extensions: [".demo"],
  clientEntry: "@hamur/adapter-demo/runtime/client",
  serverEntry: "@hamur/adapter-demo/runtime/server",
  peers: [],
  plugins: (ctx) => [{ name: label(ctx), setup() {} }],
});

export const path = (route: ResolvedRoute) => route.matched.map((record) => record.path).join(" ");

AdapterServerEntry, RenderContext, RenderResult, RenderTree

serverEntry exports render(ctx). RenderContext has url, route, tree, payload, head, app, stream (the adapter may return a ReadableStream as body when it is true), baseURL, app.baseURL with one trailing slash, which Link and useRouter() put app paths under, href(to), which returns the href of an app path (withBase) or of a route location (locationHref) under that base and throws for an unknown name or a missing required param, so Link resolves to without a route table, nonce, the request's CSP nonce when the app or server.csp set one, which the adapter writes as nonce="…" on every inline <script> its library emits, and scriptHashes, set only on a document server.csp allows by hashes, onto which the adapter pushes await cspHash(text) for each executed inline <script> its library writes (it is never set together with nonce; render such a document to completion, not streamed). RenderTree.components lists the app root, the layout and the pages, outermost first, each a RenderEntry; error is set when the error page is rendered, and route only on an outlet's tree that renders another route than the page (an intercepting route, below). RenderResult is { body: string | ReadableStream<Uint8Array>; head?: string }.

ts
import type { AdapterServerEntry, RenderContext, RenderResult, RenderTree } from "hamur/adapter";

const text = (tree: RenderTree) => tree.components.map((entry) => entry.id).join(" > ");

export const entry: AdapterServerEntry = {
  async render(ctx: RenderContext): Promise<RenderResult> {
    return { body: `<main>${text(ctx.tree)}</main>`, head: ctx.stream ? undefined : "" };
  },
};

APP_ROOT_ID

"app:root", the id of the app/app.<ext> entry of RenderTree.components. The entry is first and only present when the app has that file; render it like a layout, with the rest of the tree as its child.

ts
const APP_ROOT_ID: "app:root"

RenderEntry, routeBoundary

One level of RenderTree.components: id, component, props, key, boundary, caught and pending. boundary is set on a page entry that a route boundary (<page>.error.<ext> or _error.<ext>) or a not-found component (<page>.not-found.<ext> or _not-found.<ext>) covers, with their components as boundary.error and boundary.notFound. caught is set on an entry that shows a caught error: when a page's load, route middleware or search schema fails, the tree already ends with it in the failing route's place, { id: "<route>:not-found", caught: "not-found", component, props: { error, clearError } } for a 404 under a not-found component, else { id: "<route>:error", caught: "error", … }, below the layout and the pages above it. A URL no page matches ends the tree with { id: ":not-found", caught: "not-found", … } (app/pages/_not-found.<ext>, below the layout), or with app.notFoundMode: "fuzzy" with { id: "<parent>:outlet-not-found", … } below the parent page whose Outlet holds it. Render such an entry as any entry, with useError() below it returning props.error.

key is set on a page entry whose meta.key is set and on a route template entry (id: "template:<folder>", rendered with Outlet as its child). Key the level's element by it, so the level mounts again, with its state reset, when key changes, and keeps its state when it does not: React and Preact key, Vue :key, Svelte {#key}, Solid a memo that reads it. An html component is rendered again on every update, so it ignores key.

pending is set on the last entry of the tree a client navigation sends through update while it is still loading after 1000 ms: { id: "<route>:pending", component, pending: true }, the pending component (<page>.pending.<ext> or _pending.<ext>) of the first page that is not on screen, in that page's place, below the entries on screen above it. ctx.route and ctx.payload are still those of the page on screen. Render it in that place, with no Outlet content and useData() as null, keep the levels above it mounted, and replace it with the page on the next update. The server and the first render never send one.

outlets is set on the entry of a page with slots (app/pages/dash/@team/): the tree of each slot by name, matched against the same URL as the page. Outlet name="team" renders entry.outlets.team.components in the entry it sits in, as the unnamed Outlet renders the next level; each slot entry's id is its route name (dash@team, dash@team-settings), so useData() in it reads that route's data. A slot with no page for the URL holds its default.<ext> as { id: "<owner>@<slot>:default" }, or no entry; after a client navigation it keeps the tree it showed. After a client navigation that an intercepting route of the slot took (app/pages/feed/@modal/(..)photo/[id].<ext>), the slot holds that route's chain and its tree has route, the route of the URL as that chain resolves it: useRoute() inside the outlet is that route, and elsewhere the page on screen's. A tree without route renders under ctx.route.

Wrap each entry that has boundary in the library's error boundary. When it catches, call routeBoundary(ctx, entry, error): it returns the component to render in that place (the not-found component for a 404, else the route boundary), the masked error, which useError() below it returns, and the id and caught of the entry in that place; or undefined when nothing covers the entry for that error or the error is a redirect or fatal, and then rethrow. On the server it also sets the answer's status and payload.boundary, until the response has started streaming.

ts
interface RenderEntry {
  id: string;
  component: unknown;
  props?: Record<string, unknown>;
  key?: string;
  boundary?: { error?: unknown; notFound?: unknown };
  caught?: "error" | "not-found";
  pending?: true;
  outlets?: Record<string, RenderTree>;
}

function routeBoundary(ctx: RenderContext | ClientContext, entry: RenderEntry, error: unknown): { component: unknown; error: ErrorPageProps; id: string; caught: "error" | "not-found" } | undefined

KeptUnit

A page subtree a client navigation left, kept with its component instances (03 §9.19). When a navigation replaces a page entry whose route keeps its pages (meta.keepalive, else app.keepalive), the subtree from that entry down goes into kept of the entry above it (the layout for a top-level page), least recently shown first. RenderEntry.keepalive is the keep-alive key of a page entry of such a route: its id and the params of its pattern (users-id:["7"]), or its id and meta.key (users-id#k); the server and the first render set it too, and every update sets it from the route on screen. A unit is shown again, with its instances, when a later tree has an entry with its key at that place, and it is dropped when the entry above it leaves without being kept, when the layout or the app root changes, on the error page, and, least recently shown first, past app.keepalive.max units in the whole app. Render each unit of entry.kept hidden beside the current child of the entry's Outlet, keyed by key, with useRoute() inside reading route and useData() reading payload.data; key the current child by its keepalive so it keeps its instance when it turns into a unit. React renders each in <Activity>, Vue keeps them in <KeepAlive>, Preact, Solid and Svelte wrap every keep-alive page in <div data-hamur-keepalive="<key>">, style="display:contents" while shown and hidden while kept; the html adapter ignores kept. In an app with no layout and no app root the units of a top-level page are on RenderTree.kept; render them where the tree's first entry goes. While keep-alive is on in the app, the tree's top and every entry whose outlet renders a page level have kept, [] when they hold nothing: wrap exactly those places, so an outlet keeps its shape when its last unit goes. A unit holds the useAsyncData entries that were in use when it was kept until it is dropped.

ts
interface RenderEntry {
  // …the fields above
  kept?: KeptUnit[];
  keepalive?: string;
}

interface RenderTree {
  // …the fields above
  kept?: KeptUnit[];
}

interface KeptUnit {
  key: string;
  tree: RenderTree;
  payload: Payload;
  route: ResolvedRoute;
}

hamur/adapter/dev

The entry for dev-only helpers: OVERLAY_HOOK, OverlayHook, mergeMappings and MapPiece. It is separate from hamur/adapter so that no production client holds them.

OVERLAY_HOOK, OverlayHook

Import from hamur/adapter/dev, which only dev code and build plugins use, so no production client holds it. "__hamurOverlayHook", the globalThis key of the object the dev error overlay installs before any module script runs under hamur dev. Its failed turns true on the first uncaught error or unhandled rejection on the page, which the overlay takes from window before other listeners see it. A dev-only adapter runtime reads it to learn that an error happened, for example to reload after a failed hot update. It is absent from production pages.

ts
const OVERLAY_HOOK: "__hamurOverlayHook"

interface OverlayHook {
  errors: unknown[];
  failed: boolean;
  report?(error: unknown): void;
}

AdapterClientEntry, ClientContext

clientEntry exports hydrate, mount and update. ClientContext has the same fields as RenderContext without stream and nonce, plus navigator and root. root is the element with id app.rootId that the app renders into; the core looks it up, so an adapter never names the id itself. baseURL is app.baseURL with one trailing slash, as on the server, and is set again on every update; href resolves against the browser's route table as RenderContext.href does on the server. hydrate attaches to server HTML, mount renders without it, update follows a navigation. A client entry may also export transitionTargets(ctx), returning { page?: Element[]; layout?: Element[] }, the elements of the page and the layout in ctx; the navigator calls it before and after update to find the elements a page or layout transition animates, and reads the update's DOM mutations when it is not exported. Only @hamur/adapter-html exports it: its update rewrites the whole root, so its renders write <!--hamur-page--> … <!--/hamur-page--> and <!--hamur-layout--> … <!--/hamur-layout--> around the deepest page entry and the layout, and transitionTargets returns the elements between each pair under ctx.root. The other five adapters export nothing: their update has changed the DOM when it settles. A client entry may also export hydrationCanBeAborted = true: update may then be called before the hydrate promise resolved and replaces the hydration in progress, so a link click during hydration becomes a client navigation instead of a document load; the generated client entry then holds such a click from its first statement until the navigator takes it. @hamur/adapter-react, @hamur/adapter-preact and @hamur/adapter-solid export it.

ts
import type { AdapterClientEntry, ClientContext } from "hamur/adapter";

const log = (name: string, ctx: ClientContext) => console.log(name, ctx.route.fullPath, ctx.tree.components.length);

export const entry: AdapterClientEntry = {
  hydrate: (ctx) => log("hydrate", ctx),
  mount: (ctx) => log("mount", ctx),
  update: (ctx) => log("update", ctx),
};

setAdapterInstance

Sets app.adapter to the library's app instance and calls the app hook app:adapter(instance, app) once per app context and instance: the first time for that context, and again when a new non-null instance comes, as for Vue's error page on the server. null counts once per context. Await it in render, hydrate and mount before the first render, after the instance exists: Vue passes the App from createSSRApp or createApp before mount, the other adapters pass null. Do not call it in update. A handler that throws rejects the promise, so the render fails: the server answers the error page, the client start rejects.

ts
function setAdapterInstance(app: object | undefined, instance: unknown): Promise<void>
ts
export async function hydrate(ctx: ClientContext): Promise<void> {
  const app = createSSRApp(Root);
  await setAdapterInstance(ctx.app, app);
  app.mount(ctx.root);
}

renderInPasses, RenderInPassesOptions

The server render loop for a library whose renderer cannot wait for data. It calls render(head, pass), and when that render started a pending entry that is not lazy (the composable called markWaiting), it drops the result (drop, if given), disposes the head entries that pass pushed, awaits app.asyncData.settled() and renders again, up to 8 passes. It returns the last render. Push into the head that render receives, not into ctx.head, so a dropped pass leaves no entries behind.

ts
interface RenderInPassesOptions<T> {
  app: object;
  head: Head;
  render(head: Head, pass: number): T | Promise<T>;
  drop?(result: T): void | Promise<void>;
}

function renderInPasses<T>(options: RenderInPassesOptions<T>): Promise<T>
ts
export const render = async (ctx: RenderContext) =>
  renderInPasses<RenderResult>({
    app: ctx.app,
    head: ctx.head as Head,
    render: (head) => ({ body: renderToString(buildElement({ ...ctx, head })) }),
  });

markWaiting

Call it from useAsyncData and useFetch on the server, with app.asyncData, when the entry the component started is pending and not lazy. It marks the current render as waiting, so renderInPasses renders again after the store has settled.

ts
function markWaiting(store: object): void

settledOf, Settled

For an Await component and useDeferred. A deferred value (a promise at the top level of what load returns) carries its outcome once it has settled, in the status, value and reason fields that React's use() reads. On the server they are set before a buffered render, and in the browser they are set when the payload or a resolve script settles the value. settledOf returns that outcome, or undefined while the value is pending, so a component can render a settled value in its first pass and the hydration render matches the server's.

ts
type Settled<T = unknown> = { status: "fulfilled"; value: T } | { status: "rejected"; reason: unknown }

function settledOf<T>(promise: PromiseLike<T>): Settled<T> | undefined

mergeMappings, MapPiece

Import from hamur/adapter/dev. For a build plugin that joins several compiled parts into one module for Bun, such as a script and a template. It merges the source maps of the parts into one mappings string over a single source file, for the inline map the plugin ends its contents with (//# sourceMappingURL=data:application/json;base64,…). In dev, the error overlay maps a position through that inline map to the original file, line and code frame. Each piece is a part's map (only its mappings is read) with the zero-based line of the module where the part starts and, when the part is cut out of the original file, the zero-based sourceLine and sourceColumn where it starts there.

ts
interface MapPiece {
  map: { mappings: string };
  line: number;
  sourceLine?: number;
  sourceColumn?: number;
}

function mergeMappings(pieces: MapPiece[]): string

ResolvedRoute

A matched route: name, path, fullPath, params, query, search (the query after the chain's search schemas, equal to query when no page exports one), hash, meta (a PageMeta) and matched, a RouteMatch per page from the outermost to the current one.

RouteMatch

One entry of route.matched: the page's route name, its path pattern ("/blog/:slug") and its own meta export, not merged with its parents' ({} when it exports none). The server and the browser build the same entries, and an entry stays the same object between navigations. The page file and loader file that pages:extend sees never reach it.

ts
interface RouteMatch {
  name: string
  path: string
  meta: PageMeta
}

PageMeta

The type of the meta export of a page. layout picks a layout or turns layouts off with false, middleware is a middleware name, an inline Middleware or an array of them, and ssr: false renders the page in the browser only, and scripts: false makes an html page script-free (no script in its document, so its links are full loads). key is a string or a function of the route that returns one: the page mounts again, with its state reset, when it changes. Other keys are yours. hamur/app exports the same type, which is where an app imports it from.

ts
import type { PageMeta } from "hamur/adapter";

export const meta: PageMeta = {
  layout: "plain",
  middleware: ["auth"],
  ssr: false,
};

App primitives for adapters

The stores and helpers that an adapter, the client entry and tests build an app with. App code does not call them, so they are not in hamur/app and auto-import does not offer them.

createAppContext, CreateAppContextOptions

Makes the app context (AppContext of hamur/app): one per request on the server, one per page load in the browser.

ts
function createAppContext(options: CreateAppContextOptions): AppContext
interface CreateAppContextOptions { state: State; asyncData?: AsyncData; config: AppConfigs; head: Head; cookies?: CookieJar; fetch?: $Fetch }
ts
import { defineAppConfig } from "hamur/app";
import { createAppContext, createHead, createState } from "hamur/adapter";

export const appConfig = defineAppConfig({ title: "Shop", theme: { primary: "#0a7" } });

export const app = createAppContext({
  state: createState({ cart: [] }),
  head: createHead(),
  config: { public: { apiBase: "/api" }, app: appConfig },
});

app.hooks.hook("app:created", () => console.log("ready"));

runtimeConfigOf

What useRuntimeConfig() of every adapter returns (ClientRuntimeConfig of hamur/app). It builds the object once per app context and returns that object on every call.

ts
function runtimeConfigOf(app: AppContext): ClientRuntimeConfig

siteConfigOf

What useSiteConfig() of every adapter returns (SiteConfig of hamur/app). It builds the object once per app context.

ts
function siteConfigOf(app: AppContext): SiteConfig

publicError

The error a server-side ErrorBoundary may show and record for the client. On the server it is app.maskError(error): a HamurError stays as it is, any other error is logged and becomes 500 Internal Server Error (or the foreign status and its status text) outside dev. In the browser, where the app context has no maskError, it returns the error unchanged.

ts
function publicError(app: AppContext, error: unknown): unknown

reportClientError

A browser error that reached the adapter's root error hook. It always calls the app:error hook. With render: true (the library cannot show the tree past the error) it shows the error page; with render: false it shows it only for a HamurError with fatal: true, otherwise the page stays. source is what app:error gets: "render" when render is true, else "hook".

ts
function reportClientError(app: object, error: unknown, options: { render: boolean; source?: "render" | "navigation" | "plugin" | "hook" | "chunk" | "window" | "rejection" }): void

createState

Makes the keyed store State of hamur/app, optionally restored from the server's dump.

ts
function createState(initial?: Record<string, unknown>): State
ts
import { createState } from "hamur/adapter";
import type { State } from "hamur/app";

export const state: State = createState({ count: 1 });

const stop = state.subscribe("count", (value) => console.log("count", value));
state.set("count", 2);
console.log(state.use("theme", "dark"), state.has("theme"), state.get<number>("count"));
console.log(state.dump());
stop();

createAsyncData, CreateAsyncDataOptions

Makes the keyed store behind useAsyncData and useFetch (AsyncData of hamur/app). CreateAsyncDataOptions is { ssr?: boolean; initial?; mask?; redirect? }: ssr makes server: false skip the handler and turns off the purge, initial restores a server render's entries, mask turns the error of a failed run into the one the entry holds (the server passes its error masking), and redirect checks a thrown redirect before the entry holds it (the server passes its target checks; a throw there is the run's error).

ts
function createAsyncData(options?: CreateAsyncDataOptions): AsyncData
ts
import { clearAsyncData } from "hamur/app";
import { createAsyncData } from "hamur/adapter";

const store = createAsyncData({ ssr: true });

const entry = store.fetch("user", async () => ({ name: "Ada" }), { default: () => ({ name: "" }) });
console.log(entry.status);

await store.settled();
console.log(store.get<{ name: string }>("user")?.data?.name);
console.log(store.dump());

await store.refresh("user");
clearAsyncData({ asyncData: store }, "user");

asyncDataKey, isHandlerReference, HandlerReference

The key of useAsyncData(fn, input): $fn:<handler id>:<functionInputHash(input)>, the same hash that names the prerendered file of that input. An input the serializer refuses throws its TypeError at the call. isHandlerReference(value) is true for a client stub and for the handler on the server, so a handler and a getter key are told apart without reading length. Neither is for app code: a user names an entry with (fn, input).

ts
function asyncDataKey(fn: HandlerReference, input?: unknown): string
function isHandlerReference(value: unknown): boolean

stateArguments, asyncDataArguments

Read the arguments of useState and of useAsyncData / useLazyAsyncData, including the key the build appends to a call that has none (build.keyedComposables). Every adapter calls them first and passes its own (...args) through, so keying is not written again in an adapter. A branded last argument, { [Symbol.for("hamur.key")]: "$s<8 hex>" }, is dropped from the arguments and is the key only when the call gave none: useState(init) and useAsyncData(handler, options?). A call whose first argument is a handler (isHandlerReference) takes no key from it. A call still without a key throws useState() needs a key; pass one or list the function in build.keyedComposables (useAsyncData() and useLazyAsyncData() for those). asyncDataArguments(name, args, isKey?) returns [first, second, options] as (key | getter | handler, handler | input, options); isKey names a key of the library besides a string and a getter (@hamur/adapter-vue passes isRef).

ts
function stateArguments(args: readonly unknown[]): { key: string; init: unknown }
function asyncDataArguments(name: string, args: readonly unknown[], isKey?: (value: unknown) => boolean): [first: unknown, second: unknown, options: unknown]

fetchKey

The store key of a useFetch call: $fetch:<METHOD>:<url> and, when other options identify the request, :<stable JSON> of them. The cookie and authorization request headers are left out, because the key is written into the page payload and the request-bound $fetch forwards them itself; every adapter builds its keys with it.

ts
function fetchKey(url: string, options?: FetchOptions): string

timeView, watchTime, timeAttributes, TIME_PROPS, TimeInput, TimeView

What Time of every adapter is built on. timeView(app, path, props, now?) resolves the <time> element of props (a TimeInput): iso for datetime, locale and timeZone for the data-* attributes, the formatted text, and interval for a relative text. The locale is props.locale, else the language of app.i18n.localeOf(path) when @hamur/i18n is on, else the first valid Accept-Language tag of the request, else en; the zone is props.timeZone, else app.i18n.timeZone, else UTC. The request's locale and the time of the server's render are kept in app.state under $time, so payload.state carries them and the client's first render prints the server's text; now replaces that time for a later refresh. A datetime that Date cannot read throws TypeError: Time: datetime "<value>" is not a valid date, and a relativeInterval that is not a positive number throws TypeError: Time: relativeInterval <value> must be a positive number of milliseconds. watchTime(interval, update) calls update(Date.now()) every interval ms and returns the function that stops it: an adapter starts it after mount and stops it on unmount. timeAttributes(props) is props without the Time props and the Intl.DateTimeFormatOptions keys, the attributes of the element; TIME_PROPS lists the names left out.

ts
interface TimeInput extends Intl.DateTimeFormatOptions {
  datetime: Date | number | string;
  locale?: string;
  timeZone?: string;
  relative?: boolean;
  relativeInterval?: number;
}
interface TimeView { iso: string; locale: string; timeZone: string; text: string; interval: number | undefined }
function timeView(app: AppContext, path: string, props: TimeInput, now?: number): TimeView
function watchTime(interval: number, update: (now: number) => void): () => void
function timeAttributes<T extends object>(props: T): Record<string, unknown>

createLoadingIndicator, paintLoadingIndicator, loadingIndicatorOptions, defaultEstimatedProgress, LOADING_INDICATOR_PROPS, LOADING_INDICATOR_COLOR, LOADING_INDICATOR_ERROR_COLOR, LOADING_INDICATOR_HEIGHT

What LoadingIndicator and useLoadingIndicator of every adapter are built on. createLoadingIndicator(app, options?) returns the app's one LoadingIndicatorStore, made by the first call (later calls ignore their options). get() is the immutable LoadingIndicatorState { progress, isLoading, error }, subscribe(listener) runs on every change, and start(), finish({ force?, error? }), set(progress) and clear() drive it. follow(source) binds the store to anything with get().state and subscribe, the navigator store: it starts when state leaves "idle" and finishes when it is "idle" again. Calls count, and the remover of the last one unbinds and clears, so an adapter calls it on mount and removes it on unmount. The options are duration (2000), throttle (200), hideDelay (500), resetDelay (400) and estimatedProgress. When app.event is set (a request on the server) the store is inert. paintLoadingIndicator(element, state, look?) writes the bar's styles to element.style; loadingIndicatorOptions(props) keeps the defined store options of a props object; defaultEstimatedProgress(duration, elapsed) is the default estimate; LOADING_INDICATOR_PROPS lists the props of LoadingIndicator for libraries that declare props; the three constants are the default colors and height.

ts
interface LoadingIndicatorState { progress: number; isLoading: boolean; error: boolean }
interface LoadingIndicatorOptions { duration?: number; throttle?: number; hideDelay?: number; resetDelay?: number; estimatedProgress?: (duration: number, elapsed: number) => number }
interface LoadingIndicatorStore {
  get(): LoadingIndicatorState
  subscribe(listener: () => void): () => void
  start(): void
  finish(options?: LoadingIndicatorFinish): void
  set(progress: number): void
  clear(): void
  follow(source: LoadingIndicatorSource): () => void
}
function createLoadingIndicator(app: AppContext, options?: LoadingIndicatorOptions): LoadingIndicatorStore
function paintLoadingIndicator(element: HTMLElement, state: LoadingIndicatorState, look?: LoadingIndicatorLook): void

LoadingIndicatorStore, LoadingIndicatorState, LoadingIndicatorOptions, LoadingIndicatorFinish, LoadingIndicatorSource, LoadingIndicatorLook, LoadingIndicatorProps, LoadingIndicatorActions

The types of the section above. LoadingIndicatorFinish is { force?: boolean; error?: boolean }, LoadingIndicatorSource is { get(): { state: string }; subscribe(listener: () => void): () => void }, LoadingIndicatorLook is { color?: string; errorColor?: string; height?: number }, LoadingIndicatorProps is the look plus duration, throttle and estimatedProgress, and LoadingIndicatorActions is the four methods start, finish, set and clear.

createRouteAnnouncer, createAnnouncer, announcerActions, announcerRole, hideAnnouncer, resetAnnouncerClaims, writeRouteAnnouncer, ROUTE_ANNOUNCER_ID, ANNOUNCER_POLITE_ID, ANNOUNCER_ASSERTIVE_ID

What RouteAnnouncer, useRouteAnnouncer, Announcer and useAnnouncer of every adapter are built on (03 §9.21). createRouteAnnouncer(app) returns the app's one RouteAnnouncerStore, reading app.config.routeAnnouncer (false, or { politeness }, "polite" by default) when it makes it. get() is the immutable RouteAnnouncerState { message, politeness }, subscribe(listener) runs on every change, and set(message, politeness?), polite(message) and assertive(message) announce: they clear message, write politeness, and write the text 50 ms later. enabled is false under app.routeAnnouncer: false. mount() is called by a rendered region: the navigator's own region goes away while any is mounted and comes back when the last remover runs. begin(), finish(token, message) and abort(token) are the navigator's: a call to set between begin and finish replaces the text finish gets, and abort drops it. dispose() stops the timer and removes the navigator's region.

createAnnouncer(app) returns the app's one AnnouncerStore: get() is { message, politeness, regions: { polite, assertive } } (the last call and the text each region holds), and set(message, politeness = "polite"), polite, assertive, subscribe and mount work as above. The first set creates the two regions on body unless one is mounted. announcerActions(store, politeness = "polite") returns set, polite and assertive with set defaulting to politeness, for useAnnouncer({ politeness }). When app.event is set (a request on the server) both stores are inert. announcerRole(politeness) is "status", "alert" or undefined for "off"; hideAnnouncer(element) hides a region through element.style.cssText, which a CSP style-src does not govern; resetAnnouncerClaims(app) drops the RouteAnnouncer claims of an app (a server render calls it as each pass starts); writeRouteAnnouncer(element, state) writes aria-live, aria-atomic, role and the text. The three ids are __hamur_announcer, __hamur_announcer_polite and __hamur_announcer_assertive.

ts
interface RouteAnnouncerState { message: string; politeness: "polite" | "assertive" | "off" }
function createRouteAnnouncer(app: AppContext): RouteAnnouncerStore
function createAnnouncer(app: AppContext): AnnouncerStore
function announcerActions(store: AnnouncerStore, politeness?: "polite" | "assertive"): AnnouncerActions

RouteAnnouncerStore, RouteAnnouncerState, RouteAnnouncerPoliteness, RouteAnnouncerActions, RouteAnnouncerProps, AnnouncerStore, AnnouncerState, AnnouncerPoliteness, AnnouncerActions

The types of the section above. RouteAnnouncerPoliteness is "polite" | "assertive" | "off" and AnnouncerPoliteness is "polite" | "assertive". RouteAnnouncerActions and AnnouncerActions are the methods set, polite and assertive that useRouteAnnouncer() and useAnnouncer() return next to the state. RouteAnnouncerProps is { politeness?, class?, style? }, the props of RouteAnnouncer(props) of @hamur/adapter-html.

resolveCallOptions, mergeCallOptions, isPending

What createUseFetch, createUseAsyncData and pending of every adapter are built on. mergeCallOptions(defaults, options, read?) puts a call's options over the defaults: a value of the call wins unless it is undefined, headers merge by name (the call's header replaces a default of the same name) and query by key. Objects that come from the defaults are copied, so a call that changes them never changes the defaults of the next; the call's own objects are passed on as they are, so a reactive query keeps tracking. read turns a query that is a getter or a ref into its value; such a query makes the merged one a getter. resolveCallOptions(defaults, options, read?) is mergeCallOptions for an object and, for a function, the result of calling it with a copy of the call's options. isPending(app, entry) is entry.status === "pending", or an idle entry with no data under app.asyncData.pendingWhenIdle.

ts
function mergeCallOptions<D extends object, O extends object = D>(defaults: D, options: O, read?: (value: unknown) => unknown): D & O
function resolveCallOptions<O extends object>(defaults: O | ((options: O) => O), options: O | undefined, read?: (value: unknown) => unknown): O
function isPending(app: Pick<AppContext, "config">, entry: Pick<AsyncDataEntry, "status" | "data">): boolean

matchesOf, routeDataOf, MatchedRoute, RouteDataName, RouteDataOf

What useMatches() and useRouteData() of every adapter are built on. matchesOf(route, data) is route.matched with each entry's params (the route params its path names) and data (data[name] when the payload holds it); routeDataOf(route, data, name) is data[name] when name is in route.matched, else undefined, so a route outside the chain gives nothing whatever data holds. data is the data of the render's payload. RouteDataName is the route names of HamurLoaders once hamur typegen wrote them, else string; RouteDataOf<N> is LoaderData<N> | undefined for a name of HamurLoaders, else unknown.

ts
function matchesOf(route: Pick<ResolvedRoute, "matched" | "params">, data: Record<string, unknown> | undefined): MatchedRoute[]
function routeDataOf(route: Pick<ResolvedRoute, "matched">, data: Record<string, unknown> | undefined, name: string): unknown
interface MatchedRoute extends RouteMatch { params: ResolvedRoute["params"]; data: any }

layoutSegments

What useLayoutSegment() and useLayoutSegments() of every adapter are built on. layoutSegments(route, entryId) is the segments of route.path below the level of the render entry entryId: the app root, a layout and an unmatched entry see every segment, a template:<folder> entry those below its folder, and a page (or its <route>:error entry) those below its own pattern in route.matched. A pathless group among the matches below the level is listed as (group) where it sits. null or undefined for entryId gives [].

ts
function layoutSegments(route: Pick<ResolvedRoute, "path" | "matched">, entryId: string | null | undefined): string[]

layoutOf

What useLayout() of every adapter is built on. layoutOf(tree) is the name and props of the tree's layout:<name> entry, or { name: false, props: {} } when the tree has none.

ts
function layoutOf(tree: Pick<RenderTree, "components">): { name: string | false; props: Record<string, unknown> }

RouteName, RouteFor

What useRoute(name) of every adapter is typed with. RouteName is the route names of HamurRoutes once hamur typegen wrote them, else string; RouteFor<N> is RouteValue for never, else the route with params from HamurRoutes[N], search from HamurSearch[N] and name any RouteName. RouteFor distributes over a union N.

ts
type RouteName = [keyof HamurRoutes] extends [never] ? string : keyof HamurRoutes & string
type RouteFor<N extends string> = [N] extends [never] ? RouteValue : RouteOf<N, RouteName>

RouteError

What useError() of every adapter is typed with. While no page exports Errors it is ErrorPageProps. Once one does, it is a union discriminated by route and status: for each route of HamurErrors, one member per declared status, { route; status; data?: Serialized<Errors[status]> }, and one for its other statuses from 400 to 599 with data?: unknown; and one plain member, route any other route name or absent, data?: unknown. So if (error?.route === "blog-slug" && error.status === 404) error.data?.slug compiles, and a check of any other route or status still does. data stays optional: an error of a declared status may carry none (a bare createError({ status: 404 }), showError). Only the routes that declare Errors enter the union.

ts
type RouteError = [keyof HamurErrors] extends [never] ? ErrorPageProps : { [N in keyof HamurErrors & string]: PageError<N, HamurErrors[N]> }[keyof HamurErrors & string] | (Omit<ErrorPageProps, "status" | "data" | "route"> & { route?: Exclude<RouteName, keyof HamurErrors>; status: number; data?: unknown })

routeStateOf

What status, error, renderMode, state, key, navigationType and mask of useRoute() are built from. routeStateOf({ route, app, payload, tree }) gives them for one render; state, key, navigationType and mask are those of route, which the navigator sets from the history entry on screen (03 §9.5, §9.15), else {}, "", "initial" and undefined. Of the others: status is the status of tree.error when an error page is shown, else the number in payload.status, else 200; error is the value useError() gives: the app's error store when it holds one, else tree.error.toJSON(); renderMode is "prerendered" when payload.prerendered is true, else the mode of the page load, which it remembers per app: "spa" when the first payload it saw had serverRendered: false, "ssr" otherwise. The server sets payload.status when it is not 200 and payload.prerendered for a page the prerender requested; a client navigation takes the status a handler set during its load (the last one other than 200), and a static build writes it into _payload.json. Every adapter calls it once per render and per navigation.

ts
function routeStateOf(source: { route?: Pick<ResolvedRoute, "state" | "key" | "navigationType" | "mask">; app?: object; payload?: Record<string, unknown>; tree?: { error?: HamurError } }): RouteState

snapshotResponse

Returns a function that puts the response status, status text and headers of app.event back as they are when snapshotResponse is called. An adapter that drops a render pass and renders again calls it before each pass and the function when it drops the pass, so a status or header written by the dropped pass does not reach the answer. renderInPasses does this itself.

ts
function snapshotResponse(app: object): () => void

cspHash

The CSP source of an inline script's text, 'sha256-<base64>', as a browser hashes it. An adapter pushes it onto RenderContext.scriptHashes for each inline script its library writes; Hamur lists those sources in the hash policy of server.csp.

ts
function cspHash(text: string): Promise<string>

createHead, CreateHeadOptions

Makes the head manager (Head of hamur/app). With document, apply() brings the real document in line with the entries; without it, apply has nothing to change. nonce (server only) is written on each script, style and nonce-checked link without one. subresource(url) returns the integrity and crossOrigin of a URL that is one of the build's files, or undefined; a script with that src or a modulepreload, preload or stylesheet link with that href gets them unless it sets integrity itself.

ts
function createHead(options?: CreateHeadOptions): Head
interface CreateHeadOptions {
  document?: HeadDocument;
  nonce?: string;
  subresource?: (url: string) => { nonce?: string; integrity?: string; crossOrigin?: "anonymous" | "use-credentials" | false } | undefined;
}
ts
import { SEO_META_KEYS, createHead, seoMetaToHead } from "hamur/adapter";

const head = createHead();
const entry = head.push({ title: "Home", titleTemplate: "%s · Shop", meta: [{ name: "description", content: "Welcome" }] });
head.push(seoMetaToHead({ ogTitle: "Shop", twitterCard: "summary" }));

entry.patch({ title: "Welcome" });
export const html = head.render();
console.log(html.head.join("\n"), Object.keys(SEO_META_KEYS).length);
entry.dispose();
ts
import { createHead } from "hamur/adapter";
import type { HeadDocument } from "hamur/app";

export function startHead(document: HeadDocument) {
  const head = createHead({ document });
  head.push({ htmlAttrs: { lang: "en" } });
  head.apply();
  return head;
}

HEAD_MARK

"data-hamur-head", the attribute every head tag Hamur writes carries, so the browser can find and replace them.

sanitizeHead

The allow-list behind useHeadSafe: returns the part of input that cannot run script, load a stylesheet, redirect or move the page's URLs, and drops everything else (see useHeadSafe of the adapters). It takes unknown, reads own keys only and returns objects with no prototype.

ts
function sanitizeHead(input: unknown): HeadInput

seoMetaToHead, SEO_META_KEYS

seoMetaToHead turns the flat keys of useSeoMeta (SeoMetaInput of hamur/app) into a HeadInput. SEO_META_KEYS maps each flat key to the [attribute, name] of its meta tag, such as ogTitle to ["property", "og:title"].

ts
function seoMetaToHead(input: SeoMetaInput): HeadInput
ts
import { seoMetaToHead } from "hamur/adapter";
import type { SeoMetaInput } from "hamur/app";

const input: SeoMetaInput = { title: "Pricing", description: "Plans and prices", ogImage: "/og.png", twitterCard: "summary_large_image" };

export const head = seoMetaToHead(input);

viewTransitionAttribute

The rule behind the viewTransition prop of Link (03 §9.18): it returns the data-hamur-view-transition value, undefined (no attribute) for an unset prop, "" for true, "false" for false and the types joined with single spaces for { types }. The navigator reads it back, "" as true, "false" as false and any other text as the types. An empty types array gives "", which reads as true.

ts
function viewTransitionAttribute(value: boolean | { types: readonly string[] } | undefined): string | undefined

checkTransitionName

The rule behind transitionName in the six adapters (03 §9.18): it returns name when it is a CSS <custom-ident> usable as a view-transition-name, and throws TypeError('transitionName("1x") is not a CSS identifier') otherwise. An identifier is made of ASCII letters, digits, -, _ and non-ASCII characters; it does not start with a digit, or with a hyphen and a digit; --brand is allowed, - and -- alone are not. Backslash escapes and spaces are refused. none, auto, default, match-element, inherit, initial, unset, revert and revert-layer are refused in any letter case.

ts
function checkTransitionName(name: string): string

prefetchAttribute, PrefetchOn, PrefetchProps, PrefetchOptions, PrefetchResult

The rule behind the prefetch props of Link: prefetchAttribute({ prefetch, prefetchOn, noPrefetch }) returns the data-hamur-prefetch value. prefetch: false or noPrefetch gives none; otherwise prefetchOn (default "interaction") gives the words of its triggers in the order hover (interaction), visible (visibility), tap and render, such as hover visible or hover tap, and an object with no flag true gives none. The old strings "hover", "visible" and "none" as prefetch are returned as they are, with one dev warning.

ts
type PrefetchOn = "visibility" | "interaction" | "tap" | "render" | { visibility?: boolean; interaction?: boolean; tap?: boolean; render?: boolean }
function prefetchAttribute(props: { prefetch?: boolean; prefetchOn?: PrefetchOn; noPrefetch?: boolean }): string

PrefetchOptions is { data?: boolean } and PrefetchResult what prefetch(to, options) of the navigator and of RouterApi resolves to. prefetch(to, { data? }) resolves, never rejects, to { type: "loaded", data } (a load ran; data is the data of the load files that ran for this prefetch, so a layout or parent route the screen keeps is not in it), { type: "redirect", location } or { type: "error", error } (a load redirected or threw), { type: "chunks" } (the chunks are loaded and no load ran: data: false, no load on the route, or a static build whose payload file says to reload) or { type: "skipped" } (a target on another origin, no page, a malformed path, a route name or params that match no page, or a prefetch cancelled by a navigation to the same page); a chunk that fails to load gives error when no load ran. A prefetch of a URL a navigation is already loading joins that load and runs none. The load result is held 30 seconds and the next navigate() to the same URL uses it once and runs no second load; a redirect or error result is not held. data: false loads the chunks only and calls no load and no handler.

ts
type PrefetchResult =
  | { type: "loaded"; data: Record<string, unknown> }
  | { type: "redirect"; location: string }
  | { type: "error"; error: HamurError }
  | { type: "chunks" }
  | { type: "skipped" }

linkState, LinkState

The rule behind the active classes of Link: linkState(to, route) returns { active, exact } for the app path to and a route (path, params, matched). exact is true when the pathname of to equals route.path; active is true then, or when it equals the path of a record in route.matched other than the last, filled with route.params. Query, hash, a trailing / and percent-encoding do not matter. A to that does not start with a single / is neither.

ts
function linkState(to: string, route: Pick<ResolvedRoute, "path" | "params" | "matched">): { active: boolean; exact: boolean }

linkPending, PENDING_CLASS_ATTRIBUTE

The rule behind aria-busy and the pending class of Link, and behind useLinkStatus(): linkPending(href, state) is true when state.state is "loading" and state.to has the same path and query as href; the hash of either is left out. href is the anchor's resolved href (based, as a Link writes it; #/path under the hash history), and a URL of another origin never matches. state.requested, the URL asked for before a rewrite or a canonical redirect, matches as well as state.to. baseURL (default "/") puts a hash-history #/path under the base. PENDING_CLASS_ATTRIBUTE is "data-hamur-pending-class", the attribute that names the class the navigator adds to an anchor it marks; without it the class is router-link-pending. The navigator marks a[data-hamur-prefetch] and a[data-hamur-pending-class], which every Link is.

ts
function linkPending(href: string, state: Pick<NavigationState, "state" | "to" | "requested">, baseURL?: string): boolean

resolveRelative, relativeTarget

resolveRelative(to, route, relative?) is the rule behind Link relative, useResolvedPath and navigate(to, { relative }): the app path a relative to (./x, x, ..) leads to from route (path, params, matched). With relative "route" it resolves against the path of the last route.matched pattern filled with route.params, and drops the trailing / that . and .. leave; without it, against route.path as a browser does. A to that starts with /, has a scheme, or is empty or ?/#-only is returned as given. relativeTarget(to, route, relative?) is resolveRelative for a string to when relative is "route", and to itself otherwise, which is what an adapter's Link calls before searchTarget.

ts
function resolveRelative(to: string, route: Pick<ResolvedRoute, "path" | "params" | "matched">, relative?: "route"): string
function relativeTarget<T extends string | RouteLocation>(to: T, route: Pick<ResolvedRoute, "path" | "params" | "matched">, relative?: "route"): T | string

setLinkState, LinkBeforeNavigate

Keeps the state and the onBeforeNavigate handler of a Link for its anchor element, in memory: setLinkState(anchor, state, onBeforeNavigate?) when the anchor mounts or either changes, setLinkState(anchor, undefined) to drop both. The navigator calls the handler for a click it intercepts on that element, after the onBeforeNavigate hooks, with the Navigation; nav.cancel() stops the navigation. A click the navigator intercepts on that element stores the state with the history entry it pushes, as navigate(to, { state }) does. Nothing is read from the DOM, so an anchor in user HTML cannot set a state. A state that is not payload-serializable (04 §4) and structured-cloneable, or longer than 65 536 characters serialized, is logged and the click navigates without it.

ts
function setLinkState(element: object, state: Record<string, unknown> | undefined, onBeforeNavigate?: LinkBeforeNavigate): void
type LinkBeforeNavigate = (nav: Navigation) => void

linkRel, linkTarget, linkExtraAttributes, linkAttributes, createLinkSlot, LinkRelInput, LinkExtraInput, LinkAttributeInput, LinkSlotInput

The rules behind the Link props of 03 §9.23, which every adapter calls so that six Links write one markup.

linkRel({ href, target, rel, noRel, external, externalRelAttribute }) is the rel a Link renders, or undefined to leave what the props carry. A target="_blank" or an href that starts with http://, https:// or // gets "noopener noreferrer" unless rel or noRel is given; external puts the external token first ("external", "external noopener noreferrer", "external nofollow"). linkTarget(to, href) is to, or its alias href; both given is a dev warning, Link has both to and href; href is ignored. linkExtraAttributes({ href, external, noRel, rel, target, prefetchedClass, scroll, prefetchDelay }) returns the attributes C-563 adds to the anchor and nothing for a prop that is not set: rel, data-hamur-prefetched-class, for scroll: false, data-hamur-scroll="false" and, for a prefetchDelay above 0 on a link that is not external, data-hamur-prefetch-delay. linkAttributes(input) returns every attribute a Link writes (href, data-hamur-prefetch (none for external), data-hamur-replace, data-hamur-view-transition, data-hamur-pending-class, data-hamur-trim, data-hamur-mask, data-hamur-unmask, aria-current, target and the extras) for a custom render to spread on its own <a>. createLinkSlot(input) builds the LinkSlot a custom render is given from the resolved pieces and the router.

ts
function linkRel(input: { href: string; target?: unknown; rel?: unknown; noRel?: boolean; external?: boolean }): string | undefined
function linkTarget<T>(to: T | undefined, href: T | undefined): T
function linkExtraAttributes(input: LinkRelInput & { prefetchedClass?: string; scroll?: boolean; prefetchDelay?: number }): Record<string, string>
function linkAttributes(input: LinkAttributeInput): Record<string, string>
function createLinkSlot(input: LinkSlotInput): LinkSlot

LinkRelInput, LinkExtraInput, LinkAttributeInput and LinkSlotInput are the argument types of these functions.

LinkSlot

What a custom-rendered Link is given (a children function in React, Preact and Solid and html, a scoped default slot with custom in Vue, the children snippet with custom in Svelte): href is the based href with app.trailingSlash's form; attrs the attributes to spread on an <a>; active, exact and pending are the linkState and linkPending answers; navigate(event?) calls preventDefault on the event and then the navigator with the link's replace, state, mask, viewTransition and scroll; prefetch() prefetches the target.

ts
interface LinkSlot {
  href: string;
  attrs: Record<string, string>;
  active: boolean;
  exact: boolean;
  pending: boolean;
  navigate(event?: Event): Promise<void>;
  prefetch(): Promise<PrefetchResult>;
}

LinkDefaults, ResolvedLinkDefaults, LINK_DEFAULTS, linkDefaultsOf, linkPrefetchProps, UseLinkOptions

What app.link and defineLink set for every Link, and what useLink takes. LinkDefaults is { activeClass?, exactActiveClass?, pendingClass?, prefetchedClass?, externalRelAttribute?, prefetch?, prefetchOn?, prefetchDelay? } (03 §9.23). LINK_DEFAULTS holds the three class names a Link uses when nothing says otherwise: router-link-active, router-link-exact-active and router-link-pending. linkDefaultsOf(app, defaults?) returns LINK_DEFAULTS, then app.config.link of the app (null or an app without it adds nothing), then defaults (what defineLink was given), a key of a later layer winning, as a ResolvedLinkDefaults; an adapter reads its props over that. linkPrefetchProps({ prefetch, prefetchOn, noPrefetch }, defaults) returns those three props when the element carries any of them and { prefetch, prefetchOn } of the defaults otherwise, ready for prefetchAttribute or linkAttributes. linkRel and linkExtraAttributes take externalRelAttribute (default "noopener noreferrer", false adds no rel). UseLinkOptions is { replace?, relative?, query?, state?, scroll?, viewTransition? }, the Link props useLink(to, options) takes.

ts
interface LinkDefaults { activeClass?: string; exactActiveClass?: string; pendingClass?: string; prefetchedClass?: string; externalRelAttribute?: string | false; prefetch?: boolean; prefetchOn?: PrefetchOn; prefetchDelay?: number }
type ResolvedLinkDefaults = LinkDefaults & { activeClass: string; exactActiveClass: string; pendingClass: string }
const LINK_DEFAULTS: ResolvedLinkDefaults
function linkDefaultsOf(app: Pick<AppContext, "config"> | null | undefined, defaults?: LinkDefaults): ResolvedLinkDefaults
function linkPrefetchProps(props: PrefetchProps, defaults: LinkDefaults): PrefetchProps
interface UseLinkOptions { replace?: boolean; relative?: "route"; query?: (prev: RouteValue["search"]) => RouteValue["search"]; state?: Record<string, unknown>; scroll?: boolean; viewTransition?: boolean | { types: readonly string[] } }

pendingRuns, optimisticSource, OptimisticSource

pendingRuns(app) lists the running PendingRuns of an app, oldest first; the array is the same until a run starts or ends. optimisticSource(app) is what useOptimistic reads: a store over pendingRuns, whose get() returns the same array until the list changed.

ts
function pendingRuns(app: object): readonly PendingRun[]
function optimisticSource(app: object | null | undefined): OptimisticSource
interface OptimisticSource { get(): readonly OptimisticEntry[]; subscribe(listener: () => void): () => void }

runFunctionForm, linkActionRunner

<Form action={fn}> with JavaScript: runFunctionForm(app, fn, input, formData, refresh, form?, options?) calls the handler through its stub with input (the form's fields as formToObject makes them), one call after another per function and app, and refreshes the page as useAction does. The value lands in state, or the error in error, of the runners of the useAction(fn) called below that form (form.owner, which useAction finds through the form's context), else of the runners outside any form, linked with linkActionRunner(app, fn.id, runner, instance?) (the returned function unlinks). options.instance keys the post by (id, instance): its queue and its result stay with that instance, and only the runners linked with the same instance get it, through form.owner.link(fn.id, runner, instance) below a form. The runners are taken when the post starts: one that was unlinked, mounted later or reset() since does not get the result (ActionRunner.epoch() and adopt(result, epoch)), and a result with no runner goes nowhere but the form's own callbacks. form.track hears the post, which is how useFormStatus is pending for it. It resolves true after a success, "invalid" after a fail() or an error whose data holds issues, and false after any other end, a redirect included (the stub follows the redirect). ActionRunner.adopt leaves pending and the queue alone.

ts
function runFunctionForm<I, O>(app: object, fn: Handler<I, O>, input: I, formData: FormData, refresh: () => Promise<void>, form?: { owner; track(done: Promise<unknown>, action: string): void }, options?: { refresh?: boolean; instance?: string | number }): Promise<boolean | "invalid">
function linkActionRunner(app: object, id: string, runner: ActionRunner<any, any>, instance?: string | number): () => void

restoredResult, RestoredResult

restoredResult(state, id, instance?) reads payload.handlerState, the result of a post without JavaScript to a handler, for the handler id and instance: { state } for { id, value }, { error } (a HamurError) for { id, error }, { failure } (an ActionFailure) for { id, failure }, undefined for another function, another instance or no state. Pass it as restored of createActionRunner, which then starts from it; useAction does.

ts
function restoredResult<O>(state: unknown, id: string, instance?: string | number): RestoredResult<O> | undefined
interface RestoredResult<O> { state?: O; error?: HamurError; failure?: ActionFailure }

functionFormAction

The action of Form action={fn} without JavaScript: functionFormAction(fn, page, instance?) adds _fn=<id> to page, a path with its base and query, with :<instance> after the id, and drops any hash. The post runs the handler and renders the page in one answer. A GET handler throws TypeError: Form action takes a POST handler; <label> is GET.

ts
function functionFormAction(fn: Pick<Handler<never, unknown>, "id" | "method" | "label">, page: string, instance?: string | number): string

assertFormMethod

The one check of every adapter's Form: assertFormMethod(action, method) throws TypeError: Form posts through a handler: Form action={fn}; use a plain <form> for another URL when action is not a function and method is anything but get.

ts
function assertFormMethod(action: unknown, method: string | undefined): void

createActionRunner, ActionRunner, ActionRunnerConfig, ActionOptions, ActionSnapshot, Handler

What useAction is made of: createActionRunner(fn, { options, refresh }) runs the handler fn one call after another and keeps { state, pending, error, failure }. With app, each call is listed in pendingRuns(app) under instance, and post is run with the entry to list. A fail() lands in failure, with no onSuccess and no refresh, and the next run clears it. options() returns the ActionOptions (initial, onSuccess, onError, refresh) and is read on every call, so an adapter hands in new callbacks without a new runner; refresh() is router.refresh() and runs after each success unless refresh is false. run(input) queues a call and returns its value, get() returns the same ActionSnapshot until something changed, subscribe(listener) hears each change, and reset() aborts the running call, drops the waiting ones and returns to initial: none of them commits. pending is true from run until the call and its refresh ended and the calls behind it did. A redirect rejects run and is no error. Handler<I, O> is the type of a function and of its client stub (hamur/server exports it for server code).

ts
function createActionRunner<I, O>(fn: Handler<I, O>, config: { options(): ActionOptions<O>; refresh(): Promise<void>; restored?: RestoredResult<O>; app?: object | null; instance?: string | number }): ActionRunner<I, O>
interface ActionRunner<I, O> { run(input: I): Promise<O>; post(input: I, run: PendingRun): Promise<O>; get(): ActionSnapshot<O>; subscribe(listener: () => void): () => void; reset(): void }
interface ActionSnapshot<O> { state: O | undefined; pending: boolean; error: HamurError | undefined; failure: ActionFailure | undefined }
interface ActionOptions<O> { initial?: O; onSuccess?(value: O): void; onError?(error: HamurError): void; refresh?: boolean }

createFormStatus, FormStatus, FormStatusStore, IDLE_FORM_STATUS

What useFormStatus reads: createFormStatus() makes the store of one Form. The Form passes the FormData of each submit it starts to submitted(formData) (from the onSubmit it registers with enhance). runFunctionForm reports the post with track(done, action), and get() is { pending: true, data, action }, with the form's data and the handler's url as action, until it settles, and IDLE_FORM_STATUS otherwise. get() returns the same object until the status changed. owner is where the useAction runners called below the form link themselves (owner.link(id, runner), owner.runners(id)). subscribe hears the tracked posts.

ts
function createFormStatus(): FormStatusStore
interface FormStatus { pending: boolean; data: FormData | null; action: string | null }
interface FormStatusStore { get(): FormStatus; subscribe(listener: () => void): () => void; submitted(formData: FormData): void; track(done: Promise<unknown>, action: string): void; readonly owner: { link(id: string, runner: ActionRunner<any, any>): () => void; runners(id: string): ActionRunner<any, any>[] } }
const IDLE_FORM_STATUS: FormStatus

locationHref

Builds the URL of a named route. Params are encoded, **:name takes an array, query and hash are appended, and the result starts with baseURL. A missing required param or an unknown name throws.

ts
function locationHref(routes: NamedRoute[], to: RouteLocation, baseURL?: string): string

NamedRoute is { name: string; path: string; children: NamedRoute[] }.

ts
import { locationHref } from "hamur/adapter";
import type { RouteLocation } from "hamur/app";

const routes = [{ name: "blog-slug", path: "/blog/:slug", children: [] }];
const to: RouteLocation = { name: "blog-slug", params: { slug: "hello world" }, query: { ref: "home" }, hash: "top" };

export const href = locationHref(routes, to, "/shop/");

CheckedTarget

CheckedTarget<T, External = true, Http = false> is the type a string target T of Link, navigate or redirect is checked with (06 §10.3): T itself when it may be given (any string before typegen, a string, a relative path, a path some entry of HamurRoutePaths can match or one with a % escape and, unless External is false, //host or a URL with a scheme app.linkProtocols lists, only http(s):// with Http). Else the union of the app's path patterns for a path, and for any other target a string type that names the cause ("<T> needs { external: true }", "<T> has a scheme app.linkProtocols does not list"), so the call fails on its line. An adapter's Link takes to: CheckedTarget<T> | RouteLocation (LinkTarget<T>) with T extends string as a type parameter of the component.

ts
type CheckedTarget<T extends string, External extends boolean = true, Http extends boolean = false>

rejectBlockedTarget

What useRouter().navigate() and replace() check before they put app.baseURL in front of a string target. It returns a rejected promise holding the HamurError 400 that navigate() throws (03 §9, C-262) when the scheme of to is not in app.linkProtocols, so history.pushState is never called, and undefined for a path, an allowed scheme or a named route.

ts
function rejectBlockedTarget(to: unknown): Promise<never> | undefined

subscribeAppConfig, liveAppConfig

What an adapter's useAppConfig() is built from. subscribeAppConfig(app, listener) calls listener after every updateAppConfig of app and returns the unsubscribe function. liveAppConfig(app, track) returns the app config as an object that calls track before every read, so the adapter's own reactive primitive re-runs the readers after an update.

ts
function subscribeAppConfig(app: AppContext, listener: () => void): () => void
function liveAppConfig<T extends object>(app: AppContext, track: () => void): T

startPoll, pollInterval

What an adapter's usePoll(ms, { keys? }) is built from. pollInterval(ms) returns ms when it is at least 1000 and otherwise throws RangeError: usePoll() needs at least 1000 ms (got 200); call it where the hook is called, so the error is the component's. startPoll(ms, run) checks ms the same way, then calls run every ms while the document is visible and the browser online (hiding it stops the timer, showing it starts a new one; a tick while offline is skipped; a refresh a tick starts keeps the page when the network fails) and returns the stop function, which the adapter calls on unmount; run is () => router.refresh({ keys }). Without a document (the server) it does nothing.

ts
function pollInterval(ms: number): number
function startPoll(ms: number, run: () => unknown): () => void

isOnline, subscribeOnline

What an adapter's useOnline() is built from. isOnline() is navigator.onLine, and true on the server or where the browser does not say. subscribeOnline(listener) calls listener(true) on online and listener(false) on offline and returns the unsubscribe function. useOnline() is true on the server and during hydration, so the adapter reads isOnline() only once mounted.

ts
function isOnline(): boolean
function subscribeOnline(listener: (online: boolean) => void): () => void

searchTarget, uncoveredQuery, equalSearch, SearchUpdate, SetSearch

What an adapter's Link query and useSearch are built from. searchTarget(to, route, update) returns to with the query update(route.search) makes plus uncoveredQuery(route) (the raw query keys of route that no search schema outputs, such as a layout's searchKeys), flat-encoded and untrimmed (arrays as repeated keys, undefined and null left out): for a string target the path and hash are kept and its old query is replaced, for a { name, … } location query is set. The adapter's Link calls it with the route's search and marks the anchor data-hamur-trim; the navigator leaves out the keys at their default when that anchor is clicked. equalSearch(a, b) is the deep equality useSearch(select) uses to keep the previous selection. SearchUpdate is { query: (prev) => next, hash? }, the extra target RouterApi.navigate, push and replace take; SetSearch is the type of the set that useSearch returns.

ts
function searchTarget(to: string | RouteLocation, route: { search: Record<string, unknown>; query?: Record<string, string | string[]> }, update: (prev: never) => Record<string, unknown>): string | RouteLocation
function equalSearch(a: unknown, b: unknown): boolean

setNavigateTarget, NavigateTarget

What navigateTo navigates with in the browser. The client entry sets it before the first navigation: the navigator, ClientContext.href and the page origin. With none set (the server) navigateTo throws a redirect. Adapters do not call it; a test may.

ts
function setNavigateTarget(target: NavigateTarget | undefined): void
interface NavigateTarget { navigator: Pick<Navigator, "navigate" | "replace">; href(to: string | RouteLocation): string; origin: string }

createRouterApi, RouterSource

Builds the RouterApi an adapter's useRouter() returns (03 §9.1), so no adapter writes its own. In the browser navigator is ClientContext.navigator: a string target of navigate, push, replace, prefetch and resolve gets baseURL in front (a blocked scheme rejects first, as rejectBlockedTarget does), and a beforeEach guard's string answer gets it too. On the server, with no navigator, resolve, getRoutes and hasRoute read the route table href was built from (RenderContext.href), currentRoute is route, beforeEach, afterEach and onError register nothing, go does nothing, isReady() and refresh resolve, prefetch resolves to { type: "skipped" }, and navigate, push, replace, back and forward throw unavailable(name), by default `${name}() is only available in the browser`. A partial navigator (a test double) falls back to the server behaviour for what it lacks.

ts
function createRouterApi(source: RouterSource): RouterApi
interface RouterSource {
  navigator?: unknown;
  baseURL?: string;
  href?: (to: string | RouteLocation) => string;
  route?: ResolvedRoute;
  url?: URL;
  unavailable?: (name: string) => Error;
}

Registers fn on the navigator of the page (03 §9.2) and returns its remover; with no navigator (the server, or before start) it registers nothing and returns a function that does nothing. An adapter's onBeforeNavigate, onNavigate and onAfterNavigate call it when the component mounts and call the remover when it unmounts.

ts
type NavigationHookKind = "before" | "navigate" | "after"
function navigationHook(kind: "before", fn: BeforeNavigateHook): () => void
function navigationHook(kind: "navigate", fn: NavigateHook): () => void
function navigationHook(kind: "after", fn: AfterNavigateHook): () => void

routeGuard, RouteGuardKind

Registers fn as the leave or update guard (03 §9.3, step 3) of the tree entry entry, the id of RenderTree.components the calling component renders under, and returns its remover. With entry undefined the guard belongs to the leaf page on screen when it registers. With no navigator (the server, or before start) it registers nothing. An adapter's onBeforeRouteLeave and onBeforeRouteUpdate call it when the component mounts and call the remover when it unmounts.

ts
type RouteGuardKind = "leave" | "update"
function routeGuard(kind: RouteGuardKind, entry: string | undefined, fn: NavigationGuard): () => void

Registers fn as a blocker on the navigator of the page (03 §9.4) and returns its remover; with no navigator it registers nothing. fn is asked after onBeforeNavigate of every navigation but a form's, in registration order: true blocks it, false lets it go, a promise is awaited (a back or forward is undone with history.go while it waits and repeated once all blockers let it go). An adapter's usePreventNavigate calls it.

ts
interface BlockerArgs { from: ResolvedRoute; to: ResolvedRoute | null; type: NavigationType }
type NavigationBlocker = (args: BlockerArgs) => boolean | Promise<boolean>
function navigationBlocker(fn: NavigationBlocker): () => void

createBlocker, Blocker, BlockerStore, ShouldBlock, UseBlockerOptions

The store behind every adapter's useBlocker (03 §9.4). start() registers its blocker with navigationBlocker and, unless beforeUnload: false, a beforeunload listener that calls preventDefault(), present only while shouldBlock({ from, to: null, type: "leave" }) is true and skipped for an unload the navigator let go or a form submission's; it returns the remover, which also answers a blocked navigation true. sync() asks shouldBlock for leave again and adds or removes that listener; the adapter calls it after each render or in an effect, and the store calls it on document input and change and after each navigation. A blocked navigation that another one supersedes turns the store unblocked. get() is the current Blocker, a new object on every change, which subscribe reports. setOptions replaces shouldBlock and beforeUnload for the next navigation (React and Preact call it on each render).

ts
type ShouldBlock = (args: BlockerArgs) => boolean
interface UseBlockerOptions { shouldBlock: ShouldBlock; beforeUnload?: boolean }
interface Blocker { state: "unblocked" | "blocked" | "proceeding"; location?: ResolvedRoute; proceed(): void; reset(): void }
interface BlockerStore {
  get(): Blocker;
  subscribe(listener: () => void): () => void;
  setOptions(options: ShouldBlock | UseBlockerOptions): void;
  sync(): void;
  start(): () => void;
}
function createBlocker(options: ShouldBlock | UseBlockerOptions): BlockerStore

registerSnapshot, SnapshotOptions

What every adapter's useSnapshot calls (03 §9.6): registers { key, capture, restore } and returns its remover; with no navigator it registers nothing. The first registration watches the page's navigator: before a navigation commits, every live capture() is kept (as a payload-serialized copy) under the history key of the page it leaves; after a popstate navigation or the first page of a reload (enter), each live restore whose key that entry holds gets its value, and a key that registers later, before the next navigation, gets it when it registers. A value over 65 536 characters serialized is logged and not kept, and a cookie change drops every value. On pagehide the entry on screen is captured and the map is written to sessionStorage item hamur:snapshot (at most 100 history keys, the oldest dropped).

ts
interface SnapshotOptions<T> { capture: () => T; restore: (value: T) => void }
function registerSnapshot<T>(key: string, options: SnapshotOptions<T>): () => void

Adapter API types

The types that app code names and that every adapter re-exports under the same name (import type { RouterApi } from "@hamur/adapter-react"). They are defined here once, so an adapter imports them and never declares its own.

RouteValue, RouterApi, NavigateOptions, NavigationState, GetCachedData, GetCachedDataCause, AsyncDataHandler, FetchRequest, ErrorBoundaryFallbackProps, RouteLoaderData, UseDataArgs, RouteState, RenderMode

ts
type RouteValue = {
  path: string;
  fullPath: string;
  params: ResolvedRoute["params"];
  query: ResolvedRoute["query"];
  hash: string;
  name: string;
  meta: ResolvedRoute["meta"];
  matched: RouteMatch[];
  status: number;
  error: ErrorPageProps | undefined;
  renderMode: RenderMode;
  state: Record<string, unknown>;
  key: string;
  navigationType: "initial" | "push" | "replace" | "pop";
  mask: string | undefined;
}

type RenderMode = "ssr" | "spa" | "prerendered"
type RouteState = Pick<RouteValue, "status" | "error" | "renderMode" | "state" | "key" | "navigationType" | "mask">
type RouteLoaderData<T> = T extends keyof HamurLoaders ? LoaderData<T> : T
type UseDataArgs<T> = [] | [never]

interface NavigateOptions { replace?: boolean; scroll?: boolean; external?: boolean; document?: true; shallow?: boolean; state?: Record<string, unknown>; refreshAll?: boolean; refresh?: string[]; keepFocus?: boolean; mask?: string; unmaskOnReload?: boolean; viewTransition?: boolean | { types: readonly string[] } }

type RouterApi = Pick<
  Navigator,
  "navigate" | "push" | "replace" | "back" | "forward" | "go" | "prefetch" | "refresh" | "resolve" | "beforeEach" | "afterEach" | "onError" | "isReady" | "getRoutes" | "hasRoute" | "canGoBack" | "pushState" | "replaceState"
> & {
  readonly revalidation: "idle" | "loading";
  readonly currentRoute: ResolvedRoute;
}

interface NavigationState {
  state: "idle" | "loading" | "submitting";
  pending: boolean;
  to?: string;
  formMethod?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
  formAction?: string;
  formData?: FormData;
  formEncType?: "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json";
  json?: unknown;
  revalidation?: "idle" | "loading";
  type?: NavigationType;
  from?: ResolvedRoute;
  complete?: Promise<void>;
}

type GetCachedDataCause = "initial" | "refresh:hook" | "refresh:manual" | "watch"
type GetCachedData<T = unknown> = (key: string, app: AppContext, ctx: { cause: GetCachedDataCause }) => T | undefined
type AsyncDataHandler<R> = (ctx: { signal: AbortSignal }) => R | Promise<R>

interface FetchRequest extends Omit<FetchOptions, "query" | "body"> {
  query?: FetchOptions["query"] | (() => FetchOptions["query"]);
  body?: unknown;
}

interface ErrorBoundaryFallbackProps { error: unknown; reset: () => void }

RouterApi has the signatures of the navigator: navigate(to, options?), its alias push, replace(to, options?), refresh() and isReady() return Promise<void>, prefetch(to, options?) returns Promise<PrefetchResult>, and back(), forward() and go(delta) return void; resolve(to) returns a ResolvedLocation (below); beforeEach, afterEach and onError return their remover; getRoutes() returns RouteListEntry[] and hasRoute(name) a boolean; revalidation and currentRoute are read when you access them. RouteValue is the fields of ResolvedRoute; once hamur typegen wrote HamurRoutes and HamurSearch, name is the union of the route names and params and search are the route's types for a narrowed name (if (route.name === "blog-slug") route.params.slug), string and the record of ResolvedRoute before. RouteLoaderData<T> is the loader data when T is a key of HamurLoaders, else T; UseDataArgs<T> is [], except that after typegen a string that is no loader name makes useData<"nope">() a type error. The wrappers a library needs, such as Accessor<…> or Ref<…>, stay in the adapter.

One client navigation as the navigation hooks see it (03 §9.2). type is "enter" for the first page of the document, "link" for an intercepted <a> click, "goto" for navigate, push, replace, navigateTo and every redirect, "popstate" for back and forward, "form" for a GET form and a submission's navigation, and "leave" for the document unloading. from is null for enter; to is null for leave and for a target that is no page (a full load), and is known once the target's route is resolved. delta is set for popstate. willUnload is true for leave and for a navigation that ends in a full load. complete resolves after the commit and rejects with a NavigationFailure (cancelled or superseded) or the error shown; a full load leaves it pending. cancel() works only inside onBeforeNavigate: the URL and the page stay, a back or forward is undone, and for leave the browser asks the user to stay.

ts
type NavigationType = "enter" | "link" | "goto" | "popstate" | "form" | "leave"
interface Navigation { type: NavigationType; from: ResolvedRoute | null; to: ResolvedRoute | null; delta?: number; willUnload: boolean; complete: Promise<void>; cancel(): void }
type BeforeNavigateHook = (navigation: Navigation) => void
type NavigateHook = (navigation: Navigation) => void | Promise<void>
type AfterNavigateHook = (navigation: Navigation) => void

ResolvedLocation, NavigationGuard, NavigationGuardResult, NavigationFailure, AfterEachHook, RouterErrorHandler, RouteListEntry

The types of the router calls of 03 §9.1. resolve(to) gives a ResolvedLocation: href with app.baseURL, path without it, name and params of the page it matches (none and {} when it matches no page), query and hash; an unknown route name or a missing param throws as locationHref does. A guard returns false to cancel, an app path or a RouteLocation to redirect (through the checks of a middleware redirect, so a loop ends on the error page with Redirect loop: "<to>" was reached twice in one navigation), anything else to go on; a throw shows the error page. afterEach runs once per navigation that reached its route: after the commit with no failure, or with { type: "cancelled" } when a middleware or guard cancelled it, or { type: "superseded" } when a newer navigation, submission or a back/forward started first. onError gets each error a navigation shows or reloads for, with the target route once it is known.

ts
interface ResolvedLocation { href: string; path: string; name?: string; params: Record<string, string | string[]>; query: Record<string, string | string[]>; hash: string }
type NavigationGuardResult = void | boolean | string | RouteLocation
type NavigationGuard = (to: ResolvedRoute, from: ResolvedRoute) => NavigationGuardResult | Promise<NavigationGuardResult>
interface NavigationFailure { type: "cancelled" | "superseded" }
type AfterEachHook = (to: ResolvedRoute, from: ResolvedRoute, failure?: NavigationFailure) => void
type RouterErrorHandler = (error: HamurError, to: ResolvedRoute | undefined) => void
interface RouteListEntry { name: string; path: string }