Documentation navigation

Published API · 0.1.0-rc.1

foldkit · experimental, experimental/machine, experimental/query, experimental/server

Published foldkit API declarations for experimental, experimental/machine, experimental/query, experimental/server.

./experimental

@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES

This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.

import * as Wseffect from '@wsagency/wseffect-foldkit/experimental'

Exported declarations

Machine

export * from './machine.js';

Query

export { define } from './define.js';
export type { KeyedQuery } from './keyedQuery.js';
export type { Query } from './query.js';

Server

export * from './document.js';
export * from './entry.js';
export * from './fetch.js';
export * from './host.js';
export * from './server.js';
export * from './template.js';

./experimental/machine

@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES

This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.

import * as Wseffect from '@wsagency/wseffect-foldkit/experimental/machine'

Exported declarations

DeadTransition

An Edge that cannot fire in a walk of the declared Edge set, with the reason.

export type DeadTransition<State extends Tagged, Message extends Tagged> = Readonly<{
    edge: EdgeSummary<State, Message>;
    reason: DeadTransitionReason;
}>;

DeadTransitionReason

export type DeadTransitionReason = 'UnreachableSource' | 'ShadowedByOtherwise' | 'ShadowedByIgnore';

define

export declare function define<State extends Tagged, Message extends Tagged, ContextSchema extends Schema.Top>(schemas: MachineSchemas<State, Message, ContextSchema>): <R = never>(definition: MachineDefinition<State, Message, R, ContextSchema['Type']>) => Machine<State, Message, R, ContextSchema['Type']>;

define

export declare function define<State extends Tagged, Message extends Tagged>(schemas: MachineSchemas<State, Message>): <R = never>(definition: MachineDefinition<State, Message, R>) => Machine<State, Message, R>;

Edge

export type Edge<State extends Tagged, Message extends Tagged, SourceState extends State, TriggerMessage extends Message, GuardValue = void, R = never, Context = NoMachineContext> = Readonly<{
    _tag: 'Edge';
    target: TagOf<State>;
    handler: (input: EdgeInput<SourceState, TriggerMessage, unknown, Context>) => Update.Return<State, Message, R>;
    readonly '~foldkit/EdgeGuardValue'?: GuardValue;
}>;

EdgeGuard

Which guard construct an Edge sits under, with its position in the guard list.

export type EdgeGuard = Readonly<{
    _tag: 'Unguarded';
}> | Readonly<{
    _tag: 'When';
    position: number;
}> | Readonly<{
    _tag: 'Otherwise';
    position: number;
}>;

EdgeInput

export type EdgeInput<SourceState extends Tagged, TriggerMessage extends Tagged, GuardValue = void, Context = NoMachineContext> = HasMachineContext<Context> extends true ? Readonly<{
    state: SourceState;
    message: TriggerMessage;
    guardValue: GuardValue;
    context: Context;
}> : Readonly<{
    state: SourceState;
    message: TriggerMessage;
    guardValue: GuardValue;
}>;

EdgeSummary

One Edge of the table as plain data: source, trigger, target, and guard placement.

export type EdgeSummary<State extends Tagged, Message extends Tagged> = Readonly<{
    from: TagOf<State>;
    messageTag: TagOf<Message>;
    target: TagOf<State>;
    guard: EdgeGuard;
}>;

fold

Folds a Machine state field into an enclosing Model. Any transition-time Commands pass through unchanged. When `read` returns `None`, the fold returns the original Model without running a transition. For a contextual Machine, `context` is read only when the Machine state is present and is supplied to that transition. ```ts const foldUpload = Machine.fold({ machine: uploadMachine, read: (model: Model) => Option.some(model.upload), write: (model, nextUpload) => modifyFields(model, { upload: () => nextUpload }), context: model => model.uploadQueues, }) // Data-first in update foldUpload(model, message) // Data-last in a composed update Update.combine(model, [foldUpload(message), recordUploadAttempt]) ```

fold: {
    <ParentModel, State extends Tagged, Message extends Tagged, R = never, Context = NoMachineContext>(config: FoldConfig<ParentModel, State, Message, R, Context>): Update.Fold<ParentModel, Message, Message, R>;
}

FoldConfig

The capabilities needed to fold a Machine state field into its enclosing Model. `read` returns an `Option` because the field may be absent in the current Model variant; `write` replaces it after a transition. A contextual Machine also requires `context`, which reads the current context from the enclosing Model for each transition.

export type FoldConfig<ParentModel, State extends Tagged, Message extends Tagged, R = never, Context = NoMachineContext> = Readonly<{
    machine: Machine<State, Message, R, Context>;
    read: (model: ParentModel) => Option.Option<State>;
    write: (model: ParentModel, nextState: State) => ParentModel;
}> & FoldContextField<ParentModel, Context>;

forStates

Selects source state tags for a shared transition map. The `on` handler's `state` is narrowed to the union of the selected variants, and its `message` is narrowed by the map key. Add the resulting fragment to a Machine definition's `shared` array. Shared transitions are defaults: a state-local transition for the same Message replaces the shared transition. Defining the same state/Message pair in two shared fragments throws when the Machine is defined.

forStates: <const SourceTags extends Array.NonEmptyReadonlyArray<string>>(sourceTags: SourceTags) => ForStatesBuilder<SourceTags>

GuardedEdge

export type GuardedEdge<State extends Tagged, Message extends Tagged, SourceState extends State, TriggerMessage extends Message, R = never, Context = NoMachineContext> = When<State, Message, SourceState, TriggerMessage, unknown, R, Context> | Otherwise<State, Message, SourceState, TriggerMessage, R, Context> | Ignore;

ignore

ignore: () => Ignore

Ignore

export type Ignore = Readonly<{
    _tag: 'Ignore';
}>;

Ignored

export type Ignored<State extends Tagged, Message extends Tagged> = Readonly<{
    _tag: 'Ignored';
    stateTag: TagOf<State>;
    messageTag: TagOf<Message>;
    state: State;
    reason: IgnoredReason;
}>;

IgnoredReason

export type IgnoredReason = 'OutOfAlphabet' | 'NotApplicable' | 'GuardsFellThrough' | 'ExplicitlyIgnored';

Machine

A compiled state Machine: a pure transition function plus static analysis over the Edge set.

export type Machine<State extends Tagged, Message extends Tagged, R = never, Context = NoMachineContext> = Readonly<{
    initial: State;
    stateTags: ReadonlyArray<TagOf<State>>;
    edges: ReadonlyArray<EdgeSummary<State, Message>>;
    /** Runs one Message through the Machine as a Foldkit update. The returned
     * `Update.Return<State, Message, R>` stores the next Machine state in
     * `model` and any transition-time Commands in `commands`. Use {@link fold}
     * to read and write the Machine state inside an enclosing Model. Use `step`
     * when code needs to distinguish a `Transitioned` result from an `Ignored`
     * result or inspect Edge metadata.
     */
    transition: (state: State, message: Message, ...context: MachineContextArguments<Context>) => Update.Return<State, Message, R>;
    step: (state: State, message: Message, ...context: MachineContextArguments<Context>) => TransitionResult<State, Message, R>;
    /**
     * The state tags a walk of the statically selectable declared Edges visits
     * starting from `tag`. Edges listed after an `otherwise` or {@link ignore}
     * are excluded because the runtime can never select them.
     */
    reachableFrom: (tag: TagOf<State>) => ReadonlySet<TagOf<State>>;
    /**
     * The state tags a walk of the statically selectable declared Edges never
     * visits, starting from the initial state's tag plus `extraRoots`. Edges
     * listed after an `otherwise` or {@link ignore} are excluded because the
     * runtime can never select them. The walk sees only declared Edges, so state
     * changes made outside `transition` and `step` are invisible to it, and it
     * always starts at `initial`. Entry points other than `initial`, such as
     * restored persistence, deep links, or SSR hydration, must be passed as
     * `extraRoots`, or the states they enter are reported unreachable even
     * though the running program visits them.
     */
    unreachableStates: (extraRoots?: ReadonlyArray<TagOf<State>>) => ReadonlyArray<TagOf<State>>;
    /**
     * The Edges that cannot fire in a walk of the declared Edge set starting
     * from the initial state's tag plus `extraRoots`, each with its
     * {@link DeadTransitionReason}. Each Edge appears at most once;
     * `ShadowedByOtherwise` and `ShadowedByIgnore` take precedence when a source
     * is also unreachable. The same assumptions as `unreachableStates` apply:
     * the walk cannot see state changes made outside `transition` and `step`,
     * and entry points other than `initial` must be passed as `extraRoots`, or
     * their outgoing Edges are reported as `UnreachableSource` even though the
     * running program fires them.
     */
    deadTransitions: (extraRoots?: ReadonlyArray<TagOf<State>>) => ReadonlyArray<DeadTransition<State, Message>>;
    toMermaid: () => string;
}>;

MachineDefinition

The Machine definition: the initial state, shared transition defaults, and the state-local transition table. A state-local transition replaces a shared transition for the same state and Message.

export type MachineDefinition<State extends Tagged, Message extends Tagged, R = never, Context = NoMachineContext> = Readonly<{
    initial: State;
    shared?: ReadonlyArray<ForStatesFragment<State, Message, R, Context>>;
    states: TransitionTable<State, Message, R, Context>;
}>;

MachineSchemas

The Schemas a Machine is defined over, including an optional read-only context Schema. A declared context is required by the Machine's guards, Edge handlers, `transition`, and `step`.

export type MachineSchemas<State extends Tagged, Message extends Tagged, ContextSchema extends Schema.Top | undefined = undefined> = MachineSchemaFields<State, Message> & ([ContextSchema] extends [Schema.Top] ? Readonly<{
    context: ContextSchema;
}> : Readonly<{
    context?: never;
}>);

otherwise

otherwise: <State extends Tagged, Message extends Tagged, SourceState extends State, TriggerMessage extends Message, R = never, Context = NoMachineContext>(edge: Edge<State, Message, SourceState, TriggerMessage, void, R, Context>) => Otherwise<State, Message, SourceState, TriggerMessage, R, Context>

Otherwise

export type Otherwise<State extends Tagged, Message extends Tagged, SourceState extends State, TriggerMessage extends Message, R = never, Context = NoMachineContext> = Readonly<{
    _tag: 'Otherwise';
    edge: Edge<State, Message, SourceState, TriggerMessage, void, R, Context>;
}>;

StateTransitions

The transition table entry for one source state. Use this alias when extracting an entry from a Machine's `states` record to preserve the source state and triggering Message narrowing inside its Edges.

export type StateTransitions<State extends Tagged, Message extends Tagged, SourceTag extends TagOf<State>, R = never, Context = NoMachineContext> = NonNullable<TransitionTable<State, Message, R, Context>[SourceTag]>;

Tagged

Any value discriminated by a `_tag` field. Both states and Messages satisfy this shape.

export type Tagged = Readonly<{
    _tag: string;
}>;

TagOf

The union of `_tag` literals in a Tagged union.

export type TagOf<Union extends Tagged> = Union['_tag'];

to

to: <State extends Tagged, Message extends Tagged, SourceState extends State, TriggerMessage extends Message, const TargetTag extends TagOf<State>, R = never, Context = NoMachineContext>(target: TargetTag, handler: (input: NoInfer<EdgeInput<SourceState, TriggerMessage, void, Context>>) => Update.Return<NoInfer<Variant<State, TargetTag>>, NoInfer<Message>, R>) => Edge<State, Message, SourceState, TriggerMessage, void, R, Context>

Transitioned

A step that matched an Edge: the next state plus any transition-time Commands.

export type Transitioned<State extends Tagged, Message extends Tagged, R = never> = Readonly<{
    _tag: 'Transitioned';
    from: TagOf<State>;
    target: TagOf<State>;
    messageTag: TagOf<Message>;
    state: State;
    commands: ReadonlyArray<Command<Message, never, R>>;
}>;

TransitionResult

The observable outcome of one step: `Transitioned` or `Ignored`.

export type TransitionResult<State extends Tagged, Message extends Tagged, R = never> = Transitioned<State, Message, R> | Ignored<State, Message>;

TransitionTable

The transition table: for each source state tag, the Messages it responds to and the Edge (or ordered guard list) each Message fires. States absent from the table, and Messages absent from a state's `on` record, are ignored: `Machine.step` reports them as `Ignored` rather than transitioning.

export type TransitionTable<State extends Tagged, Message extends Tagged, R = never, Context = NoMachineContext> = Readonly<{
    [SourceTag in TagOf<State>]?: Readonly<{
        on: Readonly<{
            [MessageTag in TagOf<Message>]?: Edge<State, Message, Variant<State, SourceTag>, Variant<Message, MessageTag>, void, R, Context> | ReadonlyArray<GuardedEdge<State, Message, Variant<State, SourceTag>, Variant<Message, MessageTag>, R, Context>>;
        }>;
    }>;
}>;

Variant

The single variant of a Tagged union carrying the given tag.

export type Variant<Union extends Tagged, Tag extends TagOf<Union>> = Extract<Union, Readonly<{
    _tag: Tag;
}>>;

when

when: <State extends Tagged, Message extends Tagged, SourceState extends State, TriggerMessage extends Message, GuardResult extends Option.Option<unknown> | boolean, const TargetTag extends TagOf<State>, R = never, Context = NoMachineContext>(guard: (state: NoInfer<SourceState>, message: NoInfer<TriggerMessage>, ...context: ContextArguments<NoInfer<Context>>) => GuardResult, target: TargetTag, handler: (input: NoInfer<EdgeInput<SourceState, TriggerMessage, GuardValueOf<GuardResult>, Context>>) => Update.Return<NoInfer<Variant<State, TargetTag>>, NoInfer<Message>, R>) => When<State, Message, SourceState, TriggerMessage, GuardValueOf<GuardResult>, R, Context>

When

export type When<State extends Tagged, Message extends Tagged, SourceState extends State, TriggerMessage extends Message, GuardValue = unknown, R = never, Context = NoMachineContext> = Readonly<{
    _tag: 'When';
    guard: (state: SourceState, message: TriggerMessage, ...context: ContextArguments<Context>) => Option.Option<unknown>;
    edge: Edge<State, Message, SourceState, TriggerMessage, GuardValue, R, Context>;
}>;

./experimental/query

@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES

This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.

import * as Wseffect from '@wsagency/wseffect-foldkit/experimental/query'

Exported declarations

define

export declare function define<Name extends string, A, AI, E, EI, Fields extends SyncFields, R = never>(config: KeyedQueryConfig<Name, A, AI, E, EI, Fields, R>): KeyedQuery<Name, A, AI, E, EI, Fields, R>;

define

export declare function define<Name extends string, A, AI, E, EI, R = never>(config: QueryConfig<Name, A, AI, E, EI, R> & {
    readonly args?: never;
    readonly toKey?: never;
}): Query<Name, A, AI, E, EI, R>;

KeyedQuery

Submodel for fetching and retaining `AsyncData` values by argument key.

export interface KeyedQuery<Name extends string, A, AI, E, EI, Fields extends SyncFields, R = never> {
    /** Schema for this KeyedQuery's Model. */
    readonly Model: KeyedQueryModel<A, AI, E, EI, Fields>;
    /** Schema-backed union of Messages handled by this KeyedQuery. */
    readonly Message: KeyedQueryMessage<A, AI, E, EI, Fields>;
    /**
     * Command definition for matching this KeyedQuery's pending fetch in Story
     * and Scene tests. Start fetches through a loading operation so the Model
     * and request generation advance together; do not call this directly.
     */
    readonly Fetch: Command.CommandDefinitionWithArgs<`Fetch${Name}`, {
        readonly args: Schema.Struct<Fields>;
        readonly generation: typeof Schema.Number;
    }, Effect.Effect<CompletedFetchOf<KeyedQueryMessage<A, AI, E, EI, Fields>>, never, R>>;
    /**
     * Creates a KeyedQuery Model for initial parent Model construction. Never
     * replace a live KeyedQuery with `init()`: it can reuse an in-flight request
     * generation. Use `reset` instead.
     */
    readonly init: () => KeyedQueryModel<A, AI, E, EI, Fields>['Type'];
    /** Clears every entry while preserving request identity. */
    readonly reset: (model: KeyedQueryModel<A, AI, E, EI, Fields>['Type']) => Update.Return<KeyedQueryModel<A, AI, E, EI, Fields>['Type'], KeyedQueryMessage<A, AI, E, EI, Fields>['Type']>;
    /** Reads one entry, returning `Idle` when that entry does not exist. */
    readonly read: (model: KeyedQueryModel<A, AI, E, EI, Fields>['Type'], args: KeyedArgs<Fields>) => AsyncData.AsyncData<A, E>;
    /** Folds a keyed Fetch completion into the matching entry. */
    readonly update: (model: KeyedQueryModel<A, AI, E, EI, Fields>['Type'], message: KeyedQueryMessage<A, AI, E, EI, Fields>['Type']) => Update.Return<KeyedQueryModel<A, AI, E, EI, Fields>['Type'], KeyedQueryMessage<A, AI, E, EI, Fields>['Type']>;
    /** Refreshes a loaded entry and does nothing when it has no data. */
    readonly revalidate: Update.Fold<KeyedQueryModel<A, AI, E, EI, Fields>['Type'], KeyedQueryMessage<A, AI, E, EI, Fields>['Type'], KeyedArgs<Fields>, R>;
    /** Loads a missing entry or refreshes a loaded entry. */
    readonly revalidateOrLoad: Update.Fold<KeyedQueryModel<A, AI, E, EI, Fields>['Type'], KeyedQueryMessage<A, AI, E, EI, Fields>['Type'], KeyedArgs<Fields>, R>;
    /** Loads an entry only when it has no usable value. */
    readonly loadIfMissing: Update.Fold<KeyedQueryModel<A, AI, E, EI, Fields>['Type'], KeyedQueryMessage<A, AI, E, EI, Fields>['Type'], KeyedArgs<Fields>, R>;
    /** Lifts this KeyedQuery's update and loading operations into a parent Model. */
    readonly lift: LiftKeyedQuery<KeyedQueryModel<A, AI, E, EI, Fields>['Type'], KeyedQueryMessage<A, AI, E, EI, Fields>['Type'], KeyedArgs<Fields>, R>;
    /** Executes one keyed fetch directly and returns settled `AsyncData`. */
    readonly run: (args: KeyedArgs<Fields>) => Effect.Effect<AsyncData.AsyncData<A, E>, never, R>;
}

Query

Submodel for fetching and retaining one `AsyncData` value.

export interface Query<Name extends string, A, AI, E, EI, R = never> {
    /** Schema for this Query's Model. */
    readonly Model: QueryModel<A, AI, E, EI>;
    /** Schema-backed union of Messages handled by this Query. */
    readonly Message: QueryMessage<A, AI, E, EI>;
    /**
     * Command definition for matching this Query's pending fetch in Story and
     * Scene tests. Start fetches through a loading operation so the Model and
     * request generation advance together; do not call this directly.
     */
    readonly Fetch: Command.CommandDefinitionWithArgs<`Fetch${Name}`, {
        readonly generation: typeof Schema.Number;
    }, Effect.Effect<CompletedFetchOf<QueryMessage<A, AI, E, EI>>, never, R>>;
    /**
     * Creates a Query Model for initial parent Model construction. Never replace
     * a live Query with `init()`: it can reuse an in-flight request generation.
     * Use `reset` instead.
     */
    readonly init: () => QueryModel<A, AI, E, EI>['Type'];
    /** Clears the Query while preserving its request identity. */
    readonly reset: (model: QueryModel<A, AI, E, EI>['Type']) => Update.Return<QueryModel<A, AI, E, EI>['Type'], QueryMessage<A, AI, E, EI>['Type']>;
    /** Reads the `AsyncData` value from the Query Model. */
    readonly read: (model: QueryModel<A, AI, E, EI>['Type']) => AsyncData.AsyncData<A, E>;
    /** Folds a Fetch completion into the Query Model. */
    readonly update: (model: QueryModel<A, AI, E, EI>['Type'], message: QueryMessage<A, AI, E, EI>['Type']) => Update.Return<QueryModel<A, AI, E, EI>['Type'], QueryMessage<A, AI, E, EI>['Type']>;
    /** Refreshes loaded data and does nothing when no data is present. */
    readonly revalidate: (model: QueryModel<A, AI, E, EI>['Type']) => Update.Return<QueryModel<A, AI, E, EI>['Type'], QueryMessage<A, AI, E, EI>['Type'], R>;
    /** Loads missing data or refreshes loaded data. */
    readonly revalidateOrLoad: (model: QueryModel<A, AI, E, EI>['Type']) => Update.Return<QueryModel<A, AI, E, EI>['Type'], QueryMessage<A, AI, E, EI>['Type'], R>;
    /** Loads data only when the Query has no usable value. */
    readonly loadIfMissing: (model: QueryModel<A, AI, E, EI>['Type']) => Update.Return<QueryModel<A, AI, E, EI>['Type'], QueryMessage<A, AI, E, EI>['Type'], R>;
    /** Lifts this Query's update and loading operations into a parent Model. */
    readonly lift: LiftQuery<QueryModel<A, AI, E, EI>['Type'], QueryMessage<A, AI, E, EI>['Type'], R>;
    /** Executes the configured fetch directly and returns settled `AsyncData`. */
    readonly run: Effect.Effect<AsyncData.AsyncData<A, E>, never, R>;
}

./experimental/server

@wsagency/wseffect-foldkit · MIT · source · MIT license · WS-AGENCY-NOTICE · THIRD-PARTY-NOTICES

This entry point is published in @wsagency/wseffect-foldkit@0.1.0-rc.1. Import it from the package subpath shown below; the signatures and documentation are read from the installed package declarations.

import * as Wseffect from '@wsagency/wseffect-foldkit/experimental/server'

Exported declarations

acceptsHtml

Decides whether a client accepts an HTML response, given its `Accept` header. An absent or empty header accepts anything. Otherwise the most specific media range that covers `text/html` (`text/html`, then `text/*`, then `*​/*`) decides, using its `q` value, so `text/html;q=0` is refused even alongside `*​/*`. A page host renders the application for a request that accepts HTML and serves a non-page response otherwise, so this is the negotiation a host runs before falling through to a render.

acceptsHtml: (acceptHeader: string | undefined) => boolean

ApplicationConfig

Server-side subset of a non-routing `makeApplication` config.

export type ApplicationConfig<Model, Message> = Readonly<{
    init: () => InitReturn<Model, Message>;
    view: (model: Model, h: HtmlBuilder<Message>) => Document;
}>;

ApplicationConfigWithFlags

Server-side subset of a non-routing `makeApplication` config with Flags.

export type ApplicationConfigWithFlags<Model, Message, Flags> = Readonly<{
    Flags: Schema.Codec<Flags, any, never, never>;
    init: (flags: Flags) => InitReturn<Model, Message>;
    view: (model: Model, h: HtmlBuilder<Message>) => Document;
}>;

classifyRequest

Classifies a request that no static file answered, from its path and, when the client sent one, its `Sec-Fetch-Dest`. A host answers a static miss by content negotiation, and a browser requests scripts, stylesheets, and images with `Accept: *​/*`, which accepts HTML. A request for a hashed asset that is no longer deployed would therefore be answered with the application shell at 200, so a stale bundle reads as a blank page rather than the 404 it is. The path is read first, so a request the URL alone settles is never made to depend on a header the client may or may not send.

classifyRequest: (requestUrl: string, fetchDestination?: string) => RequestClassification

DocumentAssets

Browser assets supplied to the server entry's document renderer.

DocumentAssets: Schema.Struct<{
    readonly entryScript: Schema.String;
    readonly stylesheets: Schema.$Array<Schema.String>;
    readonly modulePreloads: Schema.$Array<Schema.String>;
}>

DocumentAssets

The resolved browser asset URLs for one document.

export type DocumentAssets = typeof DocumentAssets.Type;

DocumentEntryModule

The server entry shape used when the application renders the complete HTML document.

export type DocumentEntryModule = EntryModule & Readonly<{
    renderDocument: DocumentRenderer;
}>;

DocumentOptions

export type DocumentOptions = Readonly<{
    /** Default language, overridden by the application's Document. Defaults to English. */
    lang?: string;
    /** Trusted HTML to add to the head, such as a favicon or site-wide metadata. Never pass unescaped request data. */
    head?: string;
}>;

DocumentRenderer

Produces a complete HTML document from application markup and browser assets.

export type DocumentRenderer = (application: RenderedApplication, assets: DocumentAssets) => string;

EntryModule

The module shape a Foldkit server entry exports for hosts to call: one Web `Request` in, one delivery result out. The outer boundary is a `Promise` so Vite, build scripts, serverless functions, and long-running HTTP hosts can call it without owning the application's Effect requirements. The entry may use Effect internally and settles that work before returning. Rendering itself must run in the same Foldkit module instance as the application's view because the HTML builder's render frame is module-local.

export type EntryModule = Readonly<{
    renderPage: (request: Request) => Promise<EntryResult>;
}>;

EntryResult

The result of handling one request through a Foldkit server entry.

export type EntryResult = Rendered | Responded;

FlagsEncodeError

Failure producing the Flags payload: the Schema encode step rejected the Flags value, the encoded value could not be serialized to JSON, or the encoded value could not be decoded back for the hydration-consistent render.

export declare class FlagsEncodeError extends FlagsEncodeError_base<{
    cause: unknown;
}> {
}

FOLDKIT_APP_ATTRIBUTE

Attribute stamped on a hydratable server-rendered application root. Its nonempty value is the runtime id used to pair the root with its Flags payload and scope Model and scroll preservation. `makeApplication` locates the root; `Runtime.hydrate` adopts it.

FOLDKIT_APP_ATTRIBUTE = "data-foldkit-app"

FOLDKIT_FLAGS_ATTRIBUTE

Attribute on the JSON script tag carrying the Schema-encoded flags the server rendered with. A hydrating runtime decodes this payload instead of running the client `flags` Effect, so both sides call `init` with the same value.

FOLDKIT_FLAGS_ATTRIBUTE = "data-foldkit-flags"

handleRequest

Answers one request as a Web `fetch` handler: refuse methods the `Request` constructor cannot represent, classify a static miss so a hashed asset is not answered with the application shell, and otherwise call `renderPage`. Static files are the platform's job. This function is what remains after Vite, a file server, or Worker assets have already missed. Node and workerd both call it, so development predicts production. `Request.url` is trusted as the platform constructed it. On Workers and Deno that is the URL the platform resolved. A Node adapter receives a raw request target instead, which may be an absolute URL or a network-path reference naming another host, so the adapter resolves that target against its configured origin with `resolveRequestUrl` and refuses an off-origin one before constructing the `Request` it passes here.

handleRequest: (request: Request, options: HandleRequestOptions) => Promise<Response>

HandleRequestOptions

export type HandleRequestOptions = Readonly<{
    /**
     * The application's server entry. One Web `Request` in, one delivery
     * result out.
     */
    renderPage: (request: Request) => Promise<EntryResult>;
}> & (Readonly<{
    /** Produces the complete HTML document for a rendered application. */
    renderDocument: (application: RenderedApplication) => string;
    template?: never;
    containerId?: never;
}> | Readonly<{
    /** The unfilled HTML shell owned by a custom host. */
    template: string;
    /** The empty container replaced by the application. Defaults to `'root'`. */
    containerId?: string;
    renderDocument?: never;
}>);

HOST_METHOD_ANSWERS

The answer a host gives for the methods it cannot hand to a server entry. The WHATWG `Request` constructor rejects `CONNECT`, `TRACE`, and `TRACK`, so an entry can never be handed one: forwarding it turns a malformed request into a 500. A host refuses them itself, with `405` and an `Allow` header naming what it does forward. On Node only `TRACE` reaches this rule. The HTTP parser rejects `TRACK` with a 400 before any handler runs, and `CONNECT` arrives on its own event rather than as an ordinary request. Both are named anyway, so a host on another runtime refuses them rather than handing one to `new Request`. Every other method reaches the entry, `OPTIONS` included. A preflight is a question about a resource, so the application answers it: the entry can allow one origin for one route and refuse it for another, which no host-level policy could express. The Vite dev host applies Vite's CORS option only to Vite-owned modules and assets. An application preflight therefore reaches the entry rather than middleware a deployed host has no counterpart for.

HOST_METHOD_ANSWERS: Readonly<{
    refusedStatus: number;
    allow: string;
}>

HydratableRenderOptions

Render options for output a client will hydrate, which is the default. Hydration compares the render's build id against the client's own before adopting any DOM, and a page carrying none has no such protection.

export type HydratableRenderOptions = CommonRenderOptions & Readonly<{
    isHydratable?: true;
    /**
     * The deployment this render belongs to, stamped on the root so hydration
     * can refuse a page from a different one before adopting its DOM. Foldkit
     * normally reads the identity compiled into the server artifact by
     * `@foldkit/vite-plugin`. This explicit option is for integrations that
     * cannot compile the shared identity into the artifact. Give the client
     * the same public value.
     */
    buildId?: string;
}>;

injectIntoTemplate

Places a rendered page into an HTML template. The rendered markup (root element plus the flags payload script) replaces the empty container element, so the booting runtime finds the root by its `data-foldkit-app` stamp and hydrates in place. The `Document` head fields are stamped into the shell so the served HTML is correct before the runtime boots: `title` replaces the `<title>` text, `lang` and `dir` are set on the `<html>` element, `canonical` replaces the `href` of a `<link rel="canonical">` element, and `ogUrl` replaces the `content` of a `<meta property="og:url">` element. A field the render omits, or a head element the template does not carry, leaves the template untouched at that spot. The template is parsed with an HTML tokenizer, so every mutation targets a real element rather than a byte pattern. The container contract is deliberately exact: the template must contain one `<div id="root"></div>` placeholder, or the equivalent for `containerId`, with no additional attributes and no content. It must also contain exactly one `<title>` element in its head. Throws when either required location is missing or appears more than once. Pass the `RenderedApplication` returned by `renderToString` unchanged. A hydratable value must parse as exactly one top-level element carrying one nonempty root stamp and build stamp, optionally followed by one matching top-level JSON Flags script. Static output may contain one element, text, or comment root, or no body output. The helper rejects additional top-level content, ambiguous handoff markers, and source that the HTML parser drops, splits, moves, or reconstructs before insertion. It also refuses to place a hydratable application in a template that already contains one. Static body output may be inserted beside a hydratable application because no runtime adopts it. Each insertion still applies that render's `Document` head fields. This helper is pure with no module state, so a host process may import it directly even when the render itself must stay inside the server entry's module graph.

injectIntoTemplate: (template: string, rendered: RenderedApplication, options?: InjectIntoTemplateOptions) => string

InjectIntoTemplateOptions

export type InjectIntoTemplateOptions = Readonly<{
    /** The `id` of the exact `<div id="..."></div>` placeholder the rendered
     *  markup replaces. Defaults to `'root'`. */
    containerId?: string;
}>;

InvalidHydrationRoot

Failure of a hydratable render whose view did not return an element root. Text, comments, and an empty body cannot carry the hydration marker the client runtime uses to adopt the server-rendered DOM.

export declare class InvalidHydrationRoot extends InvalidHydrationRoot_base<{
    rootKind: 'Empty' | 'Text' | 'Comment';
}> {
}

InvalidRuntimeId

Failure of a render whose `runtimeId` is empty.

export declare class InvalidRuntimeId extends InvalidRuntimeId_base<{
    runtimeId: string;
}> {
}

InvalidUrl

Failure of a routing render whose `url` option cannot be parsed.

export declare class InvalidUrl extends InvalidUrl_base<{
    url: string;
}> {
}

isHostSettledMethod

isHostSettledMethod: (method: string) => boolean

MissingBuildId

Failure of a hydratable render that has no build id. Hydration compares the id on the served root with the client's own to refuse a page from another deployment, so a render that carries none has no such protection. Build both artifacts together with `@foldkit/vite-plugin`, or supply the same nonempty `buildId` explicitly when client and server builds are orchestrated separately. A render that nothing will hydrate (`isHydratable: false`) needs none.

export declare class MissingBuildId extends MissingBuildId_base<{}> {
}

renderDocument

renderDocument: (application: RenderedApplication, assets: DocumentAssets, options?: DocumentOptions) => string

Rendered

A server entry result whose application markup still needs a document.

export type Rendered = Readonly<{
    _tag: 'Rendered';
    application: RenderedApplication;
    status?: number;
    headers?: HeadersInit;
}>;

Rendered

Constructs a rendered server entry result with optional HTTP status and headers.

Rendered: (application: RenderedApplication, options?: ResponseOptions) => Rendered

RenderedApplication

The server render of one request: the body markup and the `Document` head fields for the document renderer or a custom host's template. Hydratable output contains a stamped root and, when the application declares Flags, its payload script. Static output carries no handoff markers.

export type RenderedApplication = Readonly<{
    html: string;
    title: string;
    lang?: string;
    dir?: 'ltr' | 'rtl' | 'auto';
    canonical?: string;
    ogUrl?: string;
}>;

RenderError

export type RenderError = MissingBuildId | InvalidUrl | FlagsEncodeError | SerializationError | InvalidRuntimeId | InvalidHydrationRoot;

RenderFlagsOptions

Render options for a Flags application, adding the per-request Flags.

export type RenderFlagsOptions<Flags> = RenderOptions & Readonly<{
    flags: Flags;
}>;

RenderOptions

export type RenderOptions = HydratableRenderOptions | StaticRenderOptions;

renderToString

export declare function renderToString<Model, Message, Flags>(config: ApplicationConfigWithFlags<Model, Message, Flags>, options: RenderFlagsOptions<Flags>): Effect.Effect<RenderedApplication, RenderError>;

renderToString

export declare function renderToString<Model, Message, Flags>(config: RoutingApplicationConfigWithFlags<Model, Message, Flags>, options: RenderUrlFlagsOptions<Flags>): Effect.Effect<RenderedApplication, RenderError>;

renderToString

export declare function renderToString<Model, Message>(config: ApplicationConfig<Model, Message>, options?: RenderOptions): Effect.Effect<RenderedApplication, RenderError>;

renderToString

export declare function renderToString<Model, Message>(config: RoutingApplicationConfig<Model, Message>, options: RenderUrlOptions): Effect.Effect<RenderedApplication, RenderError>;

RenderUrlFlagsOptions

Render options for a routing Flags application: the request URL plus the per-request Flags.

export type RenderUrlFlagsOptions<Flags> = RenderUrlOptions & RenderFlagsOptions<Flags>;

RenderUrlOptions

Render options for a routing application, adding the request URL.

export type RenderUrlOptions = RenderOptions & Readonly<{
    url: string;
}>;

RequestClassification

How a host should read a request that no static file answered. `PathAsset`: the path names an asset, whatever the request headers say, so a refusal is the same for every client and needs no `Vary`. `DestinationAsset`: the path could be a page, and only the request's `Sec-Fetch-Dest` says otherwise. A refusal here depends on that header, so it has to declare it in `Vary` before a shared cache may store it: a cross-site script request would otherwise seed a cached 404 for a real page. `Page`: nothing marks it as an asset, so the usual `Accept` negotiation decides.

export type RequestClassification = 'PathAsset' | 'DestinationAsset' | 'Page';

resolveRequestUrl

Resolves a request target against the origin the host serves, returning the absolute URL to hand the server entry, or `undefined` when the target names a different origin. A request target is not a URL. HTTP allows origin-form (`/page?q=1`) and absolute-form (`http://host/page`), and a client can send a network-path reference (`//elsewhere.example/page`) that resolves against no scheme at all. Resolving one of those against the host origin silently adopts the origin the client wrote, so an entry that derives redirects, canonical URLs, cookie domains, or tenant selection from `Request.url` would take them from the request rather than from the deployment. Only a target that resolves to the host's own origin is accepted; a host behind a proxy that must serve a different public origin passes that origin in explicitly.

resolveRequestUrl: (requestTarget: string, origin: string) => string | undefined

resolvesToIndexHtml

Decides whether a request path resolves to the `index.html` template, the way a static file server resolves it: percent-decoded, backslashes and repeated separators collapsed, and dot segments resolved. A host renders the application for such a request rather than serving the raw, unfilled template, so `/`, `/index.html`, `/%2findex.html`, and `/foo/../index.html` all resolve to it. An undecodable or null-byte path resolves to nothing.

resolvesToIndexHtml: (requestUrl: string) => boolean

Responded

A server entry result that bypasses application rendering and returns a complete Web `Response`, such as a redirect or another non-page response to a page request. A dedicated data API belongs on a separate backend rather than the render host; this is for responses the page request itself resolves without rendering the shell.

export type Responded = Readonly<{
    _tag: 'Responded';
    response: Response;
}>;

Responded

Constructs a complete Web `Response` server entry result.

Responded: (response: Response) => Responded

ResponseOptions

Optional HTTP metadata for a rendered application.

export type ResponseOptions = Readonly<{
    status?: number;
    headers?: HeadersInit;
}>;

RoutingApplicationConfig

Server-side subset of a routing `makeApplication` config without Flags.

export type RoutingApplicationConfig<Model, Message> = Readonly<{
    routing: unknown;
    init: (url: Url) => InitReturn<Model, Message>;
    view: (model: Model, h: HtmlBuilder<Message>) => Document;
}>;

RoutingApplicationConfigWithFlags

Server-side subset of a routing `makeApplication` config with Flags. The full application config is structurally assignable; `container`, `update`, and `subscriptions` play no part in a server render.

export type RoutingApplicationConfigWithFlags<Model, Message, Flags> = Readonly<{
    Flags: Schema.Codec<Flags, any, never, never>;
    routing: unknown;
    init: (flags: Flags, url: Url) => InitReturn<Model, Message>;
    view: (model: Model, h: HtmlBuilder<Message>) => Document;
}>;

SerializationError

Failure serializing the view-produced vnode tree to safe HTML.

export declare class SerializationError extends SerializationError_base<{
    cause: unknown;
}> {
}

StaticRenderOptions

Render options for static markup nothing will hydrate. No build id applies, because no client will compare one.

export type StaticRenderOptions = CommonRenderOptions & Readonly<{
    isHydratable: false;
    buildId?: undefined;
}>;

toResponse

Turns a server entry result into the Web `Response` a host sends. Supply a document renderer, or an HTML template for a host that owns one. Rendered applications default to status 200 with a UTF-8 HTML content type. Complete responses pass through unchanged without calling the document renderer.

toResponse: (document: string | ((application: RenderedApplication) => string), result: EntryResult, options?: InjectIntoTemplateOptions) => Response

varyWith

Merges a field name into an existing `Vary` header value, parsing it as a comma-separated, case-insensitive list of field names. `Vary: *` already varies on everything and is returned unchanged, a token already present (in any case, and distinct from a longer name that merely starts with it, such as `Accept-Language` beside `Accept`) is not duplicated, and otherwise the field name is appended. A host whose response depends on a request header must declare that header in `Vary` so a shared cache does not serve one client's representation to another. The dev host, reference server, and scaffold merge through this one helper rather than assigning `Vary`, which would drop the fields already there.

varyWith: (existing: string | undefined, fieldName: string) => string

varyWithAccept

Merges the `Accept` field name into an existing `Vary` header value. A page host that negotiates HTML on the `Accept` header must declare that in `Vary` so a shared cache does not serve one representation in place of the other.

varyWithAccept: (existing: string | undefined) => string