foldkit-ssr 0.1.0 → 0.3.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/dist/index.mjs CHANGED
@@ -1,608 +1,25 @@
1
- import { Cause, Effect, Exit, Option, Result, Schema, Stream } from "effect";
2
- import { FOLDKIT_APP_ATTRIBUTE, FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, renderToString, toResponse } from "foldkit/experimental/server";
3
- import { inertHtml } from "foldkit/html";
4
- import { hydrate, makeApplication, run } from "foldkit/runtime";
1
+ import { C as FALLBACK_DEPTH_FIELD, E as withContext, S as BINDING_ATTRIBUTE, T as SLOT_ATTRIBUTE, _ as serializeJsonScript, a as RESUME_ATTRIBUTE, b as staticRegion, c as allowedTags, d as metaMarkup, f as modelFrom, g as routeOf, h as resume, i as META_ATTRIBUTE, l as attributeOf, m as plan, n as SSR$1, o as ResumeRefused, p as pathKey, r as FOLDKIT_APP_ATTRIBUTE, s as STATIC_ATTRIBUTE, t as Resume, u as codecOf, v as serving, w as FALLBACK_FIELD, x as tagOf, y as startingFrom } from "./client-CsCXJa_9.mjs";
2
+ import { Cause, Effect, Exit, Option, Result, Schema } from "effect";
3
+ import { FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, renderToString } from "foldkit/experimental/server";
5
4
  import { Metadata } from "foldkit-surface";
6
- //#region src/context.ts
7
- let context;
8
- /** The context of the view call in progress, if any. */
9
- const current = () => context;
10
- const within = (next, run) => {
11
- const previous = context;
12
- context = next;
13
- try {
14
- return run();
15
- } finally {
16
- context = previous;
17
- }
18
- };
19
- /** The config whose view runs inside `next`. */
20
- const withContext = (config, next) => ({
21
- ...config,
22
- view: (model, h) => within(next, () => config.view(model, h))
23
- });
24
- //#endregion
25
- //#region src/resumable.ts
26
- /** The attribute prefix of an element's binding marker. */
27
- const BINDING_ATTRIBUTE = "data-foldkit-plus-on-";
28
- /**
29
- * The DOM event each of Foldkit's event attributes listens to, read from
30
- * Foldkit's own attribute table (0.163). `OnCustomEvent` names its event in
31
- * its payload, and `OnMount` and `OnUnmount` listen to none.
32
- */
33
- const EVENT_OF = {
34
- OnClick: "click",
35
- OnDoubleClick: "dblclick",
36
- OnMouseDown: "mousedown",
37
- OnMouseUp: "mouseup",
38
- OnMouseEnter: "mouseenter",
39
- OnMouseLeave: "mouseleave",
40
- OnMouseOver: "mouseover",
41
- OnMouseOut: "mouseout",
42
- OnMouseMove: "mousemove",
43
- OnPointerMove: "pointermove",
44
- OnPointerLeave: "pointerleave",
45
- OnPointerDown: "pointerdown",
46
- OnPointerUp: "pointerup",
47
- OnKeyDown: "keydown",
48
- OnKeyDownPreventDefault: "keydown",
49
- OnKeyDownSelf: "keydown",
50
- OnKeyDownSelfPreventDefault: "keydown",
51
- OnKeyDownFocus: "keydown",
52
- OnKeyUp: "keyup",
53
- OnKeyUpPreventDefault: "keyup",
54
- OnKeyPress: "keypress",
55
- OnFocus: "focus",
56
- OnBlur: "blur",
57
- OnFocusEnter: "focusin",
58
- OnFocusLeave: "focusout",
59
- OnInput: "input",
60
- OnChange: "change",
61
- OnBeforeInput: "beforeinput",
62
- OnBeforeInputPreventDefault: "beforeinput",
63
- OnFileChange: "change",
64
- OnSubmit: "submit",
65
- OnReset: "reset",
66
- OnScroll: "scroll",
67
- OnWheel: "wheel",
68
- OnCopy: "copy",
69
- OnCut: "cut",
70
- OnPaste: "paste",
71
- OnPastePreventDefault: "paste",
72
- OnCopyText: "copy",
73
- OnCutText: "cut",
74
- OnCancel: "cancel",
75
- OnCancelPreventDefault: "cancel",
76
- OnToggle: "toggle",
77
- OnContextMenu: "contextmenu",
78
- OnDragStart: "dragstart",
79
- OnDrag: "drag",
80
- OnDragEnd: "dragend",
81
- OnDragEnter: "dragenter",
82
- OnDragLeave: "dragleave",
83
- OnDragOver: "dragover",
84
- OnDrop: "drop",
85
- OnDropFiles: "drop",
86
- OnTouchStart: "touchstart",
87
- OnTouchEnd: "touchend",
88
- OnTouchMove: "touchmove",
89
- OnTouchCancel: "touchcancel",
90
- OnAnimationStart: "animationstart",
91
- OnAnimationEnd: "animationend",
92
- OnAnimationIteration: "animationiteration",
93
- OnTransitionEnd: "transitionend",
94
- OnLoad: "load",
95
- OnError: "error",
96
- OnPlay: "play",
97
- OnPause: "pause",
98
- OnEnded: "ended",
99
- OnTimeUpdate: "timeupdate",
100
- OnVolumeChange: "volumechange",
101
- OnSelect: "select"
102
- };
103
- /**
104
- * The attributes whose binding the page can describe: a Message value, or one
105
- * of the hole forms this builder records. Any other handler still runs on the
106
- * live page, so its event is marked `*`: the page does something there it
107
- * cannot name, and a dispatcher that ran only the named bindings would do less.
108
- */
109
- const MARKABLE = /* @__PURE__ */ new Set([
110
- "OnClick",
111
- "OnDoubleClick",
112
- "OnMouseDown",
113
- "OnMouseUp",
114
- "OnMouseEnter",
115
- "OnMouseLeave",
116
- "OnMouseOver",
117
- "OnMouseOut",
118
- "OnMouseMove",
119
- "OnFocus",
120
- "OnBlur",
121
- "OnSubmit",
122
- "OnReset",
123
- "OnInput",
124
- "OnChange",
125
- "OnKeyDown",
126
- "OnKeyUp"
127
- ]);
128
- /** The posted field that carries a form's encoded Message, for the server fallback. */
129
- const FALLBACK_FIELD = "foldkit-plus-message";
130
- /** The posted field that says how many placement wrappers the form's fields sit under. */
131
- const FALLBACK_DEPTH_FIELD = "foldkit-plus-depth";
132
- /** The attribute on a placement's root naming its slot, while the server renders. */
133
- const SLOT_ATTRIBUTE = "data-foldkit-plus-slot";
134
- const isMember = (value) => typeof value === "function" && typeof value.fields === "object";
135
- const tagOf$1 = (member) => {
136
- const literal = member.fields._tag?.ast?.literal;
137
- return typeof literal === "string" ? literal : "the member";
138
- };
139
- /** The fields a member leaves for the event to fill, given what is fixed. */
140
- const holeOf = (member, fixed) => Object.keys(member.fields).filter((field) => field !== "_tag" && !(field in fixed));
141
- const NO_MODIFIERS = {
142
- shiftKey: false,
143
- ctrlKey: false,
144
- altKey: false,
145
- metaKey: false
146
- };
147
- /** Each hole-form attribute, with its Message filled by a placeholder and the fields the event fills. */
148
- const holes = /* @__PURE__ */ new WeakMap();
149
- const isTagged = (value) => typeof value === "object" && value !== null && typeof value._tag === "string";
150
- const builders = /* @__PURE__ */ new WeakMap();
151
- /** A hole form's placeholder Message, or `undefined` when its field's checks refuse one. */
152
- const placeholder = (make) => {
153
- try {
154
- return make();
155
- } catch {
156
- return;
157
- }
158
- };
159
- /**
160
- * The resumable builder for a view's `h`. Use it in place of `h`; it has the
161
- * same elements and attributes, and the hole forms of the four value events.
162
- */
163
- const builder = (h) => {
164
- const cached = builders.get(h);
165
- if (cached !== void 0) return cached;
166
- const source = h;
167
- const attribute = source.Attribute;
168
- /** The attributes with a marker for each binding, while the server renders. */
169
- const mark = (tag, attributes) => {
170
- const now = current();
171
- if (now?.mode !== "collect" && now?.mode !== "replay") return attributes;
172
- const id = attributes.find((item) => isTagged(item) && item._tag === "Id");
173
- const element = id === void 0 ? tag : `${tag}#${id.value}`;
174
- const tokens = /* @__PURE__ */ new Map();
175
- for (const item of attributes) {
176
- if (!isTagged(item)) continue;
177
- const event = item._tag === "OnCustomEvent" && typeof item.name === "string" ? item.name : EVENT_OF[item._tag];
178
- if (event === void 0) continue;
179
- if (now.mode === "collect" && now.region !== void 0) now.inStatic.push({
180
- region: now.region,
181
- element,
182
- event
183
- });
184
- const recorded = holes.get(item);
185
- const nested = now.depth === 0 ? {} : { depth: now.depth };
186
- const binding = !MARKABLE.has(item._tag) ? void 0 : "message" in item ? {
187
- attribute: item._tag,
188
- event,
189
- element,
190
- message: now.wrap(item.message),
191
- ...item.options === void 0 ? {} : { options: item.options }
192
- } : recorded === void 0 ? void 0 : {
193
- attribute: item._tag,
194
- event,
195
- element,
196
- message: now.wrap(recorded.template),
197
- hole: recorded.hole,
198
- ...nested
199
- };
200
- const list = tokens.get(event) ?? [];
201
- tokens.set(event, list);
202
- if (binding === void 0) list.push("*");
203
- else {
204
- list.push(String(now.bindings.length));
205
- now.bindings.push(binding);
206
- }
207
- }
208
- if (tokens.size === 0) return attributes;
209
- const markers = [...tokens].map(([event, list]) => attribute(`${BINDING_ATTRIBUTE}${event}`, list.join(" ")));
210
- return [...attributes, ...markers];
211
- };
212
- /**
213
- * A form whose `OnSubmit` names a Message, while the server renders for a
214
- * plan with a fallback, also posts that Message: `method="post"` to its own
215
- * URL, and a hidden input carrying the Message encoded. Posted fields named
216
- * as the Message's own fields override them, so a typed title reaches
217
- * `update` as it would through the page.
218
- */
219
- const fallback = (tag, attributes, children) => {
220
- const now = current();
221
- if (tag !== "form" || now?.mode === void 0 || now.mode === "resume" || now.fallback === void 0) return {
222
- attributes,
223
- children
224
- };
225
- const submit = attributes.find((item) => isTagged(item) && item._tag === "OnSubmit" && "message" in item);
226
- if (submit === void 0 || !Array.isArray(children)) return {
227
- attributes,
228
- children
229
- };
230
- const encoded = now.fallback(now.wrap(submit.message));
231
- if (encoded === void 0) return {
232
- attributes,
233
- children
234
- };
235
- const make = (name) => source[name];
236
- const input = source.input;
237
- const hidden = (name, value) => input([
238
- make("Type")("hidden"),
239
- make("Name")(name),
240
- make("Value")(value)
241
- ]);
242
- return {
243
- attributes: [...attributes, make("Method")("post")],
244
- children: [
245
- ...children,
246
- hidden(FALLBACK_FIELD, encoded),
247
- ...now.depth === 0 ? [] : [hidden(FALLBACK_DEPTH_FIELD, String(now.depth))]
248
- ]
249
- };
250
- };
251
- const textHole = (name) => (given, fixed = {}) => {
252
- const make = source[name];
253
- if (!isMember(given)) return make(given);
254
- const hole = holeOf(given, fixed);
255
- if (hole.length !== 1) throw new Error(`Resume.builder: ${name}(${tagOf$1(given)}) leaves ${hole.length === 0 ? "no field" : hole.join(", ")} for the event to fill; it must leave one string field`);
256
- const [field] = hole;
257
- const made = make((value) => given({
258
- ...fixed,
259
- [field]: value
260
- }));
261
- const template = placeholder(() => given({
262
- ...fixed,
263
- [field]: ""
264
- }));
265
- if (template !== void 0) holes.set(made, {
266
- template,
267
- hole
268
- });
269
- return made;
270
- };
271
- const keyHole = (name) => (given, fixed = {}) => {
272
- const make = source[name];
273
- if (!isMember(given)) return make(given);
274
- const hole = holeOf(given, fixed);
275
- if (hole.length !== 2 || !hole.includes("key") || !hole.includes("modifiers")) throw new Error(`Resume.builder: ${name}(${tagOf$1(given)}) leaves ${hole.join(", ") || "no field"} for the event to fill; it must leave exactly key and modifiers`);
276
- const made = make((key, modifiers) => given({
277
- ...fixed,
278
- key,
279
- modifiers
280
- }));
281
- const template = placeholder(() => given({
282
- ...fixed,
283
- key: "",
284
- modifiers: NO_MODIFIERS
285
- }));
286
- if (template !== void 0) holes.set(made, {
287
- template,
288
- hole
289
- });
290
- return made;
291
- };
292
- /**
293
- * `h.submodel` with the child's root stamped with its slot, while the
294
- * server renders: a boundary a tool can find, which the browser's first
295
- * patch removes as it removes the markers.
296
- */
297
- const submodel = (config) => {
298
- const original = source.submodel;
299
- const now = current();
300
- if (now?.mode !== "collect" && now?.mode !== "replay") return original(config);
301
- const view = config.view;
302
- const stamped = (...args) => {
303
- const outer = {
304
- wrap: now.wrap,
305
- depth: now.depth
306
- };
307
- now.wrap = (message) => outer.wrap(config.toParentMessage(message));
308
- now.depth = outer.depth + 1;
309
- let out;
310
- try {
311
- out = view(...args);
312
- } finally {
313
- now.wrap = outer.wrap;
314
- now.depth = outer.depth;
315
- }
316
- if (out !== null && typeof out === "object" && out.data !== void 0) out.data.attrs = {
317
- ...out.data.attrs,
318
- [SLOT_ATTRIBUTE]: config.slotId
319
- };
320
- return out;
321
- };
322
- return original({
323
- ...config,
324
- view: Object.assign(stamped, view)
325
- });
326
- };
327
- const wrapped = {};
328
- for (const [name, value] of Object.entries(source)) if (name === "submodel") wrapped[name] = submodel;
329
- else if (name === "OnInput" || name === "OnChange") wrapped[name] = textHole(name);
330
- else if (name === "OnKeyDown" || name === "OnKeyUp") wrapped[name] = keyHole(name);
331
- else if (name === "keyed") {
332
- const keyed = value;
333
- wrapped[name] = (tag) => (key, attributes = [], ...rest) => {
334
- const posted = fallback(tag, attributes, rest[0]);
335
- return keyed(tag)(key, mark(tag, posted.attributes), posted.children, ...rest.slice(1));
336
- };
337
- } else if (/^[a-z]/.test(name) && typeof value === "function") {
338
- const element = value;
339
- wrapped[name] = (attributes, ...rest) => {
340
- const posted = fallback(name, attributes, rest[0]);
341
- return element(mark(name, posted.attributes), posted.children, ...rest.slice(1));
342
- };
343
- } else wrapped[name] = value;
344
- builders.set(h, wrapped);
345
- return wrapped;
346
- };
347
- /**
348
- * A view or renderer written against the resumable builder, as one that takes
349
- * the builder it is given: `Surface.rootView(Page, params, Resume.view(render))`,
350
- * `SurfaceView.define`, or an application's own view.
351
- */
352
- const view = (render) => (model, h) => render(model, builder(h));
353
- //#endregion
354
- //#region src/listen.ts
355
- /**
356
- * Delegated dispatch: the page answers an event from its markers, before the
357
- * application has booted.
358
- *
359
- * One capture-phase listener per event type sits at the root, so events that
360
- * do not bubble (`focus`, `blur`) are caught, and it runs before anything
361
- * Foldkit attaches later. On an event it walks from the target to the root
362
- * and, for every marker of that event on the way, collects each binding's
363
- * Message in order, the way Foldkit's own handler would dispatch it: a hole is
364
- * filled from the event, `OnClick`'s options are honoured, `OnSubmit`
365
- * prevents the default. A marker token the page could not name (`*`) means
366
- * the live page does something here the page cannot describe, so the walk
367
- * ends and the answer names that element.
368
- */
369
- /**
370
- * A binding as the envelope carries it: Foldkit's attribute (`OnSubmit`,
371
- * `OnBlur`), whose tag says what its handler does beside dispatching; the
372
- * Message, encoded through the application's Message Schema (for a hole, with
373
- * the hole filled by a placeholder); the fields the event fills, `depth`
374
- * placement wrappers down; and the attribute's options. Its ordinal is its
375
- * index. The page is read through this Schema, so a tampered list is refused.
376
- */
377
- const EncodedBinding = Schema.Struct({
378
- attribute: Schema.String,
379
- message: Schema.Unknown,
380
- hole: Schema.optionalKey(Schema.Array(Schema.String)),
381
- depth: Schema.optionalKey(Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))),
382
- options: Schema.optionalKey(Schema.Unknown)
383
- });
384
- const EncodedBindings = Schema.Array(EncodedBinding);
385
- /**
386
- * The page's bindings, decoded through the application's Message Schema, and
387
- * every marker in `root` checked against them. A page whose markers name a
388
- * binding it does not carry, or whose entry is not one of the application's
389
- * Messages, is refused whole, with the reason.
390
- */
391
- const decodeBindings = (Message, encoded, root, allowed) => {
392
- if (encoded.length > 0 && Message === void 0) return Result.fail("the page has bindings and the plan has no Message Schema to decode them with");
393
- const decode = Message === void 0 ? void 0 : Schema.decodeUnknownResult(Message);
394
- const bindings = [];
395
- for (const [index, entry] of encoded.entries()) {
396
- const event = EVENT_OF[entry.attribute];
397
- if (event === void 0) return Result.fail(`binding ${index} is for "${entry.attribute}", which is no event attribute`);
398
- const message = decode(entry.message);
399
- if (Result.isFailure(message)) return Result.fail(`binding ${index} does not decode as a Message: ${message.failure.message}`);
400
- const tag = message.success._tag;
401
- if (typeof tag !== "string" || !allowed.has(tag)) return Result.fail(`binding ${index} dispatches ${typeof tag === "string" ? tag : "an untagged Message"}, which no active Surface lists in its messages`);
402
- bindings.push({
403
- attribute: entry.attribute,
404
- event,
405
- message: message.success,
406
- ...entry.hole === void 0 ? {} : { hole: entry.hole },
407
- ...entry.depth === void 0 ? {} : { depth: entry.depth },
408
- ...entry.options === void 0 ? {} : { options: entry.options }
409
- });
410
- }
411
- for (const element of Array.from(root.querySelectorAll("*"))) for (const attribute of element.getAttributeNames()) {
412
- if (!attribute.startsWith("data-foldkit-plus-on-")) continue;
413
- for (const token of (element.getAttribute(attribute) ?? "").split(" ")) {
414
- if (token === "*") continue;
415
- const ordinal = Number(token);
416
- if (!Number.isInteger(ordinal) || bindings[ordinal] === void 0) return Result.fail(`the marker ${attribute}="${token}" names no binding the page carries`);
417
- }
418
- }
419
- return Result.succeed(bindings);
420
- };
421
- /** A string property of the target, if it has one. */
422
- const stringProperty = (target, name) => {
423
- if (target === null || !(name in target)) return void 0;
424
- const value = Reflect.get(target, name);
425
- return typeof value === "string" ? value : void 0;
426
- };
427
- /**
428
- * Foldkit's reading of an input's value (`inputEventValue`): any target's
429
- * string `value`, a custom element's included, else its `innerText`, else its
430
- * `textContent`.
431
- */
432
- const inputValue = (target) => stringProperty(target, "value") ?? stringProperty(target, "innerText") ?? stringProperty(target, "textContent") ?? "";
433
- const modifiersOf = (event) => ({
434
- shiftKey: event.shiftKey,
435
- ctrlKey: event.ctrlKey,
436
- altKey: event.altKey,
437
- metaKey: event.metaKey
438
- });
439
- /** The Message a binding dispatches for this event: its own, with the hole filled. */
440
- const messageFor = (binding, event) => {
441
- if (binding.hole === void 0) return binding.message;
442
- const fill = (template) => {
443
- if (binding.event === "input" || binding.event === "change") {
444
- const [field] = binding.hole ?? [];
445
- return {
446
- ...template,
447
- [field ?? "value"]: inputValue(event.target)
448
- };
449
- }
450
- if (event instanceof KeyboardEvent) return {
451
- ...template,
452
- key: event.key,
453
- modifiers: modifiersOf(event)
454
- };
455
- return template;
456
- };
457
- const inside = (template, depth) => depth === 0 ? fill(template) : {
458
- ...template,
459
- message: inside(template.message, depth - 1)
460
- };
461
- return inside(binding.message, binding.depth ?? 0);
462
- };
463
- /**
464
- * Listens at `root` for every event the bindings name, and answers each from
465
- * the markers. Returns what removes the listeners.
466
- */
467
- const listen = (root, options) => {
468
- const events = new Set(options.bindings.map((binding) => binding.event));
469
- for (const element of [root, ...Array.from(root.querySelectorAll("*"))]) for (const { name } of Array.from(element.attributes)) if (name.startsWith("data-foldkit-plus-on-")) events.add(name.slice(21));
470
- const handler = (event) => {
471
- const type = event.type;
472
- const attribute = `${BINDING_ATTRIBUTE}${type}`;
473
- const messages = [];
474
- const path = event.bubbles ? event.composedPath() : [event.target];
475
- for (const node of path) {
476
- if (!(node instanceof Element)) continue;
477
- const tokens = node.getAttribute(attribute);
478
- let stopped = false;
479
- if (tokens !== null) for (const token of tokens.split(" ")) {
480
- if (token === "*") {
481
- options.onAnswer({
482
- event,
483
- messages,
484
- unnamed: node
485
- });
486
- return;
487
- }
488
- const binding = options.bindings[Number(token)];
489
- if (binding === void 0) continue;
490
- if (binding.attribute === "OnSubmit") event.preventDefault();
491
- if (binding.attribute === "OnClick") {
492
- const click = binding.options ?? {};
493
- if (click.defaultAction === "Prevent") event.preventDefault();
494
- if (click.propagation === "Stop") event.stopPropagation();
495
- if (click.focusSelector !== void 0) {
496
- const focusTarget = document.querySelector(click.focusSelector);
497
- if (focusTarget instanceof HTMLElement) focusTarget.focus();
498
- }
499
- if (click.propagation === "Stop") stopped = true;
500
- }
501
- messages.push(messageFor(binding, event));
502
- }
503
- if (stopped || node === root) break;
504
- }
505
- options.onAnswer({
506
- event,
507
- messages
508
- });
509
- };
510
- for (const type of events) root.addEventListener(type, handler, true);
511
- return () => {
512
- for (const type of events) root.removeEventListener(type, handler, true);
513
- };
514
- };
515
- //#endregion
516
5
  //#region src/index.ts
517
6
  /**
518
7
  * `foldkit-ssr`: what crosses from the server to the browser when a page is
519
8
  * rendered on one and resumed on the other.
520
9
  *
521
10
  * Built from the plan in `docs/design/ssr-PLAN.md`. A resume plan names the
522
- * slice of the Model the browser owns. The server writes that slice into the
523
- * page as a JSON script; the browser reads it back and sets it onto a baseline
11
+ * slice of the Model the browser owns. The server writes that slice onto the
12
+ * stamped root as a JSON attribute, beside Foldkit's own stamps; the browser
13
+ * reads it back and sets it onto a baseline
524
14
  * Model. Nothing outside the slice crosses, and a payload that cannot be read
525
15
  * back exactly is refused, never half-restored.
526
16
  *
527
17
  * Rendering and hydrating stay Foldkit's own: this package adds only the
528
- * handover.
529
- */
530
- /** The attribute on the script that carries a page's resume envelope. */
531
- const RESUME_ATTRIBUTE = "data-foldkit-plus-resume";
532
- /** The envelope format this package writes and reads. */
533
- const PROTOCOL = 1;
534
- /**
535
- * JSON that is safe inside `<script type="application/json">`. Escaping `<`
536
- * keeps `<\/script`, `<!--` and `<script` out of it, as Foldkit escapes its
537
- * Flags. U+2028 and U+2029 are escaped too: they are fine in JSON and break a
538
- * reader that treats the text as JavaScript.
539
- */
540
- const LINE_SEPARATOR = String.fromCharCode(8232);
541
- const PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
542
- const serializeJsonScript = (value) => JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(LINE_SEPARATOR, "\\u2028").replaceAll(PARAGRAPH_SEPARATOR, "\\u2029");
543
- /** Why a page's resume envelope was refused. */
544
- var ResumeRefused = class extends Schema.TaggedError()("ResumeRefused", {
545
- reason: Schema.Literals([
546
- "Missing",
547
- "Duplicate",
548
- "Unreadable",
549
- "Protocol",
550
- "Plan",
551
- "Invalid",
552
- "Route"
553
- ]),
554
- message: Schema.String
555
- }) {};
556
- const refuse = (reason, message) => Result.fail(new ResumeRefused({
557
- reason,
558
- message
559
- }));
560
- /**
561
- * The slice's Schema as a codec needing no services. A resume plan's state is
562
- * plain data, so any field that needs one cannot cross a page anyway.
563
- */
564
- const codecOf = (schema) => schema;
565
- /**
566
- * A resume plan for an application. The baseline defaults to the
567
- * application's initial Model. It is never written: a writable projection's
568
- * `set` returns a new Model, so a baseline Foldkit freezes in development is
569
- * safe to start from.
570
- *
571
- * `surfaces` are the Surfaces the browser may activate, and `local` the Model
572
- * fields allowed to start from the baseline, such as an open menu. Rendering
573
- * refuses a plan that leaves a Surface's read or activation in neither.
18
+ * handover. This module is the server's side and the browser's
19
+ * (`foldkit-ssr/client`) together.
574
20
  */
575
- const plan = (application, config) => {
576
- const surfaces = config.surfaces ?? [];
577
- const parts = config.parts ?? [];
578
- const repeated = parts.find((part, index) => parts.findIndex((p) => p.id === part.id) !== index);
579
- if (repeated !== void 0) throw new Error(`SSR.plan: two parts of plan "${config.id}" share the id "${repeated.id}"; give one an id of its own`);
580
- const foreign = surfaces.find((surface) => application.owner !== void 0 && surface.owner !== application.owner);
581
- if (foreign !== void 0) throw new Error(`SSR.plan: the Surface "${foreign.name}" belongs to another application than plan "${config.id}"`);
582
- return {
583
- id: config.id,
584
- state: config.state,
585
- baseline: config.baseline ?? application.initial,
586
- ...config.boot === void 0 ? {} : { boot: config.boot },
587
- local: (config.local ?? []).map((place) => place.dependency),
588
- surfaces,
589
- parts,
590
- ...application.Message === void 0 ? {} : { Message: application.Message },
591
- start: config.start ?? "now",
592
- deferrable: config.deferrable ?? [],
593
- ...config.fallback === void 0 ? {} : { fallback: config.fallback }
594
- };
595
- };
596
- /** A path as a `path` match compares it. */
597
- const pathKey = (route) => {
598
- const trimmed = (route.split(/[?#]/)[0] ?? "").replace(/\/index\.html$/, "/").replace(/\/+$/, "");
599
- return trimmed === "" ? "/" : trimmed;
600
- };
601
21
  /** The projections of the plan's Surfaces that are active for `model`. */
602
- const activeProjections = (plan, model) => plan.surfaces.flatMap((surface) => {
603
- const projection = surface.projectionOf(model);
604
- return projection === void 0 ? [] : [projection];
605
- });
22
+ const activeProjections = (plan, model) => plan.surfaces.flatMap((surface) => Option.toArray(surface.projectionOf(model)));
606
23
  /**
607
24
  * What the envelope carries of `model`: the plan's slice, encoded through its
608
25
  * own Schema, and each part's capture.
@@ -617,77 +34,77 @@ const payloadOf = (plan, model) => {
617
34
  };
618
35
  };
619
36
  /**
620
- * The Model a payload resumes: the baseline with the slice set onto it, then
621
- * each part restored, in order. Every part the plan names must be there and
622
- * restore, and no other may be: a page is never half-restored.
37
+ * The envelope for `model`: the plan's slice, each part's capture, and
38
+ * the route it was rendered for, if it was rendered for one. `SSR.render`
39
+ * carries it on the stamped root, beside Foldkit's own stamps, escaped for
40
+ * the attribute; this is the same JSON unescaped, for tests and hosts that
41
+ * place the page themselves.
623
42
  */
624
- const modelFrom = (plan, payload) => {
625
- const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state);
626
- if (Result.isFailure(decoded)) return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`);
627
- const given = payload.parts ?? {};
628
- if (typeof given !== "object" || Array.isArray(given)) return Result.fail("the envelope's parts are not an object of parts by id");
629
- const parts = given;
630
- const unknown = Object.keys(parts).find((id) => !plan.parts.some((part) => part.id === id));
631
- if (unknown !== void 0) return Result.fail(`the envelope carries a part "${unknown}" the plan does not name`);
632
- let model = plan.state.set(plan.baseline, decoded.success);
633
- for (const part of plan.parts) {
634
- if (!Object.hasOwn(parts, part.id)) return Result.fail(`the envelope carries no "${part.id}" part`);
635
- const restored = part.restore(model, parts[part.id]);
636
- if (Result.isFailure(restored)) return Result.fail(`the "${part.id}" part does not restore: ${restored.failure}`);
637
- model = restored.success;
638
- }
639
- return Result.succeed(model);
640
- };
43
+ const envelope = (resume, model, options = {}) => envelopeOf(resume, payloadOf(resume, model), options);
641
44
  /**
642
- * The script a server writes into its page's template: the plan's slice of
643
- * `model`, encoded through the slice's own Schema, each part's capture, and
644
- * the route it was rendered for, if it was rendered for one.
45
+ * The envelope for a payload already built: the JSON the stamped root carries.
645
46
  */
646
- const envelope = (resume, model, options = {}) => envelopeOf(resume, payloadOf(resume, model), options);
647
- /** The envelope script for a payload already built. */
648
- const envelopeOf = (resume, payload, options) => {
649
- const body = serializeJsonScript({
650
- v: PROTOCOL,
651
- plan: resume.id,
652
- ...payload,
653
- ...options.route === void 0 ? {} : { route: options.route },
654
- ...options.match === "path" ? { match: "path" } : {},
655
- ...options.bindings === void 0 || options.bindings.length === 0 ? {} : { bindings: options.bindings }
656
- });
657
- return `<script type="application/json" ${RESUME_ATTRIBUTE}>${body}<\/script>`;
47
+ const envelopeOf = (resume, payload, options) => serializeJsonScript({
48
+ v: 1,
49
+ plan: resume.id,
50
+ ...payload,
51
+ ...options.route === void 0 ? {} : { route: options.route },
52
+ ...options.match === "path" ? { match: "path" } : {},
53
+ ...options.bindings === void 0 || options.bindings.length === 0 ? {} : { bindings: options.bindings },
54
+ ...options.events === void 0 || options.events.length === 0 ? {} : { events: options.events }
55
+ });
56
+ /**
57
+ * The rendered application with the envelope on its stamped root, beside
58
+ * Foldkit's own app and build stamps. `injectIntoTemplate` accepts the
59
+ * envelope there, as part of the root, and refuses it beside the root, so a
60
+ * page the host injects carries the handover without the entry owning the
61
+ * template. Hydration adopts the server's nodes around it and drops the
62
+ * attribute on its first patch, so the browser reads the envelope before it
63
+ * boots.
64
+ */
65
+ const withEnvelopeAttribute = (html, json) => {
66
+ const stamp = "data-foldkit-app=\"";
67
+ let from = 0;
68
+ for (;;) {
69
+ const at = html.indexOf(stamp, from);
70
+ if (at === -1) throw new Error("foldkit-ssr: the rendered application has no stamped root to carry the resume envelope");
71
+ if (isInRootTag(html, at)) {
72
+ const end = html.indexOf("\"", at + 18);
73
+ if (end === -1) throw new Error("foldkit-ssr: the rendered application has no stamped root to carry the resume envelope");
74
+ return `${html.slice(0, end + 1)}${attributeOf(json)}${html.slice(end + 1)}`;
75
+ }
76
+ from = at + 18;
77
+ }
658
78
  };
659
- /** The page's one envelope, parsed; refused when there is none, more than one, or not JSON. */
660
- const readEnvelope = (page) => {
661
- const scripts = page.querySelectorAll(`script[${RESUME_ATTRIBUTE}]`);
662
- if (scripts.length === 0) return refuse("Missing", "the page holds no resume envelope");
663
- if (scripts.length > 1) return refuse("Duplicate", `the page holds ${scripts.length} resume envelopes`);
664
- try {
665
- const parsed = JSON.parse(scripts[0].textContent ?? "");
666
- return Result.succeed(parsed ?? {});
667
- } catch (error) {
668
- return refuse("Unreadable", `the resume envelope is not JSON: ${String(error)}`);
79
+ /** Whether `at` sits inside the markup's first tag: quoted values skipped whole. */
80
+ const isInRootTag = (html, at) => {
81
+ if (!html.startsWith("<")) return false;
82
+ let index = 1;
83
+ while (index < at) {
84
+ const char = html[index];
85
+ if (char === "\"" || char === "'") {
86
+ const close = html.indexOf(char, index + 1);
87
+ if (close === -1 || close >= at) return false;
88
+ index = close + 1;
89
+ } else if (char === ">") return false;
90
+ else index++;
669
91
  }
92
+ return true;
670
93
  };
671
94
  /**
672
- * The Model a page resumes from: the baseline with the envelope's slice set
673
- * onto it. Refused, with the reason, when the page holds no envelope or more
674
- * than one, when it is not this protocol or this plan, or when the slice does
675
- * not decode through the plan's Schema. A page is never half-restored.
95
+ * The rendered markup with `extra` as the root's last child, so the first
96
+ * paint is styled before any script runs where no template head can take it.
97
+ * A void root holds no children: styles for one are refused, naming the tag,
98
+ * rather than served where no browser could keep them.
676
99
  */
677
- const resume = (plan, page, options = {}) => {
678
- const read = readEnvelope(page);
679
- if (Result.isFailure(read)) return Result.fail(read.failure);
680
- const { v, plan: id, state, parts, route, match } = read.success;
681
- if (v !== PROTOCOL) return refuse("Protocol", `the envelope is protocol ${String(v)}, not ${PROTOCOL}`);
682
- if (id !== plan.id) return refuse("Plan", `the envelope is for plan "${String(id)}", not "${plan.id}"`);
683
- if (route !== void 0 && options.route !== void 0) {
684
- if (!(match === "path" ? pathKey(String(route)) === pathKey(options.route) : route === options.route)) return refuse("Route", `the page was ${match === "path" ? "generated" : "rendered"} for ${String(route)}, not ${options.route}`);
685
- }
686
- const resumed = modelFrom(plan, {
687
- state,
688
- parts
689
- });
690
- return Result.isFailure(resumed) ? refuse("Invalid", resumed.failure) : Result.succeed(resumed.success);
100
+ const withInRoot = (html, extra) => {
101
+ const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1];
102
+ const at = tag === void 0 ? -1 : html.search(new RegExp(`</${tag}>\\s*$`));
103
+ if (tag === void 0 || at === -1) return Result.fail(new ResumeUnsafe({
104
+ reason: "VoidRootWithStyles",
105
+ 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`
106
+ }));
107
+ return Result.succeed(`${html.slice(0, at)}${extra}${html.slice(at)}`);
691
108
  };
692
109
  /**
693
110
  * The Model the browser will start from when the server's Model is `model`:
@@ -728,7 +145,7 @@ const coverage = (plan, model, browser) => {
728
145
  local: plan.local.map(pathOf),
729
146
  parts: plan.parts.map((part) => part.id),
730
147
  surfaces: plan.surfaces.map((surface) => {
731
- const served = surface.projectionOf(model);
148
+ const served = Option.getOrUndefined(surface.projectionOf(model));
732
149
  return {
733
150
  name: surface.name,
734
151
  active: served !== void 0,
@@ -741,7 +158,7 @@ const coverage = (plan, model, browser) => {
741
158
  cover: coverOf(path, plan)
742
159
  })),
743
160
  unresumed: served === void 0 ? [] : Metadata.summarize(served.metadata).filter((summary) => !covered.has(summary.name)),
744
- sameInBrowser: readsKey(served) === readsKey(surface.projectionOf(browser))
161
+ sameInBrowser: readsKey(served) === readsKey(Option.getOrUndefined(surface.projectionOf(browser)))
745
162
  };
746
163
  })
747
164
  };
@@ -765,89 +182,18 @@ var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
765
182
  "UnencodableBinding",
766
183
  "EagerStartRequired",
767
184
  "UndeclaredSurfaces",
768
- "BindingInStaticRegion"
185
+ "BindingInStaticRegion",
186
+ "VoidRootWithStyles"
769
187
  ]),
770
188
  message: Schema.String
771
189
  }) {};
772
- /** The tag a Message value carries, for naming it. */
773
- const tagOf = (message) => typeof message === "object" && message !== null && "_tag" in message && typeof message._tag === "string" ? message._tag : "an untagged Message";
774
- /**
775
- * The Message tags the plan's Surfaces active for `model` may send, which is
776
- * what a page's bindings may dispatch (the design's rule 3).
777
- */
778
- const allowedTags = (plan, model) => new Set(plan.surfaces.flatMap((surface) => surface.projectionOf(model) === void 0 ? [] : surface.messages));
779
190
  /** Each binding whose Message no active Surface lists, one line each. */
780
191
  const unlistedBindings = (plan, model, bindings) => {
781
192
  const allowed = allowedTags(plan, model);
782
193
  return bindings.filter((binding) => !allowed.has(tagOf(binding.message))).map((binding) => `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`);
783
194
  };
784
- /** The attribute on a static region's element, naming the region. */
785
- const STATIC_ATTRIBUTE = "data-foldkit-plus-static";
786
- const boundary = (id, trusted, children) => inertHtml.div([inertHtml.Attribute(STATIC_ATTRIBUTE, id), ...trusted === void 0 ? [] : [inertHtml.InnerHTML(trusted)]], children);
787
- /**
788
- * A region of the page the server owns for the life of the document. It is
789
- * rendered on the server with the inert builder, so it can dispatch no
790
- * Message. The browser adopts the server's markup as trusted `InnerHTML` and
791
- * never runs `render`, so the region reads nothing from the browser's Model
792
- * and a plan need not send what it reads.
793
- *
794
- * A region changes only with a new document. Content a Message should change
795
- * belongs in a Surface, not here.
796
- */
797
- const staticRegion = (id, render) => {
798
- const now = current();
799
- if (now?.mode === "resume") {
800
- const snapshot = now.snapshots.get(id);
801
- if (snapshot !== void 0) return boundary(id, snapshot, []);
802
- if (!now.reported.has(id)) {
803
- now.reported.add(id);
804
- console.error(`[foldkit-ssr] the static region "${id}" is not in the server's page, so it is rendered in the browser`);
805
- }
806
- return boundary(id, void 0, render(inertHtml));
807
- }
808
- const replayed = now?.mode === "replay" ? now.regions.get(id) : void 0;
809
- if (replayed !== void 0) return boundary(id, void 0, replayed);
810
- if (now?.mode !== "collect") return boundary(id, void 0, render(inertHtml));
811
- const outer = now.region;
812
- now.region = id;
813
- try {
814
- const children = render(inertHtml);
815
- if (now.regions.has(id)) now.duplicates.add(id);
816
- else now.regions.set(id, children);
817
- return boundary(id, void 0, children);
818
- } finally {
819
- now.region = outer;
820
- }
821
- };
822
- /** Each static region's markup in the page, read before hydration touches it. */
823
- const snapshotsOf = (root) => new Map(Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), (element) => [element.getAttribute("data-foldkit-plus-static") ?? "", element.innerHTML]));
824
195
  /** Loads every lazy bundle's bodies, so the view renders whole. */
825
196
  const loadLazy = (config) => Effect.promise(() => Promise.all((config.lazy ?? []).map((bundle) => bundle.load())));
826
- /**
827
- * The build attribute on Foldkit's hydration root. Foldkit does not export it,
828
- * as it does the app and Flags attributes; a test pins it to what Foldkit's
829
- * server stamps.
830
- */
831
- const BUILD_ATTRIBUTE = "data-foldkit-build";
832
- /**
833
- * The config without a `Flags` key at all. Deleted, never set to `undefined`:
834
- * Foldkit's server asks whether `Flags` is defined and its client whether the
835
- * key exists, so an `undefined` one renders and is then refused.
836
- */
837
- const withoutFlags = (config) => {
838
- const { Flags: _flags, ...rest } = config;
839
- return rest;
840
- };
841
- /** The config whose `init` returns this start, whatever arguments it is given. */
842
- const startingFrom = (config, start) => ({
843
- ...withoutFlags(config),
844
- init: () => start
845
- });
846
- /** A route as the envelope records it: the path and the query. */
847
- const routeOf = (url) => {
848
- const parsed = new URL(url, "http://localhost");
849
- return `${parsed.pathname}${parsed.search}`;
850
- };
851
197
  /** Foldkit's own Flags script, which a resumed page never carries. */
852
198
  const FLAGS_SCRIPT = new RegExp(`<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\s\\S]*?<\/script>`, "g");
853
199
  /**
@@ -925,6 +271,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
925
271
  const servedBindings = [];
926
272
  const browserBindings = [];
927
273
  const inStatic = [];
274
+ const unnamed = [];
928
275
  const fallback = fallbackEncoder(plan);
929
276
  const capturing = withContext({
930
277
  ...config,
@@ -938,7 +285,8 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
938
285
  wrap: (message) => message,
939
286
  depth: 0,
940
287
  region: void 0,
941
- inStatic
288
+ inStatic,
289
+ unnamed
942
290
  });
943
291
  const full = yield* renderToString(capturing, options);
944
292
  if (duplicates.size > 0) return yield* new ResumeUnsafe({
@@ -990,47 +338,138 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
990
338
  reason: "UnencodableBinding",
991
339
  message: encoded.failure
992
340
  });
341
+ const meta = plan.meta === void 0 ? "" : metaMarkup(plan.meta(started.model));
993
342
  const differing = [
994
343
  ...full.html.replace(FLAGS_SCRIPT, "") === rendered.html ? [] : ["body"],
995
344
  ...HEAD_FIELDS.filter((field) => full[field] !== rendered[field]),
345
+ ...plan.meta === void 0 || metaMarkup(plan.meta(browser)) === meta ? [] : ["meta"],
996
346
  ...changedBindings(servedBindings, encoded.success, Result.isFailure(reencoded) ? [] : reencoded.success)
997
347
  ];
998
348
  if (differing.length > 0) return yield* new ResumeUnsafe({
999
349
  reason: "ViewDependsOnUnsentState",
1000
350
  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`
1001
351
  });
352
+ const envelope = envelopeOf(plan, payload, {
353
+ ...options.url === void 0 ? {} : { route: match === "path" ? pathKey(routeOf(options.url)) : routeOf(options.url) },
354
+ match,
355
+ bindings: encoded.success,
356
+ events: [.../* @__PURE__ */ new Set([...servedBindings.map((binding) => binding.event), ...unnamed.map((handler) => handler.event)])].sort()
357
+ });
358
+ const styled = options.styles === void 0 ? Result.succeed(rendered.html) : withInRoot(rendered.html, options.styles(rendered));
359
+ if (Result.isFailure(styled)) return yield* styled.failure;
1002
360
  return {
1003
- rendered,
1004
- envelope: envelopeOf(plan, payload, {
1005
- ...options.url === void 0 ? {} : { route: match === "path" ? pathKey(routeOf(options.url)) : routeOf(options.url) },
1006
- match,
1007
- bindings: encoded.success
1008
- })
361
+ rendered: {
362
+ ...rendered,
363
+ html: withEnvelopeAttribute(styled.success, envelope)
364
+ },
365
+ meta,
366
+ envelope,
367
+ unnamed
1009
368
  };
1010
369
  });
1011
370
  /**
1012
- * The template with the envelope before its last `</body>`, in any case. A
1013
- * slice, not `String.replace`, which would read `$&` or `$$` in the Model's
1014
- * data as a replacement pattern. A template with no `</body>` is refused: the
1015
- * page would be served without its envelope and refused in every browser.
1016
- */
1017
- const withEnvelope = (template, envelope) => {
1018
- const at = template.search(/<\/body>(?![\s\S]*<\/body>)/i);
1019
- if (at === -1) throw new Error("foldkit-ssr: the template has no </body> to put the resume envelope before");
1020
- return `${template.slice(0, at)}${envelope}${template.slice(at)}`;
1021
- };
371
+ * The template with `extra` before its last `</head>`, as a slice for the same
372
+ * reason as the envelope. Nothing to add leaves it as it is; something to add
373
+ * and no `</head>` is refused, rather than dropped.
374
+ */
375
+ const withHead = (template, extra) => {
376
+ if (extra === "") return template;
377
+ const at = template.search(/<\/head>(?![\s\S]*<\/head>)/i);
378
+ if (at === -1) throw new Error("foldkit-ssr: the template has no </head> to put the head in");
379
+ return `${template.slice(0, at)}${extra}${template.slice(at)}`;
380
+ };
381
+ /**
382
+ * Foldkit fills `canonical` and `og:url` only into a tag the template already
383
+ * has, and leaves the page without one otherwise. A render that sets either
384
+ * and a template without its tag is refused, naming the tag.
385
+ */
386
+ const FILLED_TAGS = [{
387
+ field: "canonical",
388
+ tag: "<link rel=\"canonical\" href=\"\">",
389
+ at: /<link\b[^>]*\brel\s*=\s*["']?canonical["'\s>]/i
390
+ }, {
391
+ field: "ogUrl",
392
+ tag: "<meta property=\"og:url\" content=\"\">",
393
+ at: /<meta\b[^>]*\bproperty\s*=\s*["']?og:url["'\s>]/i
394
+ }];
395
+ const withFilledTags = (template, rendered) => {
396
+ const missing = FILLED_TAGS.filter(({ field, at }) => rendered[field] !== void 0 && !at.test(template));
397
+ if (missing.length > 0) throw new Error(`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`);
398
+ return template;
399
+ };
400
+ /** The plan's `meta`, then what `head` adds, one line apart. */
401
+ const headOf = (result, head) => [result.meta, head?.(result.rendered) ?? ""].filter((markup) => markup !== "").join("\n");
1022
402
  /**
1023
403
  * The page to serve: the rendered application in the template, with the
1024
- * envelope before `</body>`. Not in the rendered HTML, which
1025
- * `injectIntoTemplate` requires to hold only the root and Foldkit's payload.
404
+ * plan's `meta` and `head`'s markup, if any, before `</head>`. The envelope
405
+ * is already in the rendered root, so this is Foldkit's `injectIntoTemplate`
406
+ * with a head, and nothing else.
1026
407
  */
1027
- const page = (template, result) => injectIntoTemplate(withEnvelope(template, result.envelope), result.rendered);
408
+ const page = (template, result, options = {}) => injectIntoTemplate(withHead(withFilledTags(template, result.rendered), headOf(result, options.head)), result.rendered);
1028
409
  /** The file a static host serves for a path: `/about` is `about/index.html`. */
1029
410
  const fileOf = (path) => {
1030
411
  const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "");
1031
412
  if (trimmed === "") return "index.html";
1032
413
  return trimmed.endsWith(".html") ? trimmed : `${trimmed}/index.html`;
1033
414
  };
415
+ const xmlText = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
416
+ /**
417
+ * A sitemap of the pages a build generated, each at its full address under
418
+ * `origin`, in the order given. `modified`, when a page has it, is any date
419
+ * `Date` reads, written as the UTC day. A path that does not start with `/`,
420
+ * a path given twice, and a date `Date` cannot read are refused: each would
421
+ * make a sitemap a search engine rejects or misreads.
422
+ */
423
+ const sitemap = (pages, options) => {
424
+ const seen = /* @__PURE__ */ new Set();
425
+ return [
426
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
427
+ "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">",
428
+ ...pages.map(({ path, modified }) => {
429
+ if (!path.startsWith("/")) throw new Error(`SSR.sitemap: "${path}" does not start with /`);
430
+ if (seen.has(path)) throw new Error(`SSR.sitemap: "${path}" is listed twice`);
431
+ seen.add(path);
432
+ const loc = `<loc>${xmlText(new URL(path, options.origin).href)}</loc>`;
433
+ if (modified === void 0) return ` <url>${loc}</url>`;
434
+ const at = new Date(modified);
435
+ if (Number.isNaN(at.getTime())) throw new Error(`SSR.sitemap: "${modified}", the date of "${path}", is not a date`);
436
+ return ` <url>${loc}<lastmod>${at.toISOString().slice(0, 10)}</lastmod></url>`;
437
+ }),
438
+ "</urlset>",
439
+ ""
440
+ ].join("\n");
441
+ };
442
+ /**
443
+ * A `robots.txt` that lets every crawler in, except under `disallow`, and
444
+ * names the sitemap at `sitemap` (default `/sitemap.xml`) under `origin`.
445
+ */
446
+ const robots = (options) => [
447
+ "User-agent: *",
448
+ "Allow: /",
449
+ ...(options.disallow ?? []).map((path) => `Disallow: ${path}`),
450
+ "",
451
+ `Sitemap: ${new URL(options.sitemap ?? "/sitemap.xml", options.origin).href}`,
452
+ ""
453
+ ].join("\n");
454
+ const warnedUnnamed = /* @__PURE__ */ new Set();
455
+ /**
456
+ * Warns, once per process, about each handler that keeps a page from
457
+ * answering before boot. Only a page that waits to boot is held up: one
458
+ * started `'now'`, with no lazy bundle to load, boots before any event.
459
+ */
460
+ const warnUnnamed = (config, plan, unnamed) => {
461
+ if (plan.start === "now" && (config.lazy ?? []).length === 0) return;
462
+ for (const { element, event } of unnamed) {
463
+ const key = JSON.stringify([
464
+ plan.id,
465
+ element,
466
+ event
467
+ ]);
468
+ if (warnedUnnamed.has(key)) continue;
469
+ warnedUnnamed.add(key);
470
+ console.warn(`[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.`);
471
+ }
472
+ };
1034
473
  /**
1035
474
  * Renders pages at build time, one per path, each as `SSR.render` and
1036
475
  * `SSR.page` would, to be written as files. `origin` makes each path the full
@@ -1060,195 +499,103 @@ const generate = (config, plan, options) => Effect.gen(function* () {
1060
499
  buildId: options.buildId,
1061
500
  url: new URL(path, options.origin).href,
1062
501
  ...options.flags === void 0 ? {} : { flags: options.flags(path) }
1063
- }, "path"), (result) => ({
1064
- path,
1065
- file: fileOf(path),
1066
- html: page(options.template, result)
1067
- })));
502
+ }, "path"), (result) => {
503
+ warnUnnamed(config, plan, result.unnamed);
504
+ return {
505
+ path,
506
+ file: fileOf(path),
507
+ html: page(options.template, result, { head: options.head })
508
+ };
509
+ }));
1068
510
  });
1069
511
  /**
1070
- * The server entry for Foldkit's fetch handler: the `renderPage` that
1071
- * `handleRequest` calls, and that the `fetch.js` a Foldkit build emits
1072
- * exports, so a resumed page is served by Node and Workers alike.
512
+ * The server entry for Foldkit's pipeline: the `renderPage` a dev server,
513
+ * a fetch handler, or `handleRequest` calls, and that the `fetch.js` a Foldkit
514
+ * build emits imports from the server entry module, so a resumed page is
515
+ * served by Node and Workers alike.
1073
516
  *
1074
517
  * `GET` and `HEAD` render the page against the plan, with the request's URL
1075
518
  * and, when the application has Flags, `flags(request)`. `POST` goes to
1076
519
  * `SSR.handle` when the plan has a server fallback, and is answered `400` when
1077
- * the post is unusable. Any other method is answered `405` (`handleRequest`
520
+ * the post is unusable. `OPTIONS` is answered `204`, and any other method
521
+ * `405`, each with the methods the entry answers in `allow` (`handleRequest`
1078
522
  * passes every method through). A render that fails, or a plan the render
1079
523
  * refuses, is answered `500` with the reason logged, never with a page the
1080
- * browser cannot resume.
524
+ * browser cannot resume. `headers(request)` rides on the `Rendered` result, so
525
+ * Foldkit's `toResponse` sets it over its own on the page: a cache policy, or
526
+ * a CORS answer to a preflight.
1081
527
  *
1082
- * The page is answered whole, as `Responded`: a `Rendered` result is placed in
1083
- * `handleRequest`'s one template, which has no place for a per-request
1084
- * envelope. Foldkit's own `toResponse` still builds the response, from a
1085
- * template that already holds the envelope, so the headers and the
1086
- * injection are Foldkit's. `handleRequest` still classifies static misses and
1087
- * answers `HEAD` without a body.
528
+ * The page is answered as `Rendered`: the rendered application carries the
529
+ * envelope in its root, so the host injects it into its own template with
530
+ * Foldkit's `injectIntoTemplate`, and a build can generate it with Foldkit's
531
+ * `prerender`. The template, and the container it fills, are the host's:
532
+ * `handleRequest` still classifies static misses and answers `HEAD` without
533
+ * a body.
534
+ *
535
+ * What the page says of itself (`meta`) and per-page `head` markup are
536
+ * written into a template's head, which the host owns here: a plan with
537
+ * `meta` is refused when the entry is made, and served with `SSR.generate`.
1088
538
  */
1089
539
  const entry = (config, plan, options) => {
1090
- withEnvelope(options.template, "");
1091
- return { renderPage: async (request) => {
540
+ if (plan.meta !== void 0) throw new Error(`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`);
541
+ const allow = plan.fallback === "server" ? "GET, HEAD, POST, OPTIONS" : "GET, HEAD, OPTIONS";
542
+ const merge = (response, extra) => {
543
+ for (const name of new Set(extra.keys())) response.headers.delete(name);
544
+ extra.forEach((value, name) => response.headers.append(name, value));
545
+ return response;
546
+ };
547
+ const answer = async (request) => {
1092
548
  const method = request.method.toUpperCase();
1093
549
  const posting = method === "POST" && plan.fallback === "server";
1094
- if (method !== "GET" && method !== "HEAD" && !posting) {
1095
- const allow = plan.fallback === "server" ? "GET, HEAD, POST" : "GET, HEAD";
1096
- return Responded(new Response(null, {
1097
- status: 405,
1098
- headers: { allow }
1099
- }));
550
+ const headersOf = options.headers;
551
+ let extra;
552
+ if (headersOf !== void 0) try {
553
+ extra = new Headers(headersOf(request));
554
+ } catch (error) {
555
+ console.error(`[foldkit-ssr] ${request.url} was not answered: headers threw ${String(error)}`);
556
+ return Responded(plainText(500, "The page could not be rendered."));
1100
557
  }
558
+ const responded = (response) => Responded(extra === void 0 ? response : merge(response, extra));
559
+ if (method === "OPTIONS") return responded(new Response(null, {
560
+ status: 204,
561
+ headers: { allow }
562
+ }));
563
+ if (method !== "GET" && method !== "HEAD" && !posting) return responded(new Response(null, {
564
+ status: 405,
565
+ headers: { allow }
566
+ }));
1101
567
  const flagsOf = options.flags;
568
+ const styled = options.styles === void 0 ? {} : { styles: options.styles };
1102
569
  const exit = await Effect.runPromiseExit(Effect.gen(function* () {
1103
570
  const flags = flagsOf === void 0 ? void 0 : yield* Effect.tryPromise(async () => flagsOf(request));
1104
571
  const flagged = flagsOf === void 0 ? {} : { flags };
1105
- return posting ? yield* handle(request, config, plan, {
572
+ if (posting) return yield* handle(request, config, plan, {
1106
573
  buildId: options.buildId,
1107
- ...flagged
1108
- }) : yield* render(config, plan, {
574
+ ...flagged,
575
+ ...styled
576
+ });
577
+ return yield* render(config, plan, {
1109
578
  buildId: options.buildId,
1110
579
  url: request.url,
1111
- ...flagged
580
+ ...flagged,
581
+ ...styled
1112
582
  });
1113
583
  }));
1114
584
  if (Exit.isFailure(exit)) {
1115
585
  const refused = Cause.findErrorOption(exit.cause).pipe(Option.filter((error) => error instanceof FallbackRefused));
1116
- if (Option.isSome(refused)) return Responded(new Response(`The form could not be handled: ${refused.value.message}`, {
1117
- status: 400,
1118
- headers: { "content-type": "text/plain; charset=utf-8" }
1119
- }));
586
+ if (Option.isSome(refused)) return responded(plainText(400, `The form could not be handled: ${refused.value.message}`));
1120
587
  console.error(`[foldkit-ssr] ${request.url} was not rendered: ${Cause.pretty(exit.cause)}`);
1121
- return Responded(new Response("The page could not be rendered.", {
1122
- status: 500,
1123
- headers: { "content-type": "text/plain; charset=utf-8" }
1124
- }));
1125
- }
1126
- const template = withEnvelope(options.template, exit.value.envelope);
1127
- return Responded(toResponse(template, Rendered(exit.value.rendered), options.containerId === void 0 ? void 0 : { containerId: options.containerId }));
1128
- } };
1129
- };
1130
- /**
1131
- * Starts the browser from the page's resumed Model, without running `init`.
1132
- *
1133
- * In the order Foldkit checks a page: the build id first, before the payload
1134
- * is read, then the envelope and its route. A page from another build is
1135
- * refused by Foldkit itself. A page that cannot resume is refused and contained
1136
- * by Foldkit's own refusal, and the reason is logged. A server page is never
1137
- * rendered again on the client. A page with no server render at all, no
1138
- * stamped root, is rendered on the client as usual.
1139
- */
1140
- const hydrate$1 = (config, plan, options) => {
1141
- const root = document.querySelector(`[${FOLDKIT_APP_ATTRIBUTE}]`);
1142
- if (root === null) {
1143
- run(makeApplication(config));
1144
- return;
1145
- }
1146
- const program = (start) => makeApplication({
1147
- ...startingFrom(config, start),
1148
- container: root
1149
- });
1150
- if (root.getAttribute(BUILD_ATTRIBUTE) !== options.buildId) {
1151
- hydrate(program({ model: plan.baseline }), { buildId: options.buildId });
1152
- return;
1153
- }
1154
- const resumed = resume(plan, document, { route: routeOf(window.location.href) });
1155
- if (Result.isFailure(resumed)) {
1156
- console.error(`[foldkit-ssr] the page cannot resume: ${resumed.failure.message}`);
1157
- hydrate(program({ model: plan.baseline }), { buildId: "" });
1158
- return;
1159
- }
1160
- const model = resumed.success;
1161
- const commands = plan.boot?.(model) ?? [];
1162
- const resuming = {
1163
- mode: "resume",
1164
- snapshots: snapshotsOf(root),
1165
- reported: /* @__PURE__ */ new Set()
1166
- };
1167
- const boot = (subscriptions = {}) => hydrate(makeApplication({
1168
- ...withContext(startingFrom(config, {
1169
- model,
1170
- commands
1171
- }), resuming),
1172
- container: root,
1173
- subscriptions: {
1174
- ...config.subscriptions,
1175
- ...subscriptions
1176
- }
1177
- }), { buildId: options.buildId });
1178
- const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
1179
- if (plan.start === "now" && pending.length === 0) {
1180
- boot();
1181
- return;
1182
- }
1183
- const decoded = bindings(plan, document, root, model);
1184
- if (Result.isFailure(decoded)) {
1185
- console.error(`[foldkit-ssr] the page cannot resume: ${decoded.failure.message}`);
1186
- hydrate(program({ model: plan.baseline }), { buildId: "" });
1187
- return;
1188
- }
1189
- deferBoot(root, decoded.success, plan.start, boot, pending);
1190
- };
1191
- /**
1192
- * Lets the page answer from its bindings until something asks for the
1193
- * runtime, then boots it with the answers queued for replay.
1194
- *
1195
- * The queued Messages reach the runtime through one Subscription entry added
1196
- * for the purpose, so they go through Foldkit's own queue, in order, after
1197
- * its first render, and the Model ends where an eager boot would have taken
1198
- * it. When lazy bundles must load first, the boot waits for them.
1199
- */
1200
- const deferBoot = (root, decoded, start, boot, pending) => {
1201
- const queue = [];
1202
- const unanswered = [];
1203
- let booted = false;
1204
- const stop = listen(root, {
1205
- bindings: decoded,
1206
- onAnswer: ({ event, messages, unnamed }) => {
1207
- if (unnamed !== void 0) {
1208
- startNow();
1209
- if (event.target instanceof Element) unanswered.push({
1210
- event,
1211
- element: event.target
1212
- });
1213
- return;
1214
- }
1215
- startNow();
1216
- if (messages.length === 0) return;
1217
- queue.push(...messages);
1218
- event.stopPropagation();
1219
- }
1220
- });
1221
- const replay = {
1222
- dependenciesSchema: Schema.Null,
1223
- modelToDependencies: () => null,
1224
- dependenciesToStream: () => Stream.fromIterable(queue)
1225
- };
1226
- const commit = () => {
1227
- boot({ "foldkit-ssr.replay": replay });
1228
- stop();
1229
- for (const { event, element } of unanswered.splice(0)) {
1230
- const Ctor = event.constructor;
1231
- element.dispatchEvent(new Ctor(event.type, event));
1232
- }
1233
- };
1234
- const startNow = () => {
1235
- if (booted) return;
1236
- booted = true;
1237
- if (pending.length === 0) {
1238
- commit();
1239
- return;
588
+ return responded(plainText(500, "The page could not be rendered."));
1240
589
  }
1241
- Promise.all(pending.map((bundle) => bundle.load())).then(commit, (error) => {
1242
- console.error(`[foldkit-ssr] a bundle's bodies did not load: ${String(error)}`);
1243
- commit();
1244
- });
590
+ warnUnnamed(config, plan, exit.value.unnamed);
591
+ return extra === void 0 ? Rendered(exit.value.rendered) : Rendered(exit.value.rendered, { headers: extra });
1245
592
  };
1246
- if (start === "now") startNow();
1247
- else if (start === "idle") {
1248
- if (typeof window.requestIdleCallback === "function") window.requestIdleCallback(startNow);
1249
- else setTimeout(startNow, 0);
1250
- }
593
+ return { renderPage: answer };
1251
594
  };
595
+ const plainText = (status, body) => new Response(body, {
596
+ status,
597
+ headers: { "content-type": "text/plain; charset=utf-8" }
598
+ });
1252
599
  /** How a form's Message is written into the page for the fallback, when the plan has one. */
1253
600
  const fallbackEncoder = (plan) => {
1254
601
  if (plan.fallback !== "server" || plan.Message === void 0) return void 0;
@@ -1378,49 +725,28 @@ const handle = (request, config, plan, options) => Effect.gen(function* () {
1378
725
  const model = yield* fold(config, booted, [message], []);
1379
726
  return yield* render(startingFrom(config, { model }), plan, {
1380
727
  buildId: options.buildId,
1381
- url: request.url
728
+ url: request.url,
729
+ ...options.styles === void 0 ? {} : { styles: options.styles }
1382
730
  });
1383
731
  });
1384
- /**
1385
- * The page's bindings, decoded through the plan's Message Schema, kept to the
1386
- * Messages the Surfaces active for `model` may send, and checked against
1387
- * every marker in `root`. Refused, with the reason, when the page carries
1388
- * none, an entry is not one of the application's Messages or one no active
1389
- * Surface lists, or a marker names a binding the page does not carry: a page
1390
- * is answered whole or not at all.
1391
- */
1392
- const bindings = (plan, page, root, model) => {
1393
- const parsed = readEnvelope(page);
1394
- if (Result.isFailure(parsed)) return Result.fail(parsed.failure);
1395
- const read = Schema.decodeUnknownResult(EncodedBindings)(parsed.success.bindings ?? []);
1396
- if (Result.isFailure(read)) return refuse("Invalid", `the page's bindings are malformed: ${read.failure.message}`);
1397
- const encoded = read.success;
1398
- if (encoded.length > 0 && plan.surfaces.length === 0) return refuse("Invalid", "the page has bindings and the plan declares no surfaces to allow them");
1399
- const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model));
1400
- return Result.isFailure(decoded) ? refuse("Invalid", decoded.failure) : Result.succeed(decoded.success);
1401
- };
1402
- /** The resumable track: bindings the server's markup names, so a page can answer before it boots. */
1403
- const Resume = {
1404
- builder,
1405
- view,
1406
- bindings,
1407
- listen
1408
- };
1409
732
  const SSR = {
1410
733
  plan,
1411
734
  envelope,
1412
735
  resume,
1413
736
  render,
1414
737
  page,
1415
- hydrate: hydrate$1,
738
+ hydrate: SSR$1.hydrate,
1416
739
  inspect,
1417
740
  static: staticRegion,
741
+ serving,
1418
742
  generate,
1419
743
  entry,
1420
744
  handle,
1421
- serializeJsonScript
745
+ serializeJsonScript,
746
+ sitemap,
747
+ robots
1422
748
  };
1423
749
  //#endregion
1424
- export { BINDING_ATTRIBUTE, FALLBACK_FIELD, FallbackRefused, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, serializeJsonScript };
750
+ export { BINDING_ATTRIBUTE, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, FallbackRefused, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, metaMarkup };
1425
751
 
1426
752
  //# sourceMappingURL=index.mjs.map