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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Glenn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,592 @@
1
+ # `foldkit-ssr`
2
+
3
+ Server rendering for a Foldkit application that hands the browser **the Model
4
+ the server reached**, not the inputs to rebuild it. `init` runs once, on the
5
+ server. The browser adopts the server's HTML and starts from the slice of the
6
+ Model it owns.
7
+
8
+ **Early.** The API below is built and tested; as a 0.x package it may still
9
+ change between minor versions.
10
+
11
+ ```bash
12
+ pnpm add foldkit-ssr foldkit-surface foldkit effect
13
+ ```
14
+
15
+ ```ts
16
+ // Which part of the Model the browser owns.
17
+ const Post = SSR.plan(App, {
18
+ id: 'post',
19
+ state: Projection.pick(App.model.route, App.model.draft),
20
+ })
21
+
22
+ // Server: render, and write that slice into the page.
23
+ const html = SSR.page(template, await Effect.runPromise(SSR.render(config, Post, { buildId, url })))
24
+
25
+ // Browser: take the page over from the slice, without running init.
26
+ SSR.hydrate(config, Post, { buildId })
27
+ ```
28
+
29
+ ## Why you would use it
30
+
31
+ Foldkit already renders on the server. What its page carries is the **input**:
32
+ the Flags that produced the first Model, which the browser decodes and feeds to
33
+ `init` again. That is simple and right when `init` is cheap and its Flags are
34
+ small.
35
+
36
+ It stops being right when `init` does real work: it loads a post, reads a
37
+ session, computes something expensive. Then the browser either repeats that
38
+ work or has to receive everything `init` read, as Flags, including data the
39
+ page never shows. `foldkit-ssr` sends the **result** instead: the fields the
40
+ browser owns, and nothing else.
41
+
42
+ | | Foldkit's own (`renderToString` + `Runtime.hydrate`) | `foldkit-ssr` (`SSR.render` + `SSR.hydrate`) |
43
+ | ------------------------------- | ---------------------------------------------------- | --------------------------------------------------------------- |
44
+ | The page carries | The Flags | The plan's slice of the Model; no Flags |
45
+ | `init` runs | On the server, then again in the browser | On the server only |
46
+ | Server-only data | Crosses if `init` needs it | Stays on the server unless the slice includes it |
47
+ | A view that reads unsent state | Rebuilt in the browser; only development warns | Refused by `SSR.render`, naming the field, before it is served |
48
+ | What you write | Nothing beyond the config | A plan |
49
+
50
+ Beyond the handover it offers three things you can adopt one at a time:
51
+ server-owned **static regions** that never render in the browser, **resumable
52
+ pages** that answer clicks and typing before the runtime has booted, and
53
+ **forms that work with scripts off**, answered by running `update` on the
54
+ server.
55
+
56
+ ## What it owns, and what it does not
57
+
58
+ It owns **the handover**: which slice crosses, how it is written into the page,
59
+ and the checks that the browser can start from it.
60
+
61
+ - **Rendering and adoption stay Foldkit's.** `SSR.render` calls Foldkit's
62
+ `renderToString` and `SSR.hydrate` calls `Runtime.hydrate`. Foldkit still
63
+ refuses a page from another build and still adopts the server's nodes.
64
+ - **The Model stays the application's.** A plan names fields of it; it adds no
65
+ state of its own, and every change after boot goes through `update`.
66
+ - **Data belongs to its package.** Remote's store crosses through Remote's own
67
+ part (`Remote.resume`), which decides what to capture.
68
+
69
+ ## The mental model
70
+
71
+ ```text
72
+ server init ──▶ Model ──┬── plan.state ──▶ slice ──▶ envelope (JSON in the page)
73
+ └── view ──▶ HTML (checked, see below)
74
+
75
+ browser envelope ──▶ baseline with the slice set on it ──▶ Model
76
+ Model + the server's HTML ──▶ Runtime.hydrate adopts ──▶ plan.boot Commands
77
+ ```
78
+
79
+ The one rule everything else serves: **the browser's first Model renders the
80
+ same page the server sent.** The browser's Model is the plan's baseline, by
81
+ default the application's `initial`, with the slice set onto it. So
82
+ `SSR.render` renders the view twice, once from the server's Model and once from
83
+ the browser's, and refuses the plan if the two differ. A view that reads a
84
+ field the plan does not send is caught there, on the server, instead of being
85
+ silently rebuilt in the browser.
86
+
87
+ ## A first page
88
+
89
+ The examples in this README share one application, a post page, sketched [at
90
+ the end](#the-application-in-these-examples). `App` is its Surface application
91
+ from `foldkit-surface`, and `config` is what you would pass to
92
+ `makeApplication`, the same object on both sides.
93
+
94
+ ```ts
95
+ import { Effect } from 'effect'
96
+ import { Projection } from 'foldkit-surface'
97
+ import { SSR } from 'foldkit-ssr'
98
+
99
+ // Which part of the Model the browser owns. The rest starts from the
100
+ // baseline, by default the application's initial Model.
101
+ export const Post = SSR.plan(App, {
102
+ id: 'post',
103
+ state: Projection.pick(App.model.route, App.model.draft),
104
+ })
105
+
106
+ // On the server, per request.
107
+ const result = await Effect.runPromise(SSR.render(config, Post, { buildId, url: request.url }))
108
+ const html = SSR.page(template, result)
109
+
110
+ // In the browser, instead of Runtime.hydrate.
111
+ SSR.hydrate(config, Post, { buildId })
112
+ ```
113
+
114
+ What each call does:
115
+
116
+ - **`SSR.plan`** is a declaration. It does no I/O and holds no state. It
117
+ throws only for a plan that could never work, such as two parts with one id.
118
+ - **`SSR.render`** is an Effect. It runs `init` once, renders the view twice,
119
+ checks the plan, and returns the rendered application and the envelope
120
+ script. It fails with `ResumeUnsafe` when the browser could not start where
121
+ the server did; [the refusals](#when-a-page-is-refused) say why and how to
122
+ fix each.
123
+ - **`SSR.page`** is pure: the template with the application and the envelope in
124
+ it. The envelope goes before the template's last `</body>`, and a template
125
+ without one is refused, by `SSR.page` and by `SSR.entry` when it is made.
126
+ - **`SSR.hydrate`** reads the envelope, starts Foldkit's runtime from the
127
+ resumed Model, and runs the plan's `boot` Commands. `init` does not run. A
128
+ page with no server render at all starts on the client as usual.
129
+
130
+ An application with Flags passes `flags` to `SSR.render`. They shape the
131
+ server's `init` and never reach the page.
132
+
133
+ ### Commands `init` would have run: `boot`
134
+
135
+ The browser does not run `init`, so the Commands it returns would run nowhere.
136
+ `SSR.render` refuses a plan that would drop them, naming them. Say what the
137
+ browser runs on load in `boot`:
138
+
139
+ ```ts
140
+ const Post = SSR.plan(App, {
141
+ id: 'post',
142
+ state: Projection.pick(App.model.route, App.model.draft),
143
+ boot: () => [LoadPreferences()],
144
+ })
145
+ ```
146
+
147
+ An application assembled with `foldkit-bundle` runs its assembly's startup
148
+ Commands, which is where a `Mirror.kv` restores what the user saved:
149
+
150
+ ```ts
151
+ boot: model => assembly.init(model).commands ?? []
152
+ ```
153
+
154
+ ### The head is part of the view
155
+
156
+ `title`, `lang`, `dir`, `canonical` and `ogUrl` are checked like the body.
157
+ Since Foldkit 0.163 nothing gives `canonical` a default from the URL, so a page
158
+ that wants one derives it from the route in its Model, as it does its `title`,
159
+ and sends the route in `state`.
160
+
161
+ ## Serving pages
162
+
163
+ ### Through Foldkit's fetch handler
164
+
165
+ Foldkit's server entry is one function, `renderPage(request)`, which
166
+ `handleRequest` calls for every request that is not a static file, on Node and
167
+ on Workers alike. `SSR.entry` is that function for a plan:
168
+
169
+ ```ts
170
+ import { handleRequest } from 'foldkit/experimental/server'
171
+
172
+ // The server entry.
173
+ export const { renderPage } = SSR.entry(config, Post, { buildId, template })
174
+
175
+ // A Worker, or any host that hands you a Web Request.
176
+ export default {
177
+ fetch: (request: Request) => handleRequest(request, { renderPage, template }),
178
+ }
179
+ ```
180
+
181
+ `GET` and `HEAD` render the page for the request's URL; an application with
182
+ Flags passes `flags: request => ...`. `POST` is handled only for a plan with a
183
+ [server fallback](#forms-that-work-without-scripts), and any other method is
184
+ answered `405`. A render that fails or throws, `flags` that reject, and a plan
185
+ the render refuses are answered `500` with the reason logged, never with a page
186
+ the browser could not resume.
187
+
188
+ The page comes back whole, as Foldkit's `Responded`, built by Foldkit's own
189
+ `toResponse`. A `Rendered` result has no room for the envelope, which is why
190
+ the entry takes the template itself, and why Foldkit's built-in `prerender`
191
+ cannot generate these pages; `SSR.generate` below does.
192
+ [foldkit#1448](https://github.com/foldkit/foldkit/issues/1448) asks Foldkit
193
+ for that room.
194
+
195
+ ### At build time
196
+
197
+ ```ts
198
+ import { mkdir, writeFile } from 'node:fs/promises'
199
+ import { dirname, join } from 'node:path'
200
+
201
+ const pages = await Effect.runPromise(
202
+ SSR.generate(config, Post, {
203
+ buildId,
204
+ template,
205
+ origin: 'https://example.com',
206
+ paths: ['/', '/about', '/docs/intro'],
207
+ }),
208
+ )
209
+ for (const page of pages) {
210
+ await mkdir(dirname(join('dist', page.file)), { recursive: true })
211
+ await writeFile(join('dist', page.file), page.html)
212
+ }
213
+ ```
214
+
215
+ Each path becomes `index.html` in its own folder (`/about` is
216
+ `about/index.html`); a path ending in `.html` keeps its name. `origin` makes
217
+ each path the full URL a routing application parses, and `flags: path => ...`
218
+ gives each its own Flags. The pages come back in the order of `paths`, typed as
219
+ a tuple, so `const [home, about] = pages` needs no check.
220
+
221
+ A static host serves one file for every query, and for `/about` and `/about/`
222
+ alike, so a generated page records its path alone: `/about?ref=mail` resumes
223
+ the page generated for `/about`, and `/other` is refused. A server-rendered page
224
+ records its path and query, and resumes only there.
225
+
226
+ ## Checking what the browser will read
227
+
228
+ The view check sees what the first render shows. A Surface can read a field the
229
+ first view never shows: a like button's state, a menu's contents. Name the
230
+ Surfaces the browser may activate, and the fields that may start from the
231
+ baseline on purpose:
232
+
233
+ ```ts
234
+ const Post = SSR.plan(App, {
235
+ id: 'post',
236
+ state: Projection.pick(App.model.route, App.model.post.id, App.model.post.liked),
237
+ local: [App.model.menuOpen], // starts from the baseline, on purpose
238
+ surfaces: [
239
+ Surface.when(PostActions, App.model.route, AppRoute.Post, route => ({ id: route.id })),
240
+ Surface.at(Menu, undefined),
241
+ ],
242
+ })
243
+ ```
244
+
245
+ `SSR.render` then refuses the plan, naming the Surface and the field, when an
246
+ active Surface reads a field that is in neither `state` nor `local`, is
247
+ activated by one, reads data no part of the plan resumes, or would activate
248
+ differently from the Model the browser starts from. The check runs for the
249
+ server's Model, because a Surface's reads follow its params.
250
+ `SSR.inspect(plan, model)` returns the same findings as data, for a test or a
251
+ debugging session: for each Surface, whether it is active, and where each read
252
+ comes from, `state`, `local` or `missing`.
253
+
254
+ ## State the slice cannot carry
255
+
256
+ ### Parts: another package's state
257
+
258
+ Some state is not a field to pick. Remote's normalized store holds whatever the
259
+ server read, most of which the page never shows. A **part** is a package's own
260
+ contribution to the envelope: it captures what the plan's active Surfaces read,
261
+ and restores it in the browser.
262
+
263
+ ```ts
264
+ const Post = SSR.plan(App, {
265
+ id: 'post',
266
+ state: Projection.pick(App.model.route),
267
+ surfaces: [PostPageAt],
268
+ parts: [Remote.resume(Data)],
269
+ })
270
+ ```
271
+
272
+ `Remote.resume` sends each field the Surfaces select, through relations, each
273
+ connection with its boundaries, and the live cursors of what it sends, and
274
+ nothing else of the store. The browser requests none of it again, and the
275
+ coverage check counts those reads as sent. Every part the plan names must be in
276
+ the page and restore, or the page is refused whole. The server restores each
277
+ part from its own capture before serving, so a part that could not is refused
278
+ there (`UnrestorablePart`), not in a user's browser.
279
+
280
+ ### Static regions: parts of the page the server owns
281
+
282
+ An article body, a product description, highlighted code: a part of the page no
283
+ Message changes need not render in the browser at all, and what it reads need
284
+ not be sent. Mark it with `SSR.static`:
285
+
286
+ ```ts
287
+ const view = (model: Model, h: HtmlBuilder<Message>) => ({
288
+ title: 'Post', // not the post's title: the browser does not have it
289
+ body: h.main(
290
+ [],
291
+ [
292
+ SSR.static('post-copy', ih => [
293
+ ih.h1([], [model.post.title]),
294
+ ih.p([], [model.post.body]),
295
+ ]),
296
+ PostActionsView(model, h), // the part the browser owns
297
+ ],
298
+ ),
299
+ })
300
+ ```
301
+
302
+ The region renders once, on the server, with Foldkit's inert builder, so it
303
+ cannot attach a handler. The browser adopts the server's markup as it is and
304
+ never runs the render, so this plan sends neither `post.title` nor `post.body`
305
+ and the view check still passes. A region changes only with a new document;
306
+ content a Message should change belongs in a Surface. A region the browser
307
+ needs that is not in the page, say after a Message shows one, is logged and
308
+ rendered in the browser.
309
+
310
+ ## Resumable pages: answering before the runtime boots
311
+
312
+ Everything above boots Foldkit's runtime as soon as the page loads. A resumable
313
+ page waits: it answers clicks and typing from the server's markup, and boots
314
+ only when it must, so the first interaction does not wait for the application's
315
+ code to start.
316
+
317
+ ```text
318
+ server each handler ──▶ its Message, encoded ──▶ a marker on the element + an entry in the envelope
319
+
320
+ browser event ──▶ the markers name its Messages ──▶ queued ──▶ the runtime boots
321
+ ──▶ the queue replays through update
322
+ ```
323
+
324
+ It rests on the fact that a Foldkit handler is already a Message value.
325
+ `Resume.builder(h)` is `h` that writes those values into the server's markup:
326
+
327
+ ```ts
328
+ const view = (model: Model, h: HtmlBuilder<Message>) => {
329
+ const rh = Resume.builder(h)
330
+ return {
331
+ title: 'Post',
332
+ body: rh.main(
333
+ [],
334
+ [
335
+ rh.button([rh.OnClick(Message.Liked({ id: model.post.id }))], ['Like']),
336
+ // A Message with a hole: the event fills `value`.
337
+ rh.input([rh.Value(model.draft), rh.OnInput(Message.ChangedDraft)]),
338
+ // Fixed fields beside the hole: the event fills `title`.
339
+ rh.input([rh.OnChange(Message.Renamed, { id: model.post.id })]),
340
+ // A key event fills `key` and `modifiers`.
341
+ rh.div([rh.OnKeyDown(Message.Pressed)], []),
342
+ ],
343
+ ),
344
+ }
345
+ }
346
+ ```
347
+
348
+ `rh` differs from `h` in one place: `OnInput`, `OnChange`, `OnKeyDown` and
349
+ `OnKeyUp` also take a Message's own constructor, and the event fills the field
350
+ it leaves open. The types check it where it is written: the member must be one
351
+ of the view's Messages, and leave exactly one string field, or exactly `key`
352
+ and `modifiers`. A closure still works. It is not data, so the page cannot
353
+ answer that event itself and boots on it instead, letting the live page answer.
354
+ So does a hole form whose field has checks the empty placeholder fails, such
355
+ as `Schema.isMinLength(1)`: it cannot be written into the page as data, so it
356
+ is treated as a closure.
357
+
358
+ A Surface renderer gets the same builder through `Resume.view`, and its `rh`
359
+ makes only that Surface's Messages:
360
+
361
+ ```ts
362
+ const LikeView = Surface.rootView(
363
+ Like,
364
+ undefined,
365
+ Resume.view((like, rh) => rh.button([rh.OnClick(Message.Liked({ id: like.id }))], ['Like'])),
366
+ )
367
+ ```
368
+
369
+ Then say when the runtime starts:
370
+
371
+ ```ts
372
+ const Post = SSR.plan(App, {
373
+ id: 'post',
374
+ state: Projection.pick(App.model.post),
375
+ surfaces: [PostActionsAt],
376
+ start: 'on-interaction', // or 'idle'; 'now', the default, boots on load
377
+ })
378
+ ```
379
+
380
+ The event that boots the page is not lost and does not count twice. Messages
381
+ answered before boot replay in order through the same `update`, so the Model
382
+ ends where an eager boot would have taken it, and the input typed into is
383
+ adopted, not rebuilt.
384
+
385
+ ### What a resumable page must declare
386
+
387
+ - **Its Surfaces.** A Surface's `messages` list is what the page may dispatch
388
+ before boot. A binding whose Message no active Surface lists is refused on
389
+ the server, naming the element and the Message, and the browser refuses a
390
+ page that carries one.
391
+ - **What may start late.** A Subscription or Managed Resource that starts at
392
+ boot starts later on a deferred page, which can change what the application
393
+ does. `SSR.render` refuses a deferred plan while one would be active,
394
+ naming each, until the plan declares it:
395
+
396
+ ```ts
397
+ const Post = SSR.plan(App, {
398
+ id: 'post',
399
+ state: Projection.pick(App.model.post),
400
+ parts: [Remote.resume(Data)], // Remote's entries may start late; its part says so
401
+ start: 'idle',
402
+ deferrable: ['tick'], // this application's own clock may start late
403
+ })
404
+ ```
405
+
406
+ For the check to see them, pass the application's `subscriptions` and
407
+ `managedResources` in the config given to `SSR.render`, as you would to
408
+ Foldkit. `boot` Commands run at boot, so a deferred page's `Mirror.kv`
409
+ restore waits for the first interaction.
410
+
411
+ ### Bundles whose code loads on demand
412
+
413
+ A `Bundle.lazy` from `foldkit-bundle` keeps a bundle's `update` and `view` out
414
+ of the boot chunk. Name each in the config's `lazy` list:
415
+
416
+ ```ts
417
+ const config = {
418
+ Model,
419
+ init: () => placements.init({ title: 'Uploads', upload }),
420
+ update: placements.update(),
421
+ view: (model: Model, h: HtmlBuilder<Message>) => {
422
+ const rh = Resume.builder(h)
423
+ return { title: model.title, body: rh.main([], [PlacedUpload.view(model, rh)]) }
424
+ },
425
+ container: null,
426
+ subscriptions: placements.subscriptions(),
427
+ lazy: [Upload],
428
+ }
429
+ ```
430
+
431
+ The server loads the code before it renders, so the page carries the real
432
+ view. The browser loads it before it boots and answers from the markers
433
+ meanwhile, whatever `start` says. A binding inside a placement dispatches the
434
+ parent's Message, as Foldkit's own handlers do, so the plan's Surface lists the
435
+ wrapper variant, `Message.GotUploadMessage`.
436
+
437
+ ## Forms that work without scripts
438
+
439
+ A form whose `OnSubmit` names a Message can be answered by the server, before
440
+ any script has run or with scripts blocked, because `update` is pure and the
441
+ server can run it. The plan opts in:
442
+
443
+ ```ts
444
+ const Todos = SSR.plan(App, {
445
+ id: 'todos',
446
+ state: Projection.pick(App.model.draft, App.model.todos),
447
+ surfaces: [Surface.at(TodoList, undefined)],
448
+ fallback: 'server',
449
+ })
450
+ ```
451
+
452
+ ```ts
453
+ rh.form(
454
+ [rh.OnSubmit(Message.Added({ title: model.draft }))],
455
+ [rh.input([rh.Name('title'), rh.Value(model.draft), rh.OnInput(Message.Typed)])],
456
+ )
457
+ ```
458
+
459
+ With scripts on, nothing changes: the page answers the submit and the form
460
+ never posts. Without them, the server wrote the form to post the Message to the
461
+ page's own URL, and `SSR.entry` hands that post to `SSR.handle`:
462
+
463
+ ```text
464
+ POST ──▶ decode the Message ──▶ set the posted fields into it (the typed `title`)
465
+ ──▶ init, then boot and its Commands ──▶ update, and every Command after it
466
+ ──▶ the page, rendered
467
+ ```
468
+
469
+ The Message must be one the page's active Surfaces list. Commands run under the
470
+ config's `resources` Layer, as Foldkit's runtime would provide them. A post the
471
+ server cannot use is answered `400` with the reason (`FallbackRefused`); a
472
+ Command that fails is answered `500`. The browser's loop runs for the life of
473
+ the page, so a Command that reschedules itself, a poll or a tick, is ordinary
474
+ there; on the server a post that has not settled within 100 Messages and
475
+ Commands is answered `500`, naming the last Command. `SSR.handle(request,
476
+ config, plan, { buildId, flags? })` can also be called from an entry of your
477
+ own.
478
+
479
+ ## When a page is refused
480
+
481
+ A refusal never shows a user a half-working page. On the server it is an error
482
+ before anything is served; in the browser the page is contained, as Foldkit
483
+ contains a page from another build, and the reason is logged.
484
+
485
+ On the server, `SSR.render` fails with `ResumeUnsafe`, whose `reason` is one
486
+ of:
487
+
488
+ | `reason` | What it means | The fix |
489
+ | -------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------- |
490
+ | `ViewDependsOnUnsentState` | The view, or its head, renders differently from the browser's Model | Add the field the message names to `state`, or stop the view reading it |
491
+ | `UndeclaredStartup` | `init` returned Commands and the plan has no `boot` | Name them in `boot` |
492
+ | `Uncovered` | An active Surface reads or is activated by an unsent field, or a binding sends a Message no active Surface lists | Send the field, name it `local`, or list the Message on the Surface |
493
+ | `UnrestorablePart` | A part cannot restore its own capture | A bug in that part |
494
+ | `DuplicateStaticRegion` | Two `SSR.static` regions share an id | Give each its own id |
495
+ | `BindingInStaticRegion` | A handler inside an `SSR.static` region | Move the element out, into a Surface |
496
+ | `UndeclaredSurfaces` | The page has bindings and the plan no `surfaces` | Name the Surfaces the page may activate |
497
+ | `UnencodableBinding` | The plan has no Message Schema, or a binding's Message does not encode through it | Make the plan from the application; build the Message with its constructor |
498
+ | `EagerStartRequired` | A deferred plan would start a Subscription or Managed Resource late | Declare it in `deferrable`, or start `'now'` |
499
+ | `UngeneratablePath` | `SSR.generate` was given a path no file can be served at | Leave out the query and fragment; keep paths to distinct files |
500
+
501
+ In the browser, `SSR.hydrate` checks in Foldkit's order: the build id first,
502
+ then the envelope. `SSR.resume` returns the envelope's refusal as
503
+ `ResumeRefused`: `Missing` or `Duplicate` envelope, `Unreadable` JSON, another
504
+ `Protocol` version or `Plan`, state, parts or bindings that are `Invalid`, or a
505
+ `Route` other than the one the page was rendered for. A page is resumed whole or
506
+ not at all.
507
+
508
+ ## Costs and limits
509
+
510
+ - **`SSR.render` renders the view twice.** That is the view check. A static
511
+ region's render runs once.
512
+ - **`SSR.hydrate` relies on how Foldkit hydrates today.** It gives Foldkit a
513
+ config whose `init` returns the resumed Model, and removes the `Flags` key,
514
+ which Foldkit would otherwise require a payload for. The tests pin both, and
515
+ fail the day Foldkit changes.
516
+ [foldkit#1449](https://github.com/foldkit/foldkit/issues/1449) asks whether
517
+ Foldkit would support this directly.
518
+ - **A resumable page leans on three Foldkit behaviours,** each pinned by a test
519
+ here and two by Foldkit's own: the first patch removes attributes the
520
+ browser's view does not assert, a control's value is re-asserted to the
521
+ Model's, and `Runtime.hydrate` renders its first frame before it returns.
522
+ - **Development is not production.** Under Vite's dev server, Foldkit's model
523
+ preservation restores the previous Model after a reload and skips adoption.
524
+ - **A closure handler makes its event wait for boot,** with no warning yet
525
+ naming the element.
526
+
527
+ ## Lower-level API
528
+
529
+ `SSR.render` and `SSR.hydrate` are built from pieces usable on their own:
530
+
531
+ - **`SSR.envelope(plan, model, { route? })`** returns the envelope script for a
532
+ Model, and **`SSR.resume(plan, document, { route? })`** reads it back as a
533
+ `Result`. The envelope escapes `<` as Foldkit escapes its Flags, and U+2028
534
+ and U+2029, so no string in the Model can close the script.
535
+ - **`SSR.inspect(plan, model)`**: the plan's coverage as data.
536
+ - **`Resume.bindings(plan, document, root, model)`** decodes and checks a
537
+ page's bindings, and **`Resume.listen(root, { bindings, onAnswer })`**
538
+ answers events from the markers, one `{ event, messages, unnamed? }` per
539
+ event. `SSR.hydrate` uses both; they are there for a custom boot.
540
+ - **Attribute names**, for tools and tests: `RESUME_ATTRIBUTE` (the envelope
541
+ script), `STATIC_ATTRIBUTE`, `BINDING_ATTRIBUTE` (a prefix, followed by the
542
+ event), `SLOT_ATTRIBUTE` (a placement's root while the server renders) and
543
+ `FALLBACK_FIELD` (the posted Message).
544
+
545
+ ## The application in these examples
546
+
547
+ A post page. `App` is `Surface.application({ Model, Message, initial, update
548
+ })`. The Surfaces (`PostActions`, `Menu`, `Like`), `Data` (a `Remote.make`
549
+ domain over `App.model.remote`) and `LoadPreferences` (a `Command.define`) are
550
+ the application's own. `PostActionsAt` and `PostPageAt` are Surfaces placed
551
+ for a plan, as `Surface.when(PostActions, App.model.route, AppRoute.Post, route
552
+ => ({ id: route.id }))` places one in
553
+ [the coverage example](#checking-what-the-browser-will-read).
554
+
555
+ ```ts
556
+ const AppRoute = defineRouteUnion({ Home: {}, Post: { id: Schema.String } })
557
+
558
+ const Model = Schema.Struct({
559
+ route: AppRoute,
560
+ post: Schema.Struct({
561
+ id: Schema.String,
562
+ title: Schema.String,
563
+ body: Schema.String,
564
+ liked: Schema.Boolean,
565
+ }),
566
+ draft: Schema.String,
567
+ menuOpen: Schema.Boolean,
568
+ remote: Remote.Model,
569
+ })
570
+
571
+ const Modifiers = Schema.Struct({
572
+ shiftKey: Schema.Boolean,
573
+ ctrlKey: Schema.Boolean,
574
+ altKey: Schema.Boolean,
575
+ metaKey: Schema.Boolean,
576
+ })
577
+
578
+ const Message = defineMessageUnion({
579
+ ...Remote.messages,
580
+ Liked: { id: Schema.String },
581
+ ChangedDraft: { value: Schema.String },
582
+ Renamed: { id: Schema.String, title: Schema.String },
583
+ Pressed: { key: Schema.String, modifiers: Modifiers },
584
+ })
585
+ ```
586
+
587
+ ## See also
588
+
589
+ - [The implementation plan](../../docs/design/ssr-PLAN.md): the decisions and
590
+ why, phase by phase.
591
+ - [What the tests prove](./test/README.md).
592
+ - [What this package asks of Foldkit](../../docs/upstream-foldkit-ssr.md).