foldkit-ssr 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -0
- package/dist/{client-CsCXJa_9.mjs → client-ASzkY6Sw.mjs} +42 -4
- package/dist/{client-CsCXJa_9.mjs.map → client-ASzkY6Sw.mjs.map} +1 -1
- package/dist/{client-4jzvxuwf.d.mts → client-BDyZf200.d.mts} +12 -2
- package/dist/{client-4jzvxuwf.d.mts.map → client-BDyZf200.d.mts.map} +1 -1
- package/dist/client.d.mts +2 -2
- package/dist/client.mjs +2 -2
- package/dist/index.d.mts +3 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/vite.d.mts +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -719,6 +719,31 @@ than one, a root with no envelope (`Missing`, also for a second root as
|
|
|
719
719
|
parts or bindings that are `Invalid`, or a `Route` other than the one the page
|
|
720
720
|
was rendered for. A page is resumed whole or not at all.
|
|
721
721
|
|
|
722
|
+
### A page the browser does not take over
|
|
723
|
+
|
|
724
|
+
A page can be declined before anything is adopted: `when(document)` says
|
|
725
|
+
whether to take it over (a page rendered for a visitor, opened by an author),
|
|
726
|
+
and `fresh(plan.version)` whether its data is still current. A declined or
|
|
727
|
+
stale page is contained, as a refused one is, unless `otherwise: 'render'`
|
|
728
|
+
runs the application afresh in its place.
|
|
729
|
+
|
|
730
|
+
Drawn afresh at once, the page would show the fresh application's first draw,
|
|
731
|
+
usually its loading state, until its reads answer: the page blinks to "Loading"
|
|
732
|
+
and back. `until(model)` keeps the served page in view meanwhile. The fresh
|
|
733
|
+
application draws in a hidden element beside it, and when a Model it has drawn
|
|
734
|
+
satisfies `until`, it takes the page's place in one step, with the served
|
|
735
|
+
page's id. It never waits longer than `UNTIL_LIMIT_MS` (3 s). The CMS site
|
|
736
|
+
(`examples/cms/src/ssr/sitePlan.ts`) declines a page opened by an author, and
|
|
737
|
+
waits for the route's read and its Blocks' reads, which its `Site.answered`
|
|
738
|
+
checks with `RemoteData.answered` and `QueryBlock.active(...).answered`:
|
|
739
|
+
|
|
740
|
+
```ts
|
|
741
|
+
SSR.hydrate(config, plan, { buildId, when, otherwise: 'render', until: Site.answered })
|
|
742
|
+
```
|
|
743
|
+
|
|
744
|
+
The served page stays as it was served while it waits: its links are plain
|
|
745
|
+
links, and nothing it shows becomes live.
|
|
746
|
+
|
|
722
747
|
## Costs and limits
|
|
723
748
|
|
|
724
749
|
- **`SSR.render` renders the view twice.** That is the view check. A static
|
|
@@ -889,11 +889,12 @@ const hydrate$1 = (config, plan, options) => {
|
|
|
889
889
|
});
|
|
890
890
|
const contain = () => hydrate(program({ model: plan.baseline }), { buildId: "" });
|
|
891
891
|
if (declined || stale) {
|
|
892
|
-
if (options.otherwise
|
|
892
|
+
if (options.otherwise !== "render") contain();
|
|
893
|
+
else if (options.until === void 0) run(makeApplication({
|
|
893
894
|
...config,
|
|
894
895
|
container: root
|
|
895
896
|
}));
|
|
896
|
-
else
|
|
897
|
+
else renderBeside(config, root, options.until);
|
|
897
898
|
return;
|
|
898
899
|
}
|
|
899
900
|
if (root.getAttribute(BUILD_ATTRIBUTE) !== options.buildId) {
|
|
@@ -959,6 +960,43 @@ const hydrate$1 = (config, plan, options) => {
|
|
|
959
960
|
answered
|
|
960
961
|
}, pending);
|
|
961
962
|
};
|
|
963
|
+
/** The longest a served page stays in view while a fresh application waits for `until`. */
|
|
964
|
+
const UNTIL_LIMIT_MS = 3e3;
|
|
965
|
+
/**
|
|
966
|
+
* Runs the application afresh out of view, beside the served page, and puts
|
|
967
|
+
* it in the page's place once a Model it drew satisfies `until`, or after
|
|
968
|
+
* `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its
|
|
969
|
+
* Mounts start in the document as they would in place.
|
|
970
|
+
*/
|
|
971
|
+
const renderBeside = (config, served, until) => {
|
|
972
|
+
const holder = document.createElement("div");
|
|
973
|
+
holder.hidden = true;
|
|
974
|
+
const container = document.createElement("div");
|
|
975
|
+
container.id = served.id === "" ? "foldkit-ssr-app" : served.id;
|
|
976
|
+
served.removeAttribute("id");
|
|
977
|
+
served.removeAttribute(FOLDKIT_APP_ATTRIBUTE);
|
|
978
|
+
holder.append(container);
|
|
979
|
+
served.after(holder);
|
|
980
|
+
let shown = false;
|
|
981
|
+
const show = () => {
|
|
982
|
+
if (shown) return;
|
|
983
|
+
shown = true;
|
|
984
|
+
clearTimeout(limit);
|
|
985
|
+
holder.replaceWith(...holder.childNodes);
|
|
986
|
+
served.remove();
|
|
987
|
+
};
|
|
988
|
+
const limit = setTimeout(show, UNTIL_LIMIT_MS);
|
|
989
|
+
const view = (model, h) => {
|
|
990
|
+
const drawn = config.view(model, h);
|
|
991
|
+
if (!shown && until(model)) queueMicrotask(show);
|
|
992
|
+
return drawn;
|
|
993
|
+
};
|
|
994
|
+
run(makeApplication({
|
|
995
|
+
...config,
|
|
996
|
+
view,
|
|
997
|
+
container
|
|
998
|
+
}));
|
|
999
|
+
};
|
|
962
1000
|
/**
|
|
963
1001
|
* The Message the handover entry sends so the runtime takes the answered
|
|
964
1002
|
* Messages when nothing else has asked it to. The wrapped `update` consumes
|
|
@@ -1053,6 +1091,6 @@ const SSR = {
|
|
|
1053
1091
|
serving
|
|
1054
1092
|
};
|
|
1055
1093
|
//#endregion
|
|
1056
|
-
export {
|
|
1094
|
+
export { BINDING_ATTRIBUTE as C, withContext as D, SLOT_ATTRIBUTE as E, tagOf as S, FALLBACK_FIELD as T, routeOf as _, META_ATTRIBUTE as a, startingFrom as b, STATIC_ATTRIBUTE as c, codecOf as d, metaMarkup as f, resume as g, plan as h, FOLDKIT_APP_ATTRIBUTE as i, allowedTags as l, pathKey as m, SSR as n, RESUME_ATTRIBUTE as o, modelFrom as p, UNTIL_LIMIT_MS as r, ResumeRefused as s, Resume as t, attributeOf as u, serializeJsonScript as v, FALLBACK_DEPTH_FIELD as w, staticRegion as x, serving as y };
|
|
1057
1095
|
|
|
1058
|
-
//# sourceMappingURL=client-
|
|
1096
|
+
//# sourceMappingURL=client-ASzkY6Sw.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-CsCXJa_9.mjs","names":["tagOf","hydrate","adopt"],"sources":["../src/context.ts","../src/resumable.ts","../src/listen.ts","../src/shared.ts","../src/client.ts"],"sourcesContent":["/**\n * The render context: what the page's server-owned parts do, set around one\n * synchronous call of the view. `SSR.static` reads it to decide whether a\n * region renders, replays, or adopts the server's markup, and the resumable\n * builder reads it to decide whether to mark the bindings it builds. With no\n * context, as in a client-only render, both behave as ordinary view code.\n *\n * - `collect`: the server's render. Each region runs once and is kept, and\n * each binding is recorded in render order.\n * - `replay`: the server's second render, from the browser's Model. Each\n * region is the one already rendered, so it never reads the browser's Model;\n * bindings are recorded again, to be compared with the first render's.\n * - `resume`: the browser. Each region is the markup the server left in the\n * page, and its render never runs; no binding is marked.\n */\nimport type { Html } from 'foldkit/html'\n\nexport type Region = ReadonlyArray<Html | string>\n\n/** An element whose handler for `event` is a function, which the page cannot describe. */\nexport interface UnnamedHandler {\n readonly element: string\n readonly event: string\n}\n\n/**\n * An element's binding as the server's render records it, before encoding:\n * the Foldkit attribute and its DOM event, the element for diagnostics, and\n * the Message it causes. For a Message with a hole, `message` is the Message\n * with the hole filled by a placeholder, and `hole` names the fields the event\n * fills.\n */\nexport interface Binding {\n /** Foldkit's attribute, whose tag says what the handler does beside dispatching. */\n readonly attribute: string\n readonly event: string\n readonly element: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n /** How many placement wrappers enclose the hole's fields: `message` is entered that many times. */\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\nexport type RenderContext =\n | {\n readonly mode: 'collect'\n readonly regions: Map<string, Region>\n readonly duplicates: Set<string>\n readonly bindings: Array<Binding>\n /** Encodes a form's Message for its no-script fallback; absent when the plan has none. */\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n /** Lifts a Message of the view in progress to the application's, through each enclosing placement. */\n wrap: (message: unknown) => unknown\n /** How many placements enclose the view in progress. */\n depth: number\n /** The static region whose render is in progress, if any. */\n region: string | undefined\n /** Handlers met inside a static region, which the server alone renders. */\n readonly inStatic: Array<{\n readonly region: string\n readonly element: string\n readonly event: string\n }>\n /** Each element and event marked `*`: a handler the page cannot name. */\n readonly unnamed: Array<UnnamedHandler>\n }\n | {\n readonly mode: 'replay'\n readonly regions: ReadonlyMap<string, Region>\n readonly bindings: Array<Binding>\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n wrap: (message: unknown) => unknown\n depth: number\n }\n | {\n readonly mode: 'resume'\n readonly snapshots: ReadonlyMap<string, string>\n readonly reported: Set<string>\n }\n\nlet context: RenderContext | undefined\n\n/** The context of the view call in progress, if any. */\nexport const current = (): RenderContext | undefined => context\n\nexport const within = <A>(next: RenderContext, run: () => A): A => {\n const previous = context\n context = next\n try {\n return run()\n } finally {\n context = previous\n }\n}\n\n/** The config whose view runs inside `next`. */\nexport const withContext = <Config extends { readonly view: (model: any, h: any) => unknown }>(\n config: Config,\n next: RenderContext,\n): Config => ({\n ...config,\n view: (model: unknown, h: unknown) => within(next, () => config.view(model, h)),\n})\n","/**\n * The resumable builder: the application's `h`, whose event attributes say, in\n * the server's markup, which Message each element causes.\n *\n * A Foldkit handler is a Message value (`h.OnClick(Message.Liked({ id }))`), so\n * for most events that is already data. The events that carry a value\n * (`OnInput`, `OnChange`, `OnKeyDown`, `OnKeyUp`) take a closure only to put\n * the value into a Message field; this builder also takes the Message's own\n * constructor there, a Message with a hole, and fills the hole the same way.\n *\n * During the server's renders each binding gets an ordinal, recorded in render\n * order, and its element a `data-foldkit-plus-on-<event>` attribute naming it.\n * In the browser the builder marks nothing: it is the application's `h`, with\n * the hole forms turned into the closures Foldkit expects.\n */\nimport { Schema, SchemaAST } from 'effect'\nimport type { Attribute, ChildAttribute, HtmlBuilder, KeyboardModifiers } from 'foldkit/html'\nimport { current, type Binding } from './context.js'\n\n/** The attribute prefix of an element's binding marker. */\nexport const BINDING_ATTRIBUTE = 'data-foldkit-plus-on-'\n\n/**\n * The DOM event each of Foldkit's event attributes listens to, read from\n * Foldkit's own attribute table (0.163). `OnCustomEvent` names its event in\n * its payload, and `OnMount` and `OnUnmount` listen to none.\n */\nexport const EVENT_OF: Readonly<Record<string, string>> = {\n OnClick: 'click',\n OnDoubleClick: 'dblclick',\n OnMouseDown: 'mousedown',\n OnMouseUp: 'mouseup',\n OnMouseEnter: 'mouseenter',\n OnMouseLeave: 'mouseleave',\n OnMouseOver: 'mouseover',\n OnMouseOut: 'mouseout',\n OnMouseMove: 'mousemove',\n OnPointerMove: 'pointermove',\n OnPointerLeave: 'pointerleave',\n OnPointerDown: 'pointerdown',\n OnPointerUp: 'pointerup',\n OnKeyDown: 'keydown',\n OnKeyDownPreventDefault: 'keydown',\n OnKeyDownSelf: 'keydown',\n OnKeyDownSelfPreventDefault: 'keydown',\n OnKeyDownFocus: 'keydown',\n OnKeyUp: 'keyup',\n OnKeyUpPreventDefault: 'keyup',\n OnKeyPress: 'keypress',\n OnFocus: 'focus',\n OnBlur: 'blur',\n OnFocusEnter: 'focusin',\n OnFocusLeave: 'focusout',\n OnInput: 'input',\n OnChange: 'change',\n OnBeforeInput: 'beforeinput',\n OnBeforeInputPreventDefault: 'beforeinput',\n OnFileChange: 'change',\n OnSubmit: 'submit',\n OnReset: 'reset',\n OnScroll: 'scroll',\n OnWheel: 'wheel',\n OnCopy: 'copy',\n OnCut: 'cut',\n OnPaste: 'paste',\n OnPastePreventDefault: 'paste',\n OnCopyText: 'copy',\n OnCutText: 'cut',\n OnCancel: 'cancel',\n OnCancelPreventDefault: 'cancel',\n OnToggle: 'toggle',\n OnContextMenu: 'contextmenu',\n OnDragStart: 'dragstart',\n OnDrag: 'drag',\n OnDragEnd: 'dragend',\n OnDragEnter: 'dragenter',\n OnDragLeave: 'dragleave',\n OnDragOver: 'dragover',\n OnDrop: 'drop',\n OnDropFiles: 'drop',\n OnTouchStart: 'touchstart',\n OnTouchEnd: 'touchend',\n OnTouchMove: 'touchmove',\n OnTouchCancel: 'touchcancel',\n OnAnimationStart: 'animationstart',\n OnAnimationEnd: 'animationend',\n OnAnimationIteration: 'animationiteration',\n OnTransitionEnd: 'transitionend',\n OnLoad: 'load',\n OnError: 'error',\n OnPlay: 'play',\n OnPause: 'pause',\n OnEnded: 'ended',\n OnTimeUpdate: 'timeupdate',\n OnVolumeChange: 'volumechange',\n OnSelect: 'select',\n}\n\n/**\n * The attributes whose binding the page can describe: a Message value, or one\n * of the hole forms this builder records. Any other handler still runs on the\n * live page, so its event is marked `*`: the page does something there it\n * cannot name, and a dispatcher that ran only the named bindings would do less.\n */\nconst MARKABLE: ReadonlySet<string> = new Set([\n 'OnClick',\n 'OnDoubleClick',\n 'OnMouseDown',\n 'OnMouseUp',\n 'OnMouseEnter',\n 'OnMouseLeave',\n 'OnMouseOver',\n 'OnMouseOut',\n 'OnMouseMove',\n 'OnFocus',\n 'OnBlur',\n 'OnSubmit',\n 'OnReset',\n 'OnInput',\n 'OnChange',\n 'OnKeyDown',\n 'OnKeyUp',\n])\n\n/** The token in a marker for a handler the page cannot describe. */\nexport const UNNAMED_HANDLER = '*'\n\n/** The posted field that carries a form's encoded Message, for the server fallback. */\nexport const FALLBACK_FIELD = 'foldkit-plus-message'\n\n/** The posted field that says how many placement wrappers the form's fields sit under. */\nexport const FALLBACK_DEPTH_FIELD = 'foldkit-plus-depth'\n\n/** The attribute on a placement's root naming its slot, while the server renders. */\nexport const SLOT_ATTRIBUTE = 'data-foldkit-plus-slot'\n\ndeclare const invalid: unique symbol\n\n/** A compile-time failure that names its cause. */\nexport interface Invalid<Message extends string> {\n readonly [invalid]: Message\n}\n\ntype IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never\n\n/** A Message constructor from `defineMessageUnion`: a tagged Schema that can be called. */\ntype AnyMemberSchema = Schema.Top & { readonly fields: Schema.Struct.Fields }\n\n/** The Message a member makes. */\ntype Made<M> = M extends { readonly Type: infer T } ? T : never\n\n/** The fields a member's event may be given fixed: all but `_tag`. */\ntype Fixable<M> = Partial<Omit<Made<M>, '_tag'>>\n\n/** The fields of a member the event fills: those neither `_tag` nor fixed. */\ntype Rest<M, Fixed> = Omit<Made<M>, '_tag' | keyof Fixed>\n\ntype ProducesMessage<M, Message> = [Made<M>] extends [Message]\n ? unknown\n : Invalid<\"the member is not one of this view's Messages\">\n\ntype TextHoleCheck<M, Fixed> = [keyof Rest<M, Fixed>] extends [never]\n ? Invalid<'the member has no field left for the event to fill'>\n : true extends IsUnion<keyof Rest<M, Fixed>>\n ? Invalid<'the member leaves more than one field for the event to fill: fix the others'>\n : Rest<M, Fixed>[keyof Rest<M, Fixed>] extends string\n ? string extends Rest<M, Fixed>[keyof Rest<M, Fixed>]\n ? unknown\n : Invalid<'the field the event fills must be a string'>\n : Invalid<'the field the event fills must be a string'>\n\ntype KeyHoleCheck<M, Fixed> = [keyof Rest<M, Fixed>] extends ['key' | 'modifiers']\n ? ['key' | 'modifiers'] extends [keyof Rest<M, Fixed>]\n ? unknown\n : Invalid<'the member must leave exactly key and modifiers for the event to fill'>\n : Invalid<'the member must leave exactly key and modifiers for the event to fill'>\n\n/** `OnInput` and `OnChange`: a closure, or a member whose one string field the event fills. */\nexport interface TextHole<Message> {\n (toMessage: (value: string) => Message): Attribute<Message>\n <M extends AnyMemberSchema, const Fixed extends Fixable<M> = {}>(\n member: M & ProducesMessage<M, Message> & TextHoleCheck<M, Fixed>,\n fixed?: Fixed,\n ): Attribute<Message>\n}\n\n/** `OnKeyDown` and `OnKeyUp`: a closure, or a member whose `key` and `modifiers` the event fills. */\nexport interface KeyHole<Message> {\n (toMessage: (key: string, modifiers: KeyboardModifiers) => Message): Attribute<Message>\n <M extends AnyMemberSchema, const Fixed extends Fixable<M> = {}>(\n member: M & ProducesMessage<M, Message> & KeyHoleCheck<M, Fixed>,\n fixed?: Fixed,\n ): Attribute<Message>\n}\n\n/**\n * A builder a view is given: Foldkit's `HtmlBuilder`, or a Surface renderer's,\n * which leaves out Foldkit's phantom key. Its Message is what `OnClick` takes.\n */\nexport type AnyBuilder = {\n readonly OnClick: (message: never, ...rest: ReadonlyArray<never>) => unknown\n}\n\n/** The Message a builder's handlers make. */\nexport type MessageOf<Builder> = Builder extends {\n readonly OnClick: (message: infer Message, ...rest: ReadonlyArray<never>) => unknown\n}\n ? Message\n : never\n\n/**\n * The resumable builder for a view whose Messages are `Message`: its elements\n * and attributes, and the hole forms of the four value events. One shape\n * whether it wraps a view's `HtmlBuilder` or a Surface renderer's builder, so a\n * helper typed with it takes either. It keeps Foldkit's phantom Message key,\n * so a placement's view accepts it as the parent's builder.\n */\nexport type ResumableBuilder<Message> = Omit<\n HtmlBuilder<Message>,\n 'OnInput' | 'OnChange' | 'OnKeyDown' | 'OnKeyUp'\n> & {\n readonly OnInput: TextHole<Message>\n readonly OnChange: TextHole<Message>\n readonly OnKeyDown: KeyHole<Message>\n readonly OnKeyUp: KeyHole<Message>\n}\n\ntype AnyMember = ((value: Record<string, unknown>) => unknown) & {\n readonly fields: Readonly<Record<string, unknown>>\n}\n\nconst isMember = (value: unknown): value is AnyMember =>\n typeof value === 'function' && typeof (value as { fields?: unknown }).fields === 'object'\n\nconst tagOf = (member: AnyMember): string => {\n const tag = member.fields._tag\n return Schema.isSchema(tag) && SchemaAST.isLiteral(tag.ast) && typeof tag.ast.literal === 'string'\n ? tag.ast.literal\n : 'the member'\n}\n\n/** The fields a member leaves for the event to fill, given what is fixed. */\nconst holeOf = (member: AnyMember, fixed: object): ReadonlyArray<string> =>\n Object.keys(member.fields).filter(field => field !== '_tag' && !(field in fixed))\n\nconst NO_MODIFIERS: KeyboardModifiers = {\n shiftKey: false,\n ctrlKey: false,\n altKey: false,\n metaKey: false,\n}\n\n/** Each hole-form attribute, with its Message filled by a placeholder and the fields the event fills. */\nconst holes = new WeakMap<\n object,\n { readonly template: unknown; readonly hole: ReadonlyArray<string> }\n>()\n\n/** What an element is given: Foldkit's attributes, and a Submodel's wrapped ones, which carry no tag. */\ntype Item = Attribute<unknown> | ChildAttribute\n\nconst isAttribute = (item: Item): item is Attribute<unknown> => '_tag' in item\n\nconst builders = new WeakMap<object, unknown>()\n\n/** A hole form's placeholder Message, or `undefined` when its field's checks refuse one. */\nconst placeholder = (make: () => unknown): unknown => {\n try {\n return make()\n } catch {\n return undefined\n }\n}\n\n/**\n * The resumable builder for a view's `h`. Use it in place of `h`; it has the\n * same elements and attributes, and the hole forms of the four value events.\n */\nexport const builder = <Builder extends AnyBuilder>(\n h: Builder,\n): ResumableBuilder<MessageOf<Builder>> => {\n const cached = builders.get(h)\n if (cached !== undefined) return cached as ResumableBuilder<MessageOf<Builder>>\n const source = h as unknown as Record<string, unknown>\n const attribute = source.Attribute as (name: string, value: string) => unknown\n\n /** The attributes with a marker for each binding, while the server renders. */\n const mark = (tag: string, attributes: ReadonlyArray<Item>): ReadonlyArray<unknown> => {\n const now = current()\n if (now?.mode !== 'collect' && now?.mode !== 'replay') return attributes\n const id = attributes.find(\n (item): item is Extract<Attribute<unknown>, { readonly _tag: 'Id' }> =>\n isAttribute(item) && item._tag === 'Id',\n )\n const element = id === undefined ? tag : `${tag}#${id.value}`\n // Foldkit chains every handler of an event, in the order the attributes\n // come, so a marker lists every binding of its event in that order.\n const tokens = new Map<string, Array<string>>()\n for (const item of attributes) {\n if (!isAttribute(item)) continue\n const event = item._tag === 'OnCustomEvent' ? item.name : EVENT_OF[item._tag]\n if (event === undefined) continue\n // Recorded for the refusal; the render does not survive it.\n if (now.mode === 'collect' && now.region !== undefined) {\n now.inStatic.push({ region: now.region, element, event })\n }\n const recorded = holes.get(item)\n const nested = now.depth === 0 ? {} : { depth: now.depth }\n const binding: Binding | undefined = !MARKABLE.has(item._tag)\n ? undefined\n : 'message' in item\n ? {\n attribute: item._tag,\n event,\n element,\n message: now.wrap(item.message),\n ...('options' in item && item.options !== undefined ? { options: item.options } : {}),\n }\n : recorded === undefined\n ? undefined\n : {\n attribute: item._tag,\n event,\n element,\n message: now.wrap(recorded.template),\n hole: recorded.hole,\n ...nested,\n }\n const list = tokens.get(event) ?? []\n tokens.set(event, list)\n if (binding === undefined) {\n // One entry per element and event, however many handlers it chains.\n if (now.mode === 'collect' && !list.includes(UNNAMED_HANDLER)) {\n now.unnamed.push({ element, event })\n }\n list.push(UNNAMED_HANDLER)\n } else {\n list.push(String(now.bindings.length))\n now.bindings.push(binding)\n }\n }\n if (tokens.size === 0) return attributes\n const markers = [...tokens].map(([event, list]) =>\n attribute(`${BINDING_ATTRIBUTE}${event}`, list.join(' ')),\n )\n return [...attributes, ...markers]\n }\n\n /**\n * A form whose `OnSubmit` names a Message, while the server renders for a\n * plan with a fallback, also posts that Message: `method=\"post\"` to its own\n * URL, and a hidden input carrying the Message encoded. Posted fields named\n * as the Message's own fields override them, so a typed title reaches\n * `update` as it would through the page.\n */\n const fallback = (\n tag: string,\n attributes: ReadonlyArray<Item>,\n children: unknown,\n ): { readonly attributes: ReadonlyArray<Item>; readonly children: unknown } => {\n const now = current()\n if (\n tag !== 'form' ||\n now?.mode === undefined ||\n now.mode === 'resume' ||\n now.fallback === undefined\n ) {\n return { attributes, children }\n }\n const submit = attributes.find(\n (item): item is Extract<Attribute<unknown>, { readonly _tag: 'OnSubmit' }> =>\n isAttribute(item) && item._tag === 'OnSubmit',\n )\n if (submit === undefined || !Array.isArray(children)) return { attributes, children }\n const encoded = now.fallback(now.wrap(submit.message))\n if (encoded === undefined) return { attributes, children }\n const make = (name: string) => source[name] as (value: string) => Attribute<unknown>\n const input = source.input as (attributes: ReadonlyArray<unknown>) => unknown\n const hidden = (name: string, value: string) =>\n input([make('Type')('hidden'), make('Name')(name), make('Value')(value)])\n return {\n attributes: [...attributes, make('Method')('post')],\n children: [\n ...children,\n hidden(FALLBACK_FIELD, encoded),\n ...(now.depth === 0 ? [] : [hidden(FALLBACK_DEPTH_FIELD, String(now.depth))]),\n ],\n }\n }\n\n const textHole =\n (name: string) =>\n (given: unknown, fixed: Record<string, unknown> = {}): unknown => {\n const make = source[name] as (toMessage: (value: string) => unknown) => object\n if (!isMember(given)) return make(given as (value: string) => unknown)\n const hole = holeOf(given, fixed)\n if (hole.length !== 1) {\n throw new Error(\n `Resume.builder: ${name}(${tagOf(given)}) leaves ${hole.length === 0 ? 'no field' : hole.join(', ')} for the event to fill; it must leave one string field`,\n )\n }\n const [field] = hole as [string]\n const made = make(value => given({ ...fixed, [field]: value }))\n const template = placeholder(() => given({ ...fixed, [field]: '' }))\n // A field whose checks refuse the empty placeholder cannot be written\n // into the page as data; left unrecorded, the handler is marked as one\n // the page cannot name, and the live page answers it.\n if (template !== undefined) holes.set(made, { template, hole })\n return made\n }\n\n const keyHole =\n (name: string) =>\n (given: unknown, fixed: Record<string, unknown> = {}): unknown => {\n const make = source[name] as (\n toMessage: (key: string, modifiers: KeyboardModifiers) => unknown,\n ) => object\n if (!isMember(given)) {\n return make(given as (key: string, modifiers: KeyboardModifiers) => unknown)\n }\n const hole = holeOf(given, fixed)\n if (hole.length !== 2 || !hole.includes('key') || !hole.includes('modifiers')) {\n throw new Error(\n `Resume.builder: ${name}(${tagOf(given)}) leaves ${hole.join(', ') || 'no field'} for the event to fill; it must leave exactly key and modifiers`,\n )\n }\n const made = make((key, modifiers) => given({ ...fixed, key, modifiers }))\n const template = placeholder(() => given({ ...fixed, key: '', modifiers: NO_MODIFIERS }))\n if (template !== undefined) holes.set(made, { template, hole })\n return made\n }\n\n /**\n * `h.submodel` with the child's root stamped with its slot, while the\n * server renders: a boundary a tool can find, which the browser's first\n * patch removes as it removes the markers.\n */\n const submodel = (config: {\n readonly slotId: string\n readonly view: unknown\n readonly toParentMessage: (message: unknown) => unknown\n }): unknown => {\n const original = source.submodel as (config: unknown) => unknown\n const now = current()\n if (now?.mode !== 'collect' && now?.mode !== 'replay') return original(config)\n const view = config.view as (...args: ReadonlyArray<unknown>) => unknown\n const stamped = (...args: ReadonlyArray<unknown>) => {\n // A binding inside dispatches the parent's Message, as Foldkit's own\n // handlers do, so it is recorded lifted through this placement.\n const outer = { wrap: now.wrap, depth: now.depth }\n now.wrap = message => outer.wrap(config.toParentMessage(message))\n now.depth = outer.depth + 1\n let out: { data?: { attrs?: Record<string, unknown> } } | null\n try {\n out = view(...args) as typeof out\n } finally {\n now.wrap = outer.wrap\n now.depth = outer.depth\n }\n if (out !== null && typeof out === 'object' && out.data !== undefined) {\n out.data.attrs = { ...out.data.attrs, [SLOT_ATTRIBUTE]: config.slotId }\n }\n return out\n }\n // The view carries Foldkit's Submodel brand as an own property; keep it.\n return original({ ...config, view: Object.assign(stamped, view) })\n }\n\n const wrapped: Record<string, unknown> = {}\n for (const [name, value] of Object.entries(source)) {\n if (name === 'submodel') wrapped[name] = submodel\n else if (name === 'OnInput' || name === 'OnChange') wrapped[name] = textHole(name)\n else if (name === 'OnKeyDown' || name === 'OnKeyUp') wrapped[name] = keyHole(name)\n else if (name === 'keyed') {\n const keyed = value as (tag: string) => (key: PropertyKey, ...rest: Array<unknown>) => unknown\n wrapped[name] =\n (tag: string) =>\n (key: PropertyKey, attributes: ReadonlyArray<Item> = [], ...rest: Array<unknown>) => {\n const posted = fallback(tag, attributes, rest[0])\n return keyed(tag)(key, mark(tag, posted.attributes), posted.children, ...rest.slice(1))\n }\n } else if (/^[a-z]/.test(name) && typeof value === 'function') {\n const element = value as (\n attributes: ReadonlyArray<unknown>,\n ...rest: Array<unknown>\n ) => unknown\n wrapped[name] = (attributes: ReadonlyArray<Item>, ...rest: Array<unknown>) => {\n const posted = fallback(name, attributes, rest[0])\n return element(mark(name, posted.attributes), posted.children, ...rest.slice(1))\n }\n } else wrapped[name] = value\n }\n builders.set(h, wrapped)\n return wrapped as unknown as ResumableBuilder<MessageOf<Builder>>\n}\n\n/**\n * A view or renderer written against the resumable builder, as one that takes\n * the builder it is given: `Surface.rootView(Page, params, Resume.view(render))`,\n * `SurfaceView.define`, or an application's own view.\n */\nexport const view =\n <Model, Builder extends AnyBuilder, Out>(\n render: (model: Model, rh: ResumableBuilder<MessageOf<Builder>>) => Out,\n ) =>\n (model: Model, h: Builder): Out =>\n render(model, builder(h))\n","/**\n * Delegated dispatch: the page answers an event from its markers, before the\n * application has booted.\n *\n * One capture-phase listener per event type sits at the root, so events that\n * do not bubble (`focus`, `blur`) are caught, and it runs before anything\n * Foldkit attaches later. On an event it walks from the target to the root\n * and, for every marker of that event on the way, collects each binding's\n * Message in order, the way Foldkit's own handler would dispatch it: a hole is\n * filled from the event, `OnClick`'s options are honoured, `OnSubmit`\n * prevents the default. A marker token the page could not name (`*`) means\n * the live page does something here the page cannot describe, so the walk\n * ends and the answer names that element.\n */\nimport { Predicate, Result, Schema } from 'effect'\nimport type { KeyboardModifiers } from 'foldkit/html'\nimport { BINDING_ATTRIBUTE, EVENT_OF, UNNAMED_HANDLER } from './resumable.js'\n\n/**\n * A binding as the envelope carries it: Foldkit's attribute (`OnSubmit`,\n * `OnBlur`), whose tag says what its handler does beside dispatching; the\n * Message, encoded through the application's Message Schema (for a hole, with\n * the hole filled by a placeholder); the fields the event fills, `depth`\n * placement wrappers down; and the attribute's options. Its ordinal is its\n * index.\n */\nexport interface EncodedBinding {\n readonly attribute: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string>\n readonly depth?: number\n readonly options?: unknown\n}\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The page's list of bindings, read as untrusted input: each entry checked,\n * and only its known keys kept, or the reason the list is refused. Checked by\n * hand rather than through a Schema, which at a thousand rows took most of a\n * frame for a shape this plain; the Message inside each entry is still decoded\n * through the application's Schema by `decodeBindings`.\n */\nexport const readBindings = (\n value: unknown,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (!Array.isArray(value)) return Result.fail('the list is not an array')\n const out: Array<EncodedBinding> = []\n for (const [index, entry] of value.entries()) {\n if (!isRecord(entry)) return Result.fail(`entry ${index} is not an object`)\n if (typeof entry.attribute !== 'string') {\n return Result.fail(`entry ${index} has no attribute`)\n }\n if (!Object.hasOwn(entry, 'message')) return Result.fail(`entry ${index} has no message`)\n const { hole, depth } = entry\n if (\n hole !== undefined &&\n !(Array.isArray(hole) && hole.every(field => typeof field === 'string'))\n ) {\n return Result.fail(`entry ${index} has a hole that is not a list of fields`)\n }\n if (depth !== undefined && !(Number.isInteger(depth) && (depth as number) >= 0)) {\n return Result.fail(`entry ${index} has a depth that is not a count`)\n }\n out.push({\n attribute: entry.attribute,\n message: entry.message,\n ...(hole === undefined ? {} : { hole: hole as ReadonlyArray<string> }),\n ...(depth === undefined ? {} : { depth: depth as number }),\n ...(Object.hasOwn(entry, 'options') ? { options: entry.options } : {}),\n })\n }\n return Result.succeed(out)\n}\n\n/** A binding decoded from the page: its Message is one of the application's. */\nexport interface DecodedBinding {\n readonly attribute: string\n readonly event: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\n/**\n * The page's bindings, decoded through the application's Message Schema, and\n * every marker in `root` checked against them. A page whose markers name a\n * binding it does not carry, or whose entry is not one of the application's\n * Messages, is refused whole, with the reason.\n */\nexport const decodeBindings = (\n Message: Schema.Top | undefined,\n encoded: ReadonlyArray<EncodedBinding>,\n root: ParentNode,\n allowed: ReadonlySet<string>,\n): Result.Result<ReadonlyArray<DecodedBinding>, string> => {\n if (encoded.length > 0 && Message === undefined) {\n return Result.fail(\n 'the page has bindings and the plan has no Message Schema to decode them with',\n )\n }\n const decode =\n Message === undefined\n ? undefined\n : Schema.decodeUnknownResult(Message as Schema.Codec<unknown, unknown>)\n const bindings: Array<DecodedBinding> = []\n for (const [index, entry] of encoded.entries()) {\n const event = EVENT_OF[entry.attribute]\n if (event === undefined) {\n return Result.fail(\n `binding ${index} is for \"${entry.attribute}\", which is no event attribute`,\n )\n }\n const message = decode!(entry.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `binding ${index} does not decode as a Message: ${message.failure.message}`,\n )\n }\n const tag = Predicate.hasProperty(message.success, '_tag') ? message.success._tag : undefined\n if (typeof tag !== 'string' || !allowed.has(tag)) {\n return Result.fail(\n `binding ${index} dispatches ${typeof tag === 'string' ? tag : 'an untagged Message'}, which no active Surface lists in its messages`,\n )\n }\n bindings.push({\n attribute: entry.attribute,\n event,\n message: message.success,\n ...(entry.hole === undefined ? {} : { hole: entry.hole }),\n ...(entry.depth === undefined ? {} : { depth: entry.depth }),\n ...(entry.options === undefined ? {} : { options: entry.options }),\n })\n }\n for (const element of Array.from(root.querySelectorAll('*'))) {\n for (const attribute of element.getAttributeNames()) {\n if (!attribute.startsWith(BINDING_ATTRIBUTE)) continue\n for (const token of (element.getAttribute(attribute) ?? '').split(' ')) {\n if (token === UNNAMED_HANDLER) continue\n const ordinal = Number(token)\n if (!Number.isInteger(ordinal) || bindings[ordinal] === undefined) {\n return Result.fail(`the marker ${attribute}=\"${token}\" names no binding the page carries`)\n }\n }\n }\n }\n return Result.succeed(bindings)\n}\n\n/** A string property of the target, if it has one. */\nconst stringProperty = (target: EventTarget | null, name: string): string | undefined => {\n if (target === null || !(name in target)) return undefined\n const value: unknown = Reflect.get(target, name)\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Foldkit's reading of an input's value (`inputEventValue`): any target's\n * string `value`, a custom element's included, else its `innerText`, else its\n * `textContent`.\n */\nconst inputValue = (target: EventTarget | null): string =>\n stringProperty(target, 'value') ??\n stringProperty(target, 'innerText') ??\n stringProperty(target, 'textContent') ??\n ''\n\nconst modifiersOf = (event: KeyboardEvent): KeyboardModifiers => ({\n shiftKey: event.shiftKey,\n ctrlKey: event.ctrlKey,\n altKey: event.altKey,\n metaKey: event.metaKey,\n})\n\n/** The Message a binding dispatches for this event: its own, with the hole filled. */\nconst messageFor = (binding: DecodedBinding, event: Event): unknown => {\n if (binding.hole === undefined) return binding.message\n const fill = (template: Readonly<Record<string, unknown>>): unknown => {\n if (binding.event === 'input' || binding.event === 'change') {\n const [field] = binding.hole ?? []\n return { ...template, [field ?? 'value']: inputValue(event.target) }\n }\n if (event instanceof KeyboardEvent) {\n return { ...template, key: event.key, modifiers: modifiersOf(event) }\n }\n return template\n }\n // The hole's fields sit inside each placement wrapper's `message`.\n const inside = (template: Readonly<Record<string, unknown>>, depth: number): unknown =>\n depth === 0\n ? fill(template)\n : {\n ...template,\n message: inside(template.message as Readonly<Record<string, unknown>>, depth - 1),\n }\n return inside(binding.message as Readonly<Record<string, unknown>>, binding.depth ?? 0)\n}\n\n/** What `OnClick` declares beside its Message. */\ninterface ClickOptions {\n readonly defaultAction?: 'Allow' | 'Prevent'\n readonly propagation?: 'Bubble' | 'Stop'\n readonly focusSelector?: string\n}\n\n/**\n * What the markers make of one event: the Messages its bindings dispatch, in\n * the order the live page would, and, when the walk met a handler the page\n * could not name, that element. An answer with `unnamed` is incomplete: the\n * live page would do more than its Messages say.\n */\nexport interface Answer {\n readonly event: Event\n readonly messages: ReadonlyArray<unknown>\n readonly unnamed?: Element | undefined\n}\n\nexport interface ListenOptions {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly onAnswer: (answer: Answer) => void\n /**\n * Every event the page's markers name, as the envelope lists them. Given,\n * `listen` needs no pass over the page to find the events a marker names\n * with `*` alone; without it, it reads every element's attributes, which on\n * a large page is most of its cost.\n */\n readonly events?: Iterable<string> | undefined\n}\n\n/**\n * Listens at `root` for every event the bindings name, and answers each from\n * the markers. Returns what removes the listeners.\n */\nexport const listen = (root: Element, options: ListenOptions): (() => void) => {\n // The bindings name most events; a marker whose handlers the page could not\n // name is `*` alone, so the markers themselves say the rest.\n const events = new Set(options.bindings.map(binding => binding.event))\n if (options.events !== undefined) {\n for (const event of options.events) events.add(event)\n } else {\n for (const element of [root, ...Array.from(root.querySelectorAll('*'))]) {\n for (const { name } of Array.from(element.attributes)) {\n if (name.startsWith(BINDING_ATTRIBUTE)) events.add(name.slice(BINDING_ATTRIBUTE.length))\n }\n }\n }\n const handler = (event: Event) => {\n const type = event.type\n const attribute = `${BINDING_ATTRIBUTE}${type}`\n const messages: Array<unknown> = []\n // An event that does not bubble (`focus`, `blur`, `mouseenter`) reaches only\n // its target's own handlers on the live page, so only those answer it here.\n const path = event.bubbles ? event.composedPath() : [event.target]\n for (const node of path) {\n if (!(node instanceof Element)) continue\n const tokens = node.getAttribute(attribute)\n // Foldkit chains an element's handlers in one listener, so a Stop among\n // them keeps the event from other elements, not from its siblings.\n let stopped = false\n if (tokens !== null) {\n for (const token of tokens.split(' ')) {\n if (token === UNNAMED_HANDLER) {\n options.onAnswer({ event, messages, unnamed: node })\n return\n }\n const binding = options.bindings[Number(token)]\n if (binding === undefined) continue\n if (binding.attribute === 'OnSubmit') event.preventDefault()\n if (binding.attribute === 'OnClick') {\n const click = (binding.options ?? {}) as ClickOptions\n if (click.defaultAction === 'Prevent') event.preventDefault()\n if (click.propagation === 'Stop') event.stopPropagation()\n if (click.focusSelector !== undefined) {\n const focusTarget = document.querySelector(click.focusSelector)\n if (focusTarget instanceof HTMLElement) focusTarget.focus()\n }\n if (click.propagation === 'Stop') stopped = true\n }\n messages.push(messageFor(binding, event))\n }\n }\n if (stopped || node === root) break\n }\n options.onAnswer({ event, messages })\n }\n for (const type of events) root.addEventListener(type, handler, true)\n return () => {\n for (const type of events) root.removeEventListener(type, handler, true)\n }\n}\n","/**\n * What the server and the browser both read: the plan, the envelope as the\n * browser reads it, static regions, and the page's bindings. Nothing here\n * imports Foldkit's server renderer, so `client.ts` can carry all of it.\n */\nimport { Effect, Option, Result, Schema, Stream, type Layer } from 'effect'\nimport type { Runtime } from 'foldkit'\nimport { inertHtml, type Html, type HtmlBuilder } from 'foldkit/html'\nimport type { Ports } from 'foldkit/port'\nimport type { ActiveSurface, Metadata, WritableProjection } from 'foldkit-surface'\nimport { current, type Region } from './context.js'\nimport { decodeBindings, readBindings, type DecodedBinding } from './listen.js'\n\n/**\n * The attribute Foldkit's server stamps on an application's root, as\n * `foldkit/experimental/server` exports it. Written out here so a page can\n * find its root without that module; a test pins the two together.\n */\nexport const FOLDKIT_APP_ATTRIBUTE = 'data-foldkit-app'\n\n/**\n * The attribute on the stamped root that carries a page's resume envelope.\n * Foldkit pairs its own handoff the same way: the build id rides on the root\n * beside the app stamp, and the client reads it before adopting anything.\n */\nexport const RESUME_ATTRIBUTE = 'data-foldkit-plus-resume'\n\n/** The envelope format this package writes and reads. */\nexport const PROTOCOL = 1\n\nconst LINE_SEPARATOR = String.fromCharCode(0x2028)\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029)\n\n/**\n * JSON for a script element: `<` is escaped so `</script>` in the data ends\n * nothing. U+2028 and U+2029 are escaped too: they are fine in JSON and break a\n * reader that treats the text as JavaScript.\n */\nexport const serializeJsonScript = (value: unknown): string =>\n JSON.stringify(value)\n .replaceAll('<', '\\\\u003c')\n .replaceAll(LINE_SEPARATOR, '\\\\u2028')\n .replaceAll(PARAGRAPH_SEPARATOR, '\\\\u2029')\n\n/**\n * The envelope JSON as the stamped root carries it: `serializeJsonScript`\n * already escaped `<` and the line separators, and an attribute must escape\n * `&` and `\"` besides, so no string in the Model can break out of the value.\n * `getAttribute` resolves the entities back, which is exactly the JSON.\n */\nexport const attributeOf = (json: string): string =>\n ` ${RESUME_ATTRIBUTE}=\"${json.replaceAll('&', '&').replaceAll('\"', '"')}\"`\n\n/**\n * What a page says of itself beyond Foldkit's `Document` (`title`, `lang`,\n * `dir`, `canonical`, `ogUrl`): what a search result and a link preview show.\n * `title` is the preview's title (`og:title`), when it differs from the\n * document's. Dates are ISO 8601 text; `jsonLd` is structured data, each\n * entry written as its own script.\n */\nexport interface Meta {\n readonly description?: string | undefined\n readonly title?: string | undefined\n readonly image?: string | undefined\n readonly type?: 'website' | 'article' | undefined\n readonly siteName?: string | undefined\n readonly article?:\n { readonly published?: string | undefined; readonly modified?: string | undefined } | undefined\n readonly robots?: string | undefined\n readonly alternates?:\n ReadonlyArray<{ readonly hreflang: string; readonly href: string }> | undefined\n readonly jsonLd?: ReadonlyArray<Readonly<Record<string, unknown>>> | undefined\n}\n\n/** Marks each head element a plan's `meta` wrote, so the browser can replace them. */\nexport const META_ATTRIBUTE = 'data-foldkit-meta'\n\nconst attributeText = (text: string): string =>\n text\n .replaceAll('&', '&')\n .replaceAll('\"', '"')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n\n/** The head markup of a `Meta`, every value escaped, one element per line. */\nexport const metaMarkup = (meta: Meta): string => {\n const tag = (element: string, attributes: ReadonlyArray<readonly [string, string]>) =>\n `<${element} ${META_ATTRIBUTE} ${attributes.map(([name, value]) => `${name}=\"${attributeText(value)}\"`).join(' ')}>`\n const named = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['name', name],\n ['content', value],\n ]),\n ]\n const property = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['property', name],\n ['content', value],\n ]),\n ]\n return [\n ...named('description', meta.description),\n ...property('og:title', meta.title),\n ...property('og:description', meta.description),\n ...property('og:type', meta.type),\n ...property('og:site_name', meta.siteName),\n ...property('og:image', meta.image),\n ...(meta.description === undefined && meta.image === undefined && meta.title === undefined\n ? []\n : named('twitter:card', meta.image === undefined ? 'summary' : 'summary_large_image')),\n ...property('article:published_time', meta.article?.published),\n ...property('article:modified_time', meta.article?.modified),\n ...named('robots', meta.robots),\n ...(meta.alternates ?? []).map(({ hreflang, href }) =>\n tag('link', [\n ['rel', 'alternate'],\n ['hreflang', hreflang],\n ['href', href],\n ]),\n ),\n ...(meta.jsonLd ?? []).map(\n data =>\n `<script ${META_ATTRIBUTE} type=\"application/ld+json\">${serializeJsonScript(data)}</script>`,\n ),\n ].join('\\n')\n}\n\n/**\n * The Subscription entry that keeps the head's `meta` elements in step with\n * the Model, so a move within the page (another post) changes its\n * description too. It writes the head and sends no Message.\n */\nexport const metaEntry = <Model>(meta: (model: Model) => Meta) => ({\n dependenciesSchema: Schema.String,\n modelToDependencies: (model: Model) => metaMarkup(meta(model)),\n dependenciesToStream: (markup: string) =>\n Stream.drain(\n Stream.fromEffect(\n Effect.sync(() => {\n const written = document.createElement('template')\n written.innerHTML = markup\n for (const old of document.head.querySelectorAll(`[${META_ATTRIBUTE}]`)) old.remove()\n document.head.append(written.content)\n }),\n ),\n ),\n})\n\n/**\n * Which part of the Model the browser owns, and what it starts from.\n *\n * `state` is a writable projection of that part, from `Projection.pick` or\n * `Projection.compose`. `baseline` is the Model the browser sets it onto, by\n * default the application's own initial Model. `boot` names the Commands the\n * browser runs on load, since `init` does not run there.\n */\nexport interface ResumePlan<Model, Fields extends Schema.Struct.Fields, Commands = unknown> {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline: Model\n readonly boot?: ((model: Model) => Commands) | undefined\n /** Model paths allowed to start from the baseline, as `ModelRef.dependency` gives them. */\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n /** The Surfaces the browser may activate, which the plan must cover. */\n readonly surfaces: ReadonlyArray<ActiveSurface<Model>>\n /** State another package owns, each captured and restored by that package. */\n readonly parts: ReadonlyArray<ResumePart<Model>>\n /** The application's Message Schema, which encodes the page's bindings. */\n readonly Message?: Schema.Top | undefined\n /**\n * When the browser boots the runtime: `now` on load, `idle` when the browser\n * is idle or on the first interaction, `on-interaction` on the first only.\n * Until then the page answers events from its bindings and queues the\n * Messages, which the runtime runs through `update` before any other.\n */\n readonly start: Start\n /** Subscription and Managed Resource keys that may start late (decision 10). */\n readonly deferrable: ReadonlyArray<string>\n /**\n * `server`: a form whose `OnSubmit` names a Message also posts it to the\n * page's own URL, and `SSR.handle` runs `update` there, so the form works\n * with scripts off or not yet loaded.\n */\n readonly fallback?: 'server' | undefined\n /**\n * What the page says of itself, from the Model: rendered into the head on\n * the server, checked like the view, and kept in step in the browser.\n */\n readonly meta?: ((model: Model) => Meta) | undefined\n /**\n * The data the page was built from, for the browser's freshness check: a\n * Remote cursor, a revision number, anything the check compares. Unset\n * when the page has no age.\n */\n readonly version?: unknown | undefined\n}\n\nexport type Start = 'now' | 'idle' | 'on-interaction'\n\n/**\n * A package's contribution to the envelope, for state the plan's slice cannot\n * carry, such as Remote's normalized store. On the server `capture` takes what\n * the active Surfaces' projections read and returns it as JSON; in the browser\n * `restore` sets it onto the Model, or says why it cannot. A part owns its\n * encoding: this package only carries the value.\n *\n * `covers` names the metadata keys whose reads the part resumes, so the\n * coverage check counts those reads as sent. `Remote.resume(Data)` is one.\n */\nexport interface ResumePart<Model> {\n readonly id: string\n readonly covers: ReadonlyArray<string>\n readonly capture: (\n model: Model,\n projections: ReadonlyArray<{ readonly metadata: Metadata }>,\n ) => unknown\n readonly restore: (model: Model, value: unknown) => Result.Result<Model, string>\n /**\n * Whether a Subscription or Managed Resource entry of this part's package\n * may start late, when a deferred boot is asked for. A part knows its own\n * entries; nothing is deferrable by default.\n */\n readonly deferrable?: ((key: string, entry: unknown) => boolean) | undefined\n}\n\n/** Why a page's resume envelope was refused. */\nexport class ResumeRefused extends Schema.TaggedError<ResumeRefused>()('ResumeRefused', {\n reason: Schema.Literals([\n 'Missing',\n 'Duplicate',\n 'Unreadable',\n 'Protocol',\n 'Plan',\n 'Invalid',\n 'Route',\n ]),\n message: Schema.String,\n}) {}\n\nexport const refuse = (reason: ResumeRefused['reason'], message: string) =>\n Result.fail(new ResumeRefused({ reason, message }))\n\n/**\n * The slice's Schema as a codec needing no services. A resume plan's state is\n * plain data, so any field that needs one cannot cross a page anyway.\n */\nexport const codecOf = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>\n schema as unknown as Schema.Codec<Schema.Struct.Type<Fields>, unknown>\n\n/**\n * A resume plan for an application. The baseline defaults to the\n * application's initial Model. It is never written: a writable projection's\n * `set` returns a new Model, so a baseline Foldkit freezes in development is\n * safe to start from.\n *\n * `surfaces` are the Surfaces the browser may activate, and `local` the Model\n * fields allowed to start from the baseline, such as an open menu. Rendering\n * refuses a plan that leaves a Surface's read or activation in neither.\n */\nexport const plan = <Model, Fields extends Schema.Struct.Fields, Commands = unknown>(\n application: {\n readonly initial: Model\n readonly owner?: object\n readonly Message?: Schema.Top | undefined\n },\n config: {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline?: Model | undefined\n readonly boot?: ((model: Model) => Commands) | undefined\n readonly local?: ReadonlyArray<{ readonly dependency: ReadonlyArray<string> }> | undefined\n readonly surfaces?: ReadonlyArray<ActiveSurface<Model>> | undefined\n readonly parts?: ReadonlyArray<ResumePart<Model>> | undefined\n readonly start?: Start | undefined\n readonly deferrable?: ReadonlyArray<string> | undefined\n readonly fallback?: 'server' | undefined\n readonly meta?: ((model: Model) => Meta) | undefined\n readonly version?: unknown | undefined\n },\n): ResumePlan<Model, Fields, Commands> => {\n const surfaces = config.surfaces ?? []\n const parts = config.parts ?? []\n const repeated = parts.find((part, index) => parts.findIndex(p => p.id === part.id) !== index)\n if (repeated !== undefined) {\n throw new Error(\n `SSR.plan: two parts of plan \"${config.id}\" share the id \"${repeated.id}\"; give one an id of its own`,\n )\n }\n const foreign = surfaces.find(\n surface => application.owner !== undefined && surface.owner !== application.owner,\n )\n if (foreign !== undefined) {\n throw new Error(\n `SSR.plan: the Surface \"${foreign.name}\" belongs to another application than plan \"${config.id}\"`,\n )\n }\n return {\n id: config.id,\n state: config.state,\n baseline: config.baseline ?? application.initial,\n ...(config.boot === undefined ? {} : { boot: config.boot }),\n local: (config.local ?? []).map(place => place.dependency),\n surfaces,\n parts,\n ...(application.Message === undefined ? {} : { Message: application.Message }),\n start: config.start ?? 'now',\n deferrable: config.deferrable ?? [],\n ...(config.fallback === undefined ? {} : { fallback: config.fallback }),\n ...(config.meta === undefined ? {} : { meta: config.meta }),\n ...(config.version === undefined ? {} : { version: config.version }),\n }\n}\n\n/**\n * How a page's recorded route is compared with the browser's. `full` compares\n * path and query. `path` compares the path alone, ignoring a trailing slash or\n * `index.html`, for a page generated as a file: a static host serves one file\n * for every query, and for `/about` and `/about/` alike.\n */\nexport type RouteMatch = 'full' | 'path'\n\n/** A path as a `path` match compares it. */\nexport const pathKey = (route: string): string => {\n const path = route.split(/[?#]/)[0] ?? ''\n const trimmed = path.replace(/\\/index\\.html$/, '/').replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n/**\n * The Model a payload resumes: the baseline with the slice set onto it, then\n * each part restored, in order. Every part the plan names must be there and\n * restore, and no other may be: a page is never half-restored.\n */\nexport const modelFrom = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: { readonly state: unknown; readonly parts?: unknown },\n): Result.Result<Model, string> => {\n const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state)\n if (Result.isFailure(decoded)) {\n return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`)\n }\n const given = payload.parts ?? {}\n if (typeof given !== 'object' || Array.isArray(given)) {\n return Result.fail(\"the envelope's parts are not an object of parts by id\")\n }\n const parts = given as Readonly<Record<string, unknown>>\n const unknown = Object.keys(parts).find(id => !plan.parts.some(part => part.id === id))\n if (unknown !== undefined) {\n return Result.fail(`the envelope carries a part \"${unknown}\" the plan does not name`)\n }\n let model = plan.state.set(plan.baseline, decoded.success)\n for (const part of plan.parts) {\n if (!Object.hasOwn(parts, part.id))\n return Result.fail(`the envelope carries no \"${part.id}\" part`)\n const restored = part.restore(model, parts[part.id])\n if (Result.isFailure(restored)) {\n return Result.fail(`the \"${part.id}\" part does not restore: ${restored.failure}`)\n }\n model = restored.success\n }\n return Result.succeed(model)\n}\n\n/** The page's envelope, read off its stamped root; refused when there is no root, more than one, no envelope, or not JSON. */\nconst readEnvelope = (\n page: ParentNode,\n): Result.Result<Readonly<Record<string, unknown>>, ResumeRefused> => {\n const roots = page.querySelectorAll(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (roots.length === 0) return refuse('Missing', 'the page holds no stamped application root')\n if (roots.length > 1) {\n return refuse('Duplicate', `the page holds ${roots.length} stamped application roots`)\n }\n const carried = roots[0]?.getAttribute(RESUME_ATTRIBUTE)\n if (carried === null || carried === undefined) {\n return refuse('Missing', 'the page holds no resume envelope')\n }\n try {\n const parsed: unknown = JSON.parse(carried)\n return Result.succeed((parsed ?? {}) as Readonly<Record<string, unknown>>)\n } catch (error) {\n return refuse('Unreadable', `the resume envelope is not JSON: ${String(error)}`)\n }\n}\n\n/**\n * The Model a page resumes from: the baseline with the stamped root's envelope\n * set onto it. Refused, with the reason, when the page holds no stamped root\n * or more than one, when the root carries no envelope or not JSON, when it is\n * not this protocol or this plan, or when the slice does not decode through\n * the plan's Schema. A page is never half-restored.\n */\nexport const resume = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n options: { readonly route?: string | undefined } = {},\n): Result.Result<Model, ResumeRefused> => {\n const read = readEnvelope(page)\n if (Result.isFailure(read)) return Result.fail(read.failure)\n const parsed = read.success\n const { v, plan: id, state, parts, route, match } = parsed\n if (v !== PROTOCOL) {\n return refuse('Protocol', `the envelope is protocol ${String(v)}, not ${PROTOCOL}`)\n }\n if (id !== plan.id) {\n return refuse('Plan', `the envelope is for plan \"${String(id)}\", not \"${plan.id}\"`)\n }\n // The route the Model was made for. The runtime never reports the URL at\n // boot, so a page resumed on another route would show one and be on the\n // other.\n if (route !== undefined && options.route !== undefined) {\n const matches =\n match === 'path' ? pathKey(String(route)) === pathKey(options.route) : route === options.route\n if (!matches) {\n return refuse(\n 'Route',\n `the page was ${match === 'path' ? 'generated' : 'rendered'} for ${String(route)}, not ${options.route}`,\n )\n }\n }\n const resumed = modelFrom(plan, { state, parts })\n return Result.isFailure(resumed)\n ? refuse('Invalid', resumed.failure)\n : Result.succeed(resumed.success)\n}\n\n/** The tag a Message value carries, for naming it. */\nexport const tagOf = (message: unknown): string =>\n typeof message === 'object' &&\n message !== null &&\n '_tag' in message &&\n typeof message._tag === 'string'\n ? message._tag\n : 'an untagged Message'\n\n/**\n * The Message tags the plan's Surfaces active for `model` may send, which is\n * what a page's bindings may dispatch (the design's rule 3).\n */\nexport const allowedTags = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlySet<string> =>\n new Set(\n plan.surfaces.flatMap(surface =>\n Option.isSome(surface.projectionOf(model)) ? surface.messages : [],\n ),\n )\n\n/** The attribute on a static region's element, naming the region. */\nexport const STATIC_ATTRIBUTE = 'data-foldkit-plus-static'\n\nconst boundary = (id: string, trusted: string | undefined, children: Region): Html =>\n inertHtml.div(\n [\n inertHtml.Attribute(STATIC_ATTRIBUTE, id),\n ...(trusted === undefined ? [] : [inertHtml.InnerHTML(trusted)]),\n ],\n children,\n )\n\n/**\n * A region of the page the server owns for the life of the document. It is\n * rendered on the server with the inert builder, so it can dispatch no\n * Message. The browser adopts the server's markup as trusted `InnerHTML` and\n * never runs `render`, so the region reads nothing from the browser's Model\n * and a plan need not send what it reads.\n *\n * A region changes only with a new document. Content a Message should change\n * belongs in a Surface, not here.\n */\nexport const staticRegion = (id: string, render: (ih: HtmlBuilder<never>) => Region): Html => {\n const now = current()\n if (now?.mode === 'resume') {\n const snapshot = now.snapshots.get(id)\n if (snapshot !== undefined) return boundary(id, snapshot, [])\n if (!now.reported.has(id)) {\n now.reported.add(id)\n console.error(\n `[foldkit-ssr] the static region \"${id}\" is not in the server's page, so it is rendered in the browser`,\n )\n }\n return boundary(id, undefined, render(inertHtml))\n }\n const replayed = now?.mode === 'replay' ? now.regions.get(id) : undefined\n if (replayed !== undefined) return boundary(id, undefined, replayed)\n if (now?.mode !== 'collect') return boundary(id, undefined, render(inertHtml))\n const outer = now.region\n now.region = id\n try {\n const children = render(inertHtml)\n if (now.regions.has(id)) now.duplicates.add(id)\n else now.regions.set(id, children)\n return boundary(id, undefined, children)\n } finally {\n now.region = outer\n }\n}\n\n/**\n * Whether the view call in progress is the server rendering a page, rather than the browser: true\n * through both of `render`'s passes, false while the browser resumes and outside any render. For a\n * view that sends markup it will adopt in the browser rather than draw there, such as\n * `foldkit-richtext-dom`'s editor host, whose placement takes this as `serverRendered`.\n */\nexport const serving = (): boolean => {\n const mode = current()?.mode\n return mode === 'collect' || mode === 'replay'\n}\n\n/**\n * The `makeApplication` options `SSR` hands to Foldkit as they are, typed as\n * Foldkit types them.\n */\ntype ApplicationOptions<Model, Message> = Partial<\n Pick<\n Runtime.RoutingApplicationConfig<Model, Message, never, never, Ports | undefined>,\n | 'routing'\n | 'ports'\n | 'crash'\n | 'slow'\n | 'viewTransition'\n | 'freezeModel'\n | 'preserveScroll'\n | 'devTools'\n >\n>\n\n/**\n * The part of a Foldkit application config a server render and a resumed\n * client need. The full `makeApplication` config fits, whichever of its four\n * shapes, and its callbacks (`routing`'s, say) are typed from `update`'s\n * Message as Foldkit types them.\n */\nexport interface ResumableConfig<Model, Message = any> extends ApplicationOptions<Model, Message> {\n readonly Model: Schema.Codec<Model, any, unknown, unknown>\n readonly init: (...args: ReadonlyArray<any>) => {\n readonly model: Model\n readonly commands?: ReadonlyArray<{ readonly name: string }> | undefined\n }\n readonly update: (model: Model, message: Message) => { readonly model: Model }\n readonly view: (model: Model, h: any) => unknown\n readonly container: HTMLElement | null\n readonly Flags?: unknown\n readonly subscriptions?: Readonly<Record<string, unknown>> | undefined\n readonly managedResources?: Readonly<Record<string, unknown>> | undefined\n /** The services Commands need, as Foldkit's runtime provides them. */\n readonly resources?: Layer.Layer<never, never, never> | undefined\n /**\n * Bundles whose bodies load on demand (`Bundle.lazy`). The server loads\n * them before it renders; the browser loads them before it boots, answering\n * from the markers meanwhile, so a page never shows a bundle's placeholder.\n */\n readonly lazy?: ReadonlyArray<Loadable> | undefined\n}\n\n/** What `SSR` needs of a lazy bundle: `Bundle.lazy` gives it. */\nexport interface Loadable {\n readonly name: string\n readonly load: () => Promise<void>\n readonly isLoaded: () => boolean\n}\n\n/**\n * The config without a `Flags` key at all. Deleted, never set to `undefined`:\n * Foldkit's server asks whether `Flags` is defined and its client whether the\n * key exists, so an `undefined` one renders and is then refused.\n */\nconst withoutFlags = <Config extends { readonly Flags?: unknown }>(config: Config) => {\n const { Flags: _flags, ...rest } = config\n return rest\n}\n\n/** The config whose `init` returns this start, whatever arguments it is given. */\nexport const startingFrom = <Model>(\n config: ResumableConfig<Model>,\n start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> },\n) => ({ ...withoutFlags(config), init: () => start })\n\n/** A route as the envelope records it: the path and the query. */\nexport const routeOf = (url: string): string => {\n const parsed = new URL(url, 'http://localhost')\n return `${parsed.pathname}${parsed.search}`\n}\n\n/**\n * The page's bindings, decoded through the plan's Message Schema, kept to the\n * Messages the Surfaces active for `model` may send, and checked against\n * every marker in `root`. Refused, with the reason, when the page carries\n * none, an entry is not one of the application's Messages or one no active\n * Surface lists, or a marker names a binding the page does not carry: a page\n * is answered whole or not at all.\n */\nexport const bindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<ReadonlyArray<DecodedBinding>, ResumeRefused> =>\n Result.map(bindingsAndEvents(plan, page, root, model), read => read.bindings)\n\nconst EnvelopeEvents = Schema.optional(Schema.Array(Schema.String))\n\n/**\n * `bindings`, and the events the envelope says the markers name, if it says:\n * a page from before the envelope listed them leaves `listen` to find them.\n */\nexport const bindingsAndEvents = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<\n {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n ResumeRefused\n> => {\n const parsed = readEnvelope(page)\n if (Result.isFailure(parsed)) return Result.fail(parsed.failure)\n const read = readBindings(parsed.success.bindings ?? [])\n if (Result.isFailure(read)) {\n return refuse('Invalid', `the page's bindings are malformed: ${read.failure}`)\n }\n const encoded = read.success\n if (encoded.length > 0 && plan.surfaces.length === 0) {\n return refuse(\n 'Invalid',\n 'the page has bindings and the plan declares no surfaces to allow them',\n )\n }\n const events = Schema.decodeUnknownResult(EnvelopeEvents)(parsed.success.events)\n if (Result.isFailure(events)) {\n return refuse('Invalid', `the page's events are malformed: ${events.failure.message}`)\n }\n const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model))\n return Result.isFailure(decoded)\n ? refuse('Invalid', decoded.failure)\n : Result.succeed({ bindings: decoded.success, events: events.success })\n}\n","/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { withContext, type RenderContext } from './context.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport { builder, view } from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is logged. A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n },\n): void => {\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n if (options.otherwise === 'render')\n run(makeApplication({ ...config, container: root } as never))\n else contain()\n return\n }\n if (root.getAttribute(BUILD_ATTRIBUTE) !== options.buildId) {\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n console.error(`[foldkit-ssr] the page cannot resume: ${resumed.failure.message}`)\n contain()\n return\n }\n const model = resumed.success\n const commands = (plan.boot?.(model) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n const boot = (entries: Readonly<Record<string, unknown>> = {}) =>\n adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, { model, commands }), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n if (plan.start === 'now' && pending.length === 0) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n console.error(`[foldkit-ssr] the page cannot resume: ${decoded.failure.message}`)\n contain()\n return\n }\n deferBoot(root, decoded.success, plan.start, { boot, answered }, pending)\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n const stop = listen(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n console.error(`[foldkit-ssr] a bundle's bodies did not load: ${String(error)}`)\n commit()\n })\n }\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n"],"mappings":";;;;;AAiFA,IAAI;;AAGJ,MAAa,gBAA2C;AAExD,MAAa,UAAa,MAAqB,QAAoB;CACjE,MAA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,MAAM,MAAM,KAAK,CAAC;EACnD;CACF;CACA,MAAM,eAAe;EACnB,QAAQ;EACR,QAAQ,KAAK,EACX,wBAAwB;GACtB,oBAAoB,OAAO;GAC3B,2BAA2B;GAG3B,4BACE,OAAO,WACL,OAAO,GACL,OAAO,QACL,KAAK,aAAA,kBAAkC,IAAI,OAAO,cAAc,OAAO,MACvE,OAAO,KAAK,QAAQ,CACtB,GACA,QACF,CACF;EACJ,EACF,CAAC;EACD,IAAI,CAAC,KAAK,aAAA,kBAAkC,GAAG,SAAS;CAC1D;CACA,MAAM,iBAAiB;EACrB,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,IAAI,QAAQ,WAAW,GAAG;GACxB,OAAO;GACP;EACF;EACA,QAAa,IAAI,QAAQ,KAAI,WAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,UAAmB;GACtF,QAAQ,MAAM,iDAAiD,OAAO,KAAK,GAAG;GAC9E,OAAO;EACT,CAAC;CACH;CACA,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;AAAQ"}
|
|
1
|
+
{"version":3,"file":"client-ASzkY6Sw.mjs","names":["tagOf","hydrate","adopt"],"sources":["../src/context.ts","../src/resumable.ts","../src/listen.ts","../src/shared.ts","../src/client.ts"],"sourcesContent":["/**\n * The render context: what the page's server-owned parts do, set around one\n * synchronous call of the view. `SSR.static` reads it to decide whether a\n * region renders, replays, or adopts the server's markup, and the resumable\n * builder reads it to decide whether to mark the bindings it builds. With no\n * context, as in a client-only render, both behave as ordinary view code.\n *\n * - `collect`: the server's render. Each region runs once and is kept, and\n * each binding is recorded in render order.\n * - `replay`: the server's second render, from the browser's Model. Each\n * region is the one already rendered, so it never reads the browser's Model;\n * bindings are recorded again, to be compared with the first render's.\n * - `resume`: the browser. Each region is the markup the server left in the\n * page, and its render never runs; no binding is marked.\n */\nimport type { Html } from 'foldkit/html'\n\nexport type Region = ReadonlyArray<Html | string>\n\n/** An element whose handler for `event` is a function, which the page cannot describe. */\nexport interface UnnamedHandler {\n readonly element: string\n readonly event: string\n}\n\n/**\n * An element's binding as the server's render records it, before encoding:\n * the Foldkit attribute and its DOM event, the element for diagnostics, and\n * the Message it causes. For a Message with a hole, `message` is the Message\n * with the hole filled by a placeholder, and `hole` names the fields the event\n * fills.\n */\nexport interface Binding {\n /** Foldkit's attribute, whose tag says what the handler does beside dispatching. */\n readonly attribute: string\n readonly event: string\n readonly element: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n /** How many placement wrappers enclose the hole's fields: `message` is entered that many times. */\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\nexport type RenderContext =\n | {\n readonly mode: 'collect'\n readonly regions: Map<string, Region>\n readonly duplicates: Set<string>\n readonly bindings: Array<Binding>\n /** Encodes a form's Message for its no-script fallback; absent when the plan has none. */\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n /** Lifts a Message of the view in progress to the application's, through each enclosing placement. */\n wrap: (message: unknown) => unknown\n /** How many placements enclose the view in progress. */\n depth: number\n /** The static region whose render is in progress, if any. */\n region: string | undefined\n /** Handlers met inside a static region, which the server alone renders. */\n readonly inStatic: Array<{\n readonly region: string\n readonly element: string\n readonly event: string\n }>\n /** Each element and event marked `*`: a handler the page cannot name. */\n readonly unnamed: Array<UnnamedHandler>\n }\n | {\n readonly mode: 'replay'\n readonly regions: ReadonlyMap<string, Region>\n readonly bindings: Array<Binding>\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n wrap: (message: unknown) => unknown\n depth: number\n }\n | {\n readonly mode: 'resume'\n readonly snapshots: ReadonlyMap<string, string>\n readonly reported: Set<string>\n }\n\nlet context: RenderContext | undefined\n\n/** The context of the view call in progress, if any. */\nexport const current = (): RenderContext | undefined => context\n\nexport const within = <A>(next: RenderContext, run: () => A): A => {\n const previous = context\n context = next\n try {\n return run()\n } finally {\n context = previous\n }\n}\n\n/** The config whose view runs inside `next`. */\nexport const withContext = <Config extends { readonly view: (model: any, h: any) => unknown }>(\n config: Config,\n next: RenderContext,\n): Config => ({\n ...config,\n view: (model: unknown, h: unknown) => within(next, () => config.view(model, h)),\n})\n","/**\n * The resumable builder: the application's `h`, whose event attributes say, in\n * the server's markup, which Message each element causes.\n *\n * A Foldkit handler is a Message value (`h.OnClick(Message.Liked({ id }))`), so\n * for most events that is already data. The events that carry a value\n * (`OnInput`, `OnChange`, `OnKeyDown`, `OnKeyUp`) take a closure only to put\n * the value into a Message field; this builder also takes the Message's own\n * constructor there, a Message with a hole, and fills the hole the same way.\n *\n * During the server's renders each binding gets an ordinal, recorded in render\n * order, and its element a `data-foldkit-plus-on-<event>` attribute naming it.\n * In the browser the builder marks nothing: it is the application's `h`, with\n * the hole forms turned into the closures Foldkit expects.\n */\nimport { Schema, SchemaAST } from 'effect'\nimport type { Attribute, ChildAttribute, HtmlBuilder, KeyboardModifiers } from 'foldkit/html'\nimport { current, type Binding } from './context.js'\n\n/** The attribute prefix of an element's binding marker. */\nexport const BINDING_ATTRIBUTE = 'data-foldkit-plus-on-'\n\n/**\n * The DOM event each of Foldkit's event attributes listens to, read from\n * Foldkit's own attribute table (0.163). `OnCustomEvent` names its event in\n * its payload, and `OnMount` and `OnUnmount` listen to none.\n */\nexport const EVENT_OF: Readonly<Record<string, string>> = {\n OnClick: 'click',\n OnDoubleClick: 'dblclick',\n OnMouseDown: 'mousedown',\n OnMouseUp: 'mouseup',\n OnMouseEnter: 'mouseenter',\n OnMouseLeave: 'mouseleave',\n OnMouseOver: 'mouseover',\n OnMouseOut: 'mouseout',\n OnMouseMove: 'mousemove',\n OnPointerMove: 'pointermove',\n OnPointerLeave: 'pointerleave',\n OnPointerDown: 'pointerdown',\n OnPointerUp: 'pointerup',\n OnKeyDown: 'keydown',\n OnKeyDownPreventDefault: 'keydown',\n OnKeyDownSelf: 'keydown',\n OnKeyDownSelfPreventDefault: 'keydown',\n OnKeyDownFocus: 'keydown',\n OnKeyUp: 'keyup',\n OnKeyUpPreventDefault: 'keyup',\n OnKeyPress: 'keypress',\n OnFocus: 'focus',\n OnBlur: 'blur',\n OnFocusEnter: 'focusin',\n OnFocusLeave: 'focusout',\n OnInput: 'input',\n OnChange: 'change',\n OnBeforeInput: 'beforeinput',\n OnBeforeInputPreventDefault: 'beforeinput',\n OnFileChange: 'change',\n OnSubmit: 'submit',\n OnReset: 'reset',\n OnScroll: 'scroll',\n OnWheel: 'wheel',\n OnCopy: 'copy',\n OnCut: 'cut',\n OnPaste: 'paste',\n OnPastePreventDefault: 'paste',\n OnCopyText: 'copy',\n OnCutText: 'cut',\n OnCancel: 'cancel',\n OnCancelPreventDefault: 'cancel',\n OnToggle: 'toggle',\n OnContextMenu: 'contextmenu',\n OnDragStart: 'dragstart',\n OnDrag: 'drag',\n OnDragEnd: 'dragend',\n OnDragEnter: 'dragenter',\n OnDragLeave: 'dragleave',\n OnDragOver: 'dragover',\n OnDrop: 'drop',\n OnDropFiles: 'drop',\n OnTouchStart: 'touchstart',\n OnTouchEnd: 'touchend',\n OnTouchMove: 'touchmove',\n OnTouchCancel: 'touchcancel',\n OnAnimationStart: 'animationstart',\n OnAnimationEnd: 'animationend',\n OnAnimationIteration: 'animationiteration',\n OnTransitionEnd: 'transitionend',\n OnLoad: 'load',\n OnError: 'error',\n OnPlay: 'play',\n OnPause: 'pause',\n OnEnded: 'ended',\n OnTimeUpdate: 'timeupdate',\n OnVolumeChange: 'volumechange',\n OnSelect: 'select',\n}\n\n/**\n * The attributes whose binding the page can describe: a Message value, or one\n * of the hole forms this builder records. Any other handler still runs on the\n * live page, so its event is marked `*`: the page does something there it\n * cannot name, and a dispatcher that ran only the named bindings would do less.\n */\nconst MARKABLE: ReadonlySet<string> = new Set([\n 'OnClick',\n 'OnDoubleClick',\n 'OnMouseDown',\n 'OnMouseUp',\n 'OnMouseEnter',\n 'OnMouseLeave',\n 'OnMouseOver',\n 'OnMouseOut',\n 'OnMouseMove',\n 'OnFocus',\n 'OnBlur',\n 'OnSubmit',\n 'OnReset',\n 'OnInput',\n 'OnChange',\n 'OnKeyDown',\n 'OnKeyUp',\n])\n\n/** The token in a marker for a handler the page cannot describe. */\nexport const UNNAMED_HANDLER = '*'\n\n/** The posted field that carries a form's encoded Message, for the server fallback. */\nexport const FALLBACK_FIELD = 'foldkit-plus-message'\n\n/** The posted field that says how many placement wrappers the form's fields sit under. */\nexport const FALLBACK_DEPTH_FIELD = 'foldkit-plus-depth'\n\n/** The attribute on a placement's root naming its slot, while the server renders. */\nexport const SLOT_ATTRIBUTE = 'data-foldkit-plus-slot'\n\ndeclare const invalid: unique symbol\n\n/** A compile-time failure that names its cause. */\nexport interface Invalid<Message extends string> {\n readonly [invalid]: Message\n}\n\ntype IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never\n\n/** A Message constructor from `defineMessageUnion`: a tagged Schema that can be called. */\ntype AnyMemberSchema = Schema.Top & { readonly fields: Schema.Struct.Fields }\n\n/** The Message a member makes. */\ntype Made<M> = M extends { readonly Type: infer T } ? T : never\n\n/** The fields a member's event may be given fixed: all but `_tag`. */\ntype Fixable<M> = Partial<Omit<Made<M>, '_tag'>>\n\n/** The fields of a member the event fills: those neither `_tag` nor fixed. */\ntype Rest<M, Fixed> = Omit<Made<M>, '_tag' | keyof Fixed>\n\ntype ProducesMessage<M, Message> = [Made<M>] extends [Message]\n ? unknown\n : Invalid<\"the member is not one of this view's Messages\">\n\ntype TextHoleCheck<M, Fixed> = [keyof Rest<M, Fixed>] extends [never]\n ? Invalid<'the member has no field left for the event to fill'>\n : true extends IsUnion<keyof Rest<M, Fixed>>\n ? Invalid<'the member leaves more than one field for the event to fill: fix the others'>\n : Rest<M, Fixed>[keyof Rest<M, Fixed>] extends string\n ? string extends Rest<M, Fixed>[keyof Rest<M, Fixed>]\n ? unknown\n : Invalid<'the field the event fills must be a string'>\n : Invalid<'the field the event fills must be a string'>\n\ntype KeyHoleCheck<M, Fixed> = [keyof Rest<M, Fixed>] extends ['key' | 'modifiers']\n ? ['key' | 'modifiers'] extends [keyof Rest<M, Fixed>]\n ? unknown\n : Invalid<'the member must leave exactly key and modifiers for the event to fill'>\n : Invalid<'the member must leave exactly key and modifiers for the event to fill'>\n\n/** `OnInput` and `OnChange`: a closure, or a member whose one string field the event fills. */\nexport interface TextHole<Message> {\n (toMessage: (value: string) => Message): Attribute<Message>\n <M extends AnyMemberSchema, const Fixed extends Fixable<M> = {}>(\n member: M & ProducesMessage<M, Message> & TextHoleCheck<M, Fixed>,\n fixed?: Fixed,\n ): Attribute<Message>\n}\n\n/** `OnKeyDown` and `OnKeyUp`: a closure, or a member whose `key` and `modifiers` the event fills. */\nexport interface KeyHole<Message> {\n (toMessage: (key: string, modifiers: KeyboardModifiers) => Message): Attribute<Message>\n <M extends AnyMemberSchema, const Fixed extends Fixable<M> = {}>(\n member: M & ProducesMessage<M, Message> & KeyHoleCheck<M, Fixed>,\n fixed?: Fixed,\n ): Attribute<Message>\n}\n\n/**\n * A builder a view is given: Foldkit's `HtmlBuilder`, or a Surface renderer's,\n * which leaves out Foldkit's phantom key. Its Message is what `OnClick` takes.\n */\nexport type AnyBuilder = {\n readonly OnClick: (message: never, ...rest: ReadonlyArray<never>) => unknown\n}\n\n/** The Message a builder's handlers make. */\nexport type MessageOf<Builder> = Builder extends {\n readonly OnClick: (message: infer Message, ...rest: ReadonlyArray<never>) => unknown\n}\n ? Message\n : never\n\n/**\n * The resumable builder for a view whose Messages are `Message`: its elements\n * and attributes, and the hole forms of the four value events. One shape\n * whether it wraps a view's `HtmlBuilder` or a Surface renderer's builder, so a\n * helper typed with it takes either. It keeps Foldkit's phantom Message key,\n * so a placement's view accepts it as the parent's builder.\n */\nexport type ResumableBuilder<Message> = Omit<\n HtmlBuilder<Message>,\n 'OnInput' | 'OnChange' | 'OnKeyDown' | 'OnKeyUp'\n> & {\n readonly OnInput: TextHole<Message>\n readonly OnChange: TextHole<Message>\n readonly OnKeyDown: KeyHole<Message>\n readonly OnKeyUp: KeyHole<Message>\n}\n\ntype AnyMember = ((value: Record<string, unknown>) => unknown) & {\n readonly fields: Readonly<Record<string, unknown>>\n}\n\nconst isMember = (value: unknown): value is AnyMember =>\n typeof value === 'function' && typeof (value as { fields?: unknown }).fields === 'object'\n\nconst tagOf = (member: AnyMember): string => {\n const tag = member.fields._tag\n return Schema.isSchema(tag) && SchemaAST.isLiteral(tag.ast) && typeof tag.ast.literal === 'string'\n ? tag.ast.literal\n : 'the member'\n}\n\n/** The fields a member leaves for the event to fill, given what is fixed. */\nconst holeOf = (member: AnyMember, fixed: object): ReadonlyArray<string> =>\n Object.keys(member.fields).filter(field => field !== '_tag' && !(field in fixed))\n\nconst NO_MODIFIERS: KeyboardModifiers = {\n shiftKey: false,\n ctrlKey: false,\n altKey: false,\n metaKey: false,\n}\n\n/** Each hole-form attribute, with its Message filled by a placeholder and the fields the event fills. */\nconst holes = new WeakMap<\n object,\n { readonly template: unknown; readonly hole: ReadonlyArray<string> }\n>()\n\n/** What an element is given: Foldkit's attributes, and a Submodel's wrapped ones, which carry no tag. */\ntype Item = Attribute<unknown> | ChildAttribute\n\nconst isAttribute = (item: Item): item is Attribute<unknown> => '_tag' in item\n\nconst builders = new WeakMap<object, unknown>()\n\n/** A hole form's placeholder Message, or `undefined` when its field's checks refuse one. */\nconst placeholder = (make: () => unknown): unknown => {\n try {\n return make()\n } catch {\n return undefined\n }\n}\n\n/**\n * The resumable builder for a view's `h`. Use it in place of `h`; it has the\n * same elements and attributes, and the hole forms of the four value events.\n */\nexport const builder = <Builder extends AnyBuilder>(\n h: Builder,\n): ResumableBuilder<MessageOf<Builder>> => {\n const cached = builders.get(h)\n if (cached !== undefined) return cached as ResumableBuilder<MessageOf<Builder>>\n const source = h as unknown as Record<string, unknown>\n const attribute = source.Attribute as (name: string, value: string) => unknown\n\n /** The attributes with a marker for each binding, while the server renders. */\n const mark = (tag: string, attributes: ReadonlyArray<Item>): ReadonlyArray<unknown> => {\n const now = current()\n if (now?.mode !== 'collect' && now?.mode !== 'replay') return attributes\n const id = attributes.find(\n (item): item is Extract<Attribute<unknown>, { readonly _tag: 'Id' }> =>\n isAttribute(item) && item._tag === 'Id',\n )\n const element = id === undefined ? tag : `${tag}#${id.value}`\n // Foldkit chains every handler of an event, in the order the attributes\n // come, so a marker lists every binding of its event in that order.\n const tokens = new Map<string, Array<string>>()\n for (const item of attributes) {\n if (!isAttribute(item)) continue\n const event = item._tag === 'OnCustomEvent' ? item.name : EVENT_OF[item._tag]\n if (event === undefined) continue\n // Recorded for the refusal; the render does not survive it.\n if (now.mode === 'collect' && now.region !== undefined) {\n now.inStatic.push({ region: now.region, element, event })\n }\n const recorded = holes.get(item)\n const nested = now.depth === 0 ? {} : { depth: now.depth }\n const binding: Binding | undefined = !MARKABLE.has(item._tag)\n ? undefined\n : 'message' in item\n ? {\n attribute: item._tag,\n event,\n element,\n message: now.wrap(item.message),\n ...('options' in item && item.options !== undefined ? { options: item.options } : {}),\n }\n : recorded === undefined\n ? undefined\n : {\n attribute: item._tag,\n event,\n element,\n message: now.wrap(recorded.template),\n hole: recorded.hole,\n ...nested,\n }\n const list = tokens.get(event) ?? []\n tokens.set(event, list)\n if (binding === undefined) {\n // One entry per element and event, however many handlers it chains.\n if (now.mode === 'collect' && !list.includes(UNNAMED_HANDLER)) {\n now.unnamed.push({ element, event })\n }\n list.push(UNNAMED_HANDLER)\n } else {\n list.push(String(now.bindings.length))\n now.bindings.push(binding)\n }\n }\n if (tokens.size === 0) return attributes\n const markers = [...tokens].map(([event, list]) =>\n attribute(`${BINDING_ATTRIBUTE}${event}`, list.join(' ')),\n )\n return [...attributes, ...markers]\n }\n\n /**\n * A form whose `OnSubmit` names a Message, while the server renders for a\n * plan with a fallback, also posts that Message: `method=\"post\"` to its own\n * URL, and a hidden input carrying the Message encoded. Posted fields named\n * as the Message's own fields override them, so a typed title reaches\n * `update` as it would through the page.\n */\n const fallback = (\n tag: string,\n attributes: ReadonlyArray<Item>,\n children: unknown,\n ): { readonly attributes: ReadonlyArray<Item>; readonly children: unknown } => {\n const now = current()\n if (\n tag !== 'form' ||\n now?.mode === undefined ||\n now.mode === 'resume' ||\n now.fallback === undefined\n ) {\n return { attributes, children }\n }\n const submit = attributes.find(\n (item): item is Extract<Attribute<unknown>, { readonly _tag: 'OnSubmit' }> =>\n isAttribute(item) && item._tag === 'OnSubmit',\n )\n if (submit === undefined || !Array.isArray(children)) return { attributes, children }\n const encoded = now.fallback(now.wrap(submit.message))\n if (encoded === undefined) return { attributes, children }\n const make = (name: string) => source[name] as (value: string) => Attribute<unknown>\n const input = source.input as (attributes: ReadonlyArray<unknown>) => unknown\n const hidden = (name: string, value: string) =>\n input([make('Type')('hidden'), make('Name')(name), make('Value')(value)])\n return {\n attributes: [...attributes, make('Method')('post')],\n children: [\n ...children,\n hidden(FALLBACK_FIELD, encoded),\n ...(now.depth === 0 ? [] : [hidden(FALLBACK_DEPTH_FIELD, String(now.depth))]),\n ],\n }\n }\n\n const textHole =\n (name: string) =>\n (given: unknown, fixed: Record<string, unknown> = {}): unknown => {\n const make = source[name] as (toMessage: (value: string) => unknown) => object\n if (!isMember(given)) return make(given as (value: string) => unknown)\n const hole = holeOf(given, fixed)\n if (hole.length !== 1) {\n throw new Error(\n `Resume.builder: ${name}(${tagOf(given)}) leaves ${hole.length === 0 ? 'no field' : hole.join(', ')} for the event to fill; it must leave one string field`,\n )\n }\n const [field] = hole as [string]\n const made = make(value => given({ ...fixed, [field]: value }))\n const template = placeholder(() => given({ ...fixed, [field]: '' }))\n // A field whose checks refuse the empty placeholder cannot be written\n // into the page as data; left unrecorded, the handler is marked as one\n // the page cannot name, and the live page answers it.\n if (template !== undefined) holes.set(made, { template, hole })\n return made\n }\n\n const keyHole =\n (name: string) =>\n (given: unknown, fixed: Record<string, unknown> = {}): unknown => {\n const make = source[name] as (\n toMessage: (key: string, modifiers: KeyboardModifiers) => unknown,\n ) => object\n if (!isMember(given)) {\n return make(given as (key: string, modifiers: KeyboardModifiers) => unknown)\n }\n const hole = holeOf(given, fixed)\n if (hole.length !== 2 || !hole.includes('key') || !hole.includes('modifiers')) {\n throw new Error(\n `Resume.builder: ${name}(${tagOf(given)}) leaves ${hole.join(', ') || 'no field'} for the event to fill; it must leave exactly key and modifiers`,\n )\n }\n const made = make((key, modifiers) => given({ ...fixed, key, modifiers }))\n const template = placeholder(() => given({ ...fixed, key: '', modifiers: NO_MODIFIERS }))\n if (template !== undefined) holes.set(made, { template, hole })\n return made\n }\n\n /**\n * `h.submodel` with the child's root stamped with its slot, while the\n * server renders: a boundary a tool can find, which the browser's first\n * patch removes as it removes the markers.\n */\n const submodel = (config: {\n readonly slotId: string\n readonly view: unknown\n readonly toParentMessage: (message: unknown) => unknown\n }): unknown => {\n const original = source.submodel as (config: unknown) => unknown\n const now = current()\n if (now?.mode !== 'collect' && now?.mode !== 'replay') return original(config)\n const view = config.view as (...args: ReadonlyArray<unknown>) => unknown\n const stamped = (...args: ReadonlyArray<unknown>) => {\n // A binding inside dispatches the parent's Message, as Foldkit's own\n // handlers do, so it is recorded lifted through this placement.\n const outer = { wrap: now.wrap, depth: now.depth }\n now.wrap = message => outer.wrap(config.toParentMessage(message))\n now.depth = outer.depth + 1\n let out: { data?: { attrs?: Record<string, unknown> } } | null\n try {\n out = view(...args) as typeof out\n } finally {\n now.wrap = outer.wrap\n now.depth = outer.depth\n }\n if (out !== null && typeof out === 'object' && out.data !== undefined) {\n out.data.attrs = { ...out.data.attrs, [SLOT_ATTRIBUTE]: config.slotId }\n }\n return out\n }\n // The view carries Foldkit's Submodel brand as an own property; keep it.\n return original({ ...config, view: Object.assign(stamped, view) })\n }\n\n const wrapped: Record<string, unknown> = {}\n for (const [name, value] of Object.entries(source)) {\n if (name === 'submodel') wrapped[name] = submodel\n else if (name === 'OnInput' || name === 'OnChange') wrapped[name] = textHole(name)\n else if (name === 'OnKeyDown' || name === 'OnKeyUp') wrapped[name] = keyHole(name)\n else if (name === 'keyed') {\n const keyed = value as (tag: string) => (key: PropertyKey, ...rest: Array<unknown>) => unknown\n wrapped[name] =\n (tag: string) =>\n (key: PropertyKey, attributes: ReadonlyArray<Item> = [], ...rest: Array<unknown>) => {\n const posted = fallback(tag, attributes, rest[0])\n return keyed(tag)(key, mark(tag, posted.attributes), posted.children, ...rest.slice(1))\n }\n } else if (/^[a-z]/.test(name) && typeof value === 'function') {\n const element = value as (\n attributes: ReadonlyArray<unknown>,\n ...rest: Array<unknown>\n ) => unknown\n wrapped[name] = (attributes: ReadonlyArray<Item>, ...rest: Array<unknown>) => {\n const posted = fallback(name, attributes, rest[0])\n return element(mark(name, posted.attributes), posted.children, ...rest.slice(1))\n }\n } else wrapped[name] = value\n }\n builders.set(h, wrapped)\n return wrapped as unknown as ResumableBuilder<MessageOf<Builder>>\n}\n\n/**\n * A view or renderer written against the resumable builder, as one that takes\n * the builder it is given: `Surface.rootView(Page, params, Resume.view(render))`,\n * `SurfaceView.define`, or an application's own view.\n */\nexport const view =\n <Model, Builder extends AnyBuilder, Out>(\n render: (model: Model, rh: ResumableBuilder<MessageOf<Builder>>) => Out,\n ) =>\n (model: Model, h: Builder): Out =>\n render(model, builder(h))\n","/**\n * Delegated dispatch: the page answers an event from its markers, before the\n * application has booted.\n *\n * One capture-phase listener per event type sits at the root, so events that\n * do not bubble (`focus`, `blur`) are caught, and it runs before anything\n * Foldkit attaches later. On an event it walks from the target to the root\n * and, for every marker of that event on the way, collects each binding's\n * Message in order, the way Foldkit's own handler would dispatch it: a hole is\n * filled from the event, `OnClick`'s options are honoured, `OnSubmit`\n * prevents the default. A marker token the page could not name (`*`) means\n * the live page does something here the page cannot describe, so the walk\n * ends and the answer names that element.\n */\nimport { Predicate, Result, Schema } from 'effect'\nimport type { KeyboardModifiers } from 'foldkit/html'\nimport { BINDING_ATTRIBUTE, EVENT_OF, UNNAMED_HANDLER } from './resumable.js'\n\n/**\n * A binding as the envelope carries it: Foldkit's attribute (`OnSubmit`,\n * `OnBlur`), whose tag says what its handler does beside dispatching; the\n * Message, encoded through the application's Message Schema (for a hole, with\n * the hole filled by a placeholder); the fields the event fills, `depth`\n * placement wrappers down; and the attribute's options. Its ordinal is its\n * index.\n */\nexport interface EncodedBinding {\n readonly attribute: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string>\n readonly depth?: number\n readonly options?: unknown\n}\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The page's list of bindings, read as untrusted input: each entry checked,\n * and only its known keys kept, or the reason the list is refused. Checked by\n * hand rather than through a Schema, which at a thousand rows took most of a\n * frame for a shape this plain; the Message inside each entry is still decoded\n * through the application's Schema by `decodeBindings`.\n */\nexport const readBindings = (\n value: unknown,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (!Array.isArray(value)) return Result.fail('the list is not an array')\n const out: Array<EncodedBinding> = []\n for (const [index, entry] of value.entries()) {\n if (!isRecord(entry)) return Result.fail(`entry ${index} is not an object`)\n if (typeof entry.attribute !== 'string') {\n return Result.fail(`entry ${index} has no attribute`)\n }\n if (!Object.hasOwn(entry, 'message')) return Result.fail(`entry ${index} has no message`)\n const { hole, depth } = entry\n if (\n hole !== undefined &&\n !(Array.isArray(hole) && hole.every(field => typeof field === 'string'))\n ) {\n return Result.fail(`entry ${index} has a hole that is not a list of fields`)\n }\n if (depth !== undefined && !(Number.isInteger(depth) && (depth as number) >= 0)) {\n return Result.fail(`entry ${index} has a depth that is not a count`)\n }\n out.push({\n attribute: entry.attribute,\n message: entry.message,\n ...(hole === undefined ? {} : { hole: hole as ReadonlyArray<string> }),\n ...(depth === undefined ? {} : { depth: depth as number }),\n ...(Object.hasOwn(entry, 'options') ? { options: entry.options } : {}),\n })\n }\n return Result.succeed(out)\n}\n\n/** A binding decoded from the page: its Message is one of the application's. */\nexport interface DecodedBinding {\n readonly attribute: string\n readonly event: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\n/**\n * The page's bindings, decoded through the application's Message Schema, and\n * every marker in `root` checked against them. A page whose markers name a\n * binding it does not carry, or whose entry is not one of the application's\n * Messages, is refused whole, with the reason.\n */\nexport const decodeBindings = (\n Message: Schema.Top | undefined,\n encoded: ReadonlyArray<EncodedBinding>,\n root: ParentNode,\n allowed: ReadonlySet<string>,\n): Result.Result<ReadonlyArray<DecodedBinding>, string> => {\n if (encoded.length > 0 && Message === undefined) {\n return Result.fail(\n 'the page has bindings and the plan has no Message Schema to decode them with',\n )\n }\n const decode =\n Message === undefined\n ? undefined\n : Schema.decodeUnknownResult(Message as Schema.Codec<unknown, unknown>)\n const bindings: Array<DecodedBinding> = []\n for (const [index, entry] of encoded.entries()) {\n const event = EVENT_OF[entry.attribute]\n if (event === undefined) {\n return Result.fail(\n `binding ${index} is for \"${entry.attribute}\", which is no event attribute`,\n )\n }\n const message = decode!(entry.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `binding ${index} does not decode as a Message: ${message.failure.message}`,\n )\n }\n const tag = Predicate.hasProperty(message.success, '_tag') ? message.success._tag : undefined\n if (typeof tag !== 'string' || !allowed.has(tag)) {\n return Result.fail(\n `binding ${index} dispatches ${typeof tag === 'string' ? tag : 'an untagged Message'}, which no active Surface lists in its messages`,\n )\n }\n bindings.push({\n attribute: entry.attribute,\n event,\n message: message.success,\n ...(entry.hole === undefined ? {} : { hole: entry.hole }),\n ...(entry.depth === undefined ? {} : { depth: entry.depth }),\n ...(entry.options === undefined ? {} : { options: entry.options }),\n })\n }\n for (const element of Array.from(root.querySelectorAll('*'))) {\n for (const attribute of element.getAttributeNames()) {\n if (!attribute.startsWith(BINDING_ATTRIBUTE)) continue\n for (const token of (element.getAttribute(attribute) ?? '').split(' ')) {\n if (token === UNNAMED_HANDLER) continue\n const ordinal = Number(token)\n if (!Number.isInteger(ordinal) || bindings[ordinal] === undefined) {\n return Result.fail(`the marker ${attribute}=\"${token}\" names no binding the page carries`)\n }\n }\n }\n }\n return Result.succeed(bindings)\n}\n\n/** A string property of the target, if it has one. */\nconst stringProperty = (target: EventTarget | null, name: string): string | undefined => {\n if (target === null || !(name in target)) return undefined\n const value: unknown = Reflect.get(target, name)\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Foldkit's reading of an input's value (`inputEventValue`): any target's\n * string `value`, a custom element's included, else its `innerText`, else its\n * `textContent`.\n */\nconst inputValue = (target: EventTarget | null): string =>\n stringProperty(target, 'value') ??\n stringProperty(target, 'innerText') ??\n stringProperty(target, 'textContent') ??\n ''\n\nconst modifiersOf = (event: KeyboardEvent): KeyboardModifiers => ({\n shiftKey: event.shiftKey,\n ctrlKey: event.ctrlKey,\n altKey: event.altKey,\n metaKey: event.metaKey,\n})\n\n/** The Message a binding dispatches for this event: its own, with the hole filled. */\nconst messageFor = (binding: DecodedBinding, event: Event): unknown => {\n if (binding.hole === undefined) return binding.message\n const fill = (template: Readonly<Record<string, unknown>>): unknown => {\n if (binding.event === 'input' || binding.event === 'change') {\n const [field] = binding.hole ?? []\n return { ...template, [field ?? 'value']: inputValue(event.target) }\n }\n if (event instanceof KeyboardEvent) {\n return { ...template, key: event.key, modifiers: modifiersOf(event) }\n }\n return template\n }\n // The hole's fields sit inside each placement wrapper's `message`.\n const inside = (template: Readonly<Record<string, unknown>>, depth: number): unknown =>\n depth === 0\n ? fill(template)\n : {\n ...template,\n message: inside(template.message as Readonly<Record<string, unknown>>, depth - 1),\n }\n return inside(binding.message as Readonly<Record<string, unknown>>, binding.depth ?? 0)\n}\n\n/** What `OnClick` declares beside its Message. */\ninterface ClickOptions {\n readonly defaultAction?: 'Allow' | 'Prevent'\n readonly propagation?: 'Bubble' | 'Stop'\n readonly focusSelector?: string\n}\n\n/**\n * What the markers make of one event: the Messages its bindings dispatch, in\n * the order the live page would, and, when the walk met a handler the page\n * could not name, that element. An answer with `unnamed` is incomplete: the\n * live page would do more than its Messages say.\n */\nexport interface Answer {\n readonly event: Event\n readonly messages: ReadonlyArray<unknown>\n readonly unnamed?: Element | undefined\n}\n\nexport interface ListenOptions {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly onAnswer: (answer: Answer) => void\n /**\n * Every event the page's markers name, as the envelope lists them. Given,\n * `listen` needs no pass over the page to find the events a marker names\n * with `*` alone; without it, it reads every element's attributes, which on\n * a large page is most of its cost.\n */\n readonly events?: Iterable<string> | undefined\n}\n\n/**\n * Listens at `root` for every event the bindings name, and answers each from\n * the markers. Returns what removes the listeners.\n */\nexport const listen = (root: Element, options: ListenOptions): (() => void) => {\n // The bindings name most events; a marker whose handlers the page could not\n // name is `*` alone, so the markers themselves say the rest.\n const events = new Set(options.bindings.map(binding => binding.event))\n if (options.events !== undefined) {\n for (const event of options.events) events.add(event)\n } else {\n for (const element of [root, ...Array.from(root.querySelectorAll('*'))]) {\n for (const { name } of Array.from(element.attributes)) {\n if (name.startsWith(BINDING_ATTRIBUTE)) events.add(name.slice(BINDING_ATTRIBUTE.length))\n }\n }\n }\n const handler = (event: Event) => {\n const type = event.type\n const attribute = `${BINDING_ATTRIBUTE}${type}`\n const messages: Array<unknown> = []\n // An event that does not bubble (`focus`, `blur`, `mouseenter`) reaches only\n // its target's own handlers on the live page, so only those answer it here.\n const path = event.bubbles ? event.composedPath() : [event.target]\n for (const node of path) {\n if (!(node instanceof Element)) continue\n const tokens = node.getAttribute(attribute)\n // Foldkit chains an element's handlers in one listener, so a Stop among\n // them keeps the event from other elements, not from its siblings.\n let stopped = false\n if (tokens !== null) {\n for (const token of tokens.split(' ')) {\n if (token === UNNAMED_HANDLER) {\n options.onAnswer({ event, messages, unnamed: node })\n return\n }\n const binding = options.bindings[Number(token)]\n if (binding === undefined) continue\n if (binding.attribute === 'OnSubmit') event.preventDefault()\n if (binding.attribute === 'OnClick') {\n const click = (binding.options ?? {}) as ClickOptions\n if (click.defaultAction === 'Prevent') event.preventDefault()\n if (click.propagation === 'Stop') event.stopPropagation()\n if (click.focusSelector !== undefined) {\n const focusTarget = document.querySelector(click.focusSelector)\n if (focusTarget instanceof HTMLElement) focusTarget.focus()\n }\n if (click.propagation === 'Stop') stopped = true\n }\n messages.push(messageFor(binding, event))\n }\n }\n if (stopped || node === root) break\n }\n options.onAnswer({ event, messages })\n }\n for (const type of events) root.addEventListener(type, handler, true)\n return () => {\n for (const type of events) root.removeEventListener(type, handler, true)\n }\n}\n","/**\n * What the server and the browser both read: the plan, the envelope as the\n * browser reads it, static regions, and the page's bindings. Nothing here\n * imports Foldkit's server renderer, so `client.ts` can carry all of it.\n */\nimport { Effect, Option, Result, Schema, Stream, type Layer } from 'effect'\nimport type { Runtime } from 'foldkit'\nimport { inertHtml, type Html, type HtmlBuilder } from 'foldkit/html'\nimport type { Ports } from 'foldkit/port'\nimport type { ActiveSurface, Metadata, WritableProjection } from 'foldkit-surface'\nimport { current, type Region } from './context.js'\nimport { decodeBindings, readBindings, type DecodedBinding } from './listen.js'\n\n/**\n * The attribute Foldkit's server stamps on an application's root, as\n * `foldkit/experimental/server` exports it. Written out here so a page can\n * find its root without that module; a test pins the two together.\n */\nexport const FOLDKIT_APP_ATTRIBUTE = 'data-foldkit-app'\n\n/**\n * The attribute on the stamped root that carries a page's resume envelope.\n * Foldkit pairs its own handoff the same way: the build id rides on the root\n * beside the app stamp, and the client reads it before adopting anything.\n */\nexport const RESUME_ATTRIBUTE = 'data-foldkit-plus-resume'\n\n/** The envelope format this package writes and reads. */\nexport const PROTOCOL = 1\n\nconst LINE_SEPARATOR = String.fromCharCode(0x2028)\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029)\n\n/**\n * JSON for a script element: `<` is escaped so `</script>` in the data ends\n * nothing. U+2028 and U+2029 are escaped too: they are fine in JSON and break a\n * reader that treats the text as JavaScript.\n */\nexport const serializeJsonScript = (value: unknown): string =>\n JSON.stringify(value)\n .replaceAll('<', '\\\\u003c')\n .replaceAll(LINE_SEPARATOR, '\\\\u2028')\n .replaceAll(PARAGRAPH_SEPARATOR, '\\\\u2029')\n\n/**\n * The envelope JSON as the stamped root carries it: `serializeJsonScript`\n * already escaped `<` and the line separators, and an attribute must escape\n * `&` and `\"` besides, so no string in the Model can break out of the value.\n * `getAttribute` resolves the entities back, which is exactly the JSON.\n */\nexport const attributeOf = (json: string): string =>\n ` ${RESUME_ATTRIBUTE}=\"${json.replaceAll('&', '&').replaceAll('\"', '"')}\"`\n\n/**\n * What a page says of itself beyond Foldkit's `Document` (`title`, `lang`,\n * `dir`, `canonical`, `ogUrl`): what a search result and a link preview show.\n * `title` is the preview's title (`og:title`), when it differs from the\n * document's. Dates are ISO 8601 text; `jsonLd` is structured data, each\n * entry written as its own script.\n */\nexport interface Meta {\n readonly description?: string | undefined\n readonly title?: string | undefined\n readonly image?: string | undefined\n readonly type?: 'website' | 'article' | undefined\n readonly siteName?: string | undefined\n readonly article?:\n { readonly published?: string | undefined; readonly modified?: string | undefined } | undefined\n readonly robots?: string | undefined\n readonly alternates?:\n ReadonlyArray<{ readonly hreflang: string; readonly href: string }> | undefined\n readonly jsonLd?: ReadonlyArray<Readonly<Record<string, unknown>>> | undefined\n}\n\n/** Marks each head element a plan's `meta` wrote, so the browser can replace them. */\nexport const META_ATTRIBUTE = 'data-foldkit-meta'\n\nconst attributeText = (text: string): string =>\n text\n .replaceAll('&', '&')\n .replaceAll('\"', '"')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n\n/** The head markup of a `Meta`, every value escaped, one element per line. */\nexport const metaMarkup = (meta: Meta): string => {\n const tag = (element: string, attributes: ReadonlyArray<readonly [string, string]>) =>\n `<${element} ${META_ATTRIBUTE} ${attributes.map(([name, value]) => `${name}=\"${attributeText(value)}\"`).join(' ')}>`\n const named = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['name', name],\n ['content', value],\n ]),\n ]\n const property = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['property', name],\n ['content', value],\n ]),\n ]\n return [\n ...named('description', meta.description),\n ...property('og:title', meta.title),\n ...property('og:description', meta.description),\n ...property('og:type', meta.type),\n ...property('og:site_name', meta.siteName),\n ...property('og:image', meta.image),\n ...(meta.description === undefined && meta.image === undefined && meta.title === undefined\n ? []\n : named('twitter:card', meta.image === undefined ? 'summary' : 'summary_large_image')),\n ...property('article:published_time', meta.article?.published),\n ...property('article:modified_time', meta.article?.modified),\n ...named('robots', meta.robots),\n ...(meta.alternates ?? []).map(({ hreflang, href }) =>\n tag('link', [\n ['rel', 'alternate'],\n ['hreflang', hreflang],\n ['href', href],\n ]),\n ),\n ...(meta.jsonLd ?? []).map(\n data =>\n `<script ${META_ATTRIBUTE} type=\"application/ld+json\">${serializeJsonScript(data)}</script>`,\n ),\n ].join('\\n')\n}\n\n/**\n * The Subscription entry that keeps the head's `meta` elements in step with\n * the Model, so a move within the page (another post) changes its\n * description too. It writes the head and sends no Message.\n */\nexport const metaEntry = <Model>(meta: (model: Model) => Meta) => ({\n dependenciesSchema: Schema.String,\n modelToDependencies: (model: Model) => metaMarkup(meta(model)),\n dependenciesToStream: (markup: string) =>\n Stream.drain(\n Stream.fromEffect(\n Effect.sync(() => {\n const written = document.createElement('template')\n written.innerHTML = markup\n for (const old of document.head.querySelectorAll(`[${META_ATTRIBUTE}]`)) old.remove()\n document.head.append(written.content)\n }),\n ),\n ),\n})\n\n/**\n * Which part of the Model the browser owns, and what it starts from.\n *\n * `state` is a writable projection of that part, from `Projection.pick` or\n * `Projection.compose`. `baseline` is the Model the browser sets it onto, by\n * default the application's own initial Model. `boot` names the Commands the\n * browser runs on load, since `init` does not run there.\n */\nexport interface ResumePlan<Model, Fields extends Schema.Struct.Fields, Commands = unknown> {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline: Model\n readonly boot?: ((model: Model) => Commands) | undefined\n /** Model paths allowed to start from the baseline, as `ModelRef.dependency` gives them. */\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n /** The Surfaces the browser may activate, which the plan must cover. */\n readonly surfaces: ReadonlyArray<ActiveSurface<Model>>\n /** State another package owns, each captured and restored by that package. */\n readonly parts: ReadonlyArray<ResumePart<Model>>\n /** The application's Message Schema, which encodes the page's bindings. */\n readonly Message?: Schema.Top | undefined\n /**\n * When the browser boots the runtime: `now` on load, `idle` when the browser\n * is idle or on the first interaction, `on-interaction` on the first only.\n * Until then the page answers events from its bindings and queues the\n * Messages, which the runtime runs through `update` before any other.\n */\n readonly start: Start\n /** Subscription and Managed Resource keys that may start late (decision 10). */\n readonly deferrable: ReadonlyArray<string>\n /**\n * `server`: a form whose `OnSubmit` names a Message also posts it to the\n * page's own URL, and `SSR.handle` runs `update` there, so the form works\n * with scripts off or not yet loaded.\n */\n readonly fallback?: 'server' | undefined\n /**\n * What the page says of itself, from the Model: rendered into the head on\n * the server, checked like the view, and kept in step in the browser.\n */\n readonly meta?: ((model: Model) => Meta) | undefined\n /**\n * The data the page was built from, for the browser's freshness check: a\n * Remote cursor, a revision number, anything the check compares. Unset\n * when the page has no age.\n */\n readonly version?: unknown | undefined\n}\n\nexport type Start = 'now' | 'idle' | 'on-interaction'\n\n/**\n * A package's contribution to the envelope, for state the plan's slice cannot\n * carry, such as Remote's normalized store. On the server `capture` takes what\n * the active Surfaces' projections read and returns it as JSON; in the browser\n * `restore` sets it onto the Model, or says why it cannot. A part owns its\n * encoding: this package only carries the value.\n *\n * `covers` names the metadata keys whose reads the part resumes, so the\n * coverage check counts those reads as sent. `Remote.resume(Data)` is one.\n */\nexport interface ResumePart<Model> {\n readonly id: string\n readonly covers: ReadonlyArray<string>\n readonly capture: (\n model: Model,\n projections: ReadonlyArray<{ readonly metadata: Metadata }>,\n ) => unknown\n readonly restore: (model: Model, value: unknown) => Result.Result<Model, string>\n /**\n * Whether a Subscription or Managed Resource entry of this part's package\n * may start late, when a deferred boot is asked for. A part knows its own\n * entries; nothing is deferrable by default.\n */\n readonly deferrable?: ((key: string, entry: unknown) => boolean) | undefined\n}\n\n/** Why a page's resume envelope was refused. */\nexport class ResumeRefused extends Schema.TaggedError<ResumeRefused>()('ResumeRefused', {\n reason: Schema.Literals([\n 'Missing',\n 'Duplicate',\n 'Unreadable',\n 'Protocol',\n 'Plan',\n 'Invalid',\n 'Route',\n ]),\n message: Schema.String,\n}) {}\n\nexport const refuse = (reason: ResumeRefused['reason'], message: string) =>\n Result.fail(new ResumeRefused({ reason, message }))\n\n/**\n * The slice's Schema as a codec needing no services. A resume plan's state is\n * plain data, so any field that needs one cannot cross a page anyway.\n */\nexport const codecOf = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>\n schema as unknown as Schema.Codec<Schema.Struct.Type<Fields>, unknown>\n\n/**\n * A resume plan for an application. The baseline defaults to the\n * application's initial Model. It is never written: a writable projection's\n * `set` returns a new Model, so a baseline Foldkit freezes in development is\n * safe to start from.\n *\n * `surfaces` are the Surfaces the browser may activate, and `local` the Model\n * fields allowed to start from the baseline, such as an open menu. Rendering\n * refuses a plan that leaves a Surface's read or activation in neither.\n */\nexport const plan = <Model, Fields extends Schema.Struct.Fields, Commands = unknown>(\n application: {\n readonly initial: Model\n readonly owner?: object\n readonly Message?: Schema.Top | undefined\n },\n config: {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline?: Model | undefined\n readonly boot?: ((model: Model) => Commands) | undefined\n readonly local?: ReadonlyArray<{ readonly dependency: ReadonlyArray<string> }> | undefined\n readonly surfaces?: ReadonlyArray<ActiveSurface<Model>> | undefined\n readonly parts?: ReadonlyArray<ResumePart<Model>> | undefined\n readonly start?: Start | undefined\n readonly deferrable?: ReadonlyArray<string> | undefined\n readonly fallback?: 'server' | undefined\n readonly meta?: ((model: Model) => Meta) | undefined\n readonly version?: unknown | undefined\n },\n): ResumePlan<Model, Fields, Commands> => {\n const surfaces = config.surfaces ?? []\n const parts = config.parts ?? []\n const repeated = parts.find((part, index) => parts.findIndex(p => p.id === part.id) !== index)\n if (repeated !== undefined) {\n throw new Error(\n `SSR.plan: two parts of plan \"${config.id}\" share the id \"${repeated.id}\"; give one an id of its own`,\n )\n }\n const foreign = surfaces.find(\n surface => application.owner !== undefined && surface.owner !== application.owner,\n )\n if (foreign !== undefined) {\n throw new Error(\n `SSR.plan: the Surface \"${foreign.name}\" belongs to another application than plan \"${config.id}\"`,\n )\n }\n return {\n id: config.id,\n state: config.state,\n baseline: config.baseline ?? application.initial,\n ...(config.boot === undefined ? {} : { boot: config.boot }),\n local: (config.local ?? []).map(place => place.dependency),\n surfaces,\n parts,\n ...(application.Message === undefined ? {} : { Message: application.Message }),\n start: config.start ?? 'now',\n deferrable: config.deferrable ?? [],\n ...(config.fallback === undefined ? {} : { fallback: config.fallback }),\n ...(config.meta === undefined ? {} : { meta: config.meta }),\n ...(config.version === undefined ? {} : { version: config.version }),\n }\n}\n\n/**\n * How a page's recorded route is compared with the browser's. `full` compares\n * path and query. `path` compares the path alone, ignoring a trailing slash or\n * `index.html`, for a page generated as a file: a static host serves one file\n * for every query, and for `/about` and `/about/` alike.\n */\nexport type RouteMatch = 'full' | 'path'\n\n/** A path as a `path` match compares it. */\nexport const pathKey = (route: string): string => {\n const path = route.split(/[?#]/)[0] ?? ''\n const trimmed = path.replace(/\\/index\\.html$/, '/').replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n/**\n * The Model a payload resumes: the baseline with the slice set onto it, then\n * each part restored, in order. Every part the plan names must be there and\n * restore, and no other may be: a page is never half-restored.\n */\nexport const modelFrom = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: { readonly state: unknown; readonly parts?: unknown },\n): Result.Result<Model, string> => {\n const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state)\n if (Result.isFailure(decoded)) {\n return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`)\n }\n const given = payload.parts ?? {}\n if (typeof given !== 'object' || Array.isArray(given)) {\n return Result.fail(\"the envelope's parts are not an object of parts by id\")\n }\n const parts = given as Readonly<Record<string, unknown>>\n const unknown = Object.keys(parts).find(id => !plan.parts.some(part => part.id === id))\n if (unknown !== undefined) {\n return Result.fail(`the envelope carries a part \"${unknown}\" the plan does not name`)\n }\n let model = plan.state.set(plan.baseline, decoded.success)\n for (const part of plan.parts) {\n if (!Object.hasOwn(parts, part.id))\n return Result.fail(`the envelope carries no \"${part.id}\" part`)\n const restored = part.restore(model, parts[part.id])\n if (Result.isFailure(restored)) {\n return Result.fail(`the \"${part.id}\" part does not restore: ${restored.failure}`)\n }\n model = restored.success\n }\n return Result.succeed(model)\n}\n\n/** The page's envelope, read off its stamped root; refused when there is no root, more than one, no envelope, or not JSON. */\nconst readEnvelope = (\n page: ParentNode,\n): Result.Result<Readonly<Record<string, unknown>>, ResumeRefused> => {\n const roots = page.querySelectorAll(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (roots.length === 0) return refuse('Missing', 'the page holds no stamped application root')\n if (roots.length > 1) {\n return refuse('Duplicate', `the page holds ${roots.length} stamped application roots`)\n }\n const carried = roots[0]?.getAttribute(RESUME_ATTRIBUTE)\n if (carried === null || carried === undefined) {\n return refuse('Missing', 'the page holds no resume envelope')\n }\n try {\n const parsed: unknown = JSON.parse(carried)\n return Result.succeed((parsed ?? {}) as Readonly<Record<string, unknown>>)\n } catch (error) {\n return refuse('Unreadable', `the resume envelope is not JSON: ${String(error)}`)\n }\n}\n\n/**\n * The Model a page resumes from: the baseline with the stamped root's envelope\n * set onto it. Refused, with the reason, when the page holds no stamped root\n * or more than one, when the root carries no envelope or not JSON, when it is\n * not this protocol or this plan, or when the slice does not decode through\n * the plan's Schema. A page is never half-restored.\n */\nexport const resume = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n options: { readonly route?: string | undefined } = {},\n): Result.Result<Model, ResumeRefused> => {\n const read = readEnvelope(page)\n if (Result.isFailure(read)) return Result.fail(read.failure)\n const parsed = read.success\n const { v, plan: id, state, parts, route, match } = parsed\n if (v !== PROTOCOL) {\n return refuse('Protocol', `the envelope is protocol ${String(v)}, not ${PROTOCOL}`)\n }\n if (id !== plan.id) {\n return refuse('Plan', `the envelope is for plan \"${String(id)}\", not \"${plan.id}\"`)\n }\n // The route the Model was made for. The runtime never reports the URL at\n // boot, so a page resumed on another route would show one and be on the\n // other.\n if (route !== undefined && options.route !== undefined) {\n const matches =\n match === 'path' ? pathKey(String(route)) === pathKey(options.route) : route === options.route\n if (!matches) {\n return refuse(\n 'Route',\n `the page was ${match === 'path' ? 'generated' : 'rendered'} for ${String(route)}, not ${options.route}`,\n )\n }\n }\n const resumed = modelFrom(plan, { state, parts })\n return Result.isFailure(resumed)\n ? refuse('Invalid', resumed.failure)\n : Result.succeed(resumed.success)\n}\n\n/** The tag a Message value carries, for naming it. */\nexport const tagOf = (message: unknown): string =>\n typeof message === 'object' &&\n message !== null &&\n '_tag' in message &&\n typeof message._tag === 'string'\n ? message._tag\n : 'an untagged Message'\n\n/**\n * The Message tags the plan's Surfaces active for `model` may send, which is\n * what a page's bindings may dispatch (the design's rule 3).\n */\nexport const allowedTags = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlySet<string> =>\n new Set(\n plan.surfaces.flatMap(surface =>\n Option.isSome(surface.projectionOf(model)) ? surface.messages : [],\n ),\n )\n\n/** The attribute on a static region's element, naming the region. */\nexport const STATIC_ATTRIBUTE = 'data-foldkit-plus-static'\n\nconst boundary = (id: string, trusted: string | undefined, children: Region): Html =>\n inertHtml.div(\n [\n inertHtml.Attribute(STATIC_ATTRIBUTE, id),\n ...(trusted === undefined ? [] : [inertHtml.InnerHTML(trusted)]),\n ],\n children,\n )\n\n/**\n * A region of the page the server owns for the life of the document. It is\n * rendered on the server with the inert builder, so it can dispatch no\n * Message. The browser adopts the server's markup as trusted `InnerHTML` and\n * never runs `render`, so the region reads nothing from the browser's Model\n * and a plan need not send what it reads.\n *\n * A region changes only with a new document. Content a Message should change\n * belongs in a Surface, not here.\n */\nexport const staticRegion = (id: string, render: (ih: HtmlBuilder<never>) => Region): Html => {\n const now = current()\n if (now?.mode === 'resume') {\n const snapshot = now.snapshots.get(id)\n if (snapshot !== undefined) return boundary(id, snapshot, [])\n if (!now.reported.has(id)) {\n now.reported.add(id)\n console.error(\n `[foldkit-ssr] the static region \"${id}\" is not in the server's page, so it is rendered in the browser`,\n )\n }\n return boundary(id, undefined, render(inertHtml))\n }\n const replayed = now?.mode === 'replay' ? now.regions.get(id) : undefined\n if (replayed !== undefined) return boundary(id, undefined, replayed)\n if (now?.mode !== 'collect') return boundary(id, undefined, render(inertHtml))\n const outer = now.region\n now.region = id\n try {\n const children = render(inertHtml)\n if (now.regions.has(id)) now.duplicates.add(id)\n else now.regions.set(id, children)\n return boundary(id, undefined, children)\n } finally {\n now.region = outer\n }\n}\n\n/**\n * Whether the view call in progress is the server rendering a page, rather than the browser: true\n * through both of `render`'s passes, false while the browser resumes and outside any render. For a\n * view that sends markup it will adopt in the browser rather than draw there, such as\n * `foldkit-richtext-dom`'s editor host, whose placement takes this as `serverRendered`.\n */\nexport const serving = (): boolean => {\n const mode = current()?.mode\n return mode === 'collect' || mode === 'replay'\n}\n\n/**\n * The `makeApplication` options `SSR` hands to Foldkit as they are, typed as\n * Foldkit types them.\n */\ntype ApplicationOptions<Model, Message> = Partial<\n Pick<\n Runtime.RoutingApplicationConfig<Model, Message, never, never, Ports | undefined>,\n | 'routing'\n | 'ports'\n | 'crash'\n | 'slow'\n | 'viewTransition'\n | 'freezeModel'\n | 'preserveScroll'\n | 'devTools'\n >\n>\n\n/**\n * The part of a Foldkit application config a server render and a resumed\n * client need. The full `makeApplication` config fits, whichever of its four\n * shapes, and its callbacks (`routing`'s, say) are typed from `update`'s\n * Message as Foldkit types them.\n */\nexport interface ResumableConfig<Model, Message = any> extends ApplicationOptions<Model, Message> {\n readonly Model: Schema.Codec<Model, any, unknown, unknown>\n readonly init: (...args: ReadonlyArray<any>) => {\n readonly model: Model\n readonly commands?: ReadonlyArray<{ readonly name: string }> | undefined\n }\n readonly update: (model: Model, message: Message) => { readonly model: Model }\n readonly view: (model: Model, h: any) => unknown\n readonly container: HTMLElement | null\n readonly Flags?: unknown\n readonly subscriptions?: Readonly<Record<string, unknown>> | undefined\n readonly managedResources?: Readonly<Record<string, unknown>> | undefined\n /** The services Commands need, as Foldkit's runtime provides them. */\n readonly resources?: Layer.Layer<never, never, never> | undefined\n /**\n * Bundles whose bodies load on demand (`Bundle.lazy`). The server loads\n * them before it renders; the browser loads them before it boots, answering\n * from the markers meanwhile, so a page never shows a bundle's placeholder.\n */\n readonly lazy?: ReadonlyArray<Loadable> | undefined\n}\n\n/** What `SSR` needs of a lazy bundle: `Bundle.lazy` gives it. */\nexport interface Loadable {\n readonly name: string\n readonly load: () => Promise<void>\n readonly isLoaded: () => boolean\n}\n\n/**\n * The config without a `Flags` key at all. Deleted, never set to `undefined`:\n * Foldkit's server asks whether `Flags` is defined and its client whether the\n * key exists, so an `undefined` one renders and is then refused.\n */\nconst withoutFlags = <Config extends { readonly Flags?: unknown }>(config: Config) => {\n const { Flags: _flags, ...rest } = config\n return rest\n}\n\n/** The config whose `init` returns this start, whatever arguments it is given. */\nexport const startingFrom = <Model>(\n config: ResumableConfig<Model>,\n start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> },\n) => ({ ...withoutFlags(config), init: () => start })\n\n/** A route as the envelope records it: the path and the query. */\nexport const routeOf = (url: string): string => {\n const parsed = new URL(url, 'http://localhost')\n return `${parsed.pathname}${parsed.search}`\n}\n\n/**\n * The page's bindings, decoded through the plan's Message Schema, kept to the\n * Messages the Surfaces active for `model` may send, and checked against\n * every marker in `root`. Refused, with the reason, when the page carries\n * none, an entry is not one of the application's Messages or one no active\n * Surface lists, or a marker names a binding the page does not carry: a page\n * is answered whole or not at all.\n */\nexport const bindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<ReadonlyArray<DecodedBinding>, ResumeRefused> =>\n Result.map(bindingsAndEvents(plan, page, root, model), read => read.bindings)\n\nconst EnvelopeEvents = Schema.optional(Schema.Array(Schema.String))\n\n/**\n * `bindings`, and the events the envelope says the markers name, if it says:\n * a page from before the envelope listed them leaves `listen` to find them.\n */\nexport const bindingsAndEvents = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<\n {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n ResumeRefused\n> => {\n const parsed = readEnvelope(page)\n if (Result.isFailure(parsed)) return Result.fail(parsed.failure)\n const read = readBindings(parsed.success.bindings ?? [])\n if (Result.isFailure(read)) {\n return refuse('Invalid', `the page's bindings are malformed: ${read.failure}`)\n }\n const encoded = read.success\n if (encoded.length > 0 && plan.surfaces.length === 0) {\n return refuse(\n 'Invalid',\n 'the page has bindings and the plan declares no surfaces to allow them',\n )\n }\n const events = Schema.decodeUnknownResult(EnvelopeEvents)(parsed.success.events)\n if (Result.isFailure(events)) {\n return refuse('Invalid', `the page's events are malformed: ${events.failure.message}`)\n }\n const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model))\n return Result.isFailure(decoded)\n ? refuse('Invalid', decoded.failure)\n : Result.succeed({ bindings: decoded.success, events: events.success })\n}\n","/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { withContext, type RenderContext } from './context.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport { builder, view } from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is logged. A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n },\n): void => {\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n if (root.getAttribute(BUILD_ATTRIBUTE) !== options.buildId) {\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n console.error(`[foldkit-ssr] the page cannot resume: ${resumed.failure.message}`)\n contain()\n return\n }\n const model = resumed.success\n const commands = (plan.boot?.(model) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n const boot = (entries: Readonly<Record<string, unknown>> = {}) =>\n adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, { model, commands }), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n if (plan.start === 'now' && pending.length === 0) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n console.error(`[foldkit-ssr] the page cannot resume: ${decoded.failure.message}`)\n contain()\n return\n }\n deferBoot(root, decoded.success, plan.start, { boot, answered }, pending)\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport const UNTIL_LIMIT_MS = 3000\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n const stop = listen(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n console.error(`[foldkit-ssr] a bundle's bodies did not load: ${String(error)}`)\n commit()\n })\n }\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n"],"mappings":";;;;;AAiFA,IAAI;;AAGJ,MAAa,gBAA2C;AAExD,MAAa,UAAa,MAAqB,QAAoB;CACjE,MAAM,WAAW;CACjB,UAAU;CACV,IAAI;EACF,OAAO,IAAI;CACb,UAAU;EACR,UAAU;CACZ;AACF;;AAGA,MAAa,eACX,QACA,UACY;CACZ,GAAG;CACH,OAAO,OAAgB,MAAe,OAAO,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC;AAChF;;;;;;;;;;;;;;;;;;;ACnFA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,WAA6C;CACxD,SAAS;CACT,eAAe;CACf,aAAa;CACb,WAAW;CACX,cAAc;CACd,cAAc;CACd,aAAa;CACb,YAAY;CACZ,aAAa;CACb,eAAe;CACf,gBAAgB;CAChB,eAAe;CACf,aAAa;CACb,WAAW;CACX,yBAAyB;CACzB,eAAe;CACf,6BAA6B;CAC7B,gBAAgB;CAChB,SAAS;CACT,uBAAuB;CACvB,YAAY;CACZ,SAAS;CACT,QAAQ;CACR,cAAc;CACd,cAAc;CACd,SAAS;CACT,UAAU;CACV,eAAe;CACf,6BAA6B;CAC7B,cAAc;CACd,UAAU;CACV,SAAS;CACT,UAAU;CACV,SAAS;C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;EACR,KAAK;EACL,KAAK,MAAM,EAAE,OAAO,aAAa,WAAW,OAAO,CAAC,GAAG;GACrD,MAAM,OAAO,MAAM;GACnB,QAAQ,cAAc,IAAI,KAAK,MAAM,MAAM,KAAK,CAAC;EACnD;CACF;CACA,MAAM,eAAe;EACnB,QAAQ;EACR,QAAQ,KAAK,EACX,wBAAwB;GACtB,oBAAoB,OAAO;GAC3B,2BAA2B;GAG3B,4BACE,OAAO,WACL,OAAO,GACL,OAAO,QACL,KAAK,aAAA,kBAAkC,IAAI,OAAO,cAAc,OAAO,MACvE,OAAO,KAAK,QAAQ,CACtB,GACA,QACF,CACF;EACJ,EACF,CAAC;EACD,IAAI,CAAC,KAAK,aAAA,kBAAkC,GAAG,SAAS;CAC1D;CACA,MAAM,iBAAiB;EACrB,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,IAAI,QAAQ,WAAW,GAAG;GACxB,OAAO;GACP;EACF;EACA,QAAa,IAAI,QAAQ,KAAI,WAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,UAAmB;GACtF,QAAQ,MAAM,iDAAiD,OAAO,KAAK,GAAG;GAC9E,OAAO;EACT,CAAC;CACH;CACA,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;AAAQ"}
|
|
@@ -295,6 +295,8 @@ interface Loadable {
|
|
|
295
295
|
}
|
|
296
296
|
//#endregion
|
|
297
297
|
//#region src/client.d.ts
|
|
298
|
+
/** The longest a served page stays in view while a fresh application waits for `until`. */
|
|
299
|
+
declare const UNTIL_LIMIT_MS = 3000;
|
|
298
300
|
/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */
|
|
299
301
|
declare const Resume: {
|
|
300
302
|
builder: <Builder extends AnyBuilder>(h: Builder) => ResumableBuilder<MessageOf<Builder>>;
|
|
@@ -343,6 +345,14 @@ declare const SSR: {
|
|
|
343
345
|
* way a resume failure does.
|
|
344
346
|
*/
|
|
345
347
|
readonly otherwise?: "render" | undefined;
|
|
348
|
+
/**
|
|
349
|
+
* With `otherwise: 'render'`, when the fresh application is ready to be
|
|
350
|
+
* seen: until a Model it has drawn satisfies this, it draws out of view
|
|
351
|
+
* and the served page stays, so a page is not swapped for its loading
|
|
352
|
+
* state and back. Omitted, the fresh application replaces the page at
|
|
353
|
+
* once. The served page stays no longer than `UNTIL_LIMIT_MS`.
|
|
354
|
+
*/
|
|
355
|
+
readonly until?: ((model: Model) => boolean) | undefined;
|
|
346
356
|
/**
|
|
347
357
|
* Whether the plan's data version is still current: asked once, with
|
|
348
358
|
* `plan.version`, before anything is adopted. Omitted never asks. A plan
|
|
@@ -356,5 +366,5 @@ declare const SSR: {
|
|
|
356
366
|
serving: () => boolean;
|
|
357
367
|
};
|
|
358
368
|
//#endregion
|
|
359
|
-
export {
|
|
360
|
-
//# sourceMappingURL=client-
|
|
369
|
+
export { ResumableBuilder as C, FALLBACK_FIELD as S, DecodedBinding as _, Loadable as a, UnnamedHandler as b, RESUME_ATTRIBUTE as c, ResumePlan as d, ResumeRefused as f, metaMarkup as g, Start as h, FOLDKIT_APP_ATTRIBUTE as i, ResumableConfig as l, STATIC_ATTRIBUTE as m, SSR as n, META_ATTRIBUTE as o, RouteMatch as p, UNTIL_LIMIT_MS as r, Meta as s, Resume as t, ResumePart as u, EncodedBinding as v, SLOT_ATTRIBUTE as w, BINDING_ATTRIBUTE as x, Region as y };
|
|
370
|
+
//# sourceMappingURL=client-BDyZf200.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-
|
|
1
|
+
{"version":3,"file":"client-BDyZf200.d.mts","names":[],"sources":["../src/resumable.ts","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Ac;;;UAIf;WACN;WACA,YAAY;WACZ;;;;;cCxXE;;cA8JA;4BAAA;EA0BkmK,OAAA,OAAA,4BAAA,KAAA,SAAA,OAAA,OAAA,IAAA,iBAAA,UAAA,cAAA,SAAA,OAAA,OAAa,GAAA,YAAW;;;;;cAvB1nK;;;aAlFX;aAF4B,UAAC,OAAA;;;;aAEO,WAAC;aAC/B,SAAA,OAAA,UAAA;aAED,QAAC;;;aACwB,WAAC,wCAAA,cAAA;aACkB,QAAC,cAAA,WAAA;aAE5C,QAAD;aACwB,aAAC;aACnB;aAA0C,SAAA,OAAA,UAAA;aACV;;;aA+F2kE;;EA1TvmE,UAAA,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAO,QAC1D,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;aAEpB;;;;;;;aAOA,SAAS,MAAM;;;;;;;aAOf;;;;;;;;aAQA,UAAU,OAAO;;;;;;;;aAQjB,UAAU;;kFARO"}
|
package/dist/client.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as
|
|
2
|
-
export { BINDING_ATTRIBUTE, type DecodedBinding, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, RESUME_ATTRIBUTE, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, type Start, type UnnamedHandler, metaMarkup };
|
|
1
|
+
import { C as ResumableBuilder, S as FALLBACK_FIELD, _ as DecodedBinding, a as Loadable, b as UnnamedHandler, c as RESUME_ATTRIBUTE, d as ResumePlan, f as ResumeRefused, g as metaMarkup, h as Start, i as FOLDKIT_APP_ATTRIBUTE, l as ResumableConfig, m as STATIC_ATTRIBUTE, n as SSR, o as META_ATTRIBUTE, r as UNTIL_LIMIT_MS, s as Meta, t as Resume, u as ResumePart, w as SLOT_ATTRIBUTE, x as BINDING_ATTRIBUTE } from "./client-BDyZf200.mjs";
|
|
2
|
+
export { BINDING_ATTRIBUTE, type DecodedBinding, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, RESUME_ATTRIBUTE, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, type Start, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
|
package/dist/client.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { BINDING_ATTRIBUTE, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, metaMarkup };
|
|
1
|
+
import { C as BINDING_ATTRIBUTE, E as SLOT_ATTRIBUTE, T as FALLBACK_FIELD, a as META_ATTRIBUTE, c as STATIC_ATTRIBUTE, f as metaMarkup, i as FOLDKIT_APP_ATTRIBUTE, n as SSR, o as RESUME_ATTRIBUTE, r as UNTIL_LIMIT_MS, s as ResumeRefused, t as Resume } from "./client-ASzkY6Sw.mjs";
|
|
2
|
+
export { BINDING_ATTRIBUTE, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { C as ResumableBuilder, S as FALLBACK_FIELD, _ as DecodedBinding, a as Loadable, b as UnnamedHandler, c as RESUME_ATTRIBUTE, d as ResumePlan, f as ResumeRefused, g as metaMarkup, h as Start, i as FOLDKIT_APP_ATTRIBUTE, l as ResumableConfig, m as STATIC_ATTRIBUTE, o as META_ATTRIBUTE, p as RouteMatch, r as UNTIL_LIMIT_MS, s as Meta, t as Resume, u as ResumePart, v as EncodedBinding, w as SLOT_ATTRIBUTE, x as BINDING_ATTRIBUTE, y as Region } from "./client-BDyZf200.mjs";
|
|
2
2
|
import { Cause, Effect, Result, Schema } from "effect";
|
|
3
3
|
import { EntryModule, RenderError, RenderedApplication } from "foldkit/experimental/server";
|
|
4
4
|
import { MetadataSummary } from "foldkit-surface";
|
|
@@ -139,6 +139,7 @@ export declare const SSR: {
|
|
|
139
139
|
readonly buildId: string;
|
|
140
140
|
readonly when?: ((page: Document) => boolean) | undefined;
|
|
141
141
|
readonly otherwise?: "render" | undefined;
|
|
142
|
+
readonly until?: ((model: Model) => boolean) | undefined;
|
|
142
143
|
readonly fresh?: ((version: unknown) => boolean) | undefined;
|
|
143
144
|
}) => void;
|
|
144
145
|
inspect: <Model, Fields extends Schema.Struct.Fields>(plan: ResumePlan<Model, Fields>, model: Model) => PlanInspection;
|
|
@@ -182,5 +183,5 @@ export declare const SSR: {
|
|
|
182
183
|
}) => string;
|
|
183
184
|
};
|
|
184
185
|
//#endregion
|
|
185
|
-
export { BINDING_ATTRIBUTE, type DecodedBinding, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, RESUME_ATTRIBUTE, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, STATIC_ATTRIBUTE, type Start, type UnnamedHandler, metaMarkup };
|
|
186
|
+
export { BINDING_ATTRIBUTE, type DecodedBinding, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, RESUME_ATTRIBUTE, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, STATIC_ATTRIBUTE, type Start, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
|
|
186
187
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;UAmFU;WACC;WACA,QAAQ;WACR,WAAW,cAAc;;WAEzB,SAAS;;;YA6HR;;iBAGK;WACN;;WAEA;;WAEA;aAAwB;aAAuB,OAAO;;;WAEtD,OAAO;aAAyB;aAAuB,OAAO;;;;;;WAK9D,WAAW,cAAc;;WAEzB;;;iBAIM;WACN;WACA,OAAO;WACP,OAAO;;WAEP,OAAO;WACP,UAAU,cAAc;;;;;;;qBAuHtB,qBAAqB;;iBA+HjB;;;;;;WAMN,UAAU;;WAEV;;WAEA;;;;;WAKA,SAAS,cAAc;;;;;;;;YAkMtB,QAAQ,UAAU;;iBAmEb;WACN;WACA;WACA;;;;;;YAOC,eAAe,cAAc,qCAC7B,WAAW,QAAQ;;;;;;qBAgTlB,wBAAwB;qBA+LxB;;;aAz8B0C;aAE/C,UAAA,OAAA;;;;aAIH,WAAC;aAAqC,SAAC,OAAA,UAAA;aACgB,QAAC;;;aAIrD,WAAF,wCAAA,cAAA;aAGQ,QAAb,cAAA,WAAA;aACqC,QADrC;aAE0B,aAAC;aAEhB;aACkB,SAAC,OAAA,UAAA;aAErB;;EA9NQ,WAAA,OAAO,eAAe,OAAO,OAAO,QAAM,QAClD,WAAW,OAAO,SAAO,OAC1B,OAAK,UACH;;aAmWG;;EA6DE,SAAA,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAO,QACzD,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;aAEpB;aACA;aACA;;;;;;;aAOA,SAAS;QAEnB,OAAO,OAAO,cAAc,cAAc;EA4NjC,OAAA,kBAAM;aACG,UAAU;aAA8B;KAAc;aACrD,OAAO;;;;aAnqBwC,SAAC,MAAA;aAS/B;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;UAmFU;WACC;WACA,QAAQ;WACR,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AEpB;aACA;aACA;aACA,OAAO;aACP,UAAU;aACV,OAAO;QAEjB,OAAO,OAAO,eAAe,QAAQ,cAAc;EAyEvC,QAAA,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAO,QACxD,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;aAEpB;aACA,UAAU,SAAS,sBAAsB;aACzC,YAAY,SAAS,YAAY;;;;;;aAMjC,SAAS;QAEnB;EAgNa,SAAA,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAO,SACxD,SAAO,QACR,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;aAEpB;aACA;aACA,SAAS;QAEnB,OAAO,OAAO,cAAc,cAAc,eAAe;;EA/YnD,UAAA,OAAA;aAAyB;aAAuB;MAAgC;aACnE;;EA4BG,SAAA;aACd;aACA;aACA,WAAW"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { C as BINDING_ATTRIBUTE, D as withContext, E as SLOT_ATTRIBUTE, S as tagOf, T as FALLBACK_FIELD, _ as routeOf, a as META_ATTRIBUTE, b as startingFrom, c as STATIC_ATTRIBUTE, d as codecOf, f as metaMarkup, g as resume, h as plan, i as FOLDKIT_APP_ATTRIBUTE, l as allowedTags, m as pathKey, n as SSR$1, o as RESUME_ATTRIBUTE, p as modelFrom, r as UNTIL_LIMIT_MS, s as ResumeRefused, t as Resume, u as attributeOf, v as serializeJsonScript, w as FALLBACK_DEPTH_FIELD, x as staticRegion, y as serving } from "./client-ASzkY6Sw.mjs";
|
|
2
2
|
import { Cause, Effect, Exit, Option, Result, Schema } from "effect";
|
|
3
3
|
import { FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, renderToString } from "foldkit/experimental/server";
|
|
4
4
|
import { Metadata } from "foldkit-surface";
|
|
@@ -747,6 +747,6 @@ const SSR = {
|
|
|
747
747
|
robots
|
|
748
748
|
};
|
|
749
749
|
//#endregion
|
|
750
|
-
export { BINDING_ATTRIBUTE, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, FallbackRefused, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, metaMarkup };
|
|
750
|
+
export { BINDING_ATTRIBUTE, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, FallbackRefused, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
|
|
751
751
|
|
|
752
752
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Client"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-ssr`: what crosses from the server to the browser when a page is\n * rendered on one and resumed on the other.\n *\n * Built from the plan in `docs/design/ssr-PLAN.md`. A resume plan names the\n * slice of the Model the browser owns. The server writes that slice onto the\n * stamped root as a JSON attribute, beside Foldkit's own stamps; the browser\n * reads it back and sets it onto a baseline\n * Model. Nothing outside the slice crosses, and a payload that cannot be read\n * back exactly is refused, never half-restored.\n *\n * Rendering and hydrating stay Foldkit's own: this package adds only the\n * handover. This module is the server's side and the browser's\n * (`foldkit-ssr/client`) together.\n */\nimport { Cause, Effect, Exit, Option, Result, Schema } from 'effect'\nimport {\n FOLDKIT_FLAGS_ATTRIBUTE,\n Rendered,\n Responded,\n injectIntoTemplate,\n renderToString,\n type EntryModule,\n type EntryResult,\n type RenderError,\n type RenderedApplication,\n} from 'foldkit/experimental/server'\nimport { Metadata, type MetadataSummary } from 'foldkit-surface'\nimport { withContext, type Binding, type Region, type UnnamedHandler } from './context.js'\nimport { type EncodedBinding } from './listen.js'\nimport { FALLBACK_DEPTH_FIELD, FALLBACK_FIELD } from './resumable.js'\nimport { SSR as Client } from './client.js'\nimport {\n PROTOCOL,\n allowedTags,\n attributeOf,\n codecOf,\n modelFrom,\n metaMarkup,\n pathKey,\n plan,\n resume,\n routeOf,\n serializeJsonScript,\n serving,\n startingFrom,\n staticRegion,\n tagOf,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type RouteMatch,\n} from './shared.js'\n\n/** The projections of the plan's Surfaces that are active for `model`. */\nconst activeProjections = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n) => plan.surfaces.flatMap(surface => Option.toArray(surface.projectionOf(model)))\n\n/** What the envelope carries of a Model: the encoded slice, and each part's capture. */\ninterface Payload {\n readonly state: unknown\n readonly parts?: Readonly<Record<string, unknown>>\n}\n\n/**\n * What the envelope carries of `model`: the plan's slice, encoded through its\n * own Schema, and each part's capture.\n */\nconst payloadOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): Payload => {\n const state = Schema.encodeSync(codecOf(plan.state.schema))(plan.state.get(model))\n if (plan.parts.length === 0) return { state }\n const projections = activeProjections(plan, model)\n return {\n state,\n parts: Object.fromEntries(plan.parts.map(part => [part.id, part.capture(model, projections)])),\n }\n}\n\ninterface EnvelopeOptions {\n readonly route?: string | undefined\n readonly match?: RouteMatch | undefined\n readonly bindings?: ReadonlyArray<EncodedBinding> | undefined\n /** Every event the page's markers name, so the browser listens without scanning for them. */\n readonly events?: ReadonlyArray<string> | undefined\n}\n\n/**\n * The envelope for `model`: the plan's slice, each part's capture, and\n * the route it was rendered for, if it was rendered for one. `SSR.render`\n * carries it on the stamped root, beside Foldkit's own stamps, escaped for\n * the attribute; this is the same JSON unescaped, for tests and hosts that\n * place the page themselves.\n */\nconst envelope = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n model: Model,\n options: EnvelopeOptions = {},\n): string => envelopeOf(resume, payloadOf(resume, model), options)\n\n/**\n * The envelope for a payload already built: the JSON the stamped root carries.\n */\nconst envelopeOf = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n payload: Payload,\n options: EnvelopeOptions,\n): string =>\n serializeJsonScript({\n v: PROTOCOL,\n plan: resume.id,\n ...payload,\n ...(options.route === undefined ? {} : { route: options.route }),\n ...(options.match === 'path' ? { match: 'path' } : {}),\n ...(options.bindings === undefined || options.bindings.length === 0\n ? {}\n : { bindings: options.bindings }),\n ...(options.events === undefined || options.events.length === 0\n ? {}\n : { events: options.events }),\n })\n\n/**\n * The rendered application with the envelope on its stamped root, beside\n * Foldkit's own app and build stamps. `injectIntoTemplate` accepts the\n * envelope there, as part of the root, and refuses it beside the root, so a\n * page the host injects carries the handover without the entry owning the\n * template. Hydration adopts the server's nodes around it and drops the\n * attribute on its first patch, so the browser reads the envelope before it\n * boots.\n */\nconst withEnvelopeAttribute = (html: string, json: string): string => {\n const stamp = 'data-foldkit-app=\"'\n // The stamp names the root's open tag: it opens the markup, and no quoted\n // attribute value before it may hold a `>` of its own, which would end a\n // naive scan early, or the stamp string itself. A stamp past the tag's end,\n // or in text, is not the root.\n let from = 0\n for (;;) {\n const at = html.indexOf(stamp, from)\n if (at === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n if (isInRootTag(html, at)) {\n const end = html.indexOf('\"', at + stamp.length)\n if (end === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n return `${html.slice(0, end + 1)}${attributeOf(json)}${html.slice(end + 1)}`\n }\n from = at + stamp.length\n }\n}\n\n/** Whether `at` sits inside the markup's first tag: quoted values skipped whole. */\nconst isInRootTag = (html: string, at: number): boolean => {\n if (!html.startsWith('<')) return false\n let index = 1\n while (index < at) {\n const char = html[index]\n if (char === '\"' || char === \"'\") {\n const close = html.indexOf(char, index + 1)\n if (close === -1 || close >= at) return false\n index = close + 1\n } else if (char === '>') {\n return false\n } else {\n index++\n }\n }\n return true\n}\n\n/**\n * The rendered markup with `extra` as the root's last child, so the first\n * paint is styled before any script runs where no template head can take it.\n * A void root holds no children: styles for one are refused, naming the tag,\n * rather than served where no browser could keep them.\n */\nconst withInRoot = (html: string, extra: string): Result.Result<string, ResumeUnsafe> => {\n const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1]\n const at = tag === undefined ? -1 : html.search(new RegExp(`</${tag}>\\\\s*$`))\n if (tag === undefined || at === -1) {\n return Result.fail(\n new ResumeUnsafe({\n reason: 'VoidRootWithStyles',\n message: `styles need a root element that can hold them, but the view returned <${tag ?? '?'}>: put the styles in the template's head with SSR.generate, or return an element root`,\n }),\n )\n }\n return Result.succeed(`${html.slice(0, at)}${extra}${html.slice(at)}`)\n}\n\n/**\n * The Model the browser will start from when the server's Model is `model`:\n * the payload taken through the page as the envelope carries it, as JSON, and\n * resumed exactly as `SSR.resume` resumes it. A part that cannot restore its\n * own capture fails here, on the server.\n */\nconst browserModelOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: Payload,\n): Result.Result<Model, string> => modelFrom(plan, JSON.parse(serializeJsonScript(payload)))\n\n/** Where the browser gets a Model path's value: the envelope, the baseline, or nowhere it may. */\nexport type Cover = 'state' | 'local' | 'missing'\n\n/** One Surface as a plan covers it, for the server's Model. */\nexport interface SurfaceCoverage {\n readonly name: string\n /** Whether the Surface is active for the server's Model. */\n readonly active: boolean\n /** The place a `Surface.when` activation reads; absent for `Surface.at`. */\n readonly activation?: { readonly path: string; readonly cover: Cover } | undefined\n /** The Model paths the active Surface reads. */\n readonly reads: ReadonlyArray<{ readonly path: string; readonly cover: Cover }>\n /**\n * What the active Surface reads that no Model path names, such as Remote\n * data, by its metadata. The slice cannot carry it.\n */\n readonly unresumed: ReadonlyArray<MetadataSummary>\n /** Whether the browser's Model activates it the same way, with the same reads. */\n readonly sameInBrowser: boolean\n}\n\n/** What a plan sends, what it leaves local, and how it covers each Surface. */\nexport interface PlanInspection {\n readonly id: string\n readonly state: ReadonlyArray<string>\n readonly local: ReadonlyArray<string>\n /** The ids of the parts that resume state the slice cannot carry. */\n readonly parts: ReadonlyArray<string>\n readonly surfaces: ReadonlyArray<SurfaceCoverage>\n}\n\nconst pathOf = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? '(the whole Model)' : path.join('.')\n\n/**\n * A path is covered by a sent or local path equal to it or containing it. An\n * empty path is the whole Model, which no pick covers.\n */\nconst coverOf = (\n path: ReadonlyArray<string>,\n plan: {\n readonly state: { readonly dependencies: ReadonlyArray<ReadonlyArray<string>> }\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n },\n): Cover => {\n const contains = (outer: ReadonlyArray<string>) =>\n outer.length > 0 &&\n outer.length <= path.length &&\n outer.every((key, index) => path[index] === key)\n if (plan.state.dependencies.some(contains)) return 'state'\n if (plan.local.some(contains)) return 'local'\n return 'missing'\n}\n\n/** A projection's reads as one comparable string, or `inactive`. */\nconst readsKey = (\n projection:\n | {\n readonly dependencies: ReadonlyArray<ReadonlyArray<string>>\n readonly metadata: Metadata\n }\n | undefined,\n): string =>\n projection === undefined\n ? 'inactive'\n : JSON.stringify([projection.dependencies, Metadata.summarize(projection.metadata)])\n\n/**\n * How a plan covers each of its Surfaces when the server's Model is `model`.\n * A Surface's reads depend on the Model, through its params, so coverage is\n * worked out for a Model, not for the plan alone.\n */\nconst inspect = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): PlanInspection => {\n const resumed = browserModelOf(plan, payloadOf(plan, model))\n if (Result.isFailure(resumed)) throw new Error(`SSR.inspect: ${resumed.failure}`)\n return coverage(plan, model, resumed.success)\n}\n\n/** How a plan covers its Surfaces, given the server's Model and the browser's. */\nconst coverage = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n browser: Model,\n): PlanInspection => {\n const covered = new Set(plan.parts.flatMap(part => part.covers))\n return {\n id: plan.id,\n state: plan.state.dependencies.map(pathOf),\n local: plan.local.map(pathOf),\n parts: plan.parts.map(part => part.id),\n surfaces: plan.surfaces.map(surface => {\n const served = Option.getOrUndefined(surface.projectionOf(model))\n return {\n name: surface.name,\n active: served !== undefined,\n ...(surface.activation === undefined\n ? {}\n : {\n activation: {\n path: pathOf(surface.activation.path),\n cover: coverOf(surface.activation.path, plan),\n },\n }),\n reads: (served?.dependencies ?? []).map(path => ({\n path: pathOf(path),\n cover: coverOf(path, plan),\n })),\n unresumed:\n served === undefined\n ? []\n : Metadata.summarize(served.metadata).filter(summary => !covered.has(summary.name)),\n sameInBrowser:\n readsKey(served) === readsKey(Option.getOrUndefined(surface.projectionOf(browser))),\n }\n }),\n }\n}\n\n/** Each way an inspection shows the plan falls short, one line each. */\nconst shortfalls = (inspection: PlanInspection): ReadonlyArray<string> =>\n inspection.surfaces.flatMap(surface => [\n ...(surface.activation?.cover === 'missing'\n ? [\n `Surface \"${surface.name}\" is activated by ${surface.activation.path}, which is neither in the plan's state nor local`,\n ]\n : []),\n ...surface.reads\n .filter(read => read.cover === 'missing')\n .map(\n read =>\n `Surface \"${surface.name}\" reads ${read.path}, which is neither in the plan's state nor local`,\n ),\n ...surface.unresumed.map(\n summary =>\n `Surface \"${surface.name}\" reads ${summary.name} data (${summary.entries.join(', ')}), which no part of the plan resumes`,\n ),\n ...(surface.sameInBrowser\n ? []\n : [\n `Surface \"${surface.name}\" is ${surface.active ? 'active' : 'inactive'} on the server and activates differently from the Model the browser starts from`,\n ]),\n ])\n\n/** Why a server refused to render a page against its plan. */\nexport class ResumeUnsafe extends Schema.TaggedError<ResumeUnsafe>()('ResumeUnsafe', {\n reason: Schema.Literals([\n 'UndeclaredStartup',\n 'Uncovered',\n 'ViewDependsOnUnsentState',\n 'DuplicateStaticRegion',\n 'UngeneratablePath',\n 'UnrestorablePart',\n 'UnencodableBinding',\n 'EagerStartRequired',\n 'UndeclaredSurfaces',\n 'BindingInStaticRegion',\n 'VoidRootWithStyles',\n ]),\n message: Schema.String,\n}) {}\n\n/** Each binding whose Message no active Surface lists, one line each. */\nconst unlistedBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n bindings: ReadonlyArray<Binding>,\n): ReadonlyArray<string> => {\n const allowed = allowedTags(plan, model)\n return bindings\n .filter(binding => !allowed.has(tagOf(binding.message)))\n .map(\n binding =>\n `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`,\n )\n}\n\n/** Loads every lazy bundle's bodies, so the view renders whole. */\nconst loadLazy = (config: { readonly lazy?: ReadonlyArray<Loadable> | undefined }) =>\n Effect.promise(() => Promise.all((config.lazy ?? []).map(bundle => bundle.load())))\n\n/** Foldkit's own Flags script, which a resumed page never carries. */\nconst FLAGS_SCRIPT = new RegExp(\n `<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\\\s\\\\S]*?</script>`,\n 'g',\n)\n\n/**\n * The head fields a render returns beside the body. Each is read by the view,\n * so each must come out the same from the browser's Model; since Foldkit 0.163\n * none has a default from the URL.\n */\nconst HEAD_FIELDS = ['title', 'lang', 'dir', 'canonical', 'ogUrl'] as const\n\n/** A render's bindings, encoded, or why one cannot be. */\nconst encodeBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n bindings: ReadonlyArray<Binding>,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (bindings.length === 0) return Result.succeed([])\n if (plan.Message === undefined) {\n return Result.fail(\n 'the page has bindings, and the plan has no Message Schema to encode them with: make the plan from the application',\n )\n }\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const out: Array<EncodedBinding> = []\n for (const binding of bindings) {\n const message = encode(binding.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `the ${binding.event} binding on ${binding.element} does not encode as a Message: ${message.failure.message}`,\n )\n }\n out.push({\n attribute: binding.attribute,\n message: message.success,\n ...(binding.hole === undefined ? {} : { hole: binding.hole }),\n ...(binding.depth === undefined ? {} : { depth: binding.depth }),\n ...(binding.options === undefined ? {} : { options: binding.options }),\n })\n }\n return Result.succeed(out)\n}\n\n/**\n * The bindings that differ between the server's render and the browser's, by\n * element: a Message built from a field the plan does not send would dispatch\n * one Message before boot and another after.\n */\nconst changedBindings = (\n served: ReadonlyArray<Binding>,\n encoded: ReadonlyArray<EncodedBinding>,\n reencoded: ReadonlyArray<EncodedBinding>,\n): ReadonlyArray<string> =>\n served.flatMap((binding, index) =>\n JSON.stringify(encoded[index]) === JSON.stringify(reencoded[index])\n ? []\n : [`${binding.event} binding on ${binding.element}`],\n )\n\n/**\n * The Subscription and Managed Resource entries that would start late under a\n * deferred boot and are not declared deferrable, by the plan or by a part.\n * Foldkit starts every Subscription's stream at boot, so every entry counts; a\n * Managed Resource counts when the Model asks for it.\n */\nconst eagerEntries = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlyArray<string> => {\n if (plan.start === 'now') return []\n const declared = (key: string, entry: unknown) =>\n plan.deferrable.includes(key) || plan.parts.some(part => part.deferrable?.(key, entry) === true)\n const subscriptions = Object.entries(config.subscriptions ?? {}).filter(\n ([key, entry]) => !declared(key, entry),\n )\n const resources = Object.entries(config.managedResources ?? {}).filter(([key, entry]) => {\n const asks = (\n entry as { modelToMaybeRequirements?: (model: Model) => unknown }\n ).modelToMaybeRequirements?.(model)\n const active = Option.isOption(asks) ? Option.isSome(asks) : asks !== undefined\n return active && !declared(key, entry)\n })\n return [\n ...subscriptions.map(([key]) => `subscription \"${key}\"`),\n ...resources.map(([key]) => `resource \"${key}\"`),\n ]\n}\n\n/** A page the server rendered against a plan, with its envelope. */\nexport interface RenderedPage {\n /**\n * The rendered application with the envelope on its stamped root, so\n * Foldkit's `injectIntoTemplate` places the page whole: the host owns the\n * template, and the entry never splices markup into it.\n */\n readonly rendered: RenderedApplication\n /** The envelope, as carried on the root, for tests and custom hosts. */\n readonly envelope: string\n /** The head markup of the plan's `meta`, empty without one. */\n readonly meta: string\n /**\n * Each element whose handler for an event is a function, marked `*`: the\n * page cannot answer that event before the live runtime boots.\n */\n readonly unnamed: ReadonlyArray<UnnamedHandler>\n}\n\n/**\n * Renders a page on the server against a resume plan.\n *\n * The application's `init` runs once. Its Model's slice is round-tripped\n * through the plan's Schema and set onto the baseline, which is the Model the\n * browser will start from, and the page is rendered from that Model. Every\n * way the browser could start somewhere else is a `ResumeUnsafe`, whose\n * `reason` names it; the README lists them. The one that matters most: the\n * view rendered from the browser's Model differs from the one rendered from\n * the server's, because it reads a field the plan leaves out. In production\n * Foldkit would rebuild that part of the page silently, so this is the one\n * place it shows.\n */\nconst render = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly url?: string | undefined\n readonly flags?: unknown\n /**\n * Markup for the first paint, given what was rendered, carried as the\n * root's last child: keep it to `<style>`, which the browser drops on\n * hydration. Anything a head owns (`meta`, links) stays with `SSR.page`\n * and `SSR.generate`.\n */\n readonly styles?: Head | undefined\n },\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe> =>\n renderMatching(config, plan, options, 'full')\n\nconst renderMatching = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly url?: string | undefined\n readonly flags?: unknown\n readonly styles?: Head | undefined\n },\n match: RouteMatch,\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n yield* loadLazy(config)\n let served: ReturnType<ResumableConfig<Model>['init']> | undefined\n const regions = new Map<string, Region>()\n const duplicates = new Set<string>()\n const servedBindings: Array<Binding> = []\n const browserBindings: Array<Binding> = []\n const inStatic: Array<{ region: string; element: string; event: string }> = []\n const unnamed: Array<UnnamedHandler> = []\n const fallback = fallbackEncoder(plan)\n const capturing = withContext(\n { ...config, init: (...args: ReadonlyArray<unknown>) => (served = config.init(...args)) },\n {\n mode: 'collect',\n regions,\n duplicates,\n bindings: servedBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n region: undefined,\n inStatic,\n unnamed,\n },\n )\n const full = yield* renderToString(capturing as never, options as never)\n if (duplicates.size > 0) {\n return yield* new ResumeUnsafe({\n reason: 'DuplicateStaticRegion',\n message: `two static regions share the id ${[...duplicates].map(id => `\"${id}\"`).join(', ')}: the browser could adopt only one`,\n })\n }\n if (inStatic.length > 0) {\n const found = inStatic.map(\n ({ region, element, event }) => `a ${event} handler on ${element} in \"${region}\"`,\n )\n return yield* new ResumeUnsafe({\n reason: 'BindingInStaticRegion',\n message: `a static region is the server's alone, and these would never run: ${found.join(', ')}. What a Message changes belongs in a Surface`,\n })\n }\n const started = served!\n const commands = started.commands ?? []\n if (commands.length > 0 && plan.boot === undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredStartup',\n message: `init returned ${commands.map(command => command.name).join(', ')}, which no browser would run: name them in the plan's boot`,\n })\n }\n\n // Built once: each part's capture reads the whole store it owns.\n const payload = payloadOf(plan, started.model)\n const resumed = browserModelOf(plan, payload)\n if (Result.isFailure(resumed)) {\n return yield* new ResumeUnsafe({ reason: 'UnrestorablePart', message: resumed.failure })\n }\n const browser = resumed.success\n\n const eager = eagerEntries(config, plan, started.model)\n if (eager.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'EagerStartRequired',\n message: `the plan starts ${plan.start}, and these would start late: ${eager.join(', ')}. Name each in the plan's deferrable, or start now`,\n })\n }\n\n if (servedBindings.length > 0 && plan.surfaces.length === 0) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredSurfaces',\n message: `the page has ${servedBindings.length} binding${servedBindings.length === 1 ? '' : 's'} and the plan declares no surfaces, so nothing says which Messages it may dispatch: name them in the plan's surfaces`,\n })\n }\n const uncovered = [\n ...shortfalls(coverage(plan, started.model, browser)),\n ...unlistedBindings(plan, started.model, servedBindings),\n ]\n if (uncovered.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'Uncovered',\n message: `the plan does not cover what the browser reads:\\n- ${uncovered.join('\\n- ')}`,\n })\n }\n\n // With no `Flags` key in the config, Foldkit writes no Flags script.\n const rendered = yield* renderToString(\n withContext(startingFrom(config, { model: browser }), {\n mode: 'replay',\n regions,\n bindings: browserBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n }) as never,\n options as never,\n )\n const encoded = encodeBindings(plan, servedBindings)\n const reencoded = encodeBindings(plan, browserBindings)\n if (Result.isFailure(encoded)) {\n return yield* new ResumeUnsafe({ reason: 'UnencodableBinding', message: encoded.failure })\n }\n const meta = plan.meta === undefined ? '' : metaMarkup(plan.meta(started.model))\n const differing = [\n ...(full.html.replace(FLAGS_SCRIPT, '') === rendered.html ? [] : ['body']),\n ...HEAD_FIELDS.filter(field => full[field] !== rendered[field]),\n ...(plan.meta === undefined || metaMarkup(plan.meta(browser)) === meta ? [] : ['meta']),\n ...changedBindings(\n servedBindings,\n encoded.success,\n Result.isFailure(reencoded) ? [] : reencoded.success,\n ),\n ]\n if (differing.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'ViewDependsOnUnsentState',\n message: `the view differs in its ${differing.join(', ')} when rendered from the Model the browser will start from: it reads a field the plan leaves out`,\n })\n }\n const envelope = envelopeOf(plan, payload, {\n ...(options.url === undefined\n ? {}\n : { route: match === 'path' ? pathKey(routeOf(options.url)) : routeOf(options.url) }),\n match,\n bindings: encoded.success,\n events: [\n ...new Set([\n ...servedBindings.map(binding => binding.event),\n ...unnamed.map(handler => handler.event),\n ]),\n ].sort(),\n })\n const styled =\n options.styles === undefined\n ? Result.succeed(rendered.html)\n : withInRoot(rendered.html, options.styles(rendered))\n if (Result.isFailure(styled)) return yield* styled.failure\n return {\n rendered: { ...rendered, html: withEnvelopeAttribute(styled.success, envelope) },\n meta,\n envelope,\n unnamed,\n }\n })\n\n/**\n * What a page adds to its head, given what it rendered: such as a stylesheet\n * of the classes the markup uses (`Style.usedIn` in `foldkit-mixins`). The\n * same shape describes `styles`, which rides in the rendered root instead,\n * for pages whose template the host owns.\n */\nexport type Head = (rendered: RenderedApplication) => string\n\n/**\n * The template with `extra` before its last `</head>`, as a slice for the same\n * reason as the envelope. Nothing to add leaves it as it is; something to add\n * and no `</head>` is refused, rather than dropped.\n */\nconst withHead = (template: string, extra: string): string => {\n if (extra === '') return template\n const at = template.search(/<\\/head>(?![\\s\\S]*<\\/head>)/i)\n if (at === -1) throw new Error('foldkit-ssr: the template has no </head> to put the head in')\n return `${template.slice(0, at)}${extra}${template.slice(at)}`\n}\n\n/**\n * Foldkit fills `canonical` and `og:url` only into a tag the template already\n * has, and leaves the page without one otherwise. A render that sets either\n * and a template without its tag is refused, naming the tag.\n */\nconst FILLED_TAGS = [\n {\n field: 'canonical',\n tag: '<link rel=\"canonical\" href=\"\">',\n at: /<link\\b[^>]*\\brel\\s*=\\s*[\"']?canonical[\"'\\s>]/i,\n },\n {\n field: 'ogUrl',\n tag: '<meta property=\"og:url\" content=\"\">',\n at: /<meta\\b[^>]*\\bproperty\\s*=\\s*[\"']?og:url[\"'\\s>]/i,\n },\n] as const\n\nconst withFilledTags = (template: string, rendered: RenderedApplication): string => {\n const missing = FILLED_TAGS.filter(\n ({ field, at }) => rendered[field] !== undefined && !at.test(template),\n )\n if (missing.length > 0) {\n throw new Error(\n `foldkit-ssr: the view sets ${missing.map(({ field }) => field).join(' and ')}, and the template has no ${missing.map(({ tag }) => tag).join(' or ')} for Foldkit to fill: add it to the template's head`,\n )\n }\n return template\n}\n\n/** The plan's `meta`, then what `head` adds, one line apart. */\nconst headOf = (\n result: { readonly rendered: RenderedApplication; readonly meta: string },\n head: Head | undefined,\n): string => [result.meta, head?.(result.rendered) ?? ''].filter(markup => markup !== '').join('\\n')\n\n/**\n * The page to serve: the rendered application in the template, with the\n * plan's `meta` and `head`'s markup, if any, before `</head>`. The envelope\n * is already in the rendered root, so this is Foldkit's `injectIntoTemplate`\n * with a head, and nothing else.\n */\nconst page = (\n template: string,\n result: { readonly rendered: RenderedApplication; readonly meta: string },\n options: { readonly head?: Head | undefined } = {},\n): string =>\n injectIntoTemplate(\n withHead(withFilledTags(template, result.rendered), headOf(result, options.head)),\n result.rendered,\n )\n\n/** A page generated at build time, and the file a static host serves it from. */\nexport interface GeneratedPage {\n readonly path: string\n readonly file: string\n readonly html: string\n}\n\n/**\n * One generated page per path, in the paths' order: a tuple when the paths\n * are written out, so `const [home, about] = pages` needs no check.\n */\nexport type GeneratedPages<Paths extends ReadonlyArray<string>> = {\n readonly [K in keyof Paths]: GeneratedPage\n}\n\n/** The file a static host serves for a path: `/about` is `about/index.html`. */\nconst fileOf = (path: string): string => {\n const trimmed = path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n if (trimmed === '') return 'index.html'\n return trimmed.endsWith('.html') ? trimmed : `${trimmed}/index.html`\n}\n\nconst xmlText = (text: string): string =>\n text\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''')\n\n/**\n * A sitemap of the pages a build generated, each at its full address under\n * `origin`, in the order given. `modified`, when a page has it, is any date\n * `Date` reads, written as the UTC day. A path that does not start with `/`,\n * a path given twice, and a date `Date` cannot read are refused: each would\n * make a sitemap a search engine rejects or misreads.\n */\nconst sitemap = (\n pages: ReadonlyArray<{ readonly path: string; readonly modified?: string | undefined }>,\n options: { readonly origin: string },\n): string => {\n const seen = new Set<string>()\n const urls = pages.map(({ path, modified }) => {\n if (!path.startsWith('/')) throw new Error(`SSR.sitemap: \"${path}\" does not start with /`)\n if (seen.has(path)) throw new Error(`SSR.sitemap: \"${path}\" is listed twice`)\n seen.add(path)\n const loc = `<loc>${xmlText(new URL(path, options.origin).href)}</loc>`\n if (modified === undefined) return ` <url>${loc}</url>`\n const at = new Date(modified)\n if (Number.isNaN(at.getTime())) {\n throw new Error(`SSR.sitemap: \"${modified}\", the date of \"${path}\", is not a date`)\n }\n return ` <url>${loc}<lastmod>${at.toISOString().slice(0, 10)}</lastmod></url>`\n })\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n ...urls,\n '</urlset>',\n '',\n ].join('\\n')\n}\n\n/**\n * A `robots.txt` that lets every crawler in, except under `disallow`, and\n * names the sitemap at `sitemap` (default `/sitemap.xml`) under `origin`.\n */\nconst robots = (options: {\n readonly origin: string\n readonly sitemap?: string | undefined\n readonly disallow?: ReadonlyArray<string> | undefined\n}): string =>\n [\n 'User-agent: *',\n 'Allow: /',\n ...(options.disallow ?? []).map(path => `Disallow: ${path}`),\n '',\n `Sitemap: ${new URL(options.sitemap ?? '/sitemap.xml', options.origin).href}`,\n '',\n ].join('\\n')\n\n// Keyed by plan, element and event: a server renders the same page for every\n// request, so one warning each is enough to learn which handler to name.\nconst warnedUnnamed = new Set<string>()\n\n/**\n * Warns, once per process, about each handler that keeps a page from\n * answering before boot. Only a page that waits to boot is held up: one\n * started `'now'`, with no lazy bundle to load, boots before any event.\n */\nconst warnUnnamed = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n unnamed: ReadonlyArray<UnnamedHandler>,\n): void => {\n if (plan.start === 'now' && (config.lazy ?? []).length === 0) return\n for (const { element, event } of unnamed) {\n const key = JSON.stringify([plan.id, element, event])\n if (warnedUnnamed.has(key)) continue\n warnedUnnamed.add(key)\n console.warn(\n `[foldkit-ssr] plan \"${plan.id}\": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,\n )\n }\n}\n\n/**\n * Renders pages at build time, one per path, each as `SSR.render` and\n * `SSR.page` would, to be written as files. `origin` makes each path the full\n * URL a routing application parses. `flags`, when the application has them,\n * gives each path its own.\n *\n * A generated page records its path alone: a static host serves the same file\n * whatever the query, so the browser checks the path and ignores the query. A\n * path with a query or fragment, or two paths that would be one file, are\n * refused.\n */\nconst generate = <\n Model,\n Fields extends Schema.Struct.Fields,\n const Paths extends ReadonlyArray<string>,\n Message = any,\n>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly template: string\n readonly origin: string\n readonly paths: Paths\n readonly flags?: ((path: string) => unknown) | undefined\n readonly head?: Head | undefined\n },\n): Effect.Effect<GeneratedPages<Paths>, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n const files = new Map<string, string>()\n for (const path of options.paths) {\n if (!path.startsWith('/') || /[?#]/.test(path)) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${path}\" is not a path a file can be served at: start it with / and leave out any query or fragment`,\n })\n }\n const other = files.get(fileOf(path))\n if (other !== undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${other}\" and \"${path}\" would both be written to ${fileOf(path)}`,\n })\n }\n files.set(fileOf(path), path)\n }\n const pages = yield* Effect.forEach(options.paths, path =>\n Effect.map(\n renderMatching(\n config,\n plan,\n {\n buildId: options.buildId,\n url: new URL(path, options.origin).href,\n ...(options.flags === undefined ? {} : { flags: options.flags(path) }),\n },\n 'path',\n ),\n result => {\n warnUnnamed(config, plan, result.unnamed)\n return {\n path,\n file: fileOf(path),\n html: page(options.template, result, { head: options.head }),\n }\n },\n ),\n )\n // One page per path, in order, so the array is the tuple the paths describe.\n return pages as unknown as GeneratedPages<Paths>\n })\n\n/**\n * The server entry for Foldkit's pipeline: the `renderPage` a dev server,\n * a fetch handler, or `handleRequest` calls, and that the `fetch.js` a Foldkit\n * build emits imports from the server entry module, so a resumed page is\n * served by Node and Workers alike.\n *\n * `GET` and `HEAD` render the page against the plan, with the request's URL\n * and, when the application has Flags, `flags(request)`. `POST` goes to\n * `SSR.handle` when the plan has a server fallback, and is answered `400` when\n * the post is unusable. `OPTIONS` is answered `204`, and any other method\n * `405`, each with the methods the entry answers in `allow` (`handleRequest`\n * passes every method through). A render that fails, or a plan the render\n * refuses, is answered `500` with the reason logged, never with a page the\n * browser cannot resume. `headers(request)` rides on the `Rendered` result, so\n * Foldkit's `toResponse` sets it over its own on the page: a cache policy, or\n * a CORS answer to a preflight.\n *\n * The page is answered as `Rendered`: the rendered application carries the\n * envelope in its root, so the host injects it into its own template with\n * Foldkit's `injectIntoTemplate`, and a build can generate it with Foldkit's\n * `prerender`. The template, and the container it fills, are the host's:\n * `handleRequest` still classifies static misses and answers `HEAD` without\n * a body.\n *\n * What the page says of itself (`meta`) and per-page `head` markup are\n * written into a template's head, which the host owns here: a plan with\n * `meta` is refused when the entry is made, and served with `SSR.generate`.\n */\nconst entry = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly flags?: ((request: Request) => unknown | PromiseLike<unknown>) | undefined\n readonly headers?: ((request: Request) => HeadersInit) | undefined\n /**\n * Markup for the first paint, carried as the rendered root's last child.\n * The host owns the template in dynamic serving, so this is where\n * per-page styles go; anything a head owns stays with `SSR.generate`.\n */\n readonly styles?: Head | undefined\n },\n): EntryModule => {\n if (plan.meta !== undefined) {\n throw new Error(\n `foldkit-ssr: plan \"${plan.id}\" says what the page says of itself (meta), which is written into the template's head, and the template is the host's: serve it with SSR.generate, not SSR.entry`,\n )\n }\n const allow = plan.fallback === 'server' ? 'GET, HEAD, POST, OPTIONS' : 'GET, HEAD, OPTIONS'\n // Deleted and appended rather than set, which would keep one `set-cookie` of several.\n const merge = (response: Response, extra: Headers): Response => {\n for (const name of new Set(extra.keys())) response.headers.delete(name)\n extra.forEach((value, name) => response.headers.append(name, value))\n return response\n }\n const answer = async (request: Request): Promise<EntryResult> => {\n const method = request.method.toUpperCase()\n const posting = method === 'POST' && plan.fallback === 'server'\n const headersOf = options.headers\n let extra: Headers | undefined\n if (headersOf !== undefined) {\n try {\n extra = new Headers(headersOf(request))\n } catch (error) {\n console.error(\n `[foldkit-ssr] ${request.url} was not answered: headers threw ${String(error)}`,\n )\n return Responded(plainText(500, 'The page could not be rendered.'))\n }\n }\n const responded = (response: Response): EntryResult =>\n Responded(extra === undefined ? response : merge(response, extra))\n if (method === 'OPTIONS')\n return responded(new Response(null, { status: 204, headers: { allow } }))\n if (method !== 'GET' && method !== 'HEAD' && !posting) {\n return responded(new Response(null, { status: 405, headers: { allow } }))\n }\n const flagsOf = options.flags\n const styled = options.styles === undefined ? {} : { styles: options.styles }\n // `Effect.result` would miss a defect, such as a view that throws, and a\n // `flags` that throws or rejects is not in the Effect at all: both would\n // reject `renderPage` instead of answering it.\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const flags =\n flagsOf === undefined ? undefined : yield* Effect.tryPromise(async () => flagsOf(request))\n const flagged = flagsOf === undefined ? {} : { flags }\n if (posting) {\n return yield* handle(request, config, plan, {\n buildId: options.buildId,\n ...flagged,\n ...styled,\n })\n }\n return yield* render(config, plan, {\n buildId: options.buildId,\n url: request.url,\n ...flagged,\n ...styled,\n })\n }),\n )\n if (Exit.isFailure(exit)) {\n const refused = Cause.findErrorOption(exit.cause).pipe(\n Option.filter(error => error instanceof FallbackRefused),\n )\n if (Option.isSome(refused)) {\n return responded(plainText(400, `The form could not be handled: ${refused.value.message}`))\n }\n console.error(`[foldkit-ssr] ${request.url} was not rendered: ${Cause.pretty(exit.cause)}`)\n return responded(plainText(500, 'The page could not be rendered.'))\n }\n warnUnnamed(config, plan, exit.value.unnamed)\n // No `headers` key without custom headers: a `Rendered` that carries none\n // stays generatable as a static file.\n return extra === undefined\n ? Rendered(exit.value.rendered)\n : Rendered(exit.value.rendered, { headers: extra })\n }\n return { renderPage: answer }\n}\n\nconst plainText = (status: number, body: string): Response =>\n new Response(body, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n\n/** How a form's Message is written into the page for the fallback, when the plan has one. */\nconst fallbackEncoder = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n): ((message: unknown) => string | undefined) | undefined => {\n if (plan.fallback !== 'server' || plan.Message === undefined) return undefined\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n return message => {\n const encoded = encode(message)\n return Result.isFailure(encoded) ? undefined : JSON.stringify(encoded.success)\n }\n}\n\n/** Why a posted form was not handled: the request, not the page or the plan, is at fault. */\nexport class FallbackRefused extends Schema.TaggedError<FallbackRefused>()('FallbackRefused', {\n reason: Schema.Literals(['Missing', 'Unreadable', 'Invalid', 'Unlisted', 'NoFallback']),\n message: Schema.String,\n}) {}\n\nconst refuseFallback = (reason: FallbackRefused['reason'], message: string) =>\n Effect.fail(new FallbackRefused({ reason, message }))\n\n/** A Command as Foldkit runs it: named, with the Effect that yields its Message. */\ninterface RunnableCommand {\n readonly name: string\n readonly effect: Effect.Effect<unknown, unknown, any>\n}\n\nconst isRunnable = (command: unknown): command is RunnableCommand =>\n typeof command === 'object' &&\n command !== null &&\n 'effect' in command &&\n Effect.isEffect(command.effect)\n\n/**\n * The most Messages and Commands one post may run. The browser's loop runs\n * for the life of the page, so a Command that schedules itself again, a tick\n * or a poll, is ordinary there; on the server it would hold the request open\n * for ever.\n */\nconst MAX_STEPS = 100\n\n/**\n * Foldkit's loop, once, on the server: `update` for each Message, then each\n * returned Command run under the config's `resources`, its Message folded\n * back through `update`, until no Command remains.\n */\nconst fold = <Model>(\n config: ResumableConfig<Model>,\n model: Model,\n messages: ReadonlyArray<unknown>,\n commands: ReadonlyArray<unknown>,\n): Effect.Effect<Model> =>\n Effect.gen(function* () {\n let current = model\n const pending = [...messages]\n const queue = [...commands]\n let steps = 0\n let last = ''\n while (pending.length > 0 || queue.length > 0) {\n if (++steps > MAX_STEPS) {\n return yield* Effect.die(\n new Error(\n `SSR.handle: the post did not settle within ${MAX_STEPS} Messages and Commands; the last Command run was \"${last}\". A Command that schedules itself again cannot run on the server`,\n ),\n )\n }\n if (pending.length > 0) {\n const next = config.update(current, pending.shift()) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = next.model\n queue.push(...(next.commands ?? []))\n continue\n }\n const command = queue.shift()\n if (!isRunnable(command)) {\n return yield* Effect.die(\n new Error(`SSR.handle: a Command has no Effect to run: ${JSON.stringify(command)}`),\n )\n }\n // A Command that fails would crash Foldkit's runtime; here it is a defect\n // the entry answers with 500, since the config declares its requirements.\n const provided: Effect.Effect<unknown, unknown, never> =\n config.resources === undefined\n ? (command.effect as Effect.Effect<unknown, unknown, never>)\n : (Effect.provide(command.effect, config.resources) as Effect.Effect<\n unknown,\n unknown,\n never\n >)\n last = command.name\n const result = yield* Effect.orDie(provided)\n // A Command fired and forgotten yields no Message, and folds nothing in.\n if (result !== undefined && result !== null) pending.push(result)\n }\n return current\n })\n\n/** The Model `init` gives this request, as the server's render would start from. */\nconst startOf = <Model>(\n config: ResumableConfig<Model>,\n options: { readonly url?: string | undefined; readonly flags?: unknown },\n): Effect.Effect<ReturnType<ResumableConfig<Model>['init']>, RenderError> =>\n Effect.gen(function* () {\n let started: ReturnType<ResumableConfig<Model>['init']> | undefined\n yield* renderToString(\n {\n ...config,\n init: (...args: ReadonlyArray<unknown>) => (started = config.init(...args)),\n } as never,\n { buildId: 'x', ...options } as never,\n )\n return started!\n })\n\n/**\n * Answers a form posted by a page rendered with `fallback: 'server'`: the\n * posted Message is decoded through the plan's Message Schema, with posted\n * fields of the same names as its own overriding them, and must be one the\n * Surfaces active for the request's Model may send. The server then rebuilds\n * the Model the browser had, `init` and then the plan's `boot` with every\n * Command it leads to, runs `update` with the Message and every Command that\n * follows, and renders the result as a fresh page.\n */\nconst handle = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n request: Request,\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly flags?: unknown\n readonly styles?: Head | undefined\n },\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe | FallbackRefused> =>\n Effect.gen(function* () {\n if (plan.fallback !== 'server' || plan.Message === undefined) {\n return yield* refuseFallback('NoFallback', `plan \"${plan.id}\" has no server fallback`)\n }\n const form = yield* Effect.tryPromise({\n try: () => request.formData(),\n catch: () => new FallbackRefused({ reason: 'Unreadable', message: 'the body is not a form' }),\n })\n const posted = form.get(FALLBACK_FIELD)\n if (typeof posted !== 'string') {\n return yield* refuseFallback('Missing', `the form carries no ${FALLBACK_FIELD} field`)\n }\n let raw: unknown\n try {\n raw = JSON.parse(posted)\n } catch {\n return yield* refuseFallback('Unreadable', `${FALLBACK_FIELD} is not JSON`)\n }\n const decode = Schema.decodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const invalid = (failure: { readonly message: string }) =>\n refuseFallback('Invalid', `the posted Message does not decode: ${failure.message}`)\n // The posted Message is decoded before anything reads it.\n const written = decode(raw)\n if (Result.isFailure(written)) return yield* invalid(written.failure)\n // A form inside a placement posts the parent's Message; the fields it\n // names sit `depth` wrappers down.\n const postedDepth = form.get(FALLBACK_DEPTH_FIELD) ?? '0'\n if (typeof postedDepth !== 'string' || !/^\\d{1,2}$/.test(postedDepth)) {\n return yield* refuseFallback('Unreadable', `${FALLBACK_DEPTH_FIELD} is not a depth`)\n }\n const override = (value: unknown, down: number): unknown => {\n if (typeof value !== 'object' || value === null) return value\n const copy: Record<string, unknown> = { ...value }\n if (down > 0) {\n copy.message = override(copy.message, down - 1)\n return copy\n }\n form.forEach((field, name) => {\n if (name !== FALLBACK_FIELD && Object.hasOwn(copy, name) && typeof field === 'string') {\n copy[name] = field\n }\n })\n return copy\n }\n // The fields typed into the form, set into the Message and decoded again.\n const decoded = decode(override(raw, Number(postedDepth)))\n if (Result.isFailure(decoded)) return yield* invalid(decoded.failure)\n const message = decoded.success\n const started = yield* startOf(config, { url: request.url, ...options })\n const allowed = allowedTags(plan, started.model)\n if (!allowed.has(tagOf(message))) {\n return yield* refuseFallback(\n 'Unlisted',\n `the posted ${tagOf(message)} is not one an active Surface lists in its messages`,\n )\n }\n // As the browser got here: `init` on the server, then the plan's `boot`\n // at hydration, and only then the user's Message. `init`'s own Commands\n // never run in the browser, so they do not run here.\n const boot = (plan.boot?.(started.model) as ReadonlyArray<unknown> | undefined) ?? []\n const booted = yield* fold(config, started.model, [], boot)\n const model = yield* fold(config, booted, [message], [])\n return yield* render(startingFrom(config, { model }) as ResumableConfig<Model>, plan, {\n buildId: options.buildId,\n url: request.url,\n ...(options.styles === undefined ? {} : { styles: options.styles }),\n })\n })\n\nexport const SSR = {\n plan,\n envelope,\n resume,\n render,\n page,\n hydrate: Client.hydrate,\n inspect,\n static: staticRegion,\n serving,\n generate,\n entry,\n handle,\n serializeJsonScript,\n sitemap,\n robots,\n}\n\nexport {\n FOLDKIT_APP_ATTRIBUTE,\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n Resume,\n ResumeRefused,\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n SLOT_ATTRIBUTE,\n metaMarkup,\n type DecodedBinding,\n type Loadable,\n type Meta,\n type ResumableBuilder,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n type UnnamedHandler,\n} from './client.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,qBACJ,MACA,UACG,KAAK,SAAS,SAAQ,YAAW,OAAO,QAAQ,QAAQ,aAAa,KAAK,CAAC,CAAC;;;;;AAYjF,MAAM,aACJ,MACA,UACY;CACZ,MAAM,QAAQ,OAAO,WAAW,QAAQ,KAAK,MAAM,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,IAAI,KAAK,CAAC;CACjF,IAAI,KAAK,MAAM,WAAW,GAAG,OAAO,EAAE,MAAM;CAC5C,MAAM,cAAc,kBAAkB,MAAM,KAAK;CACjD,OAAO;EACL;EACA,OAAO,OAAO,YAAY,KAAK,MAAM,KAAI,SAAQ,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AQ;EACjB,KAAK,QAAQ;EACb,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CACnE,CAAC;AACH,CAAC;AAEH,MAAa,MAAM;CACjB;CACA;CACA;CACA;CACA;CACA,SAASA,MAAO;CAChB;CACA,QAAQ;CACR;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["Client"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-ssr`: what crosses from the server to the browser when a page is\n * rendered on one and resumed on the other.\n *\n * Built from the plan in `docs/design/ssr-PLAN.md`. A resume plan names the\n * slice of the Model the browser owns. The server writes that slice onto the\n * stamped root as a JSON attribute, beside Foldkit's own stamps; the browser\n * reads it back and sets it onto a baseline\n * Model. Nothing outside the slice crosses, and a payload that cannot be read\n * back exactly is refused, never half-restored.\n *\n * Rendering and hydrating stay Foldkit's own: this package adds only the\n * handover. This module is the server's side and the browser's\n * (`foldkit-ssr/client`) together.\n */\nimport { Cause, Effect, Exit, Option, Result, Schema } from 'effect'\nimport {\n FOLDKIT_FLAGS_ATTRIBUTE,\n Rendered,\n Responded,\n injectIntoTemplate,\n renderToString,\n type EntryModule,\n type EntryResult,\n type RenderError,\n type RenderedApplication,\n} from 'foldkit/experimental/server'\nimport { Metadata, type MetadataSummary } from 'foldkit-surface'\nimport { withContext, type Binding, type Region, type UnnamedHandler } from './context.js'\nimport { type EncodedBinding } from './listen.js'\nimport { FALLBACK_DEPTH_FIELD, FALLBACK_FIELD } from './resumable.js'\nimport { SSR as Client } from './client.js'\nimport {\n PROTOCOL,\n allowedTags,\n attributeOf,\n codecOf,\n modelFrom,\n metaMarkup,\n pathKey,\n plan,\n resume,\n routeOf,\n serializeJsonScript,\n serving,\n startingFrom,\n staticRegion,\n tagOf,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type RouteMatch,\n} from './shared.js'\n\n/** The projections of the plan's Surfaces that are active for `model`. */\nconst activeProjections = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n) => plan.surfaces.flatMap(surface => Option.toArray(surface.projectionOf(model)))\n\n/** What the envelope carries of a Model: the encoded slice, and each part's capture. */\ninterface Payload {\n readonly state: unknown\n readonly parts?: Readonly<Record<string, unknown>>\n}\n\n/**\n * What the envelope carries of `model`: the plan's slice, encoded through its\n * own Schema, and each part's capture.\n */\nconst payloadOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): Payload => {\n const state = Schema.encodeSync(codecOf(plan.state.schema))(plan.state.get(model))\n if (plan.parts.length === 0) return { state }\n const projections = activeProjections(plan, model)\n return {\n state,\n parts: Object.fromEntries(plan.parts.map(part => [part.id, part.capture(model, projections)])),\n }\n}\n\ninterface EnvelopeOptions {\n readonly route?: string | undefined\n readonly match?: RouteMatch | undefined\n readonly bindings?: ReadonlyArray<EncodedBinding> | undefined\n /** Every event the page's markers name, so the browser listens without scanning for them. */\n readonly events?: ReadonlyArray<string> | undefined\n}\n\n/**\n * The envelope for `model`: the plan's slice, each part's capture, and\n * the route it was rendered for, if it was rendered for one. `SSR.render`\n * carries it on the stamped root, beside Foldkit's own stamps, escaped for\n * the attribute; this is the same JSON unescaped, for tests and hosts that\n * place the page themselves.\n */\nconst envelope = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n model: Model,\n options: EnvelopeOptions = {},\n): string => envelopeOf(resume, payloadOf(resume, model), options)\n\n/**\n * The envelope for a payload already built: the JSON the stamped root carries.\n */\nconst envelopeOf = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n payload: Payload,\n options: EnvelopeOptions,\n): string =>\n serializeJsonScript({\n v: PROTOCOL,\n plan: resume.id,\n ...payload,\n ...(options.route === undefined ? {} : { route: options.route }),\n ...(options.match === 'path' ? { match: 'path' } : {}),\n ...(options.bindings === undefined || options.bindings.length === 0\n ? {}\n : { bindings: options.bindings }),\n ...(options.events === undefined || options.events.length === 0\n ? {}\n : { events: options.events }),\n })\n\n/**\n * The rendered application with the envelope on its stamped root, beside\n * Foldkit's own app and build stamps. `injectIntoTemplate` accepts the\n * envelope there, as part of the root, and refuses it beside the root, so a\n * page the host injects carries the handover without the entry owning the\n * template. Hydration adopts the server's nodes around it and drops the\n * attribute on its first patch, so the browser reads the envelope before it\n * boots.\n */\nconst withEnvelopeAttribute = (html: string, json: string): string => {\n const stamp = 'data-foldkit-app=\"'\n // The stamp names the root's open tag: it opens the markup, and no quoted\n // attribute value before it may hold a `>` of its own, which would end a\n // naive scan early, or the stamp string itself. A stamp past the tag's end,\n // or in text, is not the root.\n let from = 0\n for (;;) {\n const at = html.indexOf(stamp, from)\n if (at === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n if (isInRootTag(html, at)) {\n const end = html.indexOf('\"', at + stamp.length)\n if (end === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n return `${html.slice(0, end + 1)}${attributeOf(json)}${html.slice(end + 1)}`\n }\n from = at + stamp.length\n }\n}\n\n/** Whether `at` sits inside the markup's first tag: quoted values skipped whole. */\nconst isInRootTag = (html: string, at: number): boolean => {\n if (!html.startsWith('<')) return false\n let index = 1\n while (index < at) {\n const char = html[index]\n if (char === '\"' || char === \"'\") {\n const close = html.indexOf(char, index + 1)\n if (close === -1 || close >= at) return false\n index = close + 1\n } else if (char === '>') {\n return false\n } else {\n index++\n }\n }\n return true\n}\n\n/**\n * The rendered markup with `extra` as the root's last child, so the first\n * paint is styled before any script runs where no template head can take it.\n * A void root holds no children: styles for one are refused, naming the tag,\n * rather than served where no browser could keep them.\n */\nconst withInRoot = (html: string, extra: string): Result.Result<string, ResumeUnsafe> => {\n const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1]\n const at = tag === undefined ? -1 : html.search(new RegExp(`</${tag}>\\\\s*$`))\n if (tag === undefined || at === -1) {\n return Result.fail(\n new ResumeUnsafe({\n reason: 'VoidRootWithStyles',\n message: `styles need a root element that can hold them, but the view returned <${tag ?? '?'}>: put the styles in the template's head with SSR.generate, or return an element root`,\n }),\n )\n }\n return Result.succeed(`${html.slice(0, at)}${extra}${html.slice(at)}`)\n}\n\n/**\n * The Model the browser will start from when the server's Model is `model`:\n * the payload taken through the page as the envelope carries it, as JSON, and\n * resumed exactly as `SSR.resume` resumes it. A part that cannot restore its\n * own capture fails here, on the server.\n */\nconst browserModelOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: Payload,\n): Result.Result<Model, string> => modelFrom(plan, JSON.parse(serializeJsonScript(payload)))\n\n/** Where the browser gets a Model path's value: the envelope, the baseline, or nowhere it may. */\nexport type Cover = 'state' | 'local' | 'missing'\n\n/** One Surface as a plan covers it, for the server's Model. */\nexport interface SurfaceCoverage {\n readonly name: string\n /** Whether the Surface is active for the server's Model. */\n readonly active: boolean\n /** The place a `Surface.when` activation reads; absent for `Surface.at`. */\n readonly activation?: { readonly path: string; readonly cover: Cover } | undefined\n /** The Model paths the active Surface reads. */\n readonly reads: ReadonlyArray<{ readonly path: string; readonly cover: Cover }>\n /**\n * What the active Surface reads that no Model path names, such as Remote\n * data, by its metadata. The slice cannot carry it.\n */\n readonly unresumed: ReadonlyArray<MetadataSummary>\n /** Whether the browser's Model activates it the same way, with the same reads. */\n readonly sameInBrowser: boolean\n}\n\n/** What a plan sends, what it leaves local, and how it covers each Surface. */\nexport interface PlanInspection {\n readonly id: string\n readonly state: ReadonlyArray<string>\n readonly local: ReadonlyArray<string>\n /** The ids of the parts that resume state the slice cannot carry. */\n readonly parts: ReadonlyArray<string>\n readonly surfaces: ReadonlyArray<SurfaceCoverage>\n}\n\nconst pathOf = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? '(the whole Model)' : path.join('.')\n\n/**\n * A path is covered by a sent or local path equal to it or containing it. An\n * empty path is the whole Model, which no pick covers.\n */\nconst coverOf = (\n path: ReadonlyArray<string>,\n plan: {\n readonly state: { readonly dependencies: ReadonlyArray<ReadonlyArray<string>> }\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n },\n): Cover => {\n const contains = (outer: ReadonlyArray<string>) =>\n outer.length > 0 &&\n outer.length <= path.length &&\n outer.every((key, index) => path[index] === key)\n if (plan.state.dependencies.some(contains)) return 'state'\n if (plan.local.some(contains)) return 'local'\n return 'missing'\n}\n\n/** A projection's reads as one comparable string, or `inactive`. */\nconst readsKey = (\n projection:\n | {\n readonly dependencies: ReadonlyArray<ReadonlyArray<string>>\n readonly metadata: Metadata\n }\n | undefined,\n): string =>\n projection === undefined\n ? 'inactive'\n : JSON.stringify([projection.dependencies, Metadata.summarize(projection.metadata)])\n\n/**\n * How a plan covers each of its Surfaces when the server's Model is `model`.\n * A Surface's reads depend on the Model, through its params, so coverage is\n * worked out for a Model, not for the plan alone.\n */\nconst inspect = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): PlanInspection => {\n const resumed = browserModelOf(plan, payloadOf(plan, model))\n if (Result.isFailure(resumed)) throw new Error(`SSR.inspect: ${resumed.failure}`)\n return coverage(plan, model, resumed.success)\n}\n\n/** How a plan covers its Surfaces, given the server's Model and the browser's. */\nconst coverage = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n browser: Model,\n): PlanInspection => {\n const covered = new Set(plan.parts.flatMap(part => part.covers))\n return {\n id: plan.id,\n state: plan.state.dependencies.map(pathOf),\n local: plan.local.map(pathOf),\n parts: plan.parts.map(part => part.id),\n surfaces: plan.surfaces.map(surface => {\n const served = Option.getOrUndefined(surface.projectionOf(model))\n return {\n name: surface.name,\n active: served !== undefined,\n ...(surface.activation === undefined\n ? {}\n : {\n activation: {\n path: pathOf(surface.activation.path),\n cover: coverOf(surface.activation.path, plan),\n },\n }),\n reads: (served?.dependencies ?? []).map(path => ({\n path: pathOf(path),\n cover: coverOf(path, plan),\n })),\n unresumed:\n served === undefined\n ? []\n : Metadata.summarize(served.metadata).filter(summary => !covered.has(summary.name)),\n sameInBrowser:\n readsKey(served) === readsKey(Option.getOrUndefined(surface.projectionOf(browser))),\n }\n }),\n }\n}\n\n/** Each way an inspection shows the plan falls short, one line each. */\nconst shortfalls = (inspection: PlanInspection): ReadonlyArray<string> =>\n inspection.surfaces.flatMap(surface => [\n ...(surface.activation?.cover === 'missing'\n ? [\n `Surface \"${surface.name}\" is activated by ${surface.activation.path}, which is neither in the plan's state nor local`,\n ]\n : []),\n ...surface.reads\n .filter(read => read.cover === 'missing')\n .map(\n read =>\n `Surface \"${surface.name}\" reads ${read.path}, which is neither in the plan's state nor local`,\n ),\n ...surface.unresumed.map(\n summary =>\n `Surface \"${surface.name}\" reads ${summary.name} data (${summary.entries.join(', ')}), which no part of the plan resumes`,\n ),\n ...(surface.sameInBrowser\n ? []\n : [\n `Surface \"${surface.name}\" is ${surface.active ? 'active' : 'inactive'} on the server and activates differently from the Model the browser starts from`,\n ]),\n ])\n\n/** Why a server refused to render a page against its plan. */\nexport class ResumeUnsafe extends Schema.TaggedError<ResumeUnsafe>()('ResumeUnsafe', {\n reason: Schema.Literals([\n 'UndeclaredStartup',\n 'Uncovered',\n 'ViewDependsOnUnsentState',\n 'DuplicateStaticRegion',\n 'UngeneratablePath',\n 'UnrestorablePart',\n 'UnencodableBinding',\n 'EagerStartRequired',\n 'UndeclaredSurfaces',\n 'BindingInStaticRegion',\n 'VoidRootWithStyles',\n ]),\n message: Schema.String,\n}) {}\n\n/** Each binding whose Message no active Surface lists, one line each. */\nconst unlistedBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n bindings: ReadonlyArray<Binding>,\n): ReadonlyArray<string> => {\n const allowed = allowedTags(plan, model)\n return bindings\n .filter(binding => !allowed.has(tagOf(binding.message)))\n .map(\n binding =>\n `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`,\n )\n}\n\n/** Loads every lazy bundle's bodies, so the view renders whole. */\nconst loadLazy = (config: { readonly lazy?: ReadonlyArray<Loadable> | undefined }) =>\n Effect.promise(() => Promise.all((config.lazy ?? []).map(bundle => bundle.load())))\n\n/** Foldkit's own Flags script, which a resumed page never carries. */\nconst FLAGS_SCRIPT = new RegExp(\n `<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\\\s\\\\S]*?</script>`,\n 'g',\n)\n\n/**\n * The head fields a render returns beside the body. Each is read by the view,\n * so each must come out the same from the browser's Model; since Foldkit 0.163\n * none has a default from the URL.\n */\nconst HEAD_FIELDS = ['title', 'lang', 'dir', 'canonical', 'ogUrl'] as const\n\n/** A render's bindings, encoded, or why one cannot be. */\nconst encodeBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n bindings: ReadonlyArray<Binding>,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (bindings.length === 0) return Result.succeed([])\n if (plan.Message === undefined) {\n return Result.fail(\n 'the page has bindings, and the plan has no Message Schema to encode them with: make the plan from the application',\n )\n }\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const out: Array<EncodedBinding> = []\n for (const binding of bindings) {\n const message = encode(binding.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `the ${binding.event} binding on ${binding.element} does not encode as a Message: ${message.failure.message}`,\n )\n }\n out.push({\n attribute: binding.attribute,\n message: message.success,\n ...(binding.hole === undefined ? {} : { hole: binding.hole }),\n ...(binding.depth === undefined ? {} : { depth: binding.depth }),\n ...(binding.options === undefined ? {} : { options: binding.options }),\n })\n }\n return Result.succeed(out)\n}\n\n/**\n * The bindings that differ between the server's render and the browser's, by\n * element: a Message built from a field the plan does not send would dispatch\n * one Message before boot and another after.\n */\nconst changedBindings = (\n served: ReadonlyArray<Binding>,\n encoded: ReadonlyArray<EncodedBinding>,\n reencoded: ReadonlyArray<EncodedBinding>,\n): ReadonlyArray<string> =>\n served.flatMap((binding, index) =>\n JSON.stringify(encoded[index]) === JSON.stringify(reencoded[index])\n ? []\n : [`${binding.event} binding on ${binding.element}`],\n )\n\n/**\n * The Subscription and Managed Resource entries that would start late under a\n * deferred boot and are not declared deferrable, by the plan or by a part.\n * Foldkit starts every Subscription's stream at boot, so every entry counts; a\n * Managed Resource counts when the Model asks for it.\n */\nconst eagerEntries = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlyArray<string> => {\n if (plan.start === 'now') return []\n const declared = (key: string, entry: unknown) =>\n plan.deferrable.includes(key) || plan.parts.some(part => part.deferrable?.(key, entry) === true)\n const subscriptions = Object.entries(config.subscriptions ?? {}).filter(\n ([key, entry]) => !declared(key, entry),\n )\n const resources = Object.entries(config.managedResources ?? {}).filter(([key, entry]) => {\n const asks = (\n entry as { modelToMaybeRequirements?: (model: Model) => unknown }\n ).modelToMaybeRequirements?.(model)\n const active = Option.isOption(asks) ? Option.isSome(asks) : asks !== undefined\n return active && !declared(key, entry)\n })\n return [\n ...subscriptions.map(([key]) => `subscription \"${key}\"`),\n ...resources.map(([key]) => `resource \"${key}\"`),\n ]\n}\n\n/** A page the server rendered against a plan, with its envelope. */\nexport interface RenderedPage {\n /**\n * The rendered application with the envelope on its stamped root, so\n * Foldkit's `injectIntoTemplate` places the page whole: the host owns the\n * template, and the entry never splices markup into it.\n */\n readonly rendered: RenderedApplication\n /** The envelope, as carried on the root, for tests and custom hosts. */\n readonly envelope: string\n /** The head markup of the plan's `meta`, empty without one. */\n readonly meta: string\n /**\n * Each element whose handler for an event is a function, marked `*`: the\n * page cannot answer that event before the live runtime boots.\n */\n readonly unnamed: ReadonlyArray<UnnamedHandler>\n}\n\n/**\n * Renders a page on the server against a resume plan.\n *\n * The application's `init` runs once. Its Model's slice is round-tripped\n * through the plan's Schema and set onto the baseline, which is the Model the\n * browser will start from, and the page is rendered from that Model. Every\n * way the browser could start somewhere else is a `ResumeUnsafe`, whose\n * `reason` names it; the README lists them. The one that matters most: the\n * view rendered from the browser's Model differs from the one rendered from\n * the server's, because it reads a field the plan leaves out. In production\n * Foldkit would rebuild that part of the page silently, so this is the one\n * place it shows.\n */\nconst render = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly url?: string | undefined\n readonly flags?: unknown\n /**\n * Markup for the first paint, given what was rendered, carried as the\n * root's last child: keep it to `<style>`, which the browser drops on\n * hydration. Anything a head owns (`meta`, links) stays with `SSR.page`\n * and `SSR.generate`.\n */\n readonly styles?: Head | undefined\n },\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe> =>\n renderMatching(config, plan, options, 'full')\n\nconst renderMatching = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly url?: string | undefined\n readonly flags?: unknown\n readonly styles?: Head | undefined\n },\n match: RouteMatch,\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n yield* loadLazy(config)\n let served: ReturnType<ResumableConfig<Model>['init']> | undefined\n const regions = new Map<string, Region>()\n const duplicates = new Set<string>()\n const servedBindings: Array<Binding> = []\n const browserBindings: Array<Binding> = []\n const inStatic: Array<{ region: string; element: string; event: string }> = []\n const unnamed: Array<UnnamedHandler> = []\n const fallback = fallbackEncoder(plan)\n const capturing = withContext(\n { ...config, init: (...args: ReadonlyArray<unknown>) => (served = config.init(...args)) },\n {\n mode: 'collect',\n regions,\n duplicates,\n bindings: servedBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n region: undefined,\n inStatic,\n unnamed,\n },\n )\n const full = yield* renderToString(capturing as never, options as never)\n if (duplicates.size > 0) {\n return yield* new ResumeUnsafe({\n reason: 'DuplicateStaticRegion',\n message: `two static regions share the id ${[...duplicates].map(id => `\"${id}\"`).join(', ')}: the browser could adopt only one`,\n })\n }\n if (inStatic.length > 0) {\n const found = inStatic.map(\n ({ region, element, event }) => `a ${event} handler on ${element} in \"${region}\"`,\n )\n return yield* new ResumeUnsafe({\n reason: 'BindingInStaticRegion',\n message: `a static region is the server's alone, and these would never run: ${found.join(', ')}. What a Message changes belongs in a Surface`,\n })\n }\n const started = served!\n const commands = started.commands ?? []\n if (commands.length > 0 && plan.boot === undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredStartup',\n message: `init returned ${commands.map(command => command.name).join(', ')}, which no browser would run: name them in the plan's boot`,\n })\n }\n\n // Built once: each part's capture reads the whole store it owns.\n const payload = payloadOf(plan, started.model)\n const resumed = browserModelOf(plan, payload)\n if (Result.isFailure(resumed)) {\n return yield* new ResumeUnsafe({ reason: 'UnrestorablePart', message: resumed.failure })\n }\n const browser = resumed.success\n\n const eager = eagerEntries(config, plan, started.model)\n if (eager.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'EagerStartRequired',\n message: `the plan starts ${plan.start}, and these would start late: ${eager.join(', ')}. Name each in the plan's deferrable, or start now`,\n })\n }\n\n if (servedBindings.length > 0 && plan.surfaces.length === 0) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredSurfaces',\n message: `the page has ${servedBindings.length} binding${servedBindings.length === 1 ? '' : 's'} and the plan declares no surfaces, so nothing says which Messages it may dispatch: name them in the plan's surfaces`,\n })\n }\n const uncovered = [\n ...shortfalls(coverage(plan, started.model, browser)),\n ...unlistedBindings(plan, started.model, servedBindings),\n ]\n if (uncovered.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'Uncovered',\n message: `the plan does not cover what the browser reads:\\n- ${uncovered.join('\\n- ')}`,\n })\n }\n\n // With no `Flags` key in the config, Foldkit writes no Flags script.\n const rendered = yield* renderToString(\n withContext(startingFrom(config, { model: browser }), {\n mode: 'replay',\n regions,\n bindings: browserBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n }) as never,\n options as never,\n )\n const encoded = encodeBindings(plan, servedBindings)\n const reencoded = encodeBindings(plan, browserBindings)\n if (Result.isFailure(encoded)) {\n return yield* new ResumeUnsafe({ reason: 'UnencodableBinding', message: encoded.failure })\n }\n const meta = plan.meta === undefined ? '' : metaMarkup(plan.meta(started.model))\n const differing = [\n ...(full.html.replace(FLAGS_SCRIPT, '') === rendered.html ? [] : ['body']),\n ...HEAD_FIELDS.filter(field => full[field] !== rendered[field]),\n ...(plan.meta === undefined || metaMarkup(plan.meta(browser)) === meta ? [] : ['meta']),\n ...changedBindings(\n servedBindings,\n encoded.success,\n Result.isFailure(reencoded) ? [] : reencoded.success,\n ),\n ]\n if (differing.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'ViewDependsOnUnsentState',\n message: `the view differs in its ${differing.join(', ')} when rendered from the Model the browser will start from: it reads a field the plan leaves out`,\n })\n }\n const envelope = envelopeOf(plan, payload, {\n ...(options.url === undefined\n ? {}\n : { route: match === 'path' ? pathKey(routeOf(options.url)) : routeOf(options.url) }),\n match,\n bindings: encoded.success,\n events: [\n ...new Set([\n ...servedBindings.map(binding => binding.event),\n ...unnamed.map(handler => handler.event),\n ]),\n ].sort(),\n })\n const styled =\n options.styles === undefined\n ? Result.succeed(rendered.html)\n : withInRoot(rendered.html, options.styles(rendered))\n if (Result.isFailure(styled)) return yield* styled.failure\n return {\n rendered: { ...rendered, html: withEnvelopeAttribute(styled.success, envelope) },\n meta,\n envelope,\n unnamed,\n }\n })\n\n/**\n * What a page adds to its head, given what it rendered: such as a stylesheet\n * of the classes the markup uses (`Style.usedIn` in `foldkit-mixins`). The\n * same shape describes `styles`, which rides in the rendered root instead,\n * for pages whose template the host owns.\n */\nexport type Head = (rendered: RenderedApplication) => string\n\n/**\n * The template with `extra` before its last `</head>`, as a slice for the same\n * reason as the envelope. Nothing to add leaves it as it is; something to add\n * and no `</head>` is refused, rather than dropped.\n */\nconst withHead = (template: string, extra: string): string => {\n if (extra === '') return template\n const at = template.search(/<\\/head>(?![\\s\\S]*<\\/head>)/i)\n if (at === -1) throw new Error('foldkit-ssr: the template has no </head> to put the head in')\n return `${template.slice(0, at)}${extra}${template.slice(at)}`\n}\n\n/**\n * Foldkit fills `canonical` and `og:url` only into a tag the template already\n * has, and leaves the page without one otherwise. A render that sets either\n * and a template without its tag is refused, naming the tag.\n */\nconst FILLED_TAGS = [\n {\n field: 'canonical',\n tag: '<link rel=\"canonical\" href=\"\">',\n at: /<link\\b[^>]*\\brel\\s*=\\s*[\"']?canonical[\"'\\s>]/i,\n },\n {\n field: 'ogUrl',\n tag: '<meta property=\"og:url\" content=\"\">',\n at: /<meta\\b[^>]*\\bproperty\\s*=\\s*[\"']?og:url[\"'\\s>]/i,\n },\n] as const\n\nconst withFilledTags = (template: string, rendered: RenderedApplication): string => {\n const missing = FILLED_TAGS.filter(\n ({ field, at }) => rendered[field] !== undefined && !at.test(template),\n )\n if (missing.length > 0) {\n throw new Error(\n `foldkit-ssr: the view sets ${missing.map(({ field }) => field).join(' and ')}, and the template has no ${missing.map(({ tag }) => tag).join(' or ')} for Foldkit to fill: add it to the template's head`,\n )\n }\n return template\n}\n\n/** The plan's `meta`, then what `head` adds, one line apart. */\nconst headOf = (\n result: { readonly rendered: RenderedApplication; readonly meta: string },\n head: Head | undefined,\n): string => [result.meta, head?.(result.rendered) ?? ''].filter(markup => markup !== '').join('\\n')\n\n/**\n * The page to serve: the rendered application in the template, with the\n * plan's `meta` and `head`'s markup, if any, before `</head>`. The envelope\n * is already in the rendered root, so this is Foldkit's `injectIntoTemplate`\n * with a head, and nothing else.\n */\nconst page = (\n template: string,\n result: { readonly rendered: RenderedApplication; readonly meta: string },\n options: { readonly head?: Head | undefined } = {},\n): string =>\n injectIntoTemplate(\n withHead(withFilledTags(template, result.rendered), headOf(result, options.head)),\n result.rendered,\n )\n\n/** A page generated at build time, and the file a static host serves it from. */\nexport interface GeneratedPage {\n readonly path: string\n readonly file: string\n readonly html: string\n}\n\n/**\n * One generated page per path, in the paths' order: a tuple when the paths\n * are written out, so `const [home, about] = pages` needs no check.\n */\nexport type GeneratedPages<Paths extends ReadonlyArray<string>> = {\n readonly [K in keyof Paths]: GeneratedPage\n}\n\n/** The file a static host serves for a path: `/about` is `about/index.html`. */\nconst fileOf = (path: string): string => {\n const trimmed = path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n if (trimmed === '') return 'index.html'\n return trimmed.endsWith('.html') ? trimmed : `${trimmed}/index.html`\n}\n\nconst xmlText = (text: string): string =>\n text\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''')\n\n/**\n * A sitemap of the pages a build generated, each at its full address under\n * `origin`, in the order given. `modified`, when a page has it, is any date\n * `Date` reads, written as the UTC day. A path that does not start with `/`,\n * a path given twice, and a date `Date` cannot read are refused: each would\n * make a sitemap a search engine rejects or misreads.\n */\nconst sitemap = (\n pages: ReadonlyArray<{ readonly path: string; readonly modified?: string | undefined }>,\n options: { readonly origin: string },\n): string => {\n const seen = new Set<string>()\n const urls = pages.map(({ path, modified }) => {\n if (!path.startsWith('/')) throw new Error(`SSR.sitemap: \"${path}\" does not start with /`)\n if (seen.has(path)) throw new Error(`SSR.sitemap: \"${path}\" is listed twice`)\n seen.add(path)\n const loc = `<loc>${xmlText(new URL(path, options.origin).href)}</loc>`\n if (modified === undefined) return ` <url>${loc}</url>`\n const at = new Date(modified)\n if (Number.isNaN(at.getTime())) {\n throw new Error(`SSR.sitemap: \"${modified}\", the date of \"${path}\", is not a date`)\n }\n return ` <url>${loc}<lastmod>${at.toISOString().slice(0, 10)}</lastmod></url>`\n })\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n ...urls,\n '</urlset>',\n '',\n ].join('\\n')\n}\n\n/**\n * A `robots.txt` that lets every crawler in, except under `disallow`, and\n * names the sitemap at `sitemap` (default `/sitemap.xml`) under `origin`.\n */\nconst robots = (options: {\n readonly origin: string\n readonly sitemap?: string | undefined\n readonly disallow?: ReadonlyArray<string> | undefined\n}): string =>\n [\n 'User-agent: *',\n 'Allow: /',\n ...(options.disallow ?? []).map(path => `Disallow: ${path}`),\n '',\n `Sitemap: ${new URL(options.sitemap ?? '/sitemap.xml', options.origin).href}`,\n '',\n ].join('\\n')\n\n// Keyed by plan, element and event: a server renders the same page for every\n// request, so one warning each is enough to learn which handler to name.\nconst warnedUnnamed = new Set<string>()\n\n/**\n * Warns, once per process, about each handler that keeps a page from\n * answering before boot. Only a page that waits to boot is held up: one\n * started `'now'`, with no lazy bundle to load, boots before any event.\n */\nconst warnUnnamed = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n unnamed: ReadonlyArray<UnnamedHandler>,\n): void => {\n if (plan.start === 'now' && (config.lazy ?? []).length === 0) return\n for (const { element, event } of unnamed) {\n const key = JSON.stringify([plan.id, element, event])\n if (warnedUnnamed.has(key)) continue\n warnedUnnamed.add(key)\n console.warn(\n `[foldkit-ssr] plan \"${plan.id}\": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,\n )\n }\n}\n\n/**\n * Renders pages at build time, one per path, each as `SSR.render` and\n * `SSR.page` would, to be written as files. `origin` makes each path the full\n * URL a routing application parses. `flags`, when the application has them,\n * gives each path its own.\n *\n * A generated page records its path alone: a static host serves the same file\n * whatever the query, so the browser checks the path and ignores the query. A\n * path with a query or fragment, or two paths that would be one file, are\n * refused.\n */\nconst generate = <\n Model,\n Fields extends Schema.Struct.Fields,\n const Paths extends ReadonlyArray<string>,\n Message = any,\n>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly template: string\n readonly origin: string\n readonly paths: Paths\n readonly flags?: ((path: string) => unknown) | undefined\n readonly head?: Head | undefined\n },\n): Effect.Effect<GeneratedPages<Paths>, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n const files = new Map<string, string>()\n for (const path of options.paths) {\n if (!path.startsWith('/') || /[?#]/.test(path)) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${path}\" is not a path a file can be served at: start it with / and leave out any query or fragment`,\n })\n }\n const other = files.get(fileOf(path))\n if (other !== undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${other}\" and \"${path}\" would both be written to ${fileOf(path)}`,\n })\n }\n files.set(fileOf(path), path)\n }\n const pages = yield* Effect.forEach(options.paths, path =>\n Effect.map(\n renderMatching(\n config,\n plan,\n {\n buildId: options.buildId,\n url: new URL(path, options.origin).href,\n ...(options.flags === undefined ? {} : { flags: options.flags(path) }),\n },\n 'path',\n ),\n result => {\n warnUnnamed(config, plan, result.unnamed)\n return {\n path,\n file: fileOf(path),\n html: page(options.template, result, { head: options.head }),\n }\n },\n ),\n )\n // One page per path, in order, so the array is the tuple the paths describe.\n return pages as unknown as GeneratedPages<Paths>\n })\n\n/**\n * The server entry for Foldkit's pipeline: the `renderPage` a dev server,\n * a fetch handler, or `handleRequest` calls, and that the `fetch.js` a Foldkit\n * build emits imports from the server entry module, so a resumed page is\n * served by Node and Workers alike.\n *\n * `GET` and `HEAD` render the page against the plan, with the request's URL\n * and, when the application has Flags, `flags(request)`. `POST` goes to\n * `SSR.handle` when the plan has a server fallback, and is answered `400` when\n * the post is unusable. `OPTIONS` is answered `204`, and any other method\n * `405`, each with the methods the entry answers in `allow` (`handleRequest`\n * passes every method through). A render that fails, or a plan the render\n * refuses, is answered `500` with the reason logged, never with a page the\n * browser cannot resume. `headers(request)` rides on the `Rendered` result, so\n * Foldkit's `toResponse` sets it over its own on the page: a cache policy, or\n * a CORS answer to a preflight.\n *\n * The page is answered as `Rendered`: the rendered application carries the\n * envelope in its root, so the host injects it into its own template with\n * Foldkit's `injectIntoTemplate`, and a build can generate it with Foldkit's\n * `prerender`. The template, and the container it fills, are the host's:\n * `handleRequest` still classifies static misses and answers `HEAD` without\n * a body.\n *\n * What the page says of itself (`meta`) and per-page `head` markup are\n * written into a template's head, which the host owns here: a plan with\n * `meta` is refused when the entry is made, and served with `SSR.generate`.\n */\nconst entry = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly flags?: ((request: Request) => unknown | PromiseLike<unknown>) | undefined\n readonly headers?: ((request: Request) => HeadersInit) | undefined\n /**\n * Markup for the first paint, carried as the rendered root's last child.\n * The host owns the template in dynamic serving, so this is where\n * per-page styles go; anything a head owns stays with `SSR.generate`.\n */\n readonly styles?: Head | undefined\n },\n): EntryModule => {\n if (plan.meta !== undefined) {\n throw new Error(\n `foldkit-ssr: plan \"${plan.id}\" says what the page says of itself (meta), which is written into the template's head, and the template is the host's: serve it with SSR.generate, not SSR.entry`,\n )\n }\n const allow = plan.fallback === 'server' ? 'GET, HEAD, POST, OPTIONS' : 'GET, HEAD, OPTIONS'\n // Deleted and appended rather than set, which would keep one `set-cookie` of several.\n const merge = (response: Response, extra: Headers): Response => {\n for (const name of new Set(extra.keys())) response.headers.delete(name)\n extra.forEach((value, name) => response.headers.append(name, value))\n return response\n }\n const answer = async (request: Request): Promise<EntryResult> => {\n const method = request.method.toUpperCase()\n const posting = method === 'POST' && plan.fallback === 'server'\n const headersOf = options.headers\n let extra: Headers | undefined\n if (headersOf !== undefined) {\n try {\n extra = new Headers(headersOf(request))\n } catch (error) {\n console.error(\n `[foldkit-ssr] ${request.url} was not answered: headers threw ${String(error)}`,\n )\n return Responded(plainText(500, 'The page could not be rendered.'))\n }\n }\n const responded = (response: Response): EntryResult =>\n Responded(extra === undefined ? response : merge(response, extra))\n if (method === 'OPTIONS')\n return responded(new Response(null, { status: 204, headers: { allow } }))\n if (method !== 'GET' && method !== 'HEAD' && !posting) {\n return responded(new Response(null, { status: 405, headers: { allow } }))\n }\n const flagsOf = options.flags\n const styled = options.styles === undefined ? {} : { styles: options.styles }\n // `Effect.result` would miss a defect, such as a view that throws, and a\n // `flags` that throws or rejects is not in the Effect at all: both would\n // reject `renderPage` instead of answering it.\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const flags =\n flagsOf === undefined ? undefined : yield* Effect.tryPromise(async () => flagsOf(request))\n const flagged = flagsOf === undefined ? {} : { flags }\n if (posting) {\n return yield* handle(request, config, plan, {\n buildId: options.buildId,\n ...flagged,\n ...styled,\n })\n }\n return yield* render(config, plan, {\n buildId: options.buildId,\n url: request.url,\n ...flagged,\n ...styled,\n })\n }),\n )\n if (Exit.isFailure(exit)) {\n const refused = Cause.findErrorOption(exit.cause).pipe(\n Option.filter(error => error instanceof FallbackRefused),\n )\n if (Option.isSome(refused)) {\n return responded(plainText(400, `The form could not be handled: ${refused.value.message}`))\n }\n console.error(`[foldkit-ssr] ${request.url} was not rendered: ${Cause.pretty(exit.cause)}`)\n return responded(plainText(500, 'The page could not be rendered.'))\n }\n warnUnnamed(config, plan, exit.value.unnamed)\n // No `headers` key without custom headers: a `Rendered` that carries none\n // stays generatable as a static file.\n return extra === undefined\n ? Rendered(exit.value.rendered)\n : Rendered(exit.value.rendered, { headers: extra })\n }\n return { renderPage: answer }\n}\n\nconst plainText = (status: number, body: string): Response =>\n new Response(body, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n\n/** How a form's Message is written into the page for the fallback, when the plan has one. */\nconst fallbackEncoder = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n): ((message: unknown) => string | undefined) | undefined => {\n if (plan.fallback !== 'server' || plan.Message === undefined) return undefined\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n return message => {\n const encoded = encode(message)\n return Result.isFailure(encoded) ? undefined : JSON.stringify(encoded.success)\n }\n}\n\n/** Why a posted form was not handled: the request, not the page or the plan, is at fault. */\nexport class FallbackRefused extends Schema.TaggedError<FallbackRefused>()('FallbackRefused', {\n reason: Schema.Literals(['Missing', 'Unreadable', 'Invalid', 'Unlisted', 'NoFallback']),\n message: Schema.String,\n}) {}\n\nconst refuseFallback = (reason: FallbackRefused['reason'], message: string) =>\n Effect.fail(new FallbackRefused({ reason, message }))\n\n/** A Command as Foldkit runs it: named, with the Effect that yields its Message. */\ninterface RunnableCommand {\n readonly name: string\n readonly effect: Effect.Effect<unknown, unknown, any>\n}\n\nconst isRunnable = (command: unknown): command is RunnableCommand =>\n typeof command === 'object' &&\n command !== null &&\n 'effect' in command &&\n Effect.isEffect(command.effect)\n\n/**\n * The most Messages and Commands one post may run. The browser's loop runs\n * for the life of the page, so a Command that schedules itself again, a tick\n * or a poll, is ordinary there; on the server it would hold the request open\n * for ever.\n */\nconst MAX_STEPS = 100\n\n/**\n * Foldkit's loop, once, on the server: `update` for each Message, then each\n * returned Command run under the config's `resources`, its Message folded\n * back through `update`, until no Command remains.\n */\nconst fold = <Model>(\n config: ResumableConfig<Model>,\n model: Model,\n messages: ReadonlyArray<unknown>,\n commands: ReadonlyArray<unknown>,\n): Effect.Effect<Model> =>\n Effect.gen(function* () {\n let current = model\n const pending = [...messages]\n const queue = [...commands]\n let steps = 0\n let last = ''\n while (pending.length > 0 || queue.length > 0) {\n if (++steps > MAX_STEPS) {\n return yield* Effect.die(\n new Error(\n `SSR.handle: the post did not settle within ${MAX_STEPS} Messages and Commands; the last Command run was \"${last}\". A Command that schedules itself again cannot run on the server`,\n ),\n )\n }\n if (pending.length > 0) {\n const next = config.update(current, pending.shift()) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = next.model\n queue.push(...(next.commands ?? []))\n continue\n }\n const command = queue.shift()\n if (!isRunnable(command)) {\n return yield* Effect.die(\n new Error(`SSR.handle: a Command has no Effect to run: ${JSON.stringify(command)}`),\n )\n }\n // A Command that fails would crash Foldkit's runtime; here it is a defect\n // the entry answers with 500, since the config declares its requirements.\n const provided: Effect.Effect<unknown, unknown, never> =\n config.resources === undefined\n ? (command.effect as Effect.Effect<unknown, unknown, never>)\n : (Effect.provide(command.effect, config.resources) as Effect.Effect<\n unknown,\n unknown,\n never\n >)\n last = command.name\n const result = yield* Effect.orDie(provided)\n // A Command fired and forgotten yields no Message, and folds nothing in.\n if (result !== undefined && result !== null) pending.push(result)\n }\n return current\n })\n\n/** The Model `init` gives this request, as the server's render would start from. */\nconst startOf = <Model>(\n config: ResumableConfig<Model>,\n options: { readonly url?: string | undefined; readonly flags?: unknown },\n): Effect.Effect<ReturnType<ResumableConfig<Model>['init']>, RenderError> =>\n Effect.gen(function* () {\n let started: ReturnType<ResumableConfig<Model>['init']> | undefined\n yield* renderToString(\n {\n ...config,\n init: (...args: ReadonlyArray<unknown>) => (started = config.init(...args)),\n } as never,\n { buildId: 'x', ...options } as never,\n )\n return started!\n })\n\n/**\n * Answers a form posted by a page rendered with `fallback: 'server'`: the\n * posted Message is decoded through the plan's Message Schema, with posted\n * fields of the same names as its own overriding them, and must be one the\n * Surfaces active for the request's Model may send. The server then rebuilds\n * the Model the browser had, `init` and then the plan's `boot` with every\n * Command it leads to, runs `update` with the Message and every Command that\n * follows, and renders the result as a fresh page.\n */\nconst handle = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n request: Request,\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly flags?: unknown\n readonly styles?: Head | undefined\n },\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe | FallbackRefused> =>\n Effect.gen(function* () {\n if (plan.fallback !== 'server' || plan.Message === undefined) {\n return yield* refuseFallback('NoFallback', `plan \"${plan.id}\" has no server fallback`)\n }\n const form = yield* Effect.tryPromise({\n try: () => request.formData(),\n catch: () => new FallbackRefused({ reason: 'Unreadable', message: 'the body is not a form' }),\n })\n const posted = form.get(FALLBACK_FIELD)\n if (typeof posted !== 'string') {\n return yield* refuseFallback('Missing', `the form carries no ${FALLBACK_FIELD} field`)\n }\n let raw: unknown\n try {\n raw = JSON.parse(posted)\n } catch {\n return yield* refuseFallback('Unreadable', `${FALLBACK_FIELD} is not JSON`)\n }\n const decode = Schema.decodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const invalid = (failure: { readonly message: string }) =>\n refuseFallback('Invalid', `the posted Message does not decode: ${failure.message}`)\n // The posted Message is decoded before anything reads it.\n const written = decode(raw)\n if (Result.isFailure(written)) return yield* invalid(written.failure)\n // A form inside a placement posts the parent's Message; the fields it\n // names sit `depth` wrappers down.\n const postedDepth = form.get(FALLBACK_DEPTH_FIELD) ?? '0'\n if (typeof postedDepth !== 'string' || !/^\\d{1,2}$/.test(postedDepth)) {\n return yield* refuseFallback('Unreadable', `${FALLBACK_DEPTH_FIELD} is not a depth`)\n }\n const override = (value: unknown, down: number): unknown => {\n if (typeof value !== 'object' || value === null) return value\n const copy: Record<string, unknown> = { ...value }\n if (down > 0) {\n copy.message = override(copy.message, down - 1)\n return copy\n }\n form.forEach((field, name) => {\n if (name !== FALLBACK_FIELD && Object.hasOwn(copy, name) && typeof field === 'string') {\n copy[name] = field\n }\n })\n return copy\n }\n // The fields typed into the form, set into the Message and decoded again.\n const decoded = decode(override(raw, Number(postedDepth)))\n if (Result.isFailure(decoded)) return yield* invalid(decoded.failure)\n const message = decoded.success\n const started = yield* startOf(config, { url: request.url, ...options })\n const allowed = allowedTags(plan, started.model)\n if (!allowed.has(tagOf(message))) {\n return yield* refuseFallback(\n 'Unlisted',\n `the posted ${tagOf(message)} is not one an active Surface lists in its messages`,\n )\n }\n // As the browser got here: `init` on the server, then the plan's `boot`\n // at hydration, and only then the user's Message. `init`'s own Commands\n // never run in the browser, so they do not run here.\n const boot = (plan.boot?.(started.model) as ReadonlyArray<unknown> | undefined) ?? []\n const booted = yield* fold(config, started.model, [], boot)\n const model = yield* fold(config, booted, [message], [])\n return yield* render(startingFrom(config, { model }) as ResumableConfig<Model>, plan, {\n buildId: options.buildId,\n url: request.url,\n ...(options.styles === undefined ? {} : { styles: options.styles }),\n })\n })\n\nexport const SSR = {\n plan,\n envelope,\n resume,\n render,\n page,\n hydrate: Client.hydrate,\n inspect,\n static: staticRegion,\n serving,\n generate,\n entry,\n handle,\n serializeJsonScript,\n sitemap,\n robots,\n}\n\nexport {\n FOLDKIT_APP_ATTRIBUTE,\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n Resume,\n ResumeRefused,\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n SLOT_ATTRIBUTE,\n UNTIL_LIMIT_MS,\n metaMarkup,\n type DecodedBinding,\n type Loadable,\n type Meta,\n type ResumableBuilder,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n type UnnamedHandler,\n} from './client.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,qBACJ,MACA,UACG,KAAK,SAAS,SAAQ,YAAW,OAAO,QAAQ,QAAQ,aAAa,KAAK,CAAC,CAAC;;;;;AAYjF,MAAM,aACJ,MACA,UACY;CACZ,MAAM,QAAQ,OAAO,WAAW,QAAQ,KAAK,MAAM,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,IAAI,KAAK,CAAC;CACjF,IAAI,KAAK,MAAM,WAAW,GAAG,OAAO,EAAE,MAAM;CAC5C,MAAM,cAAc,kBAAkB,MAAM,KAAK;CACjD,OAAO;EACL;EACA,OAAO,OAAO,YAAY,KAAK,MAAM,KAAI,SAAQ,CAAC,KAAK,IAAI,KAAK,QAAQ,OAAO,WAAW,CAAC,CAAC,CAAC;CAC/F;AACF;;;;;;;;AAiBA,MAAM,YACJ,QACA,OACA,UAA2B,CAAC,MACjB,WAAW,QAAQ,UAAU,QAAQ,KAAK,GAAG,OAAO;;;;AAKjE,MAAM,cACJ,QACA,SACA,YAEA,oBAAoB;CAClB,GAAA;CACA,M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
|
package/dist/vite.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as ResumePlan, l as ResumableConfig } from "./client-BDyZf200.mjs";
|
|
2
2
|
import { Head, ResumeUnsafe } from "./index.mjs";
|
|
3
3
|
import { Effect, Schema } from "effect";
|
|
4
4
|
import { RenderError } from "foldkit/experimental/server";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-ssr",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Server rendering for Foldkit Plus: render once on the server, hand the Model over, and hydrate without rerunning init.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -64,9 +64,9 @@
|
|
|
64
64
|
"tsdown": "^0.23.0",
|
|
65
65
|
"typescript": "5.9.3",
|
|
66
66
|
"vite": "5.4.21",
|
|
67
|
-
"foldkit-bundle": "0.5.0",
|
|
68
67
|
"foldkit-entity": "0.7.0",
|
|
69
|
-
"foldkit-
|
|
68
|
+
"foldkit-bundle": "0.5.0",
|
|
69
|
+
"foldkit-remote": "0.13.0",
|
|
70
70
|
"foldkit-mirror": "0.5.1"
|
|
71
71
|
},
|
|
72
72
|
"scripts": {
|