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.
@@ -0,0 +1,1058 @@
1
+ import { Effect, Option, Predicate, Result, Schema, SchemaAST, Stream } from "effect";
2
+ import { hydrate, makeApplication, run } from "foldkit/runtime";
3
+ import * as Render from "foldkit/render";
4
+ import { inertHtml } from "foldkit/html";
5
+ //#region src/context.ts
6
+ let context;
7
+ /** The context of the view call in progress, if any. */
8
+ const current = () => context;
9
+ const within = (next, run) => {
10
+ const previous = context;
11
+ context = next;
12
+ try {
13
+ return run();
14
+ } finally {
15
+ context = previous;
16
+ }
17
+ };
18
+ /** The config whose view runs inside `next`. */
19
+ const withContext = (config, next) => ({
20
+ ...config,
21
+ view: (model, h) => within(next, () => config.view(model, h))
22
+ });
23
+ //#endregion
24
+ //#region src/resumable.ts
25
+ /**
26
+ * The resumable builder: the application's `h`, whose event attributes say, in
27
+ * the server's markup, which Message each element causes.
28
+ *
29
+ * A Foldkit handler is a Message value (`h.OnClick(Message.Liked({ id }))`), so
30
+ * for most events that is already data. The events that carry a value
31
+ * (`OnInput`, `OnChange`, `OnKeyDown`, `OnKeyUp`) take a closure only to put
32
+ * the value into a Message field; this builder also takes the Message's own
33
+ * constructor there, a Message with a hole, and fills the hole the same way.
34
+ *
35
+ * During the server's renders each binding gets an ordinal, recorded in render
36
+ * order, and its element a `data-foldkit-plus-on-<event>` attribute naming it.
37
+ * In the browser the builder marks nothing: it is the application's `h`, with
38
+ * the hole forms turned into the closures Foldkit expects.
39
+ */
40
+ /** The attribute prefix of an element's binding marker. */
41
+ const BINDING_ATTRIBUTE = "data-foldkit-plus-on-";
42
+ /**
43
+ * The DOM event each of Foldkit's event attributes listens to, read from
44
+ * Foldkit's own attribute table (0.163). `OnCustomEvent` names its event in
45
+ * its payload, and `OnMount` and `OnUnmount` listen to none.
46
+ */
47
+ const EVENT_OF = {
48
+ OnClick: "click",
49
+ OnDoubleClick: "dblclick",
50
+ OnMouseDown: "mousedown",
51
+ OnMouseUp: "mouseup",
52
+ OnMouseEnter: "mouseenter",
53
+ OnMouseLeave: "mouseleave",
54
+ OnMouseOver: "mouseover",
55
+ OnMouseOut: "mouseout",
56
+ OnMouseMove: "mousemove",
57
+ OnPointerMove: "pointermove",
58
+ OnPointerLeave: "pointerleave",
59
+ OnPointerDown: "pointerdown",
60
+ OnPointerUp: "pointerup",
61
+ OnKeyDown: "keydown",
62
+ OnKeyDownPreventDefault: "keydown",
63
+ OnKeyDownSelf: "keydown",
64
+ OnKeyDownSelfPreventDefault: "keydown",
65
+ OnKeyDownFocus: "keydown",
66
+ OnKeyUp: "keyup",
67
+ OnKeyUpPreventDefault: "keyup",
68
+ OnKeyPress: "keypress",
69
+ OnFocus: "focus",
70
+ OnBlur: "blur",
71
+ OnFocusEnter: "focusin",
72
+ OnFocusLeave: "focusout",
73
+ OnInput: "input",
74
+ OnChange: "change",
75
+ OnBeforeInput: "beforeinput",
76
+ OnBeforeInputPreventDefault: "beforeinput",
77
+ OnFileChange: "change",
78
+ OnSubmit: "submit",
79
+ OnReset: "reset",
80
+ OnScroll: "scroll",
81
+ OnWheel: "wheel",
82
+ OnCopy: "copy",
83
+ OnCut: "cut",
84
+ OnPaste: "paste",
85
+ OnPastePreventDefault: "paste",
86
+ OnCopyText: "copy",
87
+ OnCutText: "cut",
88
+ OnCancel: "cancel",
89
+ OnCancelPreventDefault: "cancel",
90
+ OnToggle: "toggle",
91
+ OnContextMenu: "contextmenu",
92
+ OnDragStart: "dragstart",
93
+ OnDrag: "drag",
94
+ OnDragEnd: "dragend",
95
+ OnDragEnter: "dragenter",
96
+ OnDragLeave: "dragleave",
97
+ OnDragOver: "dragover",
98
+ OnDrop: "drop",
99
+ OnDropFiles: "drop",
100
+ OnTouchStart: "touchstart",
101
+ OnTouchEnd: "touchend",
102
+ OnTouchMove: "touchmove",
103
+ OnTouchCancel: "touchcancel",
104
+ OnAnimationStart: "animationstart",
105
+ OnAnimationEnd: "animationend",
106
+ OnAnimationIteration: "animationiteration",
107
+ OnTransitionEnd: "transitionend",
108
+ OnLoad: "load",
109
+ OnError: "error",
110
+ OnPlay: "play",
111
+ OnPause: "pause",
112
+ OnEnded: "ended",
113
+ OnTimeUpdate: "timeupdate",
114
+ OnVolumeChange: "volumechange",
115
+ OnSelect: "select"
116
+ };
117
+ /**
118
+ * The attributes whose binding the page can describe: a Message value, or one
119
+ * of the hole forms this builder records. Any other handler still runs on the
120
+ * live page, so its event is marked `*`: the page does something there it
121
+ * cannot name, and a dispatcher that ran only the named bindings would do less.
122
+ */
123
+ const MARKABLE = /* @__PURE__ */ new Set([
124
+ "OnClick",
125
+ "OnDoubleClick",
126
+ "OnMouseDown",
127
+ "OnMouseUp",
128
+ "OnMouseEnter",
129
+ "OnMouseLeave",
130
+ "OnMouseOver",
131
+ "OnMouseOut",
132
+ "OnMouseMove",
133
+ "OnFocus",
134
+ "OnBlur",
135
+ "OnSubmit",
136
+ "OnReset",
137
+ "OnInput",
138
+ "OnChange",
139
+ "OnKeyDown",
140
+ "OnKeyUp"
141
+ ]);
142
+ /** The posted field that carries a form's encoded Message, for the server fallback. */
143
+ const FALLBACK_FIELD = "foldkit-plus-message";
144
+ /** The posted field that says how many placement wrappers the form's fields sit under. */
145
+ const FALLBACK_DEPTH_FIELD = "foldkit-plus-depth";
146
+ /** The attribute on a placement's root naming its slot, while the server renders. */
147
+ const SLOT_ATTRIBUTE = "data-foldkit-plus-slot";
148
+ const isMember = (value) => typeof value === "function" && typeof value.fields === "object";
149
+ const tagOf$1 = (member) => {
150
+ const tag = member.fields._tag;
151
+ return Schema.isSchema(tag) && SchemaAST.isLiteral(tag.ast) && typeof tag.ast.literal === "string" ? tag.ast.literal : "the member";
152
+ };
153
+ /** The fields a member leaves for the event to fill, given what is fixed. */
154
+ const holeOf = (member, fixed) => Object.keys(member.fields).filter((field) => field !== "_tag" && !(field in fixed));
155
+ const NO_MODIFIERS = {
156
+ shiftKey: false,
157
+ ctrlKey: false,
158
+ altKey: false,
159
+ metaKey: false
160
+ };
161
+ /** Each hole-form attribute, with its Message filled by a placeholder and the fields the event fills. */
162
+ const holes = /* @__PURE__ */ new WeakMap();
163
+ const isAttribute = (item) => "_tag" in item;
164
+ const builders = /* @__PURE__ */ new WeakMap();
165
+ /** A hole form's placeholder Message, or `undefined` when its field's checks refuse one. */
166
+ const placeholder = (make) => {
167
+ try {
168
+ return make();
169
+ } catch {
170
+ return;
171
+ }
172
+ };
173
+ /**
174
+ * The resumable builder for a view's `h`. Use it in place of `h`; it has the
175
+ * same elements and attributes, and the hole forms of the four value events.
176
+ */
177
+ const builder = (h) => {
178
+ const cached = builders.get(h);
179
+ if (cached !== void 0) return cached;
180
+ const source = h;
181
+ const attribute = source.Attribute;
182
+ /** The attributes with a marker for each binding, while the server renders. */
183
+ const mark = (tag, attributes) => {
184
+ const now = current();
185
+ if (now?.mode !== "collect" && now?.mode !== "replay") return attributes;
186
+ const id = attributes.find((item) => isAttribute(item) && item._tag === "Id");
187
+ const element = id === void 0 ? tag : `${tag}#${id.value}`;
188
+ const tokens = /* @__PURE__ */ new Map();
189
+ for (const item of attributes) {
190
+ if (!isAttribute(item)) continue;
191
+ const event = item._tag === "OnCustomEvent" ? item.name : EVENT_OF[item._tag];
192
+ if (event === void 0) continue;
193
+ if (now.mode === "collect" && now.region !== void 0) now.inStatic.push({
194
+ region: now.region,
195
+ element,
196
+ event
197
+ });
198
+ const recorded = holes.get(item);
199
+ const nested = now.depth === 0 ? {} : { depth: now.depth };
200
+ const binding = !MARKABLE.has(item._tag) ? void 0 : "message" in item ? {
201
+ attribute: item._tag,
202
+ event,
203
+ element,
204
+ message: now.wrap(item.message),
205
+ ..."options" in item && item.options !== void 0 ? { options: item.options } : {}
206
+ } : recorded === void 0 ? void 0 : {
207
+ attribute: item._tag,
208
+ event,
209
+ element,
210
+ message: now.wrap(recorded.template),
211
+ hole: recorded.hole,
212
+ ...nested
213
+ };
214
+ const list = tokens.get(event) ?? [];
215
+ tokens.set(event, list);
216
+ if (binding === void 0) {
217
+ if (now.mode === "collect" && !list.includes("*")) now.unnamed.push({
218
+ element,
219
+ event
220
+ });
221
+ list.push("*");
222
+ } else {
223
+ list.push(String(now.bindings.length));
224
+ now.bindings.push(binding);
225
+ }
226
+ }
227
+ if (tokens.size === 0) return attributes;
228
+ const markers = [...tokens].map(([event, list]) => attribute(`${BINDING_ATTRIBUTE}${event}`, list.join(" ")));
229
+ return [...attributes, ...markers];
230
+ };
231
+ /**
232
+ * A form whose `OnSubmit` names a Message, while the server renders for a
233
+ * plan with a fallback, also posts that Message: `method="post"` to its own
234
+ * URL, and a hidden input carrying the Message encoded. Posted fields named
235
+ * as the Message's own fields override them, so a typed title reaches
236
+ * `update` as it would through the page.
237
+ */
238
+ const fallback = (tag, attributes, children) => {
239
+ const now = current();
240
+ if (tag !== "form" || now?.mode === void 0 || now.mode === "resume" || now.fallback === void 0) return {
241
+ attributes,
242
+ children
243
+ };
244
+ const submit = attributes.find((item) => isAttribute(item) && item._tag === "OnSubmit");
245
+ if (submit === void 0 || !Array.isArray(children)) return {
246
+ attributes,
247
+ children
248
+ };
249
+ const encoded = now.fallback(now.wrap(submit.message));
250
+ if (encoded === void 0) return {
251
+ attributes,
252
+ children
253
+ };
254
+ const make = (name) => source[name];
255
+ const input = source.input;
256
+ const hidden = (name, value) => input([
257
+ make("Type")("hidden"),
258
+ make("Name")(name),
259
+ make("Value")(value)
260
+ ]);
261
+ return {
262
+ attributes: [...attributes, make("Method")("post")],
263
+ children: [
264
+ ...children,
265
+ hidden(FALLBACK_FIELD, encoded),
266
+ ...now.depth === 0 ? [] : [hidden(FALLBACK_DEPTH_FIELD, String(now.depth))]
267
+ ]
268
+ };
269
+ };
270
+ const textHole = (name) => (given, fixed = {}) => {
271
+ const make = source[name];
272
+ if (!isMember(given)) return make(given);
273
+ const hole = holeOf(given, fixed);
274
+ 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`);
275
+ const [field] = hole;
276
+ const made = make((value) => given({
277
+ ...fixed,
278
+ [field]: value
279
+ }));
280
+ const template = placeholder(() => given({
281
+ ...fixed,
282
+ [field]: ""
283
+ }));
284
+ if (template !== void 0) holes.set(made, {
285
+ template,
286
+ hole
287
+ });
288
+ return made;
289
+ };
290
+ const keyHole = (name) => (given, fixed = {}) => {
291
+ const make = source[name];
292
+ if (!isMember(given)) return make(given);
293
+ const hole = holeOf(given, fixed);
294
+ 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`);
295
+ const made = make((key, modifiers) => given({
296
+ ...fixed,
297
+ key,
298
+ modifiers
299
+ }));
300
+ const template = placeholder(() => given({
301
+ ...fixed,
302
+ key: "",
303
+ modifiers: NO_MODIFIERS
304
+ }));
305
+ if (template !== void 0) holes.set(made, {
306
+ template,
307
+ hole
308
+ });
309
+ return made;
310
+ };
311
+ /**
312
+ * `h.submodel` with the child's root stamped with its slot, while the
313
+ * server renders: a boundary a tool can find, which the browser's first
314
+ * patch removes as it removes the markers.
315
+ */
316
+ const submodel = (config) => {
317
+ const original = source.submodel;
318
+ const now = current();
319
+ if (now?.mode !== "collect" && now?.mode !== "replay") return original(config);
320
+ const view = config.view;
321
+ const stamped = (...args) => {
322
+ const outer = {
323
+ wrap: now.wrap,
324
+ depth: now.depth
325
+ };
326
+ now.wrap = (message) => outer.wrap(config.toParentMessage(message));
327
+ now.depth = outer.depth + 1;
328
+ let out;
329
+ try {
330
+ out = view(...args);
331
+ } finally {
332
+ now.wrap = outer.wrap;
333
+ now.depth = outer.depth;
334
+ }
335
+ if (out !== null && typeof out === "object" && out.data !== void 0) out.data.attrs = {
336
+ ...out.data.attrs,
337
+ [SLOT_ATTRIBUTE]: config.slotId
338
+ };
339
+ return out;
340
+ };
341
+ return original({
342
+ ...config,
343
+ view: Object.assign(stamped, view)
344
+ });
345
+ };
346
+ const wrapped = {};
347
+ for (const [name, value] of Object.entries(source)) if (name === "submodel") wrapped[name] = submodel;
348
+ else if (name === "OnInput" || name === "OnChange") wrapped[name] = textHole(name);
349
+ else if (name === "OnKeyDown" || name === "OnKeyUp") wrapped[name] = keyHole(name);
350
+ else if (name === "keyed") {
351
+ const keyed = value;
352
+ wrapped[name] = (tag) => (key, attributes = [], ...rest) => {
353
+ const posted = fallback(tag, attributes, rest[0]);
354
+ return keyed(tag)(key, mark(tag, posted.attributes), posted.children, ...rest.slice(1));
355
+ };
356
+ } else if (/^[a-z]/.test(name) && typeof value === "function") {
357
+ const element = value;
358
+ wrapped[name] = (attributes, ...rest) => {
359
+ const posted = fallback(name, attributes, rest[0]);
360
+ return element(mark(name, posted.attributes), posted.children, ...rest.slice(1));
361
+ };
362
+ } else wrapped[name] = value;
363
+ builders.set(h, wrapped);
364
+ return wrapped;
365
+ };
366
+ /**
367
+ * A view or renderer written against the resumable builder, as one that takes
368
+ * the builder it is given: `Surface.rootView(Page, params, Resume.view(render))`,
369
+ * `SurfaceView.define`, or an application's own view.
370
+ */
371
+ const view = (render) => (model, h) => render(model, builder(h));
372
+ //#endregion
373
+ //#region src/listen.ts
374
+ /**
375
+ * Delegated dispatch: the page answers an event from its markers, before the
376
+ * application has booted.
377
+ *
378
+ * One capture-phase listener per event type sits at the root, so events that
379
+ * do not bubble (`focus`, `blur`) are caught, and it runs before anything
380
+ * Foldkit attaches later. On an event it walks from the target to the root
381
+ * and, for every marker of that event on the way, collects each binding's
382
+ * Message in order, the way Foldkit's own handler would dispatch it: a hole is
383
+ * filled from the event, `OnClick`'s options are honoured, `OnSubmit`
384
+ * prevents the default. A marker token the page could not name (`*`) means
385
+ * the live page does something here the page cannot describe, so the walk
386
+ * ends and the answer names that element.
387
+ */
388
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
389
+ /**
390
+ * The page's list of bindings, read as untrusted input: each entry checked,
391
+ * and only its known keys kept, or the reason the list is refused. Checked by
392
+ * hand rather than through a Schema, which at a thousand rows took most of a
393
+ * frame for a shape this plain; the Message inside each entry is still decoded
394
+ * through the application's Schema by `decodeBindings`.
395
+ */
396
+ const readBindings = (value) => {
397
+ if (!Array.isArray(value)) return Result.fail("the list is not an array");
398
+ const out = [];
399
+ for (const [index, entry] of value.entries()) {
400
+ if (!isRecord(entry)) return Result.fail(`entry ${index} is not an object`);
401
+ if (typeof entry.attribute !== "string") return Result.fail(`entry ${index} has no attribute`);
402
+ if (!Object.hasOwn(entry, "message")) return Result.fail(`entry ${index} has no message`);
403
+ const { hole, depth } = entry;
404
+ if (hole !== void 0 && !(Array.isArray(hole) && hole.every((field) => typeof field === "string"))) return Result.fail(`entry ${index} has a hole that is not a list of fields`);
405
+ if (depth !== void 0 && !(Number.isInteger(depth) && depth >= 0)) return Result.fail(`entry ${index} has a depth that is not a count`);
406
+ out.push({
407
+ attribute: entry.attribute,
408
+ message: entry.message,
409
+ ...hole === void 0 ? {} : { hole },
410
+ ...depth === void 0 ? {} : { depth },
411
+ ...Object.hasOwn(entry, "options") ? { options: entry.options } : {}
412
+ });
413
+ }
414
+ return Result.succeed(out);
415
+ };
416
+ /**
417
+ * The page's bindings, decoded through the application's Message Schema, and
418
+ * every marker in `root` checked against them. A page whose markers name a
419
+ * binding it does not carry, or whose entry is not one of the application's
420
+ * Messages, is refused whole, with the reason.
421
+ */
422
+ const decodeBindings = (Message, encoded, root, allowed) => {
423
+ 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");
424
+ const decode = Message === void 0 ? void 0 : Schema.decodeUnknownResult(Message);
425
+ const bindings = [];
426
+ for (const [index, entry] of encoded.entries()) {
427
+ const event = EVENT_OF[entry.attribute];
428
+ if (event === void 0) return Result.fail(`binding ${index} is for "${entry.attribute}", which is no event attribute`);
429
+ const message = decode(entry.message);
430
+ if (Result.isFailure(message)) return Result.fail(`binding ${index} does not decode as a Message: ${message.failure.message}`);
431
+ const tag = Predicate.hasProperty(message.success, "_tag") ? message.success._tag : void 0;
432
+ 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`);
433
+ bindings.push({
434
+ attribute: entry.attribute,
435
+ event,
436
+ message: message.success,
437
+ ...entry.hole === void 0 ? {} : { hole: entry.hole },
438
+ ...entry.depth === void 0 ? {} : { depth: entry.depth },
439
+ ...entry.options === void 0 ? {} : { options: entry.options }
440
+ });
441
+ }
442
+ for (const element of Array.from(root.querySelectorAll("*"))) for (const attribute of element.getAttributeNames()) {
443
+ if (!attribute.startsWith("data-foldkit-plus-on-")) continue;
444
+ for (const token of (element.getAttribute(attribute) ?? "").split(" ")) {
445
+ if (token === "*") continue;
446
+ const ordinal = Number(token);
447
+ if (!Number.isInteger(ordinal) || bindings[ordinal] === void 0) return Result.fail(`the marker ${attribute}="${token}" names no binding the page carries`);
448
+ }
449
+ }
450
+ return Result.succeed(bindings);
451
+ };
452
+ /** A string property of the target, if it has one. */
453
+ const stringProperty = (target, name) => {
454
+ if (target === null || !(name in target)) return void 0;
455
+ const value = Reflect.get(target, name);
456
+ return typeof value === "string" ? value : void 0;
457
+ };
458
+ /**
459
+ * Foldkit's reading of an input's value (`inputEventValue`): any target's
460
+ * string `value`, a custom element's included, else its `innerText`, else its
461
+ * `textContent`.
462
+ */
463
+ const inputValue = (target) => stringProperty(target, "value") ?? stringProperty(target, "innerText") ?? stringProperty(target, "textContent") ?? "";
464
+ const modifiersOf = (event) => ({
465
+ shiftKey: event.shiftKey,
466
+ ctrlKey: event.ctrlKey,
467
+ altKey: event.altKey,
468
+ metaKey: event.metaKey
469
+ });
470
+ /** The Message a binding dispatches for this event: its own, with the hole filled. */
471
+ const messageFor = (binding, event) => {
472
+ if (binding.hole === void 0) return binding.message;
473
+ const fill = (template) => {
474
+ if (binding.event === "input" || binding.event === "change") {
475
+ const [field] = binding.hole ?? [];
476
+ return {
477
+ ...template,
478
+ [field ?? "value"]: inputValue(event.target)
479
+ };
480
+ }
481
+ if (event instanceof KeyboardEvent) return {
482
+ ...template,
483
+ key: event.key,
484
+ modifiers: modifiersOf(event)
485
+ };
486
+ return template;
487
+ };
488
+ const inside = (template, depth) => depth === 0 ? fill(template) : {
489
+ ...template,
490
+ message: inside(template.message, depth - 1)
491
+ };
492
+ return inside(binding.message, binding.depth ?? 0);
493
+ };
494
+ /**
495
+ * Listens at `root` for every event the bindings name, and answers each from
496
+ * the markers. Returns what removes the listeners.
497
+ */
498
+ const listen = (root, options) => {
499
+ const events = new Set(options.bindings.map((binding) => binding.event));
500
+ if (options.events !== void 0) for (const event of options.events) events.add(event);
501
+ else 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));
502
+ const handler = (event) => {
503
+ const type = event.type;
504
+ const attribute = `${BINDING_ATTRIBUTE}${type}`;
505
+ const messages = [];
506
+ const path = event.bubbles ? event.composedPath() : [event.target];
507
+ for (const node of path) {
508
+ if (!(node instanceof Element)) continue;
509
+ const tokens = node.getAttribute(attribute);
510
+ let stopped = false;
511
+ if (tokens !== null) for (const token of tokens.split(" ")) {
512
+ if (token === "*") {
513
+ options.onAnswer({
514
+ event,
515
+ messages,
516
+ unnamed: node
517
+ });
518
+ return;
519
+ }
520
+ const binding = options.bindings[Number(token)];
521
+ if (binding === void 0) continue;
522
+ if (binding.attribute === "OnSubmit") event.preventDefault();
523
+ if (binding.attribute === "OnClick") {
524
+ const click = binding.options ?? {};
525
+ if (click.defaultAction === "Prevent") event.preventDefault();
526
+ if (click.propagation === "Stop") event.stopPropagation();
527
+ if (click.focusSelector !== void 0) {
528
+ const focusTarget = document.querySelector(click.focusSelector);
529
+ if (focusTarget instanceof HTMLElement) focusTarget.focus();
530
+ }
531
+ if (click.propagation === "Stop") stopped = true;
532
+ }
533
+ messages.push(messageFor(binding, event));
534
+ }
535
+ if (stopped || node === root) break;
536
+ }
537
+ options.onAnswer({
538
+ event,
539
+ messages
540
+ });
541
+ };
542
+ for (const type of events) root.addEventListener(type, handler, true);
543
+ return () => {
544
+ for (const type of events) root.removeEventListener(type, handler, true);
545
+ };
546
+ };
547
+ //#endregion
548
+ //#region src/shared.ts
549
+ /**
550
+ * What the server and the browser both read: the plan, the envelope as the
551
+ * browser reads it, static regions, and the page's bindings. Nothing here
552
+ * imports Foldkit's server renderer, so `client.ts` can carry all of it.
553
+ */
554
+ /**
555
+ * The attribute Foldkit's server stamps on an application's root, as
556
+ * `foldkit/experimental/server` exports it. Written out here so a page can
557
+ * find its root without that module; a test pins the two together.
558
+ */
559
+ const FOLDKIT_APP_ATTRIBUTE = "data-foldkit-app";
560
+ /**
561
+ * The attribute on the stamped root that carries a page's resume envelope.
562
+ * Foldkit pairs its own handoff the same way: the build id rides on the root
563
+ * beside the app stamp, and the client reads it before adopting anything.
564
+ */
565
+ const RESUME_ATTRIBUTE = "data-foldkit-plus-resume";
566
+ const LINE_SEPARATOR = String.fromCharCode(8232);
567
+ const PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
568
+ /**
569
+ * JSON for a script element: `<` is escaped so `<\/script>` in the data ends
570
+ * nothing. U+2028 and U+2029 are escaped too: they are fine in JSON and break a
571
+ * reader that treats the text as JavaScript.
572
+ */
573
+ const serializeJsonScript = (value) => JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(LINE_SEPARATOR, "\\u2028").replaceAll(PARAGRAPH_SEPARATOR, "\\u2029");
574
+ /**
575
+ * The envelope JSON as the stamped root carries it: `serializeJsonScript`
576
+ * already escaped `<` and the line separators, and an attribute must escape
577
+ * `&` and `"` besides, so no string in the Model can break out of the value.
578
+ * `getAttribute` resolves the entities back, which is exactly the JSON.
579
+ */
580
+ const attributeOf = (json) => ` ${RESUME_ATTRIBUTE}="${json.replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}"`;
581
+ /** Marks each head element a plan's `meta` wrote, so the browser can replace them. */
582
+ const META_ATTRIBUTE = "data-foldkit-meta";
583
+ const attributeText = (text) => text.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
584
+ /** The head markup of a `Meta`, every value escaped, one element per line. */
585
+ const metaMarkup = (meta) => {
586
+ const tag = (element, attributes) => `<${element} ${META_ATTRIBUTE} ${attributes.map(([name, value]) => `${name}="${attributeText(value)}"`).join(" ")}>`;
587
+ const named = (name, value) => value === void 0 ? [] : [tag("meta", [["name", name], ["content", value]])];
588
+ const property = (name, value) => value === void 0 ? [] : [tag("meta", [["property", name], ["content", value]])];
589
+ return [
590
+ ...named("description", meta.description),
591
+ ...property("og:title", meta.title),
592
+ ...property("og:description", meta.description),
593
+ ...property("og:type", meta.type),
594
+ ...property("og:site_name", meta.siteName),
595
+ ...property("og:image", meta.image),
596
+ ...meta.description === void 0 && meta.image === void 0 && meta.title === void 0 ? [] : named("twitter:card", meta.image === void 0 ? "summary" : "summary_large_image"),
597
+ ...property("article:published_time", meta.article?.published),
598
+ ...property("article:modified_time", meta.article?.modified),
599
+ ...named("robots", meta.robots),
600
+ ...(meta.alternates ?? []).map(({ hreflang, href }) => tag("link", [
601
+ ["rel", "alternate"],
602
+ ["hreflang", hreflang],
603
+ ["href", href]
604
+ ])),
605
+ ...(meta.jsonLd ?? []).map((data) => `<script ${META_ATTRIBUTE} type="application/ld+json">${serializeJsonScript(data)}<\/script>`)
606
+ ].join("\n");
607
+ };
608
+ /**
609
+ * The Subscription entry that keeps the head's `meta` elements in step with
610
+ * the Model, so a move within the page (another post) changes its
611
+ * description too. It writes the head and sends no Message.
612
+ */
613
+ const metaEntry = (meta) => ({
614
+ dependenciesSchema: Schema.String,
615
+ modelToDependencies: (model) => metaMarkup(meta(model)),
616
+ dependenciesToStream: (markup) => Stream.drain(Stream.fromEffect(Effect.sync(() => {
617
+ const written = document.createElement("template");
618
+ written.innerHTML = markup;
619
+ for (const old of document.head.querySelectorAll(`[${META_ATTRIBUTE}]`)) old.remove();
620
+ document.head.append(written.content);
621
+ })))
622
+ });
623
+ /** Why a page's resume envelope was refused. */
624
+ var ResumeRefused = class extends Schema.TaggedError()("ResumeRefused", {
625
+ reason: Schema.Literals([
626
+ "Missing",
627
+ "Duplicate",
628
+ "Unreadable",
629
+ "Protocol",
630
+ "Plan",
631
+ "Invalid",
632
+ "Route"
633
+ ]),
634
+ message: Schema.String
635
+ }) {};
636
+ const refuse = (reason, message) => Result.fail(new ResumeRefused({
637
+ reason,
638
+ message
639
+ }));
640
+ /**
641
+ * The slice's Schema as a codec needing no services. A resume plan's state is
642
+ * plain data, so any field that needs one cannot cross a page anyway.
643
+ */
644
+ const codecOf = (schema) => schema;
645
+ /**
646
+ * A resume plan for an application. The baseline defaults to the
647
+ * application's initial Model. It is never written: a writable projection's
648
+ * `set` returns a new Model, so a baseline Foldkit freezes in development is
649
+ * safe to start from.
650
+ *
651
+ * `surfaces` are the Surfaces the browser may activate, and `local` the Model
652
+ * fields allowed to start from the baseline, such as an open menu. Rendering
653
+ * refuses a plan that leaves a Surface's read or activation in neither.
654
+ */
655
+ const plan = (application, config) => {
656
+ const surfaces = config.surfaces ?? [];
657
+ const parts = config.parts ?? [];
658
+ const repeated = parts.find((part, index) => parts.findIndex((p) => p.id === part.id) !== index);
659
+ 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`);
660
+ const foreign = surfaces.find((surface) => application.owner !== void 0 && surface.owner !== application.owner);
661
+ if (foreign !== void 0) throw new Error(`SSR.plan: the Surface "${foreign.name}" belongs to another application than plan "${config.id}"`);
662
+ return {
663
+ id: config.id,
664
+ state: config.state,
665
+ baseline: config.baseline ?? application.initial,
666
+ ...config.boot === void 0 ? {} : { boot: config.boot },
667
+ local: (config.local ?? []).map((place) => place.dependency),
668
+ surfaces,
669
+ parts,
670
+ ...application.Message === void 0 ? {} : { Message: application.Message },
671
+ start: config.start ?? "now",
672
+ deferrable: config.deferrable ?? [],
673
+ ...config.fallback === void 0 ? {} : { fallback: config.fallback },
674
+ ...config.meta === void 0 ? {} : { meta: config.meta },
675
+ ...config.version === void 0 ? {} : { version: config.version }
676
+ };
677
+ };
678
+ /** A path as a `path` match compares it. */
679
+ const pathKey = (route) => {
680
+ const trimmed = (route.split(/[?#]/)[0] ?? "").replace(/\/index\.html$/, "/").replace(/\/+$/, "");
681
+ return trimmed === "" ? "/" : trimmed;
682
+ };
683
+ /**
684
+ * The Model a payload resumes: the baseline with the slice set onto it, then
685
+ * each part restored, in order. Every part the plan names must be there and
686
+ * restore, and no other may be: a page is never half-restored.
687
+ */
688
+ const modelFrom = (plan, payload) => {
689
+ const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state);
690
+ if (Result.isFailure(decoded)) return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`);
691
+ const given = payload.parts ?? {};
692
+ if (typeof given !== "object" || Array.isArray(given)) return Result.fail("the envelope's parts are not an object of parts by id");
693
+ const parts = given;
694
+ const unknown = Object.keys(parts).find((id) => !plan.parts.some((part) => part.id === id));
695
+ if (unknown !== void 0) return Result.fail(`the envelope carries a part "${unknown}" the plan does not name`);
696
+ let model = plan.state.set(plan.baseline, decoded.success);
697
+ for (const part of plan.parts) {
698
+ if (!Object.hasOwn(parts, part.id)) return Result.fail(`the envelope carries no "${part.id}" part`);
699
+ const restored = part.restore(model, parts[part.id]);
700
+ if (Result.isFailure(restored)) return Result.fail(`the "${part.id}" part does not restore: ${restored.failure}`);
701
+ model = restored.success;
702
+ }
703
+ return Result.succeed(model);
704
+ };
705
+ /** The page's envelope, read off its stamped root; refused when there is no root, more than one, no envelope, or not JSON. */
706
+ const readEnvelope = (page) => {
707
+ const roots = page.querySelectorAll(`[${FOLDKIT_APP_ATTRIBUTE}]`);
708
+ if (roots.length === 0) return refuse("Missing", "the page holds no stamped application root");
709
+ if (roots.length > 1) return refuse("Duplicate", `the page holds ${roots.length} stamped application roots`);
710
+ const carried = roots[0]?.getAttribute(RESUME_ATTRIBUTE);
711
+ if (carried === null || carried === void 0) return refuse("Missing", "the page holds no resume envelope");
712
+ try {
713
+ const parsed = JSON.parse(carried);
714
+ return Result.succeed(parsed ?? {});
715
+ } catch (error) {
716
+ return refuse("Unreadable", `the resume envelope is not JSON: ${String(error)}`);
717
+ }
718
+ };
719
+ /**
720
+ * The Model a page resumes from: the baseline with the stamped root's envelope
721
+ * set onto it. Refused, with the reason, when the page holds no stamped root
722
+ * or more than one, when the root carries no envelope or not JSON, when it is
723
+ * not this protocol or this plan, or when the slice does not decode through
724
+ * the plan's Schema. A page is never half-restored.
725
+ */
726
+ const resume = (plan, page, options = {}) => {
727
+ const read = readEnvelope(page);
728
+ if (Result.isFailure(read)) return Result.fail(read.failure);
729
+ const { v, plan: id, state, parts, route, match } = read.success;
730
+ if (v !== 1) return refuse("Protocol", `the envelope is protocol ${String(v)}, not 1`);
731
+ if (id !== plan.id) return refuse("Plan", `the envelope is for plan "${String(id)}", not "${plan.id}"`);
732
+ if (route !== void 0 && options.route !== void 0) {
733
+ 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}`);
734
+ }
735
+ const resumed = modelFrom(plan, {
736
+ state,
737
+ parts
738
+ });
739
+ return Result.isFailure(resumed) ? refuse("Invalid", resumed.failure) : Result.succeed(resumed.success);
740
+ };
741
+ /** The tag a Message value carries, for naming it. */
742
+ const tagOf = (message) => typeof message === "object" && message !== null && "_tag" in message && typeof message._tag === "string" ? message._tag : "an untagged Message";
743
+ /**
744
+ * The Message tags the plan's Surfaces active for `model` may send, which is
745
+ * what a page's bindings may dispatch (the design's rule 3).
746
+ */
747
+ const allowedTags = (plan, model) => new Set(plan.surfaces.flatMap((surface) => Option.isSome(surface.projectionOf(model)) ? surface.messages : []));
748
+ /** The attribute on a static region's element, naming the region. */
749
+ const STATIC_ATTRIBUTE = "data-foldkit-plus-static";
750
+ const boundary = (id, trusted, children) => inertHtml.div([inertHtml.Attribute(STATIC_ATTRIBUTE, id), ...trusted === void 0 ? [] : [inertHtml.InnerHTML(trusted)]], children);
751
+ /**
752
+ * A region of the page the server owns for the life of the document. It is
753
+ * rendered on the server with the inert builder, so it can dispatch no
754
+ * Message. The browser adopts the server's markup as trusted `InnerHTML` and
755
+ * never runs `render`, so the region reads nothing from the browser's Model
756
+ * and a plan need not send what it reads.
757
+ *
758
+ * A region changes only with a new document. Content a Message should change
759
+ * belongs in a Surface, not here.
760
+ */
761
+ const staticRegion = (id, render) => {
762
+ const now = current();
763
+ if (now?.mode === "resume") {
764
+ const snapshot = now.snapshots.get(id);
765
+ if (snapshot !== void 0) return boundary(id, snapshot, []);
766
+ if (!now.reported.has(id)) {
767
+ now.reported.add(id);
768
+ console.error(`[foldkit-ssr] the static region "${id}" is not in the server's page, so it is rendered in the browser`);
769
+ }
770
+ return boundary(id, void 0, render(inertHtml));
771
+ }
772
+ const replayed = now?.mode === "replay" ? now.regions.get(id) : void 0;
773
+ if (replayed !== void 0) return boundary(id, void 0, replayed);
774
+ if (now?.mode !== "collect") return boundary(id, void 0, render(inertHtml));
775
+ const outer = now.region;
776
+ now.region = id;
777
+ try {
778
+ const children = render(inertHtml);
779
+ if (now.regions.has(id)) now.duplicates.add(id);
780
+ else now.regions.set(id, children);
781
+ return boundary(id, void 0, children);
782
+ } finally {
783
+ now.region = outer;
784
+ }
785
+ };
786
+ /**
787
+ * Whether the view call in progress is the server rendering a page, rather than the browser: true
788
+ * through both of `render`'s passes, false while the browser resumes and outside any render. For a
789
+ * view that sends markup it will adopt in the browser rather than draw there, such as
790
+ * `foldkit-richtext-dom`'s editor host, whose placement takes this as `serverRendered`.
791
+ */
792
+ const serving = () => {
793
+ const mode = current()?.mode;
794
+ return mode === "collect" || mode === "replay";
795
+ };
796
+ /**
797
+ * The config without a `Flags` key at all. Deleted, never set to `undefined`:
798
+ * Foldkit's server asks whether `Flags` is defined and its client whether the
799
+ * key exists, so an `undefined` one renders and is then refused.
800
+ */
801
+ const withoutFlags = (config) => {
802
+ const { Flags: _flags, ...rest } = config;
803
+ return rest;
804
+ };
805
+ /** The config whose `init` returns this start, whatever arguments it is given. */
806
+ const startingFrom = (config, start) => ({
807
+ ...withoutFlags(config),
808
+ init: () => start
809
+ });
810
+ /** A route as the envelope records it: the path and the query. */
811
+ const routeOf = (url) => {
812
+ const parsed = new URL(url, "http://localhost");
813
+ return `${parsed.pathname}${parsed.search}`;
814
+ };
815
+ /**
816
+ * The page's bindings, decoded through the plan's Message Schema, kept to the
817
+ * Messages the Surfaces active for `model` may send, and checked against
818
+ * every marker in `root`. Refused, with the reason, when the page carries
819
+ * none, an entry is not one of the application's Messages or one no active
820
+ * Surface lists, or a marker names a binding the page does not carry: a page
821
+ * is answered whole or not at all.
822
+ */
823
+ const bindings = (plan, page, root, model) => Result.map(bindingsAndEvents(plan, page, root, model), (read) => read.bindings);
824
+ const EnvelopeEvents = Schema.optional(Schema.Array(Schema.String));
825
+ /**
826
+ * `bindings`, and the events the envelope says the markers name, if it says:
827
+ * a page from before the envelope listed them leaves `listen` to find them.
828
+ */
829
+ const bindingsAndEvents = (plan, page, root, model) => {
830
+ const parsed = readEnvelope(page);
831
+ if (Result.isFailure(parsed)) return Result.fail(parsed.failure);
832
+ const read = readBindings(parsed.success.bindings ?? []);
833
+ if (Result.isFailure(read)) return refuse("Invalid", `the page's bindings are malformed: ${read.failure}`);
834
+ const encoded = read.success;
835
+ if (encoded.length > 0 && plan.surfaces.length === 0) return refuse("Invalid", "the page has bindings and the plan declares no surfaces to allow them");
836
+ const events = Schema.decodeUnknownResult(EnvelopeEvents)(parsed.success.events);
837
+ if (Result.isFailure(events)) return refuse("Invalid", `the page's events are malformed: ${events.failure.message}`);
838
+ const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model));
839
+ return Result.isFailure(decoded) ? refuse("Invalid", decoded.failure) : Result.succeed({
840
+ bindings: decoded.success,
841
+ events: events.success
842
+ });
843
+ };
844
+ //#endregion
845
+ //#region src/client.ts
846
+ /**
847
+ * `foldkit-ssr/client`: what a browser page needs to take a server render
848
+ * over, and nothing that renders one. It never imports
849
+ * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating
850
+ * page would otherwise carry; `foldkit-ssr` is this and the server side.
851
+ */
852
+ /** Each static region's markup in the page, read before hydration touches it. */
853
+ const snapshotsOf = (root) => new Map(Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), (element) => [element.getAttribute("data-foldkit-plus-static") ?? "", element.innerHTML]));
854
+ /**
855
+ * The build attribute on Foldkit's hydration root. Foldkit does not export it,
856
+ * as it does the app and Flags attributes; a test pins it to what Foldkit's
857
+ * server stamps.
858
+ */
859
+ const BUILD_ATTRIBUTE = "data-foldkit-build";
860
+ /**
861
+ * Starts the browser from the page's resumed Model, without running `init`.
862
+ *
863
+ * In the order Foldkit checks a page: the build id first, before the payload
864
+ * is read, then the envelope and its route. A page from another build is
865
+ * refused by Foldkit itself. A page that cannot resume is refused and contained
866
+ * by Foldkit's own refusal, and the reason is logged. A server page is never
867
+ * rendered again on the client. A page with no server render at all, no
868
+ * stamped root, is rendered on the client as usual.
869
+ */
870
+ const hydrate$1 = (config, plan, options) => {
871
+ const planMeta = plan.meta;
872
+ if (planMeta !== void 0) config = {
873
+ ...config,
874
+ subscriptions: {
875
+ ...config.subscriptions,
876
+ "foldkit-ssr.meta": metaEntry(planMeta)
877
+ }
878
+ };
879
+ const root = document.querySelector(`[${FOLDKIT_APP_ATTRIBUTE}]`);
880
+ const declined = options.when !== void 0 && !options.when(document);
881
+ const stale = options.fresh !== void 0 && !options.fresh(plan.version);
882
+ if (root === null) {
883
+ run(makeApplication(config));
884
+ return;
885
+ }
886
+ const program = (start) => makeApplication({
887
+ ...startingFrom(config, start),
888
+ container: root
889
+ });
890
+ const contain = () => hydrate(program({ model: plan.baseline }), { buildId: "" });
891
+ if (declined || stale) {
892
+ if (options.otherwise === "render") run(makeApplication({
893
+ ...config,
894
+ container: root
895
+ }));
896
+ else contain();
897
+ return;
898
+ }
899
+ if (root.getAttribute(BUILD_ATTRIBUTE) !== options.buildId) {
900
+ hydrate(program({ model: plan.baseline }), { buildId: options.buildId });
901
+ return;
902
+ }
903
+ const resumed = resume(plan, document, { route: routeOf(window.location.href) });
904
+ if (Result.isFailure(resumed)) {
905
+ console.error(`[foldkit-ssr] the page cannot resume: ${resumed.failure.message}`);
906
+ contain();
907
+ return;
908
+ }
909
+ const model = resumed.success;
910
+ const commands = plan.boot?.(model) ?? [];
911
+ const resuming = {
912
+ mode: "resume",
913
+ snapshots: snapshotsOf(root),
914
+ reported: /* @__PURE__ */ new Set()
915
+ };
916
+ const answered = [];
917
+ const apply = config.update;
918
+ const update = (current, message) => {
919
+ const handingOver = message === HANDOVER;
920
+ if (answered.length === 0) return handingOver ? { model: current } : apply(current, message);
921
+ const returned = [];
922
+ for (const next of [...answered.splice(0), ...handingOver ? [] : [message]]) {
923
+ const step = apply(current, next);
924
+ current = step.model;
925
+ returned.push(...step.commands ?? []);
926
+ }
927
+ return {
928
+ model: current,
929
+ commands: returned
930
+ };
931
+ };
932
+ const boot = (entries = {}) => hydrate(makeApplication({
933
+ ...withContext(startingFrom({
934
+ ...config,
935
+ update
936
+ }, {
937
+ model,
938
+ commands
939
+ }), resuming),
940
+ container: root,
941
+ subscriptions: {
942
+ ...config.subscriptions,
943
+ ...entries
944
+ }
945
+ }), { buildId: options.buildId });
946
+ const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
947
+ if (plan.start === "now" && pending.length === 0) {
948
+ boot();
949
+ return;
950
+ }
951
+ const decoded = bindingsAndEvents(plan, document, root, model);
952
+ if (Result.isFailure(decoded)) {
953
+ console.error(`[foldkit-ssr] the page cannot resume: ${decoded.failure.message}`);
954
+ contain();
955
+ return;
956
+ }
957
+ deferBoot(root, decoded.success, plan.start, {
958
+ boot,
959
+ answered
960
+ }, pending);
961
+ };
962
+ /**
963
+ * The Message the handover entry sends so the runtime takes the answered
964
+ * Messages when nothing else has asked it to. The wrapped `update` consumes
965
+ * it; the application never sees it.
966
+ */
967
+ const HANDOVER = Object.freeze({ _tag: "foldkit-ssr/Handover" });
968
+ /**
969
+ * Lets the page answer from its bindings until something asks for the
970
+ * runtime, then boots it and hands over to the live page.
971
+ *
972
+ * Every Message the page answers goes to `answered`, which the runtime takes
973
+ * before its first Message. An event only the live page can answer is kept
974
+ * and sent again to where it first went once the live page listens. The page
975
+ * stops listening as soon as the runtime's first render has committed: when
976
+ * `hydrate` returns, which Foldkit does today, or else when a handover
977
+ * Subscription entry starts, after `Render.afterCommit`. When lazy bundles
978
+ * must load first, the boot waits for them and the page keeps answering.
979
+ */
980
+ const deferBoot = (root, decoded, start, runtime, pending) => {
981
+ const unanswered = [];
982
+ let phase = "waiting";
983
+ const stop = listen(root, {
984
+ bindings: decoded.bindings,
985
+ ...decoded.events === void 0 ? {} : { events: decoded.events },
986
+ onAnswer: ({ event, messages, unnamed }) => {
987
+ if (unnamed !== void 0) {
988
+ startNow();
989
+ if (phase !== "live" && event.target instanceof Element) unanswered.push({
990
+ event,
991
+ element: event.target
992
+ });
993
+ return;
994
+ }
995
+ if (messages.length === 0) {
996
+ startNow();
997
+ return;
998
+ }
999
+ runtime.answered.push(...messages);
1000
+ event.stopPropagation();
1001
+ startNow();
1002
+ }
1003
+ });
1004
+ const handOver = () => {
1005
+ if (phase === "live") return;
1006
+ phase = "live";
1007
+ stop();
1008
+ for (const { event, element } of unanswered.splice(0)) {
1009
+ const Ctor = event.constructor;
1010
+ element.dispatchEvent(new Ctor(event.type, event));
1011
+ }
1012
+ };
1013
+ const commit = () => {
1014
+ phase = "starting";
1015
+ runtime.boot({ "foldkit-ssr.handover": {
1016
+ dependenciesSchema: Schema.Null,
1017
+ modelToDependencies: () => null,
1018
+ dependenciesToStream: () => Stream.fromEffect(Effect.as(Effect.andThen(root.hasAttribute("data-foldkit-app") ? Render.afterCommit : Effect.void, Effect.sync(handOver)), HANDOVER))
1019
+ } });
1020
+ if (!root.hasAttribute("data-foldkit-app")) handOver();
1021
+ };
1022
+ const startNow = () => {
1023
+ if (phase !== "waiting") return;
1024
+ phase = "loading";
1025
+ if (pending.length === 0) {
1026
+ commit();
1027
+ return;
1028
+ }
1029
+ Promise.all(pending.map((bundle) => bundle.load())).then(commit, (error) => {
1030
+ console.error(`[foldkit-ssr] a bundle's bodies did not load: ${String(error)}`);
1031
+ commit();
1032
+ });
1033
+ };
1034
+ if (start === "now") startNow();
1035
+ else if (start === "idle") {
1036
+ if (typeof window.requestIdleCallback === "function") window.requestIdleCallback(startNow);
1037
+ else setTimeout(startNow, 0);
1038
+ }
1039
+ };
1040
+ /** The resumable track: bindings the server's markup names, so a page can answer before it boots. */
1041
+ const Resume = {
1042
+ builder,
1043
+ view,
1044
+ bindings,
1045
+ listen
1046
+ };
1047
+ /** The browser's part of `SSR`: the same functions, without the server's. */
1048
+ const SSR = {
1049
+ plan,
1050
+ resume,
1051
+ hydrate: hydrate$1,
1052
+ static: staticRegion,
1053
+ serving
1054
+ };
1055
+ //#endregion
1056
+ export { FALLBACK_DEPTH_FIELD as C, withContext as E, BINDING_ATTRIBUTE as S, SLOT_ATTRIBUTE as T, serializeJsonScript as _, RESUME_ATTRIBUTE as a, staticRegion as b, allowedTags as c, metaMarkup as d, modelFrom as f, routeOf as g, resume as h, META_ATTRIBUTE as i, attributeOf as l, plan as m, SSR as n, ResumeRefused as o, pathKey as p, FOLDKIT_APP_ATTRIBUTE as r, STATIC_ATTRIBUTE as s, Resume as t, codecOf as u, serving as v, FALLBACK_FIELD as w, tagOf as x, startingFrom as y };
1057
+
1058
+ //# sourceMappingURL=client-CsCXJa_9.mjs.map