foldkit-ssr 0.1.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/LICENSE +21 -0
- package/README.md +592 -0
- package/dist/index.d.mts +363 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1426 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +61 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1426 @@
|
|
|
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";
|
|
5
|
+
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
|
+
//#region src/index.ts
|
|
517
|
+
/**
|
|
518
|
+
* `foldkit-ssr`: what crosses from the server to the browser when a page is
|
|
519
|
+
* rendered on one and resumed on the other.
|
|
520
|
+
*
|
|
521
|
+
* 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
|
|
524
|
+
* Model. Nothing outside the slice crosses, and a payload that cannot be read
|
|
525
|
+
* back exactly is refused, never half-restored.
|
|
526
|
+
*
|
|
527
|
+
* 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.
|
|
574
|
+
*/
|
|
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
|
+
/** 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
|
+
});
|
|
606
|
+
/**
|
|
607
|
+
* What the envelope carries of `model`: the plan's slice, encoded through its
|
|
608
|
+
* own Schema, and each part's capture.
|
|
609
|
+
*/
|
|
610
|
+
const payloadOf = (plan, model) => {
|
|
611
|
+
const state = Schema.encodeSync(codecOf(plan.state.schema))(plan.state.get(model));
|
|
612
|
+
if (plan.parts.length === 0) return { state };
|
|
613
|
+
const projections = activeProjections(plan, model);
|
|
614
|
+
return {
|
|
615
|
+
state,
|
|
616
|
+
parts: Object.fromEntries(plan.parts.map((part) => [part.id, part.capture(model, projections)]))
|
|
617
|
+
};
|
|
618
|
+
};
|
|
619
|
+
/**
|
|
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.
|
|
623
|
+
*/
|
|
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
|
+
};
|
|
641
|
+
/**
|
|
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.
|
|
645
|
+
*/
|
|
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>`;
|
|
658
|
+
};
|
|
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)}`);
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
/**
|
|
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.
|
|
676
|
+
*/
|
|
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);
|
|
691
|
+
};
|
|
692
|
+
/**
|
|
693
|
+
* The Model the browser will start from when the server's Model is `model`:
|
|
694
|
+
* the payload taken through the page as the envelope carries it, as JSON, and
|
|
695
|
+
* resumed exactly as `SSR.resume` resumes it. A part that cannot restore its
|
|
696
|
+
* own capture fails here, on the server.
|
|
697
|
+
*/
|
|
698
|
+
const browserModelOf = (plan, payload) => modelFrom(plan, JSON.parse(serializeJsonScript(payload)));
|
|
699
|
+
const pathOf = (path) => path.length === 0 ? "(the whole Model)" : path.join(".");
|
|
700
|
+
/**
|
|
701
|
+
* A path is covered by a sent or local path equal to it or containing it. An
|
|
702
|
+
* empty path is the whole Model, which no pick covers.
|
|
703
|
+
*/
|
|
704
|
+
const coverOf = (path, plan) => {
|
|
705
|
+
const contains = (outer) => outer.length > 0 && outer.length <= path.length && outer.every((key, index) => path[index] === key);
|
|
706
|
+
if (plan.state.dependencies.some(contains)) return "state";
|
|
707
|
+
if (plan.local.some(contains)) return "local";
|
|
708
|
+
return "missing";
|
|
709
|
+
};
|
|
710
|
+
/** A projection's reads as one comparable string, or `inactive`. */
|
|
711
|
+
const readsKey = (projection) => projection === void 0 ? "inactive" : JSON.stringify([projection.dependencies, Metadata.summarize(projection.metadata)]);
|
|
712
|
+
/**
|
|
713
|
+
* How a plan covers each of its Surfaces when the server's Model is `model`.
|
|
714
|
+
* A Surface's reads depend on the Model, through its params, so coverage is
|
|
715
|
+
* worked out for a Model, not for the plan alone.
|
|
716
|
+
*/
|
|
717
|
+
const inspect = (plan, model) => {
|
|
718
|
+
const resumed = browserModelOf(plan, payloadOf(plan, model));
|
|
719
|
+
if (Result.isFailure(resumed)) throw new Error(`SSR.inspect: ${resumed.failure}`);
|
|
720
|
+
return coverage(plan, model, resumed.success);
|
|
721
|
+
};
|
|
722
|
+
/** How a plan covers its Surfaces, given the server's Model and the browser's. */
|
|
723
|
+
const coverage = (plan, model, browser) => {
|
|
724
|
+
const covered = new Set(plan.parts.flatMap((part) => part.covers));
|
|
725
|
+
return {
|
|
726
|
+
id: plan.id,
|
|
727
|
+
state: plan.state.dependencies.map(pathOf),
|
|
728
|
+
local: plan.local.map(pathOf),
|
|
729
|
+
parts: plan.parts.map((part) => part.id),
|
|
730
|
+
surfaces: plan.surfaces.map((surface) => {
|
|
731
|
+
const served = surface.projectionOf(model);
|
|
732
|
+
return {
|
|
733
|
+
name: surface.name,
|
|
734
|
+
active: served !== void 0,
|
|
735
|
+
...surface.activation === void 0 ? {} : { activation: {
|
|
736
|
+
path: pathOf(surface.activation.path),
|
|
737
|
+
cover: coverOf(surface.activation.path, plan)
|
|
738
|
+
} },
|
|
739
|
+
reads: (served?.dependencies ?? []).map((path) => ({
|
|
740
|
+
path: pathOf(path),
|
|
741
|
+
cover: coverOf(path, plan)
|
|
742
|
+
})),
|
|
743
|
+
unresumed: served === void 0 ? [] : Metadata.summarize(served.metadata).filter((summary) => !covered.has(summary.name)),
|
|
744
|
+
sameInBrowser: readsKey(served) === readsKey(surface.projectionOf(browser))
|
|
745
|
+
};
|
|
746
|
+
})
|
|
747
|
+
};
|
|
748
|
+
};
|
|
749
|
+
/** Each way an inspection shows the plan falls short, one line each. */
|
|
750
|
+
const shortfalls = (inspection) => inspection.surfaces.flatMap((surface) => [
|
|
751
|
+
...surface.activation?.cover === "missing" ? [`Surface "${surface.name}" is activated by ${surface.activation.path}, which is neither in the plan's state nor local`] : [],
|
|
752
|
+
...surface.reads.filter((read) => read.cover === "missing").map((read) => `Surface "${surface.name}" reads ${read.path}, which is neither in the plan's state nor local`),
|
|
753
|
+
...surface.unresumed.map((summary) => `Surface "${surface.name}" reads ${summary.name} data (${summary.entries.join(", ")}), which no part of the plan resumes`),
|
|
754
|
+
...surface.sameInBrowser ? [] : [`Surface "${surface.name}" is ${surface.active ? "active" : "inactive"} on the server and activates differently from the Model the browser starts from`]
|
|
755
|
+
]);
|
|
756
|
+
/** Why a server refused to render a page against its plan. */
|
|
757
|
+
var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
|
|
758
|
+
reason: Schema.Literals([
|
|
759
|
+
"UndeclaredStartup",
|
|
760
|
+
"Uncovered",
|
|
761
|
+
"ViewDependsOnUnsentState",
|
|
762
|
+
"DuplicateStaticRegion",
|
|
763
|
+
"UngeneratablePath",
|
|
764
|
+
"UnrestorablePart",
|
|
765
|
+
"UnencodableBinding",
|
|
766
|
+
"EagerStartRequired",
|
|
767
|
+
"UndeclaredSurfaces",
|
|
768
|
+
"BindingInStaticRegion"
|
|
769
|
+
]),
|
|
770
|
+
message: Schema.String
|
|
771
|
+
}) {};
|
|
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
|
+
/** Each binding whose Message no active Surface lists, one line each. */
|
|
780
|
+
const unlistedBindings = (plan, model, bindings) => {
|
|
781
|
+
const allowed = allowedTags(plan, model);
|
|
782
|
+
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
|
+
};
|
|
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
|
+
/** Loads every lazy bundle's bodies, so the view renders whole. */
|
|
825
|
+
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
|
+
/** Foldkit's own Flags script, which a resumed page never carries. */
|
|
852
|
+
const FLAGS_SCRIPT = new RegExp(`<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\s\\S]*?<\/script>`, "g");
|
|
853
|
+
/**
|
|
854
|
+
* The head fields a render returns beside the body. Each is read by the view,
|
|
855
|
+
* so each must come out the same from the browser's Model; since Foldkit 0.163
|
|
856
|
+
* none has a default from the URL.
|
|
857
|
+
*/
|
|
858
|
+
const HEAD_FIELDS = [
|
|
859
|
+
"title",
|
|
860
|
+
"lang",
|
|
861
|
+
"dir",
|
|
862
|
+
"canonical",
|
|
863
|
+
"ogUrl"
|
|
864
|
+
];
|
|
865
|
+
/** A render's bindings, encoded, or why one cannot be. */
|
|
866
|
+
const encodeBindings = (plan, bindings) => {
|
|
867
|
+
if (bindings.length === 0) return Result.succeed([]);
|
|
868
|
+
if (plan.Message === void 0) return Result.fail("the page has bindings, and the plan has no Message Schema to encode them with: make the plan from the application");
|
|
869
|
+
const encode = Schema.encodeUnknownResult(plan.Message);
|
|
870
|
+
const out = [];
|
|
871
|
+
for (const binding of bindings) {
|
|
872
|
+
const message = encode(binding.message);
|
|
873
|
+
if (Result.isFailure(message)) return Result.fail(`the ${binding.event} binding on ${binding.element} does not encode as a Message: ${message.failure.message}`);
|
|
874
|
+
out.push({
|
|
875
|
+
attribute: binding.attribute,
|
|
876
|
+
message: message.success,
|
|
877
|
+
...binding.hole === void 0 ? {} : { hole: binding.hole },
|
|
878
|
+
...binding.depth === void 0 ? {} : { depth: binding.depth },
|
|
879
|
+
...binding.options === void 0 ? {} : { options: binding.options }
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
return Result.succeed(out);
|
|
883
|
+
};
|
|
884
|
+
/**
|
|
885
|
+
* The bindings that differ between the server's render and the browser's, by
|
|
886
|
+
* element: a Message built from a field the plan does not send would dispatch
|
|
887
|
+
* one Message before boot and another after.
|
|
888
|
+
*/
|
|
889
|
+
const changedBindings = (served, encoded, reencoded) => served.flatMap((binding, index) => JSON.stringify(encoded[index]) === JSON.stringify(reencoded[index]) ? [] : [`${binding.event} binding on ${binding.element}`]);
|
|
890
|
+
/**
|
|
891
|
+
* The Subscription and Managed Resource entries that would start late under a
|
|
892
|
+
* deferred boot and are not declared deferrable, by the plan or by a part.
|
|
893
|
+
* Foldkit starts every Subscription's stream at boot, so every entry counts; a
|
|
894
|
+
* Managed Resource counts when the Model asks for it.
|
|
895
|
+
*/
|
|
896
|
+
const eagerEntries = (config, plan, model) => {
|
|
897
|
+
if (plan.start === "now") return [];
|
|
898
|
+
const declared = (key, entry) => plan.deferrable.includes(key) || plan.parts.some((part) => part.deferrable?.(key, entry) === true);
|
|
899
|
+
const subscriptions = Object.entries(config.subscriptions ?? {}).filter(([key, entry]) => !declared(key, entry));
|
|
900
|
+
const resources = Object.entries(config.managedResources ?? {}).filter(([key, entry]) => {
|
|
901
|
+
const asks = entry.modelToMaybeRequirements?.(model);
|
|
902
|
+
return (Option.isOption(asks) ? Option.isSome(asks) : asks !== void 0) && !declared(key, entry);
|
|
903
|
+
});
|
|
904
|
+
return [...subscriptions.map(([key]) => `subscription "${key}"`), ...resources.map(([key]) => `resource "${key}"`)];
|
|
905
|
+
};
|
|
906
|
+
/**
|
|
907
|
+
* Renders a page on the server against a resume plan.
|
|
908
|
+
*
|
|
909
|
+
* The application's `init` runs once. Its Model's slice is round-tripped
|
|
910
|
+
* through the plan's Schema and set onto the baseline, which is the Model the
|
|
911
|
+
* browser will start from, and the page is rendered from that Model. Every
|
|
912
|
+
* way the browser could start somewhere else is a `ResumeUnsafe`, whose
|
|
913
|
+
* `reason` names it; the README lists them. The one that matters most: the
|
|
914
|
+
* view rendered from the browser's Model differs from the one rendered from
|
|
915
|
+
* the server's, because it reads a field the plan leaves out. In production
|
|
916
|
+
* Foldkit would rebuild that part of the page silently, so this is the one
|
|
917
|
+
* place it shows.
|
|
918
|
+
*/
|
|
919
|
+
const render = (config, plan, options) => renderMatching(config, plan, options, "full");
|
|
920
|
+
const renderMatching = (config, plan, options, match) => Effect.gen(function* () {
|
|
921
|
+
yield* loadLazy(config);
|
|
922
|
+
let served;
|
|
923
|
+
const regions = /* @__PURE__ */ new Map();
|
|
924
|
+
const duplicates = /* @__PURE__ */ new Set();
|
|
925
|
+
const servedBindings = [];
|
|
926
|
+
const browserBindings = [];
|
|
927
|
+
const inStatic = [];
|
|
928
|
+
const fallback = fallbackEncoder(plan);
|
|
929
|
+
const capturing = withContext({
|
|
930
|
+
...config,
|
|
931
|
+
init: (...args) => served = config.init(...args)
|
|
932
|
+
}, {
|
|
933
|
+
mode: "collect",
|
|
934
|
+
regions,
|
|
935
|
+
duplicates,
|
|
936
|
+
bindings: servedBindings,
|
|
937
|
+
fallback,
|
|
938
|
+
wrap: (message) => message,
|
|
939
|
+
depth: 0,
|
|
940
|
+
region: void 0,
|
|
941
|
+
inStatic
|
|
942
|
+
});
|
|
943
|
+
const full = yield* renderToString(capturing, options);
|
|
944
|
+
if (duplicates.size > 0) return yield* new ResumeUnsafe({
|
|
945
|
+
reason: "DuplicateStaticRegion",
|
|
946
|
+
message: `two static regions share the id ${[...duplicates].map((id) => `"${id}"`).join(", ")}: the browser could adopt only one`
|
|
947
|
+
});
|
|
948
|
+
if (inStatic.length > 0) return yield* new ResumeUnsafe({
|
|
949
|
+
reason: "BindingInStaticRegion",
|
|
950
|
+
message: `a static region is the server's alone, and these would never run: ${inStatic.map(({ region, element, event }) => `a ${event} handler on ${element} in "${region}"`).join(", ")}. What a Message changes belongs in a Surface`
|
|
951
|
+
});
|
|
952
|
+
const started = served;
|
|
953
|
+
const commands = started.commands ?? [];
|
|
954
|
+
if (commands.length > 0 && plan.boot === void 0) return yield* new ResumeUnsafe({
|
|
955
|
+
reason: "UndeclaredStartup",
|
|
956
|
+
message: `init returned ${commands.map((command) => command.name).join(", ")}, which no browser would run: name them in the plan's boot`
|
|
957
|
+
});
|
|
958
|
+
const payload = payloadOf(plan, started.model);
|
|
959
|
+
const resumed = browserModelOf(plan, payload);
|
|
960
|
+
if (Result.isFailure(resumed)) return yield* new ResumeUnsafe({
|
|
961
|
+
reason: "UnrestorablePart",
|
|
962
|
+
message: resumed.failure
|
|
963
|
+
});
|
|
964
|
+
const browser = resumed.success;
|
|
965
|
+
const eager = eagerEntries(config, plan, started.model);
|
|
966
|
+
if (eager.length > 0) return yield* new ResumeUnsafe({
|
|
967
|
+
reason: "EagerStartRequired",
|
|
968
|
+
message: `the plan starts ${plan.start}, and these would start late: ${eager.join(", ")}. Name each in the plan's deferrable, or start now`
|
|
969
|
+
});
|
|
970
|
+
if (servedBindings.length > 0 && plan.surfaces.length === 0) return yield* new ResumeUnsafe({
|
|
971
|
+
reason: "UndeclaredSurfaces",
|
|
972
|
+
message: `the page has ${servedBindings.length} binding${servedBindings.length === 1 ? "" : "s"} and the plan declares no surfaces, so nothing says which Messages it may dispatch: name them in the plan's surfaces`
|
|
973
|
+
});
|
|
974
|
+
const uncovered = [...shortfalls(coverage(plan, started.model, browser)), ...unlistedBindings(plan, started.model, servedBindings)];
|
|
975
|
+
if (uncovered.length > 0) return yield* new ResumeUnsafe({
|
|
976
|
+
reason: "Uncovered",
|
|
977
|
+
message: `the plan does not cover what the browser reads:\n- ${uncovered.join("\n- ")}`
|
|
978
|
+
});
|
|
979
|
+
const rendered = yield* renderToString(withContext(startingFrom(config, { model: browser }), {
|
|
980
|
+
mode: "replay",
|
|
981
|
+
regions,
|
|
982
|
+
bindings: browserBindings,
|
|
983
|
+
fallback,
|
|
984
|
+
wrap: (message) => message,
|
|
985
|
+
depth: 0
|
|
986
|
+
}), options);
|
|
987
|
+
const encoded = encodeBindings(plan, servedBindings);
|
|
988
|
+
const reencoded = encodeBindings(plan, browserBindings);
|
|
989
|
+
if (Result.isFailure(encoded)) return yield* new ResumeUnsafe({
|
|
990
|
+
reason: "UnencodableBinding",
|
|
991
|
+
message: encoded.failure
|
|
992
|
+
});
|
|
993
|
+
const differing = [
|
|
994
|
+
...full.html.replace(FLAGS_SCRIPT, "") === rendered.html ? [] : ["body"],
|
|
995
|
+
...HEAD_FIELDS.filter((field) => full[field] !== rendered[field]),
|
|
996
|
+
...changedBindings(servedBindings, encoded.success, Result.isFailure(reencoded) ? [] : reencoded.success)
|
|
997
|
+
];
|
|
998
|
+
if (differing.length > 0) return yield* new ResumeUnsafe({
|
|
999
|
+
reason: "ViewDependsOnUnsentState",
|
|
1000
|
+
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
|
+
});
|
|
1002
|
+
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
|
+
})
|
|
1009
|
+
};
|
|
1010
|
+
});
|
|
1011
|
+
/**
|
|
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
|
+
};
|
|
1022
|
+
/**
|
|
1023
|
+
* 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.
|
|
1026
|
+
*/
|
|
1027
|
+
const page = (template, result) => injectIntoTemplate(withEnvelope(template, result.envelope), result.rendered);
|
|
1028
|
+
/** The file a static host serves for a path: `/about` is `about/index.html`. */
|
|
1029
|
+
const fileOf = (path) => {
|
|
1030
|
+
const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
1031
|
+
if (trimmed === "") return "index.html";
|
|
1032
|
+
return trimmed.endsWith(".html") ? trimmed : `${trimmed}/index.html`;
|
|
1033
|
+
};
|
|
1034
|
+
/**
|
|
1035
|
+
* Renders pages at build time, one per path, each as `SSR.render` and
|
|
1036
|
+
* `SSR.page` would, to be written as files. `origin` makes each path the full
|
|
1037
|
+
* URL a routing application parses. `flags`, when the application has them,
|
|
1038
|
+
* gives each path its own.
|
|
1039
|
+
*
|
|
1040
|
+
* A generated page records its path alone: a static host serves the same file
|
|
1041
|
+
* whatever the query, so the browser checks the path and ignores the query. A
|
|
1042
|
+
* path with a query or fragment, or two paths that would be one file, are
|
|
1043
|
+
* refused.
|
|
1044
|
+
*/
|
|
1045
|
+
const generate = (config, plan, options) => Effect.gen(function* () {
|
|
1046
|
+
const files = /* @__PURE__ */ new Map();
|
|
1047
|
+
for (const path of options.paths) {
|
|
1048
|
+
if (!path.startsWith("/") || /[?#]/.test(path)) return yield* new ResumeUnsafe({
|
|
1049
|
+
reason: "UngeneratablePath",
|
|
1050
|
+
message: `"${path}" is not a path a file can be served at: start it with / and leave out any query or fragment`
|
|
1051
|
+
});
|
|
1052
|
+
const other = files.get(fileOf(path));
|
|
1053
|
+
if (other !== void 0) return yield* new ResumeUnsafe({
|
|
1054
|
+
reason: "UngeneratablePath",
|
|
1055
|
+
message: `"${other}" and "${path}" would both be written to ${fileOf(path)}`
|
|
1056
|
+
});
|
|
1057
|
+
files.set(fileOf(path), path);
|
|
1058
|
+
}
|
|
1059
|
+
return yield* Effect.forEach(options.paths, (path) => Effect.map(renderMatching(config, plan, {
|
|
1060
|
+
buildId: options.buildId,
|
|
1061
|
+
url: new URL(path, options.origin).href,
|
|
1062
|
+
...options.flags === void 0 ? {} : { flags: options.flags(path) }
|
|
1063
|
+
}, "path"), (result) => ({
|
|
1064
|
+
path,
|
|
1065
|
+
file: fileOf(path),
|
|
1066
|
+
html: page(options.template, result)
|
|
1067
|
+
})));
|
|
1068
|
+
});
|
|
1069
|
+
/**
|
|
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.
|
|
1073
|
+
*
|
|
1074
|
+
* `GET` and `HEAD` render the page against the plan, with the request's URL
|
|
1075
|
+
* and, when the application has Flags, `flags(request)`. `POST` goes to
|
|
1076
|
+
* `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`
|
|
1078
|
+
* passes every method through). A render that fails, or a plan the render
|
|
1079
|
+
* refuses, is answered `500` with the reason logged, never with a page the
|
|
1080
|
+
* browser cannot resume.
|
|
1081
|
+
*
|
|
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.
|
|
1088
|
+
*/
|
|
1089
|
+
const entry = (config, plan, options) => {
|
|
1090
|
+
withEnvelope(options.template, "");
|
|
1091
|
+
return { renderPage: async (request) => {
|
|
1092
|
+
const method = request.method.toUpperCase();
|
|
1093
|
+
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
|
+
}));
|
|
1100
|
+
}
|
|
1101
|
+
const flagsOf = options.flags;
|
|
1102
|
+
const exit = await Effect.runPromiseExit(Effect.gen(function* () {
|
|
1103
|
+
const flags = flagsOf === void 0 ? void 0 : yield* Effect.tryPromise(async () => flagsOf(request));
|
|
1104
|
+
const flagged = flagsOf === void 0 ? {} : { flags };
|
|
1105
|
+
return posting ? yield* handle(request, config, plan, {
|
|
1106
|
+
buildId: options.buildId,
|
|
1107
|
+
...flagged
|
|
1108
|
+
}) : yield* render(config, plan, {
|
|
1109
|
+
buildId: options.buildId,
|
|
1110
|
+
url: request.url,
|
|
1111
|
+
...flagged
|
|
1112
|
+
});
|
|
1113
|
+
}));
|
|
1114
|
+
if (Exit.isFailure(exit)) {
|
|
1115
|
+
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
|
+
}));
|
|
1120
|
+
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;
|
|
1240
|
+
}
|
|
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
|
+
});
|
|
1245
|
+
};
|
|
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
|
+
}
|
|
1251
|
+
};
|
|
1252
|
+
/** How a form's Message is written into the page for the fallback, when the plan has one. */
|
|
1253
|
+
const fallbackEncoder = (plan) => {
|
|
1254
|
+
if (plan.fallback !== "server" || plan.Message === void 0) return void 0;
|
|
1255
|
+
const encode = Schema.encodeUnknownResult(plan.Message);
|
|
1256
|
+
return (message) => {
|
|
1257
|
+
const encoded = encode(message);
|
|
1258
|
+
return Result.isFailure(encoded) ? void 0 : JSON.stringify(encoded.success);
|
|
1259
|
+
};
|
|
1260
|
+
};
|
|
1261
|
+
/** Why a posted form was not handled: the request, not the page or the plan, is at fault. */
|
|
1262
|
+
var FallbackRefused = class extends Schema.TaggedError()("FallbackRefused", {
|
|
1263
|
+
reason: Schema.Literals([
|
|
1264
|
+
"Missing",
|
|
1265
|
+
"Unreadable",
|
|
1266
|
+
"Invalid",
|
|
1267
|
+
"Unlisted",
|
|
1268
|
+
"NoFallback"
|
|
1269
|
+
]),
|
|
1270
|
+
message: Schema.String
|
|
1271
|
+
}) {};
|
|
1272
|
+
const refuseFallback = (reason, message) => Effect.fail(new FallbackRefused({
|
|
1273
|
+
reason,
|
|
1274
|
+
message
|
|
1275
|
+
}));
|
|
1276
|
+
const isRunnable = (command) => typeof command === "object" && command !== null && "effect" in command && Effect.isEffect(command.effect);
|
|
1277
|
+
/**
|
|
1278
|
+
* The most Messages and Commands one post may run. The browser's loop runs
|
|
1279
|
+
* for the life of the page, so a Command that schedules itself again, a tick
|
|
1280
|
+
* or a poll, is ordinary there; on the server it would hold the request open
|
|
1281
|
+
* for ever.
|
|
1282
|
+
*/
|
|
1283
|
+
const MAX_STEPS = 100;
|
|
1284
|
+
/**
|
|
1285
|
+
* Foldkit's loop, once, on the server: `update` for each Message, then each
|
|
1286
|
+
* returned Command run under the config's `resources`, its Message folded
|
|
1287
|
+
* back through `update`, until no Command remains.
|
|
1288
|
+
*/
|
|
1289
|
+
const fold = (config, model, messages, commands) => Effect.gen(function* () {
|
|
1290
|
+
let current = model;
|
|
1291
|
+
const pending = [...messages];
|
|
1292
|
+
const queue = [...commands];
|
|
1293
|
+
let steps = 0;
|
|
1294
|
+
let last = "";
|
|
1295
|
+
while (pending.length > 0 || queue.length > 0) {
|
|
1296
|
+
if (++steps > MAX_STEPS) return yield* Effect.die(/* @__PURE__ */ new Error(`SSR.handle: the post did not settle within ${MAX_STEPS} Messages and Commands; the last Command run was "${last}". A Command that schedules itself again cannot run on the server`));
|
|
1297
|
+
if (pending.length > 0) {
|
|
1298
|
+
const next = config.update(current, pending.shift());
|
|
1299
|
+
current = next.model;
|
|
1300
|
+
queue.push(...next.commands ?? []);
|
|
1301
|
+
continue;
|
|
1302
|
+
}
|
|
1303
|
+
const command = queue.shift();
|
|
1304
|
+
if (!isRunnable(command)) return yield* Effect.die(/* @__PURE__ */ new Error(`SSR.handle: a Command has no Effect to run: ${JSON.stringify(command)}`));
|
|
1305
|
+
const provided = config.resources === void 0 ? command.effect : Effect.provide(command.effect, config.resources);
|
|
1306
|
+
last = command.name;
|
|
1307
|
+
const result = yield* Effect.orDie(provided);
|
|
1308
|
+
if (result !== void 0 && result !== null) pending.push(result);
|
|
1309
|
+
}
|
|
1310
|
+
return current;
|
|
1311
|
+
});
|
|
1312
|
+
/** The Model `init` gives this request, as the server's render would start from. */
|
|
1313
|
+
const startOf = (config, options) => Effect.gen(function* () {
|
|
1314
|
+
let started;
|
|
1315
|
+
yield* renderToString({
|
|
1316
|
+
...config,
|
|
1317
|
+
init: (...args) => started = config.init(...args)
|
|
1318
|
+
}, {
|
|
1319
|
+
buildId: "x",
|
|
1320
|
+
...options
|
|
1321
|
+
});
|
|
1322
|
+
return started;
|
|
1323
|
+
});
|
|
1324
|
+
/**
|
|
1325
|
+
* Answers a form posted by a page rendered with `fallback: 'server'`: the
|
|
1326
|
+
* posted Message is decoded through the plan's Message Schema, with posted
|
|
1327
|
+
* fields of the same names as its own overriding them, and must be one the
|
|
1328
|
+
* Surfaces active for the request's Model may send. The server then rebuilds
|
|
1329
|
+
* the Model the browser had, `init` and then the plan's `boot` with every
|
|
1330
|
+
* Command it leads to, runs `update` with the Message and every Command that
|
|
1331
|
+
* follows, and renders the result as a fresh page.
|
|
1332
|
+
*/
|
|
1333
|
+
const handle = (request, config, plan, options) => Effect.gen(function* () {
|
|
1334
|
+
if (plan.fallback !== "server" || plan.Message === void 0) return yield* refuseFallback("NoFallback", `plan "${plan.id}" has no server fallback`);
|
|
1335
|
+
const form = yield* Effect.tryPromise({
|
|
1336
|
+
try: () => request.formData(),
|
|
1337
|
+
catch: () => new FallbackRefused({
|
|
1338
|
+
reason: "Unreadable",
|
|
1339
|
+
message: "the body is not a form"
|
|
1340
|
+
})
|
|
1341
|
+
});
|
|
1342
|
+
const posted = form.get(FALLBACK_FIELD);
|
|
1343
|
+
if (typeof posted !== "string") return yield* refuseFallback("Missing", `the form carries no ${FALLBACK_FIELD} field`);
|
|
1344
|
+
let raw;
|
|
1345
|
+
try {
|
|
1346
|
+
raw = JSON.parse(posted);
|
|
1347
|
+
} catch {
|
|
1348
|
+
return yield* refuseFallback("Unreadable", `${FALLBACK_FIELD} is not JSON`);
|
|
1349
|
+
}
|
|
1350
|
+
const decode = Schema.decodeUnknownResult(plan.Message);
|
|
1351
|
+
const invalid = (failure) => refuseFallback("Invalid", `the posted Message does not decode: ${failure.message}`);
|
|
1352
|
+
const written = decode(raw);
|
|
1353
|
+
if (Result.isFailure(written)) return yield* invalid(written.failure);
|
|
1354
|
+
const postedDepth = form.get("foldkit-plus-depth") ?? "0";
|
|
1355
|
+
if (typeof postedDepth !== "string" || !/^\d{1,2}$/.test(postedDepth)) return yield* refuseFallback("Unreadable", `${FALLBACK_DEPTH_FIELD} is not a depth`);
|
|
1356
|
+
const override = (value, down) => {
|
|
1357
|
+
if (typeof value !== "object" || value === null) return value;
|
|
1358
|
+
const copy = { ...value };
|
|
1359
|
+
if (down > 0) {
|
|
1360
|
+
copy.message = override(copy.message, down - 1);
|
|
1361
|
+
return copy;
|
|
1362
|
+
}
|
|
1363
|
+
form.forEach((field, name) => {
|
|
1364
|
+
if (name !== "foldkit-plus-message" && Object.hasOwn(copy, name) && typeof field === "string") copy[name] = field;
|
|
1365
|
+
});
|
|
1366
|
+
return copy;
|
|
1367
|
+
};
|
|
1368
|
+
const decoded = decode(override(raw, Number(postedDepth)));
|
|
1369
|
+
if (Result.isFailure(decoded)) return yield* invalid(decoded.failure);
|
|
1370
|
+
const message = decoded.success;
|
|
1371
|
+
const started = yield* startOf(config, {
|
|
1372
|
+
url: request.url,
|
|
1373
|
+
...options
|
|
1374
|
+
});
|
|
1375
|
+
if (!allowedTags(plan, started.model).has(tagOf(message))) return yield* refuseFallback("Unlisted", `the posted ${tagOf(message)} is not one an active Surface lists in its messages`);
|
|
1376
|
+
const boot = plan.boot?.(started.model) ?? [];
|
|
1377
|
+
const booted = yield* fold(config, started.model, [], boot);
|
|
1378
|
+
const model = yield* fold(config, booted, [message], []);
|
|
1379
|
+
return yield* render(startingFrom(config, { model }), plan, {
|
|
1380
|
+
buildId: options.buildId,
|
|
1381
|
+
url: request.url
|
|
1382
|
+
});
|
|
1383
|
+
});
|
|
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
|
+
const SSR = {
|
|
1410
|
+
plan,
|
|
1411
|
+
envelope,
|
|
1412
|
+
resume,
|
|
1413
|
+
render,
|
|
1414
|
+
page,
|
|
1415
|
+
hydrate: hydrate$1,
|
|
1416
|
+
inspect,
|
|
1417
|
+
static: staticRegion,
|
|
1418
|
+
generate,
|
|
1419
|
+
entry,
|
|
1420
|
+
handle,
|
|
1421
|
+
serializeJsonScript
|
|
1422
|
+
};
|
|
1423
|
+
//#endregion
|
|
1424
|
+
export { BINDING_ATTRIBUTE, FALLBACK_FIELD, FallbackRefused, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, serializeJsonScript };
|
|
1425
|
+
|
|
1426
|
+
//# sourceMappingURL=index.mjs.map
|