@kovojs/runtime
Generated from 2 public subpaths — 133 exports, 133 documented. Do not edit by hand.
@kovojs/runtime#
App-authored derives, handlers, trusted HTML, and optimistic authoring helpers.
Source: packages/runtime/src/index.ts
Functions#
handler#
Type a client event handler for an island. The handler receives the DOM event
and a HandlerContext exposing the island's typed state and element params.
The compiler links it to an on:event binding and loads its module on first
interaction (SPEC §4.3). Identity function at runtime; it exists for typing.
| Parameter | Type | Description |
|---|---|---|
fn |
ClientHandler<State, Params> |
The handler implementation. |
| (returns) | ClientHandler<State, Params> |
The same handler, typed. |
function handler<State = unknown, Params = Record<string, ElementParamValue>>(
fn: ClientHandler<State, Params>,
): ClientHandler<State, Params>;Example
import { handler } from '@kovojs/runtime';
type CounterState = { count: number };
export const increment = handler<CounterState>((_event, ctx) => {
ctx.state.count += 1;
});tempId#
Fresh client-only id for a row inserted by a derived optimistic transform
(SPEC.md §10.5 INSERT × AGG): a tempId placeholder, pending-styled and
content-matched against server truth on reconcile. Re-running the transform
during rebase mints a new id — safe because the row is a prediction until the
server's <kovo-query> truth replaces it.
function tempId(): string;trustedHtml#
Marks intentional raw HTML for Kovo sinks that require an explicit escape hatch.
function trustedHtml(value: string | BrowserTrustedHTML): TrustedHtml;derive#
Declare a value derived from named query/state inputs. The runtime recomputes
run whenever any named input changes, so bindings stay consistent without
manual wiring (SPEC §4.8).
| Parameter | Type | Description |
|---|---|---|
inputs |
Inputs |
The names of the inputs this value depends on. |
fn |
(...values: any[]) => Value |
Computes the derived value from the inputs' current values. |
| (returns) | DeriveDefinition<Inputs, Value> |
A DeriveDefinition. |
function derive<const Inputs extends readonly string[], Value>(
inputs: Inputs,
fn: (...values: any[]) => Value,
): DeriveDefinition<Inputs, Value>;Example
import { derive } from '@kovojs/runtime';
export const total = derive(['price', 'quantity'], (price, quantity) =>
Number(price) * Number(quantity),
);Types & interfaces#
ElementParamValue#
Runtime API used by Kovo applications and generated runtime integration.
type ElementParamValue = string | number | boolean;HandlerContext#
Runtime API used by Kovo applications and generated runtime integration.
interface HandlerContext<State = unknown, Params = Record<string, ElementParamValue>> {
params: Params;
signal: AbortSignal;
state: State;
}ClientHandler#
A client event handler: receives the DOM event and a typed island HandlerContext.
type ClientHandler<State = unknown, Params = Record<string, ElementParamValue>> = (
event: Event,
ctx: HandlerContext<State, Params>,
) => void | Promise<void>;ImportHandlerModule#
Runtime API used by Kovo applications and generated runtime integration.
type ImportHandlerModule = (url: string) => Promise<Record<string, unknown>>;MutationChangeRecord#
A client-side record of one domain a mutation changed, optionally key-scoped.
interface MutationChangeRecord {
domain: string;
keys?: readonly string[];
}OptimisticChange#
A change a mutation made, carrying its input, used to key optimistic updates.
interface OptimisticChange<Input = unknown> extends MutationChangeRecord {
input: Input;
}OptimisticEntry#
One query's optimistic policy: a transform, or 'await-fragment' to wait for server truth.
type OptimisticEntry<Input = unknown, Value = unknown> =
| OptimisticTransform<Input, Value>
| 'await-fragment';OptimisticFor#
The exhaustiveness-checked optimistic plan for a mutation form. Keyed by the
queries the mutation invalidates, each entry is either a pure
OptimisticTransform (predict from input) or 'await-fragment' (a recorded
decision to wait for server truth). TypeScript requires an entry per
invalidated query, so deleting a transform turns the satisfies clause red
(SPEC §10.4, §10.6).
type OptimisticFor<
Definition extends Form<string, any, any>,
QueryValues extends Record<string, unknown> = InvalidatedQueryValues<Definition>,
> = Omit<OptimisticPlan<FormInput<Definition>>, 'transforms'> & {
transforms: {
[QueryName in keyof QueryValues]: OptimisticEntry<
FormInput<Definition>,
QueryValues[QueryName]
>;
};
};Example
import { form } from '@kovojs/core';
import type { OptimisticFor } from '@kovojs/runtime';
const addToCart = form('cart/add');
export const addToCartOptimistic = {
queue: 'cart',
transforms: {},
} satisfies OptimisticFor<typeof addToCart>;OptimisticPlan#
An optimistic plan: per-query transforms, an optional queue, and instance-key derivation.
interface OptimisticPlan<Input = unknown> {
keys?: Readonly<Record<string, OptimisticQueryKey<Input>>>;
queue?: string;
transforms: Record<string, OptimisticEntry<Input>>;
}OptimisticQueryKey#
How to derive the query-instance key an optimistic change applies to.
type OptimisticQueryKey<Input = unknown> =
| ((change: OptimisticChange<Input>) => string | undefined)
| string
| undefined;OptimisticTransform#
A pure optimistic predictor: map a query's current value plus the mutation input to the predicted value.
type OptimisticTransform<Input = unknown, Value = unknown> = (
current: Value,
input: Input,
) => Value;BrowserTrustedHTML#
Browser Trusted Types TrustedHTML values accepted by Kovo raw HTML sinks.
interface BrowserTrustedHTML {
readonly [Symbol.toStringTag]: 'TrustedHTML';
toString(): string;
}TrustedHtml#
Kovo's explicit raw HTML escape-hatch wrapper.
interface TrustedHtml {
readonly __kovoTrustedHtml: true;
readonly value: string | BrowserTrustedHTML;
}DeriveDefinition#
A derived value: the named inputs it depends on and the run that computes it.
interface DeriveDefinition<Inputs extends readonly string[], Value> {
inputs: Inputs;
run(...values: unknown[]): Value;
}@kovojs/runtime/client#
Browser bootstrap helpers for installing Kovo's client loader in app-owned entry files.
Source: packages/runtime/src/client.ts
Functions#
applyDeferredStreamResponseToRuntime#
Runtime API used by Kovo applications and generated runtime integration.
function applyDeferredStreamResponseToRuntime(
options: ApplyDeferredStreamResponseToRuntimeOptions & { root: MorphRoot },
): AppliedDeferredStreamResponseWithRoot;
function applyDeferredStreamResponseToRuntime(
options: ApplyDeferredStreamResponseToRuntimeOptions & { root?: undefined },
): AppliedMutationResponse & { chunks: AppliedMutationResponse[] };
function applyDeferredStreamResponseToRuntime(
options: ApplyDeferredStreamResponseToRuntimeOptions,
): AppliedDeferredStreamResponseToRuntime;createEventBus#
Runtime API used by Kovo applications and generated runtime integration.
function createEventBus<
const Definitions extends readonly EventDefinition<string, JsonValue>[],
>(
definitions: Definitions,
options: EventBusOptions = {},
): TypedEventBus<EventPayloadMap<Definitions>>;abortRemovedIslandSignals#
Runtime API used by Kovo applications and generated runtime integration.
function abortRemovedIslandSignals(
currentHtml: string,
nextHtml: string,
scope: IslandSignalScope = defaultIslandSignalScope,
): string[];readElementParams#
Runtime API used by Kovo applications and generated runtime integration.
function readElementParams(element: EventElementLike): Record<string, ElementParamValue>;readElementState#
Runtime API used by Kovo applications and generated runtime integration.
function readElementState(element: EventElementLike): JsonValue;writeElementState#
Runtime API used by Kovo applications and generated runtime integration.
function writeElementState(element: EventElementLike, state: JsonValue): void;dispatchDelegatedEvent#
Runtime API used by Kovo applications and generated runtime integration.
async function dispatchDelegatedEvent(
event: DelegatedEvent,
importModule: ImportHandlerModule,
islandSignalScope: IslandSignalScope = defaultIslandSignalScope,
): Promise<void>;installKovoLoader#
Install the Kovo client loader on a root element: wire delegated events,
hydrate the query store from inline scripts, lazy-load island handlers on
first interaction, and apply mutation fragment patches and optimistic updates.
This is the single client entry point; the compiler emits the inline bootstrap
that calls it (SPEC §8). Returns a handle whose dispose removes all listeners.
| Parameter | Type | Description |
|---|---|---|
options |
KovoLoaderOptions |
The root, an importModule to load handler bundles, and optional query/lifecycle hooks. |
| (returns) | KovoLoader |
A KovoLoader handle. |
function installKovoLoader(options: KovoLoaderOptions): KovoLoader;applyFragments#
Runtime API used by Kovo applications and generated runtime integration.
function applyFragments(
root: MorphRoot,
fragments: readonly FragmentChunk[],
morph: MorphFragment = replaceFragment,
islandSignalScope: IslandSignalScope = defaultIslandSignalScope,
): string[];keyedDomMorph#
Runtime API used by Kovo applications and generated runtime integration.
const keyedDomMorph: MorphFragment = (target, html) => { /* … */ };morphDomElement#
Runtime API used by Kovo applications and generated runtime integration.
function morphDomElement(current: Element, next: Element): Element;morphStructuralTree#
Browser-free structural morph contract from SPEC.md §11.4 and §13.2: the current tree is rewritten to the next tree shape while matching sibling keys keep their object identity and browser-owned state across insertion and reorder.
function morphStructuralTree(
current: StructuralMorphNode,
next: StructuralMorphNode,
): StructuralMorphNode;installMutationBroadcast#
Runtime API used by Kovo applications and generated runtime integration.
function installMutationBroadcast(
options: InstallMutationBroadcastOptions,
): MutationBroadcast;createMutationIdem#
Runtime API used by Kovo applications and generated runtime integration.
function createMutationIdem(): string;isMutationBroadcastMessage#
Runtime API used by Kovo applications and generated runtime integration.
function isMutationBroadcastMessage(value: unknown): value is {
body: string;
changes: MutationChangeRecord[];
type: 'kovo:mutation-response';
};readMutationChangeHeader#
Runtime API used by Kovo applications and generated runtime integration.
function readMutationChangeHeader(
response: MutationResponseHeaderLike,
onError?: RuntimeErrorReporter,
): MutationChangeRecord[];sanitizeMutationChangeRecord#
Runtime API used by Kovo applications and generated runtime integration.
function sanitizeMutationChangeRecord(value: unknown): MutationChangeRecord | null;dispatchEnhancedFormSubmit#
Runtime API used by Kovo applications and generated runtime integration.
async function dispatchEnhancedFormSubmit(
event: DelegatedEvent,
options: EnhancedMutationLoaderOptions | undefined,
islandSignalScope: IslandSignalScope = defaultIslandSignalScope,
hooks: EnhancedFormSubmitHooks = {},
): Promise<boolean>;isEnhancedSubmitEvent#
Runtime API used by Kovo applications and generated runtime integration.
function isEnhancedSubmitEvent(
event: DelegatedEvent,
options: EnhancedMutationLoaderOptions | undefined,
): boolean;submitEnhancedMutation#
Runtime API used by Kovo applications and generated runtime integration.
async function submitEnhancedMutation(
options: EnhancedMutationSubmitOptions,
): Promise<EnhancedMutationAppliedResult>;submitOptimisticEnhancedMutation#
Runtime API used by Kovo applications and generated runtime integration.
async function submitOptimisticEnhancedMutation<Input>(
options: OptimisticEnhancedMutationSubmitOptions<Input>,
): Promise<
AppliedMutationResponse & {
appliedFragments: string[];
changes: MutationChangeRecord[];
idem: string;
targets: string[];
}
>;applyOptimisticTransforms#
Runtime API used by Kovo applications and generated runtime integration.
function applyOptimisticTransforms<Input>(
store: QueryStore,
input: Input,
plan: OptimisticPlan<Input>,
change: OptimisticChange<Input> = optimisticChangeFromInput(input),
): PendingOptimism;installPagehideOptimismCleanup#
Runtime API used by Kovo applications and generated runtime integration.
function installPagehideOptimismCleanup(
options: PagehideOptimismCleanupOptions,
): () => void;now#
Client clock for now() placeholders in derived optimistic transforms (SPEC.md §10.5).
function now(): number;stampPendingQueries#
Runtime API used by Kovo applications and generated runtime integration.
function stampPendingQueries(
root: PendingRoot,
queryNames: readonly string[],
pending: boolean,
): string[];createSubmitContext#
Runtime API used by Kovo applications and generated runtime integration.
function createSubmitContext(options: SubmitContextOptions): SubmitContext;applyCompiledQueryUpdatePlan#
Runtime API used by Kovo applications and generated runtime integration.
function applyCompiledQueryUpdatePlan(
root: QueryBindingRoot,
queryName: string,
value: unknown,
plan: CompiledQueryUpdatePlan = {},
options: ApplyCompiledQueryUpdatePlanOptions = {},
): AppliedCompiledQueryUpdatePlan;applyQueryBindings#
Runtime API used by Kovo applications and generated runtime integration.
function applyQueryBindings(
root: QueryBindingRoot,
queryName: string,
value: unknown,
options: ApplyQueryBindingsOptions = {},
): string[];applyStateBindings#
Runtime API used by Kovo applications and generated runtime integration.
function applyStateBindings(
root: QueryBindingRoot,
state: unknown,
options: ApplyStateBindingsOptions = {},
): Promise<string[]>;supportsQueryBindings#
Runtime API used by Kovo applications and generated runtime integration.
function supportsQueryBindings(root: unknown): root is QueryBindingRoot;applyInlineQueryEventToRuntime#
Runtime API used by Kovo applications and generated runtime integration.
function applyInlineQueryEventToRuntime(
event: InlineQueryEvent,
options: ApplyInlineQueryEventOptions,
): readonly string[];installInlineQueryEventHydration#
Runtime API used by Kovo applications and generated runtime integration.
function installInlineQueryEventHydration(
options: InstallInlineQueryEventHydrationOptions,
): () => void;refetchQueries#
Refetch named queries over the typed-read endpoint and apply the results to
the query store and bindings. A background "visible return" layer: individual
query failures are reported via onError and skipped while the rest continue
(SPEC §4.4, §9.4).
| Parameter | Type | Description |
|---|---|---|
options |
RefetchQueriesOptions |
The queries to refetch, the queryStore, a fetch, and apply/plan hooks. |
| (returns) | Promise<RefetchedQueryResponse[]> |
The applied query responses. |
async function refetchQueries(
options: RefetchQueriesOptions,
): Promise<RefetchedQueryResponse[]>;createQueryStore#
Create the client-side query store: the in-memory source of truth the loader
hydrates from <kovo-query> scripts and that bindings and optimistic updates
read and write (SPEC §9.4).
| Parameter | Type | Description |
|---|---|---|
| (returns) | QueryStore |
A fresh QueryStore. |
function createQueryStore(): QueryStore;Example
import { createQueryStore } from '@kovojs/runtime/client';
const store = createQueryStore();
store.set('cart', { count: 1 });Types & interfaces#
AppliedDeferredStreamResponseToRuntime#
Runtime API used by Kovo applications and generated runtime integration.
type AppliedDeferredStreamResponseToRuntime =
| (AppliedMutationResponse & { chunks: AppliedMutationResponse[] })
| AppliedDeferredStreamResponseWithRoot;AppliedDeferredStreamResponseWithRoot#
Runtime API used by Kovo applications and generated runtime integration.
type AppliedDeferredStreamResponseWithRoot = AppliedMutationResponseWithRoot & {
chunks: AppliedMutationResponseWithRoot[];
};ApplyDeferredStreamResponseToRuntimeOptions#
Runtime API used by Kovo applications and generated runtime integration.
type ApplyDeferredStreamResponseToRuntimeOptions =
ApplyDeferredStreamResponseToRuntimeBaseOptions & {
root?: MorphRoot | undefined;
};DelegatedEvent#
Runtime API used by Kovo applications and generated runtime integration.
interface DelegatedEvent {
preventDefault?: () => void;
submitter?: unknown;
type: string;
target: EventTargetLike | null;
}EventBusOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface EventBusOptions {
onError?: (error: unknown, context: RuntimeErrorContext) => void;
queryDataKeys?: readonly string[];
}EventElementLike#
Runtime API used by Kovo applications and generated runtime integration.
interface EventElementLike
extends
AttributeElementLike,
ClosestElementLike<EventElementLike>,
OptionalQuerySelectorAllRootLike<UploadProgressElementLike> {}EventListener#
Runtime API used by Kovo applications and generated runtime integration.
type EventListener<Payload> = (event: TypedEvent<string, Payload>) => void | Promise<void>;EventPayloadMap#
Runtime API used by Kovo applications and generated runtime integration.
type EventPayloadMap<Definitions extends readonly EventDefinition<string, JsonValue>[]> = {
[Definition in Definitions[number] as Definition['name']]: Definition extends EventDefinition<
string,
infer Payload
>
? Payload
: never;
};EventSubscription#
Runtime API used by Kovo applications and generated runtime integration.
interface EventSubscription {
off(): void;
}EventTargetLike#
Runtime API used by Kovo applications and generated runtime integration.
interface EventTargetLike extends ClosestElementLike<EventElementLike> {}RuntimeErrorContext#
Runtime API used by Kovo applications and generated runtime integration.
interface RuntimeErrorContext {
event?: DelegatedEvent | TypedEvent<string, unknown>;
phase:
| 'delegated-event'
| 'event-listener'
| 'execution-trigger'
| 'enhanced-mutation'
| 'mutation-broadcast'
| 'query-hydration';
}TypedEvent#
Runtime API used by Kovo applications and generated runtime integration.
interface TypedEvent<Name extends string = string, Payload = unknown> {
name: Name;
payload: Payload;
}TypedEventBus#
Runtime API used by Kovo applications and generated runtime integration.
interface TypedEventBus<EventMap extends Record<string, unknown>> {
emit<Name extends Extract<keyof EventMap, string>>(name: Name, payload: EventMap[Name]): void;
events: readonly Extract<keyof EventMap, string>[];
on<Name extends Extract<keyof EventMap, string>>(
name: Name,
listener: EventListener<EventMap[Name]>,
): EventSubscription;
}UploadProgressElementLike#
Runtime API used by Kovo applications and generated runtime integration.
interface UploadProgressElementLike extends AttributeWriterLike {
setAttribute(name: string, value: string): void;
}IslandSignalScope#
Runtime API used by Kovo applications and generated runtime integration.
type IslandSignalScope = object;LoaderLifecycleTarget#
Runtime API used by Kovo applications and generated runtime integration.
interface LoaderLifecycleTarget extends ListenerTargetLike<DelegatedEvent> {}LoaderRoot#
Runtime API used by Kovo applications and generated runtime integration.
interface LoaderRoot
extends
LoaderLifecycleTarget,
OptionalQuerySelectorAllRootLike<EventElementLike | QueryScriptLike>,
VisibilityStateLike {}VisibleObserver#
Runtime API used by Kovo applications and generated runtime integration.
interface VisibleObserver {
observe(element: EventElementLike): void;
unobserve(element: EventElementLike): void;
}VisibleObserverEntry#
Runtime API used by Kovo applications and generated runtime integration.
interface VisibleObserverEntry {
isIntersecting: boolean;
target: EventElementLike;
}VisibleObserverFactory#
Runtime API used by Kovo applications and generated runtime integration.
type VisibleObserverFactory = (
callback: (entries: readonly VisibleObserverEntry[]) => void,
) => VisibleObserver;KovoLoader#
A running loader instance: the delegated events it listens for and a dispose to tear it down.
interface KovoLoader {
dispose(): void;
events: readonly string[];
}KovoLoaderOptions#
Options for installKovoLoader: the root, module importer, query store/plans, and lifecycle hooks.
interface KovoLoaderOptions {
discardPendingOptimism?: () => readonly string[] | void;
enhancedMutations?: EnhancedMutationLoaderOptions;
events?: readonly string[];
focusTarget?: LoaderLifecycleTarget;
importModule: ImportHandlerModule;
onError?: (error: unknown, context: RuntimeErrorContext) => void;
applyQuery?: QueryApplyInterposition;
queryEventTarget?: QueryEventHydrationTarget;
queryPlans?: CompiledQueryUpdatePlans;
queryRefetch?: QueryRefetchOptions;
requestIdle?: (callback: () => void) => void;
visibleObserver?: VisibleObserverFactory;
queryStore?: QueryStore;
refetchOnFocus?: (queries: readonly string[]) => void | Promise<void>;
refetchOnFocusOptOut?: readonly string[];
root: LoaderRoot;
}DomMorphRoot#
Runtime API used by Kovo applications and generated runtime integration.
class DomMorphRoot implements MorphRoot {
private readonly root: FragmentTargetRoot;
constructor(root: FragmentTargetRoot) {
this.root = root;
}
findFragmentTarget(target: string): MorphTarget | null {
const element = findFragmentTargetElement(this.root, target);
return element ? new DomMorphTarget(element) : null;
}
}DomMorphTarget#
Runtime API used by Kovo applications and generated runtime integration.
class DomMorphTarget implements MorphTarget {
element: Element;
constructor(element: Element) {
this.element = element;
}
readHtml(): string {
return this.element.innerHTML;
}
appendHtml(html: string): void {
const template = document.createElement('template');
template.innerHTML = html.trim();
this.element.append(...Array.from(template.content.childNodes));
}
replaceWithHtml(html: string): void {
const template = document.createElement('template');
template.innerHTML = html.trim();
const next = firstMorphElement(template.content);
const activeState = captureActiveDomState(this.element);
const scrollStates = captureDomScrollStates(this.element);
if (!next) {
this.element.replaceChildren();
return;
}
morphDomElement(this.element, next);
restoreActiveDomState(activeState);
restoreDomScrollStates(scrollStates);
}
}MorphFragment#
Runtime API used by Kovo applications and generated runtime integration.
type MorphFragment = (target: MorphTarget, html: string) => void;MorphRoot#
Runtime API used by Kovo applications and generated runtime integration.
interface MorphRoot {
findFragmentTarget(target: string): MorphTarget | null;
}MorphTarget#
Runtime API used by Kovo applications and generated runtime integration.
interface MorphTarget {
appendHtml?(html: string): void;
readHtml?(): string;
replaceWithHtml(html: string): void;
}StructuralMorphBrowserState#
Runtime API used by Kovo applications and generated runtime integration.
interface StructuralMorphBrowserState {
focused?: boolean;
islandState?: unknown;
scroll?: { left: number; top: number };
selection?: { direction?: 'backward' | 'forward' | 'none'; end: number; start: number };
}StructuralMorphKey#
Runtime API used by Kovo applications and generated runtime integration.
type StructuralMorphKey = string | number;StructuralMorphNode#
One node in a browser-free structural tree: its type, optional key,
props, text, children, and captured browserState. Used by the
structural-morph reconciler (SPEC.md §9.1) and by hand-written conformance
test helpers that assert keyed reuse across reorder.
interface StructuralMorphNode {
browserState?: StructuralMorphBrowserState;
children?: StructuralMorphNode[];
key?: StructuralMorphKey | null;
props?: Record<string, unknown>;
text?: string;
type: string;
}BroadcastLike#
Runtime API used by Kovo applications and generated runtime integration.
interface BroadcastLike {
close?: () => void;
onmessage: ((event: { data: unknown }) => void) | null;
postMessage(message: unknown): void;
}InstallMutationBroadcastOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface InstallMutationBroadcastOptions {
applyQuery?: QueryApplyInterposition;
channel: BroadcastLike;
morph?: MorphFragment;
onError?: RuntimeErrorReporter;
onChanges?: (changes: readonly MutationChangeRecord[]) => void;
onAppliedQueries?: (queries: readonly string[]) => void;
queryPlans?: CompiledQueryUpdatePlans;
root?: MorphRoot;
store: QueryStore;
}MutationBroadcast#
Runtime API used by Kovo applications and generated runtime integration.
interface MutationBroadcast {
close(): void;
publish(body: string, changes?: readonly MutationChangeRecord[]): void;
}EnhancedMutationAppliedResult#
Runtime API used by Kovo applications and generated runtime integration.
type EnhancedMutationAppliedResult = AppliedMutationResponse & {
appliedFragments: string[];
changes: MutationChangeRecord[];
idem: string;
targets: string[];
};MutationQueue#
Runtime API used by Kovo applications and generated runtime integration.
class MutationQueue {
#tails = new Map<string, Promise<unknown>>();
run<Value>(queue: string | undefined, task: MutationTask<Value>): Promise<Value> {
if (!queue) return Promise.resolve().then(task);
const previous = this.#tails.get(queue) ?? Promise.resolve();
const run = previous.then(task, task);
const tail = run
.catch(() => undefined)
.finally(() => {
if (this.#tails.get(queue) === tail) {
this.#tails.delete(queue);
}
});
this.#tails.set(queue, tail);
return run;
}
pending(queue: string): boolean {
return this.#tails.has(queue);
}
}MutationTask#
Runtime API used by Kovo applications and generated runtime integration.
type MutationTask<Value> = () => Promise<Value> | Value;MutationResponseHeaderLike#
Runtime API used by Kovo applications and generated runtime integration.
interface MutationResponseHeaderLike {
headers?: {
get(name: string): string | null;
};
}TargetCollectorRoot#
Runtime API used by Kovo applications and generated runtime integration.
interface TargetCollectorRoot extends QuerySelectorAllRootLike<TargetElementLike> {}EnhancedFormElementLike#
Runtime API used by Kovo applications and generated runtime integration.
interface EnhancedFormElementLike extends EventElementLike {
action: string;
id?: string | undefined;
method?: string | undefined;
submit?: () => void;
}EnhancedFormLike#
Runtime API used by Kovo applications and generated runtime integration.
interface EnhancedFormLike {
action: string;
getAttribute?(name: string): string | null;
id?: string | { toString(): string } | undefined;
method?: string | undefined;
}EnhancedMutationFetch#
Runtime API used by Kovo applications and generated runtime integration.
type EnhancedMutationFetch = (
url: string,
options: EnhancedMutationFetchOptions,
) => Promise<EnhancedMutationResponseLike>;EnhancedMutationFetchOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface EnhancedMutationFetchOptions {
body: unknown;
headers: Record<string, string>;
keepalive: boolean;
method: string;
onUploadProgress?: (progress: UploadProgress) => void;
}EnhancedMutationLoaderOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface EnhancedMutationLoaderOptions {
applyQuery?: QueryApplyInterposition;
broadcast?: MutationBroadcast;
fetch: EnhancedMutationFetch;
formData?: (form: EnhancedFormElementLike, event: DelegatedEvent) => unknown;
idem?: () => string;
morph?: MorphFragment;
/**
* Handles enhanced form submit failures after preventDefault. When present,
* the form layer owns the error and native submit fallback is skipped.
*
* SPEC.md section 9.2 keeps enhanced and no-JS form paths equivalent; this
* hook is the enhanced path's reporting seam for failed fragment submissions.
*/
onError?: (error: unknown, form: EnhancedFormElementLike) => void;
onUploadProgress?: (progress: UploadProgress, form: EnhancedFormElementLike) => void;
pendingRoot?: PendingRoot;
queryPlans?: CompiledQueryUpdatePlans;
root: MorphRoot & TargetCollectorRoot;
store: QueryStore;
}EnhancedMutationResponseLike#
Runtime API used by Kovo applications and generated runtime integration.
interface EnhancedMutationResponseLike {
headers?: {
get(name: string): string | null;
};
ok?: boolean;
status?: number;
text(): Promise<string>;
}EnhancedMutationSubmitOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface EnhancedMutationSubmitOptions {
applyQuery?: QueryApplyInterposition;
broadcast?: MutationBroadcast;
/**
* The page-level build token (SPEC §9.1.1). Defaults to `readPageBuildToken()`
* (`<meta name="kovo-build">`) when omitted; deltas apply only when it matches
* the response's `Kovo-Build` token.
*/
expectedBuildToken?: string;
fetch: EnhancedMutationFetch;
form: EnhancedFormLike;
formData: unknown;
idem?: string;
islandSignalScope?: IslandSignalScope;
morph?: MorphFragment;
/**
* Refetch-full handler for delta chunks with a missing/stale base (SPEC §9.1.1).
* Defaults to a `/_q/<wireKey>` refetcher over the submit `fetch` when omitted.
*/
onDeltaMiss?: OnDeltaMiss;
/**
* Reports mutation submit/apply failures. Direct submit callers still receive
* the thrown error; dispatchEnhancedFormSubmit decides whether a form-layer
* error has been handled.
*/
onError?: (error: unknown) => void;
onUploadProgress?: (progress: UploadProgress) => void;
pendingQueries?: readonly string[];
pendingRoot?: PendingRoot;
queryPlans?: CompiledQueryUpdatePlans;
root: MorphRoot & TargetCollectorRoot;
store: QueryStore;
}UploadProgress#
Runtime API used by Kovo applications and generated runtime integration.
interface UploadProgress {
loaded: number;
total?: number;
}OptimisticEnhancedMutationSubmitOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface OptimisticEnhancedMutationSubmitOptions<
Input,
> extends EnhancedMutationSubmitOptions {
change?: OptimisticChange<Input>;
input: Input;
optimistic: OptimisticPlan<Input>;
queue?: MutationQueue;
rebaser: OptimisticRebaser;
}OptimisticRebaser#
Runtime API used by Kovo applications and generated runtime integration.
class OptimisticRebaser {
#pendingByQuery = new Map<string, PendingTransform[]>();
#serverTruthByQuery = new Map<string, unknown>();
#store: QueryStore;
constructor(store: QueryStore) {
this.#store = store;
}
add<Input>(id: string, input: Input, plan: OptimisticPlan<Input>): void {
this.addChange(id, optimisticChangeFromInput(input), plan);
}
addChange<Input>(id: string, change: OptimisticChange<Input>, plan: OptimisticPlan<Input>): void {
for (const [queryName, transform] of Object.entries(plan.transforms)) {
if (transform === 'await-fragment') continue;
const key = optimisticQueryKey(plan, queryName, change);
const storeKey = queryStoreKey(queryName, key);
const pending = this.#pendingByQuery.get(storeKey) ?? [];
if (pending.length === 0) {
this.#serverTruthByQuery.set(storeKey, structuredClone(this.#store.get(queryName, key)));
}
pending.push({ change, id, transform: transform as OptimisticTransform });
this.#pendingByQuery.set(storeKey, pending);
this.#store.set(queryName, transform(this.#store.get(queryName, key), change.input), key);
}
}
settle(id: string): void {
for (const [queryName, pending] of this.#pendingByQuery) {
const next = pending.filter((item) => item.id !== id);
if (next.length === 0) {
this.#pendingByQuery.delete(queryName);
this.#serverTruthByQuery.delete(queryName);
} else {
this.#pendingByQuery.set(queryName, next);
}
}
// … truncated (71 more lines); see the package source for the full declaration.PagehideOptimismCleanupOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface PagehideOptimismCleanupOptions {
discardPendingOptimism: () => readonly string[] | void;
root: PagehideRoot;
}PendingOptimism#
A staged optimistic prediction: commit it to keep the predicted store state,
or restore it to roll back to the captured snapshot when the server rejects
the mutation (SPEC §10.4).
interface PendingOptimism {
commit(): void;
restore(): void;
snapshot: QuerySnapshot;
}PendingTransform#
One recorded optimistic transform awaiting reconciliation: the change that
triggered it, the mutation id it belongs to, and the pure transform re-run
on rebase against server truth (SPEC §10.5).
interface PendingTransform<Input = unknown> {
change: OptimisticChange<Input>;
id: string;
transform: OptimisticTransform<Input>;
}PendingElementLike#
Runtime API used by Kovo applications and generated runtime integration.
interface PendingElementLike extends AttributeMutatorLike {}PendingRoot#
Runtime API used by Kovo applications and generated runtime integration.
interface PendingRoot extends QuerySelectorAllRootLike<PendingElementLike> {}SubmitContext#
Runtime API used by Kovo applications and generated runtime integration.
interface SubmitContext {
submit<Definition extends SubmitFormDefinition>(
form: Definition,
options: SubmitOptions<FormInput<Definition>, FormFailure<Definition>>,
): Promise<
AppliedMutationResponse & { appliedFragments: string[]; idem: string; targets: string[] }
>;
}SubmitContextOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface SubmitContextOptions {
actionFor?: (form: SubmitFormDefinition) => string;
broadcast?: MutationBroadcast;
fetch: EnhancedMutationFetch;
method?: string;
morph?: MorphFragment;
queryPlans?: CompiledQueryUpdatePlans;
root: MorphRoot & TargetCollectorRoot;
store: QueryStore;
}SubmitFormDefinition#
Runtime API used by Kovo applications and generated runtime integration.
type SubmitFormDefinition = Form<string, any, any>;SubmitOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface SubmitOptions<Input extends Record<string, JsonValue>, Failure> {
action?: string;
idem?: string;
input: Input;
method?: string;
onError?: (failure: Failure) => void | Promise<void>;
parseError?: (body: string) => Failure;
}AppliedCompiledQueryUpdatePlan#
Runtime API used by Kovo applications and generated runtime integration.
interface AppliedCompiledQueryUpdatePlan {
bindings: string[];
derives: string[];
stamps: string[];
templateStamps: string[];
}ApplyStateBindingsOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface ApplyStateBindingsOptions extends ApplyQueryBindingsOptions {
importModule?: (url: string) => Promise<Record<string, unknown>>;
}CompiledQueryDerive#
Runtime API used by Kovo applications and generated runtime integration.
interface CompiledQueryDerive {
name: string;
select(value: unknown, root: QueryBindingRoot): unknown;
selector?: string;
}CompiledQueryStamp#
Runtime API used by Kovo applications and generated runtime integration.
interface CompiledQueryStamp {
attr: string;
select(value: unknown, root: QueryBindingRoot): unknown;
selector: string;
}CompiledQueryTemplateStamp#
Runtime API used by Kovo applications and generated runtime integration.
interface CompiledQueryTemplateStamp {
key: string | ((item: unknown, index: number) => string | number);
list: string;
render(item: unknown, index: number): string;
selector: string;
}CompiledQueryUpdatePlan#
Runtime API used by Kovo applications and generated runtime integration.
interface CompiledQueryUpdatePlan {
bindings?: boolean;
derives?: readonly CompiledQueryDerive[];
stamps?: readonly CompiledQueryStamp[];
templateStamps?: readonly CompiledQueryTemplateStamp[];
}CompiledQueryUpdatePlans#
Runtime API used by Kovo applications and generated runtime integration.
type CompiledQueryUpdatePlans = Readonly<
Record<string, CompiledQueryUpdatePlan | undefined>
>;QueryBindingElement#
Runtime API used by Kovo applications and generated runtime integration.
interface QueryBindingElement
extends AttributeElementLike, ClosestElementLike<QueryBindingElement> {
checked?: boolean;
indeterminate?: boolean;
scrollLeft?: number;
scrollTop?: number;
tagName?: string;
textContent?: string | null;
value?: string;
}QueryBindingRoot#
Runtime API used by Kovo applications and generated runtime integration.
interface QueryBindingRoot extends QuerySelectorAllRootLike<QueryBindingElement> {}TemplateStampHost#
Runtime API used by Kovo applications and generated runtime integration.
interface TemplateStampHost extends QueryBindingElement {
reconcileTemplateStamp(items: readonly TemplateStampItem[]): void;
}TemplateStampItem#
Runtime API used by Kovo applications and generated runtime integration.
interface TemplateStampItem {
html: string;
index: number;
key: string;
value: unknown;
}ApplyInlineQueryEventOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface ApplyInlineQueryEventOptions {
applyQuery?: QueryApplyInterposition;
onError?: RuntimeErrorReporter;
queryPlans?: CompiledQueryUpdatePlans;
root?: unknown;
store: QueryStore;
}InlineQueryEvent#
Runtime API used by Kovo applications and generated runtime integration.
interface InlineQueryEvent {
detail?: InlineQueryEventDetail;
}InlineQueryEventDetail#
Runtime API used by Kovo applications and generated runtime integration.
interface InlineQueryEventDetail {
queries: QueryElementChunkLike[];
}InstallInlineQueryEventHydrationOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface InstallInlineQueryEventHydrationOptions extends ApplyInlineQueryEventOptions {
onAppliedQueries?: (queries: readonly string[]) => void;
target: QueryEventHydrationTarget;
}QueryEventHydrationTarget#
Runtime API used by Kovo applications and generated runtime integration.
interface QueryEventHydrationTarget extends ListenerTargetLike<InlineQueryEvent> {}QueryRefetchFetch#
Runtime API used by Kovo applications and generated runtime integration.
interface QueryRefetchFetch {
(
url: string,
init: {
cache: 'no-store';
headers: Record<string, string>;
method: 'GET';
},
): Promise<QueryRefetchResponse> | QueryRefetchResponse;
}QueryRefetchOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface QueryRefetchOptions {
fetch: QueryRefetchFetch;
/**
* Reports typed-read fetch, response-body, and wire-apply failures. Refetch is
* a visible-return background layer, so individual query failures are reported
* and skipped while later queries continue under SPEC.md §4.4 hydration.
*/
onError?: (error: unknown) => void;
urlForQuery?: (query: string) => string | undefined;
}QueryRefetchResponse#
Runtime API used by Kovo applications and generated runtime integration.
interface QueryRefetchResponse {
ok?: boolean;
status?: number;
text(): Promise<string> | string;
}RefetchQueriesOptions#
Runtime API used by Kovo applications and generated runtime integration.
interface RefetchQueriesOptions extends QueryRefetchOptions {
applyQuery?: QueryApplyInterposition;
queryPlans?: CompiledQueryUpdatePlans;
queries: readonly string[];
queryStore: QueryStore;
root?: unknown;
}RefetchedQueryResponse#
Runtime API used by Kovo applications and generated runtime integration.
interface RefetchedQueryResponse {
fragments: [];
queries: readonly string[];
}QuerySnapshot#
A point-in-time copy of query values, used to roll back optimistic updates.
type QuerySnapshot = Map<string, unknown>;QueryStore#
The client query store: get/set/subscribe to query values and take snapshots.
interface QueryStore {
get<Value = unknown>(name: string, key?: string): Value | undefined;
snapshot(
names: readonly string[],
keys?: Readonly<Record<string, string | undefined>>,
): QuerySnapshot;
set<Value = unknown>(name: string, value: Value, key?: string): void;
subscribe<Value = unknown>(name: string, plan: QueryUpdatePlan<Value>, key?: string): () => void;
}QueryUpdatePlan#
A subscriber callback invoked with a query's new value when it changes.
type QueryUpdatePlan<Value = unknown> = (value: Value) => void;