Skip to content

@foliwake/server ​

Generated from packages/server/README.md, the README published with the package on npm.

@foliwake/server is the server toolkit for any app that shows Foliwake pages, with no framework dependency: Web Request/Response and plain functions. It parses the app's foliwake.remote.json, reads a page's body from the site's live or preview origin with the credential, checks and prepares it per request, serves the page's code release and pictures through your app's origin (proxies), builds a Content-Security-Policy, and computes preload hints. @foliwake/next is built on it; use this package directly with another server framework (a Vite or Remix server, Hono, Express with Web adapters, a worker).

EntryWhat
@foliwake/server/configloadFoliwakeConfig, parseFoliwakeConfig, clientSettings, pageAllowed, FoliwakeConfigError
@foliwake/server/origincreateOriginClient: the only place a password is read (per request, from the variable the config names)
@foliwake/server/pagereadEnvelope (primitive inputs: safe inside a cache function), preparePage, FoliwakePageError
@foliwake/server/handlerscodeHandler, mediaHandler: the code and media proxies
@foliwake/server/htmlthe strict body check: checkPlainBody, checkBody, serialize, srcsetCandidates
@foliwake/server/cspfoliwakeCsp
@foliwake/server/preloadpreloadHints: modulepreload and stylesheet hints for a page's blocks
@foliwake/server/hookverifyFoliwakeSignature, parseFoliwakeHook: the signed hook a Foliwake server sends after a change
@foliwake/server/handlercreateFoliwakeHandler: every Foliwake route of an app (code, media, hook, health) as one (request) => Promise<Response>
@foliwake/server/hook-endpointcreateHookEndpoint: the hook endpoint without a framework (verify, parse, expire, answer)
@foliwake/server/discoveryfetchDiscovery, parseDiscovery: the site's /.well-known/foliwake.json
@foliwake/server/resolveloadAppConfig, readConfigSnapshot, configFromSnapshot: FOLIWAKE_URL + discovery + the optional version 3 file, or a version 2 file
@foliwake/server/schemas/remote-2.schema.jsonthe JSON Schema of the config file (version 2)
@foliwake/server/schemas/remote-3.schema.jsonthe JSON Schema of the optional version 3 file (overrides)

Install ​

The packages are published on npm (npmjs.com) under the @foliwake scope; no registry setup or token is needed. Install an exact version, the same for every @foliwake/* package:

bash
pnpm add @foliwake/server@0.3.0

The config file sits in the app's root and holds no secrets, only the names of the variables with passwords or keys:

json
{
  "$schema": "./node_modules/@foliwake/server/schemas/remote-2.schema.json",
  "version": 2,
  "site": "mysite",
  "live": { "url": "https://mysite.example.org" },
  "preview": { "url": "https://preview.mysite.example.org", "auth": { "type": "basic", "username": "preview", "passwordEnv": "MYSITE_PREVIEW_TOKEN" } },
  "app": {
    "pages": ["/**"],
    "proxies": { "code": "/foliwake-code", "media": "/foliwake-media", "pages": null },
    "blocks": { "entry": "scripts/blocks.js", "contract": "foliwake-blocks/2", "eventPrefix": "demo" },
    "revalidate": 300
  }
}

An endpoint is open (no auth), behind HTTP Basic ("type": "basic"), or behind a delivery that checks service tokens (for example an edge worker in front of the site's storage):

json
"live": {
  "url": "https://mysite.worker.example.org",
  "auth": { "type": "service-token", "issuer": "mysite-app", "kid": "mysite-app-2026-11", "privateKeyEnv": "MYSITE_LIVE_SIGNING_KEY" }
}

With service-token, every origin request carries Authorization: Bearer <JWT>, signed for that request alone: ES256, header kid, claims iss (= issuer, the delivery's TOKEN_ISSUER), aud: site:<site>, iat, exp = iat + 60 and path, the exact path of the request as sent, without the query (/lessons/a.plain.html, /lessons/query-index.json). A token for a page does not open its .plain.html. The variable holds the ES256 private key as JWK JSON text; the delivery holds the public key under the same kid. Tokens are never cached, reused or logged.

Minimal example ​

ts
import { loadFoliwakeConfig } from '@foliwake/server/config';
import { createOriginClient } from '@foliwake/server/origin';
import { preparePage, readEnvelope } from '@foliwake/server/page';

const config = await loadFoliwakeConfig(); // FOLIWAKE_REMOTE, else ./foliwake.remote.json
const client = createOriginClient(config, process.env);

const envelope = await readEnvelope(config, client, config.site, 'live', '/lessons/a'); // cacheable
const page = preparePage(config, envelope); // per request: checked, rewritten, serialisable
console.log(page.identity, page.blocks);

Examples ​

A page endpoint for the browser, with a cache of envelopes ​

Cache only the envelope (what the origin answered) and prepare per request, so your callbacks (rewriteLink, transform) always run on the current code. The prepared page is what @foliwake/client or @foliwake/react mount.

ts
import { loadFoliwakeConfig } from '@foliwake/server/config';
import { createOriginClient } from '@foliwake/server/origin';
import { FoliwakePageError, preparePage, readEnvelope, type PageEnvelope } from '@foliwake/server/page';
import { preloadHints } from '@foliwake/server/preload';

const config = await loadFoliwakeConfig();
const client = createOriginClient(config, process.env);
const cache = new Map<string, { at: number; envelope: PageEnvelope }>();

async function liveEnvelope(path: string): Promise<PageEnvelope> {
  const hit = cache.get(path);
  if (hit && Date.now() - hit.at < config.app!.revalidate * 1000) return hit.envelope;
  const envelope = await readEnvelope(config, client, config.site, 'live', path);
  cache.set(path, { at: Date.now(), envelope });
  return envelope;
}

/** GET /api/page?path=/lessons/a */
export async function pageEndpoint(request: Request): Promise<Response> {
  const path = new URL(request.url).searchParams.get('path') ?? '/';
  try {
    const page = preparePage(config, await liveEnvelope(path), { rewriteLink: (href) => `/learn${href}` });
    page.preload = await preloadHints(config, client, page);
    return Response.json(page, { headers: { 'Cache-Control': 'private, no-store' } });
  } catch (error) {
    if (error instanceof FoliwakePageError && (error.kind === 'not_found' || error.kind === 'not_allowed')) return new Response(null, { status: 404 });
    throw error;
  }
}

Refresh the cache when the site changes ​

A Foliwake server whose site lists your app as a hook target POSTs delivery.settled once a change is live and the caches in front of the origin serve it. The body names the live generation, and either the changed paths (pages, at most 100: pages and other files such as an index) or all: true. Check the signature on the raw body, then drop what you cached:

ts
import { parseFoliwakeHook, verifyFoliwakeSignature } from '@foliwake/server/hook';

const cached = new Map<string, unknown>();

/** POST /api/webhooks/foliwake */
export async function hookEndpoint(request: Request): Promise<Response> {
  const body = new Uint8Array(await request.arrayBuffer());
  const signature = request.headers.get('foliwake-signature');
  const secrets = [process.env.FOLIWAKE_HOOK_SECRET, process.env.FOLIWAKE_HOOK_SECRET_PREVIOUS];
  if (!verifyFoliwakeSignature(body, signature, secrets).ok) return new Response(null, { status: 401 });
  const payload = parseFoliwakeHook(body);
  if (payload.event === 'ping') return Response.json({ ok: true, site: payload.site });
  if (payload.all) cached.clear();
  else for (const path of payload.pages ?? []) cached.delete(path);
  return Response.json({ ok: true });
}

The signature is t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>, accepted within 300 s of the app's clock. Answer 2xx only once the change is handled: anything else is sent again. Limit the body to 64 KiB (HOOK_BODY_LIMIT) and check that payload.site is yours.

Code and media proxies ​

Mount the handlers under the prefixes of app.proxies and pass them the path segments after the prefix. They serve only files of a cd_… code release and hashed pictures, add the credential on the server and forward nothing from the browser. Live files are cached for a year (immutable); preview answers are private, no-store and need authorizePreview.

ts
import { loadFoliwakeConfig } from '@foliwake/server/config';
import { codeHandler, mediaHandler } from '@foliwake/server/handlers';
import { createOriginClient } from '@foliwake/server/origin';

const config = await loadFoliwakeConfig();
const client = createOriginClient(config, process.env);
const isAuthor = async (request: Request) => (request.headers.get('cookie') ?? '').includes('role=author'); // your sign-in
const code = codeHandler(config, client, { authorizePreview: isAuthor });
const media = mediaHandler(config, client, { authorizePreview: isAuthor });

/** Route requests under /foliwake-code/ and /foliwake-media/ (app.proxies) to the handlers. */
export async function proxies(request: Request): Promise<Response | null> {
  const { pathname } = new URL(request.url);
  const segments = (prefix: string) => pathname.slice(prefix.length + 1).split('/').filter(Boolean);
  if (pathname.startsWith(`${config.app!.proxies.code}/`)) return code(request, { path: segments(config.app!.proxies.code) });
  if (pathname.startsWith(`${config.app!.proxies.media}/`)) return media(request, { path: segments(config.app!.proxies.media) });
  return null;
}

CSP and browser settings ​

ts
import { clientSettings, loadFoliwakeConfig } from '@foliwake/server/config';
import { foliwakeCsp } from '@foliwake/server/csp';

const config = await loadFoliwakeConfig();

// One header value for every route: blocks load from your own origin, so no Foliwake host is named.
export const csp = foliwakeCsp({
  strategy: 'self-inline',
  mediaBase: config.app?.media?.base ?? null,
  reportUri: '/csp-report',
  dev: process.env.NODE_ENV === 'development',
});

// The only part of the config a browser may see: site, proxy prefixes, blocks contract and event prefix.
export const settingsForBrowser = clientSettings(config);

Compatibility ​

Node.js22.22 or newer (Web fetch, Request, Response, streams)
Foliwake originplain/2: X-Code-Release with every .plain.html (a body without it is refused)
Configfoliwake.remote.json version 2
Blocks contractfoliwake-blocks/2

Changes per version, breaking ones marked: CHANGELOG.md in the package (node_modules/@foliwake/server/CHANGELOG.md).

Good to know ​

  • Bodies are checked before and after your transform: no scripts, styles, frames, inline SVG or MathML, no on… attributes or javascript: URLs; srcset and entities are parsed like a browser does. What is returned is serialised from the checked tree. A refused body throws FoliwakePageError with kind invalid.
  • Origin responses are size-limited while streaming (body 2 MB, code 5 MB, media 25 MB); requests time out after 10 s.
  • Credentials never appear in messages; a missing or malformed password or key variable is a FoliwakeConfigError that names the variable, not its value. The secret is read at each request, so a rotated secret works without a restart. A private key whose own kid differs from the config's is refused.
  • Rotating the hook secret: give the app the new secret as the previous one too (both accepted), switch the server to it, then drop the old one.
  • Rotating a service-token key: add the new public key to the delivery's key set first (both kids listed), then switch the app's kid and private key, then remove the old public key.
  • preparePage leaves page.preload empty; preloadHints fills it from the release's components/components.json (only blocks that declare a .js or .css get hints).

See also ​

License: Apache-2.0.

API ​

@foliwake/server/config ​

Functions and components

appOf() ​

The app settings; throws when the config has none.

ts
function appOf(config: FoliwakeAppConfig): FoliwakeAppSettings

Returns FoliwakeAppSettings

checkEnvName() ​

Validates an environment variable NAME (never a value).

ts
function checkEnvName(value: unknown, where: string, extra?: ParseOptions['envNameProblem']): string

Returns string

checkUsername() ​

Validates a Basic user name (no : or control characters, at most 128 characters).

ts
function checkUsername(value: unknown, where: string): string

Returns string

clientSettings() ​

The explicit browser projection: nothing else of the config reaches a browser.

ts
function clientSettings(config: FoliwakeAppConfig): ClientSettings

Returns ClientSettings

configFilePath() ​

Which file: an explicit file beats FOLIWAKE_REMOTE beats <cwd>/foliwake.remote.json.

ts
function configFilePath(opts?: {
    cwd?: string;
    file?: string;
    env?: NodeJS.ProcessEnv;
}): string

Returns string

endpointOf() ​

The endpoint of a channel; a missing one is an error, never replaced by the other channel.

ts
function endpointOf(config: FoliwakeAppConfig, channel: ChannelName): FoliwakeEndpoint

Returns FoliwakeEndpoint

isLoopbackName() ​

True for 127.x, localhost, *.localhost and ::1.

ts
function isLoopbackName(hostname: string): boolean

Returns boolean

loadFoliwakeConfig() ​

Reads and parses the config file (see configFilePath).

ts
function loadFoliwakeConfig(opts?: {
    cwd?: string;
    file?: string;
    env?: NodeJS.ProcessEnv;
} & Omit<ParseOptions, 'file'>): Promise<FoliwakeAppConfig>

Returns Promise<FoliwakeAppConfig>

pageAllowed() ​

Whether the app may read this page path (app.pages).

ts
function pageAllowed(config: FoliwakeAppConfig, pagePath: string): boolean

Returns boolean

parseFoliwakeConfig() ​

Parses the text of a version 2 config. Throws FoliwakeConfigError with a message that names the field.

ts
function parseFoliwakeConfig(text: string, opts?: ParseOptions): FoliwakeAppConfig

Returns FoliwakeAppConfig

parseRemoteUrl() ​

A site origin: https (http only for loopback), no credentials, path, query or fragment.

ts
function parseRemoteUrl(value: unknown, where: string): string

Returns string

Classes

FoliwakeConfigError ​

A configuration problem; the message is shown as is (it never contains a secret).

ts
class FoliwakeConfigError extends Error
MemberTypeDescription
namestring

Constants

CHANNELS ​

The channels a config can name.

ts
const CHANNELS: readonly ChannelName[]

CONFIG_ENV ​

The environment variable that names another config file.

ts
const CONFIG_ENV = "FOLIWAKE_REMOTE"

CONFIG_FILE ​

The default config file name, looked up in the current directory.

ts
const CONFIG_FILE = "foliwake.remote.json"

Interfaces

BasicAuth ​

HTTP Basic credentials: a user name and the NAME of the variable holding the password.

ts
interface BasicAuth
MemberTypeDescription
type'basic'
usernamestring
passwordEnvstring

FoliwakeAppConfig ​

A validated app config: a foliwake.remote.json version 2, or (version 3) the site's discovery document merged with the optional version 3 file. It holds credential variable names, never secrets.

ts
interface FoliwakeAppConfig
MemberTypeDescription
version2 | 3
sitestring
liveFoliwakeEndpoint | null
previewFoliwakeEndpoint | null
appFoliwakeAppSettings | nullNull only when parsed with requireApp: false (the engine CLI).
fromstringWhere the config came from, for messages.

FoliwakeAppSettings ​

The app part of the config, with defaults applied.

ts
interface FoliwakeAppSettings
MemberTypeDescription
pagesreadonly string[]Page globs the app may read.
proxies{ code: string; media: string; pages: null; }App-origin URL prefixes of the proxies.
blocks{ entry: string | null; contract: string; major: number; eventPrefix: string; fromRelease: boolean; }Where mountBlocks lives in a code release; null: bodies stay static. fromRelease: the config names no blocks (version 3), so each page's code release names them (X-Foliwake-Blocks); false for version 2.
media{ base: string; transform: 'cloudflare-images' | null; } | nullLive media through a transforming host; null: media through the proxy.
revalidatenumberSeconds before a cached envelope is stale (stale-while-revalidate).

FoliwakeEndpoint ​

A channel's origin and its optional credential.

ts
interface FoliwakeEndpoint
MemberTypeDescription
originstringOrigin only: scheme, host, port.
authRemoteAuth | null

ParseOptions ​

Options of parseFoliwakeConfig.

ts
interface ParseOptions
MemberTypeDescription
file?stringFor messages (default foliwake.remote.json).
requireApp?booleanRefuse a file without app (default true; the CLI passes false).
envNameProblem?(name: string, what: string) => string | nullAn additional rule for credential variable names (the engine CLI passes its own).

ServiceTokenAuth ​

A service token: each request carries a fresh ES256 JWT for its exact path, signed with the private key in the variable privateKeyEnv (a JWK as JSON text). Delivery checks it with the public key of kid.

ts
interface ServiceTokenAuth
MemberTypeDescription
type'service-token'
issuerstringThe iss the delivery expects (its TOKEN_ISSUER).
kidstringThe key id the delivery looks the public key up by.
privateKeyEnvstringThe NAME of the variable holding the private key.

Types

RemoteAuth ​

The credential of an endpoint.

ts
type RemoteAuth = BasicAuth | ServiceTokenAuth

Also exported (documented where they are defined)

  • from @foliwake/blocks-contract/page: ClientSettings

@foliwake/server/origin ​

Functions and components

createOriginClient() ​

The client for the config's origins. The secret is read from the environment at each request (a rotated secret takes effect without a restart) and goes only into the Authorization header: basic sends the password of passwordEnv; service-token signs a fresh token for the request's exact path with the private key of privateKeyEnv.

ts
function createOriginClient(config: FoliwakeAppConfig, env?: NodeJS.ProcessEnv, opts?: OriginClientOptions): OriginClient
ParameterTypeDescription
configFoliwakeAppConfig
env?NodeJS.ProcessEnvWhere secrets are read (default process.env).
opts?OriginClientOptions

Returns OriginClient

Constants

SERVICE_TOKEN_LIFETIME_SECONDS ​

Seconds a service token lives: exp = iat + 60. Delivery accepts at most 120, with 5 s of clock skew.

ts
const SERVICE_TOKEN_LIFETIME_SECONDS = 60

Interfaces

OriginClient ​

Requests to the configured live and preview origins, with the credential added per request.

ts
interface OriginClient
MemberTypeDescription
readonly configFoliwakeAppConfig
originOf()(channel: ChannelName) => stringThe origin of a channel (for messages and loopback checks).
request()(channel: ChannelName, path: string, opts?: OriginRequestOptions) => Promise<Response>GET/HEAD <origin><path>; redirect: 'manual', 10 s timeout unless signal is given.

OriginClientOptions ​

Options of createOriginClient.

ts
interface OriginClientOptions
MemberTypeDescription
fetch?typeof fetchA fetch implementation (tests); default globalThis.fetch.
timeoutMs?number
now?() => numberThe clock of service tokens, in milliseconds (tests); default Date.now.

OriginRequestOptions ​

Options of one origin request.

ts
interface OriginRequestOptions
MemberTypeDescription
method?'GET' | 'HEAD'
signal?AbortSignal
headers?Record<string, string>Only these headers are sent (never a browser's).

@foliwake/server/page ​

Functions and components

blocksUrlOf() ​

The same-origin URL of the blocks module, or null without an entry.

ts
function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId, entry?: string | null): {
    base: string;
    url: string;
} | null
ParameterTypeDescription
configFoliwakeAppConfig
channelChannelName
codeReleaseCodeReleaseId
entry?string | nullThe module inside the code release; default the config's app.blocks.entry.

Returns { base: string; url: string; } \| null

pageBlocksOf() ​

The blocks a page mounts: the config's, or (version 3 without app.blocks) the ones its code release names.

ts
function pageBlocksOf(config: FoliwakeAppConfig, envelope: PageEnvelope): {
    entry: string | null;
    major: number;
    eventPrefix: string;
}

Returns { entry: string \| null; major: number; eventPrefix: string; }

plainPath() ​

The origin URL path of a page's body (/ → /index.plain.html).

ts
function plainPath(pagePath: string): string

Returns string

preparePage() ​

Per request, after the cache: check → rewrite media/links → transform → check again → serialise.

ts
function preparePage(config: FoliwakeAppConfig, envelope: PageEnvelope, opts?: PrepareOptions): FoliwakePageData
ParameterTypeDescription
configFoliwakeAppConfig
envelopePageEnvelopeWhat readEnvelope (or a cached copy of it) returned.
opts?PrepareOptions

Returns FoliwakePageData: The serialisable page for a client component (preload is empty; readPage of the Next package fills it). Throws FoliwakePageError('invalid') when the body or the transform's output is refused.

readEnvelope() ​

Reads <path>.plain.html from the channel's origin. Primitive inputs only, no callbacks and no signal (an internal 10 s timeout), so it can run inside a cache function. Refuses paths outside app.pages.

ts
function readEnvelope(config: FoliwakeAppConfig, client: OriginClient, site: string, channel: ChannelName, path: string): Promise<PageEnvelope>
ParameterTypeDescription
configFoliwakeAppConfig
clientOriginClient
sitestringThe config's site (config.site); another site is refused.
channelChannelName
pathstringThe page path (/, /lessons/a).

Returns Promise<PageEnvelope>: The envelope; throws FoliwakePageError (not_found, not_allowed, origin, unauthorized, …).

Classes

FoliwakePageError ​

A page that cannot be shown. status: the origin's HTTP status when there was one.

ts
class FoliwakePageError extends Error
new FoliwakePageError(kind: PageErrorKind, message: string, opts?: {
        status?: number;
        cause?: unknown;
    })
MemberTypeDescription
namestring
readonly kindPageErrorKind
readonly status?number

Interfaces

PrepareOptions ​

Options of preparePage.

ts
interface PrepareOptions
MemberTypeDescription
mode?stringThe site's mode of the page (a token, [a-z][a-z0-9-], at most 32 characters), given to the blocks as host.mode; absent → none. exam is refused: the assessment extension's exam needs answers stripped by the origin, which does not exist yet, so an exam body would carry its answers.
rewriteLink?(href: string) => stringRoot-relative links (/x) of <a href>; returns the app's URL.
transform?(html: string, envelope: PageEnvelope) => stringThe app's own change of the body (allow-list, artwork, …); its output is checked again.

Types

PageErrorKind ​

Why a page cannot be shown (FoliwakePageError.kind).

ts
type PageErrorKind = 'not_found' | 'not_allowed' | 'origin' | 'invalid' | 'unauthorized' | 'too_large'

Also exported (documented where they are defined)

  • from @foliwake/blocks-contract/import-map: pageImportMap
  • from @foliwake/blocks-contract/page: FoliwakePageData, PageEnvelope

@foliwake/server/handlers ​

Functions and components

codeHandler() ​

GET|HEAD <proxies.code>/[preview/]<cd>/<path inside the code release>.

ts
function codeHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): Handler

Returns Handler

mediaHandler() ​

GET|HEAD <proxies.media>/[preview/]<sha256>.<ext>: images only, one hashed segment.

ts
function mediaHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): Handler

Returns Handler

Interfaces

ProxyOptions ​

Options of codeHandler and mediaHandler.

ts
interface ProxyOptions
MemberTypeDescription
authorizePreviewAuthorizePreviewThe app's author check for preview/… requests, or false to answer them 404. Required.

Types

AuthorizePreview ​

The app's author check for preview requests, or false (preview answers 404).

ts
type AuthorizePreview = ((request: Request) => boolean | Promise<boolean>) | false

Handler ​

A proxy handler: the request and the path segments after the proxy prefix.

ts
type Handler = (request: Request, params: {
    path: string[];
}) => Promise<Response>

@foliwake/server/html ​

Functions and components

checkBody() ​

Parses and checks a body; returns the checked tree. Throws FoliwakePageError('invalid').

ts
function checkBody(html: string, pagePath?: string): HtmlNode[]

Returns HtmlNode[]

checkPlainBody() ​

Checks a body (the strict body check); throws FoliwakePageError('invalid').

ts
function checkPlainBody(html: string, pagePath?: string): void

Returns void

componentNames() ​

Distinct data-component names, sorted.

ts
function componentNames(nodes: readonly HtmlNode[]): string[]

Returns string[]

elements() ​

Every element below nodes, depth first.

ts
function elements(nodes: readonly HtmlNode[]): Generator<HtmlElement>

Returns Generator<HtmlElement>

parseStrict() ​

Parses a body strictly. Comments are dropped; a doctype or processing instruction is an error.

ts
function parseStrict(html: string): HtmlNode[]

Returns HtmlNode[]

sanitizedHtml() ​

The checked body, serialised from its tree.

ts
function sanitizedHtml(nodes: readonly HtmlNode[]): string

Returns string

serialize() ​

Serialises the tree as HTML (the WHATWG fragment serialisation rules for the elements a body may hold).

ts
function serialize(nodes: readonly HtmlNode[]): string

Returns string

srcsetCandidates() ​

Splits a srcset into candidates: the URL ends at whitespace; descriptors run to the next comma.

ts
function srcsetCandidates(srcset: string): {
    url: string;
    descriptor: string;
}[]

Returns { url: string; descriptor: string; }[]

urlProblem() ​

Why a URL value is not allowed for this element/attribute, or null. Values are entity-decoded already.

ts
function urlProblem(element: string, attribute: string, value: string, pagePath?: string): string | null

Returns string \| null

Classes

HtmlParseError ​

A body that cannot be parsed strictly.

ts
class HtmlParseError extends Error
MemberTypeDescription
namestring

Constants

COMPONENT_NAME ​

A valid data-component name.

ts
const COMPONENT_NAME: RegExp

REFUSED_ELEMENTS ​

Elements a body may not hold (incl. foreign content: no inline SVG or MathML in 0.1). <form> is allowed only as the engine writes it for the question block: an explicit method="dialog", no action, target or enctype; no control may override the submission (formmethod, formaction, formtarget, formenctype) or associate itself with another form (form). Such a form closes a dialog at most; it submits nowhere.

ts
const REFUSED_ELEMENTS: ReadonlySet<string>

Types

HtmlElement ​

An element of a parsed body.

ts
type HtmlElement = {
    type: 'tag';
    name: string;
    attribs: Record<string, string>;
    children: HtmlNode[];
}

HtmlNode ​

A node of a parsed body.

ts
type HtmlNode = HtmlText | HtmlElement

HtmlText ​

A text node of a parsed body.

ts
type HtmlText = {
    type: 'text';
    data: string;
}

@foliwake/server/csp ​

Functions and components

foliwakeCsp() ​

The policy as one header value.

ts
function foliwakeCsp(opts: CspOptions): string

Returns string

Constants

REACT_SHELL_SCRIPT ​

React DOM 19.2's inline requestAnimationFrame(function(){$RT=performance.now()}); in PPR static shells.

ts
const REACT_SHELL_SCRIPT = "requestAnimationFrame(function(){$RT=performance.now()});"

REACT_SHELL_SCRIPT_HASH ​

The CSP hash source of REACT_SHELL_SCRIPT (used by the nonce strategy).

ts
const REACT_SHELL_SCRIPT_HASH = "'sha256-7mu4H06fwDCjmnxxr/xNHyuQC6pLTHr4M2E4jXw5WZs='"

Interfaces

CspOptions ​

Options of foliwakeCsp.

ts
interface CspOptions
MemberTypeDescription
strategy'self-inline' | 'nonce'self-inline (recommended; works with partial prerendering) or nonce (experimental, not recommended).
nonce?stringRequired with 'nonce'.
mediaBase?string | nullThe media host whose pictures pages show: app.media.base (live pictures through a transforming host), or the site's own CDN when the site resizes images on one (media.resize: "cdn", whose cdnBase is in every live srcset). An https address; only its origin (scheme and host) is added to img-src.
dev?booleanDevelopment: adds 'unsafe-eval' (React's debugging) and websocket connections for HMR.
reportUri?stringWhere browsers report violations (report-uri).
extra?Partial<Record<string, string[]>>More sources per directive, e.g. { 'connect-src': ['https://api.example.org'] }.

@foliwake/server/preload ​

Functions and components

clearPreloadCache() ​

Forgets every remembered code file (tests).

ts
function clearPreloadCache(): void

Returns void

codePath() ​

A path inside the code release the proxy would serve, or null.

ts
function codePath(relative: string): string | null

Returns string \| null

preloadHints() ​

Hints for a prepared page: modulepreload for its modules, preload as=style for its block stylesheets.

ts
function preloadHints(config: FoliwakeAppConfig, client: OriginClient, page: FoliwakePageData): Promise<PreloadHint[]>

Returns Promise<PreloadHint[]>

resolveInRelease() ​

Resolves specifier against the module at from (both inside the release), or null when it leaves it.

ts
function resolveInRelease(from: string, specifier: string): string | null

Returns string \| null

staticImports() ​

The relative static import specifiers of an ES module's text, and the kit's (KIT_SPECIFIER).

ts
function staticImports(source: string): string[]

Returns string[]

Also exported (documented where they are defined)

  • from @foliwake/blocks-contract/page: PreloadHint

@foliwake/server/hook ​

Functions and components

isFoliwakePagePath() ​

Whether a path of pages is a page (/lessons/a), not another file such as /lessons/query-index.json.

ts
function isFoliwakePagePath(path: string): boolean

Returns boolean

parseFoliwakeHook() ​

Parses a hook body (after its signature was checked). Unknown fields are ignored; an unknown operation kind is accepted, so a newer server's operations still refresh the app.

ts
function parseFoliwakeHook(body: Body): FoliwakeHookPayload
ParameterTypeDescription
bodyBodyThe raw body.

Returns FoliwakeHookPayload: The payload; throws FoliwakeHookError when it is not a version 1 delivery.settled or ping.

signFoliwakeHook() ​

The Foliwake-Signature value for a body: what a Foliwake server sends; useful in an app's tests.

ts
function signFoliwakeHook(body: Body, secret: string, t?: number): string
ParameterTypeDescription
bodyBodyThe raw body, byte for byte as sent.
secretstringThe shared secret.
t?numberThe signature time in unix seconds (default: now).

Returns string

verifyFoliwakeSignature() ​

Checks Foliwake-Signature against the raw body. Every secret is tried (the current one and, while it is rotated, the previous one); the comparison is constant-time.

ts
function verifyFoliwakeSignature(body: Body, header: string | null, secrets: readonly (string | null | undefined)[], options?: VerifySignatureOptions): SignatureCheck
ParameterTypeDescription
bodyBodyThe raw request body, byte for byte as received.
headerstring | nullThe Foliwake-Signature header, or null.
secretsreadonly (string | null | undefined)[]The accepted secrets; empty or blank ones are ignored.
options?VerifySignatureOptionsnow (ms) and toleranceS (default 300).

Returns SignatureCheck: { ok: true }, or { ok: false, reason }: malformed, expired, mismatch or no_secret.

Classes

FoliwakeHookError ​

A hook body that is not a valid payload.

ts
class FoliwakeHookError extends Error
MemberTypeDescription
namestring

Constants

HOOK_BODY_LIMIT ​

The largest hook body an app accepts, in bytes.

ts
const HOOK_BODY_LIMIT: number

HOOK_PAGES_LIMIT ​

The most pages a delivery lists; a larger change is sent as all: true.

ts
const HOOK_PAGES_LIMIT = 100

HOOK_TOLERANCE_SECONDS ​

How far the signature time may be from the app's clock by default, in seconds.

ts
const HOOK_TOLERANCE_SECONDS = 300

Interfaces

FoliwakeDeliveryPayload ​

delivery.settled: the live site is at generation, and the caches in front of the origin serve it.

ts
interface FoliwakeDeliveryPayload
MemberTypeDescription
version1
event'delivery.settled'
sitestring
generationnumberThe live generation; it only grows, except that init starts a new history.
releasestring | nullThe site release (sr_…), or null.
codeReleasestring | nullThe code release (cd_…), or null.
operation{ id: string; kind: FoliwakeOperationKind | (string & {}); }
pages?string[]The changed paths (pages, indexes); present only when all is false. A hint, at most 100.
allbooleanEvery live page may have changed.
verifiedbooleanWhether the server read the new generation back through its own cache before sending.
sentAtstring

FoliwakePingPayload ​

ping: the server checks the endpoint and its secret; the app changes nothing.

ts
interface FoliwakePingPayload
MemberTypeDescription
version1
event'ping'
sitestring
sentAtstring

VerifySignatureOptions ​

Options of verifyFoliwakeSignature.

ts
interface VerifySignatureOptions
MemberTypeDescription
now?numberThe app's clock, in milliseconds since the epoch (default Date.now()).
toleranceS?numberThe allowed distance between the signature time and now, in seconds (default 300).

Types

FoliwakeHookPayload ​

Any hook body.

ts
type FoliwakeHookPayload = FoliwakeDeliveryPayload | FoliwakePingPayload

FoliwakeOperationKind ​

The operations a delivery reports; a newer server may send others, which an app treats like any change.

ts
type FoliwakeOperationKind = 'content_publish' | 'unpublish' | 'rollback_full' | 'code_release' | 'rollback_code' | 'site_migration' | 'recovery_purge' | 'engine_update' | 'init'

SignatureCheck ​

The result of verifyFoliwakeSignature.

ts
type SignatureCheck = {
    ok: true;
} | {
    ok: false;
    reason: SignatureFailure;
}

SignatureFailure ​

Why a signature was refused.

ts
type SignatureFailure = 'malformed' | 'expired' | 'mismatch' | 'no_secret'

@foliwake/server/handler ​

Functions and components

createFoliwakeHandler() ​

The Foliwake routes of an app as one (request) => Promise<Response>. The config is read on the first request (FOLIWAKE_URL and its discovery document, unless config is given) and kept; a failed read is tried again on the next request and answers 503 meanwhile.

ts
function createFoliwakeHandler(opts?: FoliwakeHandlerOptions): FoliwakeFetchHandler
ParameterTypeDescription
opts?FoliwakeHandlerOptionsconfig, base, authorizePreview (default false), hook, env, fetch, log.

Returns FoliwakeFetchHandler

Constants

HANDLER_BASE ​

Where the handler is mounted by default: /foliwake/hook, /foliwake/health.

ts
const HANDLER_BASE = "/foliwake"

HOOK_SECRET_ENV ​

The variable the hook's shared secret is read from by default.

ts
const HOOK_SECRET_ENV = "FOLIWAKE_HOOK_SECRET"

Interfaces

FoliwakeHandlerOptions ​

Options of createFoliwakeHandler.

ts
interface FoliwakeHandlerOptions
MemberTypeDescription
config?FoliwakeAppConfig | (() => FoliwakeAppConfig | Promise<FoliwakeAppConfig>)The app config, or how to get it; default loadAppConfig() (FOLIWAKE_URL + the optional file), once.
base?stringThe app path of the hook and health routes; default /foliwake.
authorizePreview?AuthorizePreviewThe app's author check for preview files; default false (preview answers 404).
hook?false | FoliwakeHookOptionsThe hook endpoint's options; false answers 404 on <base>/hook.
env?NodeJS.ProcessEnvWhere secrets and FOLIWAKE_URL are read; default process.env.
fetch?typeof fetchA fetch implementation (tests); default globalThis.fetch.
log?Pick<Console, 'warn' | 'error'>

FoliwakeHookOptions ​

The hook endpoint of the handler.

ts
interface FoliwakeHookOptions
MemberTypeDescription
secretEnv?stringThe variable holding the shared secret; default FOLIWAKE_HOOK_SECRET.
previousSecretEnv?stringWhile the secret is rotated: the variable holding the previous one, also accepted.
onDelivery?(payload: FoliwakeDeliveryPayload) => void | Promise<void>Called for every delivery (expire your own caches here); a throw answers 500 and the server retries.
toleranceS?numberThe allowed clock distance of the signature, in seconds; default 300.
endpoint?(request: Request) => Promise<Response>Replaces the endpoint (a framework adapter's own, such as Next's tag expiry).

Types

FoliwakeFetchHandler ​

A request handler on the Web Fetch API.

ts
type FoliwakeFetchHandler = (request: Request) => Promise<Response>

@foliwake/server/hook-endpoint ​

Functions and components

createHookEndpoint() ​

The hook endpoint as a function of a Request: 413 over 64 KiB, 401 on a bad or expired signature, 400 on a body that is not a payload or names another site, 200 otherwise.

ts
function createHookEndpoint(deps: HookEndpointDeps): (request: Request) => Promise<Response>

Returns (request: Request) => Promise<Response>

deliveryTags() ​

The tags a delivery expires: the site's live tag on all, else one tag per listed path.

ts
function deliveryTags(payload: FoliwakeDeliveryPayload, liveTag: (path?: string) => string): string[]

Returns string[]

hookSecretsFrom() ​

The secrets() of the hook endpoint read from environment variables: each value is trimmed of leading and trailing whitespace and newlines (a secret pasted from openssl rand -hex 32 often ends in one), and an all-whitespace value counts as unset. The first time trimming changes a variable's value, one warning names the variable, never the value.

ts
function hookSecretsFrom(source: HookSecretSource): () => (string | undefined)[]

Returns () => (string \| undefined)[]

warmPaths() ​

The pages read again after a delivery: none on all, page paths only, at most WARM_LIMIT.

ts
function warmPaths(payload: FoliwakeDeliveryPayload): string[]

Returns string[]

Constants

WARM_LIMIT ​

At most this many pages are read again right after a delivery (warm); never on all.

ts
const WARM_LIMIT = 20

Interfaces

HookEndpointDeps ​

What the endpoint needs from the framework and from the app.

ts
interface HookEndpointDeps
MemberTypeDescription
sitestringThe configured site.
sdkstringWhat a ping answers as sdk: the package and its version (@foliwake/next/0.9.0).
secrets()() => (string | undefined)[]The accepted secrets, read per request (current, then previous).
liveTag()(path?: string) => stringThe live tag of the site (no path) or of one path.
expire()(tag: string) => voidExpires one tag (revalidateTag with the chosen profile).
warm()(path: string) => Promise<unknown>Reads one page into the cache again.
schedule()(task: () => Promise<void>) => voidRuns work after the response is sent.
warmPagesbooleanWhether pages are read again after a delivery.
onDelivery?(payload: FoliwakeDeliveryPayload) => void | Promise<void>
toleranceS?number
now?() => number
logPick<Console, 'warn' | 'error'>

HookSecretSource ​

Where hookSecretsFrom reads and what it warns on.

ts
interface HookSecretSource
MemberTypeDescription
namesreadonly (string | undefined)[]The variables, current first, then the previous one while it is rotated; undefined entries are skipped.
env?NodeJS.ProcessEnvWhere the variables are read, per call; default process.env.
logPick<Console, 'warn'>

@foliwake/server/discovery ​

Functions and components

fetchDiscovery() ​

Reads and validates the discovery document of the site at siteUrl (FOLIWAKE_URL: https, or http for loopback hosts; origin only). 5 s per attempt, one retry, no redirects, at most 16 KiB of JSON.

ts
function fetchDiscovery(siteUrl: string, opts?: FetchDiscoveryOptions): Promise<FoliwakeDiscovery>

Returns Promise<FoliwakeDiscovery>

parseDiscovery() ​

Validates a discovery document read from origin (the scheme, host and port of FOLIWAKE_URL). Throws FoliwakeConfigError naming the field.

ts
function parseDiscovery(value: unknown, origin: string): FoliwakeDiscovery

Returns FoliwakeDiscovery

Constants

DISCOVERY_LIMIT ​

The largest discovery document read, in bytes.

ts
const DISCOVERY_LIMIT: number

DISCOVERY_PATH ​

Where a site serves its discovery document, on each of its hosts.

ts
const DISCOVERY_PATH = "/.well-known/foliwake.json"

DISCOVERY_VERSION ​

The major of the discovery format this package reads.

ts
const DISCOVERY_VERSION = 1

PLAIN_CONTRACT ​

The plain HTML contract this package reads (X-Code-Release on .plain.html).

ts
const PLAIN_CONTRACT = 2

URL_ENV ​

The environment variable with the site's live origin.

ts
const URL_ENV = "FOLIWAKE_URL"

Interfaces

FetchDiscoveryOptions ​

Options of fetchDiscovery.

ts
interface FetchDiscoveryOptions
MemberTypeDescription
fetch?typeof fetchA fetch implementation (tests); default globalThis.fetch.
timeoutMs?numberPer attempt; default 5000.

FoliwakeDiscovery ​

A validated discovery document. Unknown keys are ignored, so a newer engine may add some.

ts
interface FoliwakeDiscovery
MemberTypeDescription
sitestring
live{ url: string; }
preview{ url: string; } | nullNull when the site has no preview host. Its Basic user is always preview.
media{ cdn: string; } | nullThe CDN that resizes live images (its origin), or null.
contracts{ plain: number; html: number | null; blocks: number | null; hook: number | null; }

@foliwake/server/resolve ​

Functions and components

configFromSnapshot() ​

The app config of a snapshot (no I/O). Throws FoliwakeConfigError naming the field.

ts
function configFromSnapshot(snapshot: FoliwakeConfigSnapshot): FoliwakeAppConfig

Returns FoliwakeAppConfig

loadAppConfig() ​

readConfigSnapshot, then configFromSnapshot.

ts
function loadAppConfig(opts?: ReadSnapshotOptions): Promise<FoliwakeAppConfig>

Returns Promise<FoliwakeAppConfig>

readConfigSnapshot() ​

Reads the inputs: FOLIWAKE_URL and its discovery document (fetched now), and the config file when there is one (a file named explicitly or by FOLIWAKE_REMOTE must exist). Throws FoliwakeConfigError.

ts
function readConfigSnapshot(opts?: ReadSnapshotOptions): Promise<FoliwakeConfigSnapshot>

Returns Promise<FoliwakeConfigSnapshot>

Constants

PREVIEW_TOKEN_ENV ​

The variable the default preview credential reads: Basic preview:<site preview token>.

ts
const PREVIEW_TOKEN_ENV = "FOLIWAKE_PREVIEW_TOKEN"

Interfaces

FoliwakeConfigSnapshot ​

The inputs of an app's config, as plain JSON.

ts
interface FoliwakeConfigSnapshot
MemberTypeDescription
urlstring | nullFOLIWAKE_URL, or null.
discoveryFoliwakeDiscovery | nullThe site's discovery document read from url, or null without it.
filestring | nullThe config file's name (for messages) and text, or null when there is none.
textstring | null

ReadSnapshotOptions ​

Options of readConfigSnapshot and loadAppConfig.

ts
interface ReadSnapshotOptions extends FetchDiscoveryOptions
MemberTypeDescription
cwd?string
env?NodeJS.ProcessEnvDefault process.env: FOLIWAKE_URL, FOLIWAKE_REMOTE.
file?stringThe config file (default FOLIWAKE_REMOTE, else ./foliwake.remote.json).

Also exported (documented where they are defined)

  • from @foliwake/server/discovery: DISCOVERY_PATH, FoliwakeDiscovery, URL_ENV

@foliwake/server/schemas/remote-2.schema.json ​

A file, not a module: schemas/remote-2.schema.json in the package.

@foliwake/server/schemas/remote-3.schema.json ​

A file, not a module: schemas/remote-3.schema.json in the package.

Apache-2.0