foldkit-ssr 0.11.0 → 0.13.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.
Files changed (63) hide show
  1. package/README.md +656 -83
  2. package/dist/{client-qmdYY-Eb.d.ts → client-cumvT9XN.d.ts} +10 -7
  3. package/dist/client-cumvT9XN.d.ts.map +1 -0
  4. package/dist/client.d.ts +6 -5
  5. package/dist/client.js +64 -16
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js.map +1 -1
  9. package/dist/diagnostics.d.ts +2 -2
  10. package/dist/diagnostics.js +7 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/handoff.d.ts +23 -0
  13. package/dist/handoff.d.ts.map +1 -0
  14. package/dist/handoff.js +15 -0
  15. package/dist/handoff.js.map +1 -0
  16. package/dist/index.d.ts +66 -26
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +282 -56
  19. package/dist/index.js.map +1 -1
  20. package/dist/keep.d.ts +3 -1
  21. package/dist/keep.d.ts.map +1 -1
  22. package/dist/keep.js +21 -6
  23. package/dist/keep.js.map +1 -1
  24. package/dist/{listen-DaUPRKVR.d.ts → listen-7HzKBhqU.d.ts} +11 -2
  25. package/dist/{listen-DaUPRKVR.d.ts.map → listen-7HzKBhqU.d.ts.map} +1 -1
  26. package/dist/listen.d.ts +2 -2
  27. package/dist/listen.js +17 -7
  28. package/dist/listen.js.map +1 -1
  29. package/dist/loader.d.ts +13 -0
  30. package/dist/loader.d.ts.map +1 -0
  31. package/dist/loader.js +156 -0
  32. package/dist/loader.js.map +1 -0
  33. package/dist/marks-CX15BwOw.d.ts +39 -0
  34. package/dist/marks-CX15BwOw.d.ts.map +1 -0
  35. package/dist/marks.d.ts +2 -0
  36. package/dist/marks.js +41 -0
  37. package/dist/marks.js.map +1 -0
  38. package/dist/{resumable-BPN_qQHU.d.ts → resumable-BV9_OKxr.d.ts} +7 -10
  39. package/dist/resumable-BV9_OKxr.d.ts.map +1 -0
  40. package/dist/resumable.d.ts +2 -1
  41. package/dist/resumable.js +16 -19
  42. package/dist/resumable.js.map +1 -1
  43. package/dist/runtimeChunk.d.ts +13 -0
  44. package/dist/runtimeChunk.d.ts.map +1 -0
  45. package/dist/runtimeChunk.js +36 -0
  46. package/dist/runtimeChunk.js.map +1 -0
  47. package/dist/runtimeUrl.d.ts +10 -0
  48. package/dist/runtimeUrl.d.ts.map +1 -0
  49. package/dist/runtimeUrl.js +13 -0
  50. package/dist/runtimeUrl.js.map +1 -0
  51. package/dist/{shared-CJN-m58Z.d.ts → shared-BuCOwm57.d.ts} +62 -20
  52. package/dist/shared-BuCOwm57.d.ts.map +1 -0
  53. package/dist/shared.d.ts +3 -2
  54. package/dist/shared.js +36 -13
  55. package/dist/shared.js.map +1 -1
  56. package/dist/vite.d.ts +19 -5
  57. package/dist/vite.d.ts.map +1 -1
  58. package/dist/vite.js +9 -2
  59. package/dist/vite.js.map +1 -1
  60. package/package.json +13 -8
  61. package/dist/client-qmdYY-Eb.d.ts.map +0 -1
  62. package/dist/resumable-BPN_qQHU.d.ts.map +0 -1
  63. package/dist/shared-CJN-m58Z.d.ts.map +0 -1
package/README.md CHANGED
@@ -12,7 +12,7 @@ change between minor versions.
12
12
  pnpm add foldkit-ssr foldkit-surface foldkit effect
13
13
  ```
14
14
 
15
- ```ts
15
+ ```ts sketch
16
16
  // In outline; `App`, `config` and `template` are the application's own, and
17
17
  // [A first page](#a-first-page) splits this into its modules.
18
18
 
@@ -76,13 +76,13 @@ and the checks that the browser can start from it.
76
76
 
77
77
  ## The mental model
78
78
 
79
- ```text
80
- server init ──▶ Model ──┬── plan.state ──▶ slice ──▶ envelope (JSON on the stamped root)
81
- └── view ──▶ HTML (checked, see below)
79
+ On the server, `init` makes the Model. The plan's `state` turns it into a slice,
80
+ which goes into an envelope as JSON on the stamped root, and the view turns the
81
+ same Model into HTML, which is checked (see below).
82
82
 
83
- browser envelope ──▶ baseline with the slice set on it ──▶ Model
84
- Model + the server's HTML ──▶ Runtime.hydrate adopts ──▶ plan.boot Commands
85
- ```
83
+ In the browser, the envelope sets the slice onto the baseline Model, and that is
84
+ the first Model. `Runtime.hydrate` adopts the server's HTML with that Model, and
85
+ then the plan's `boot` Commands run.
86
86
 
87
87
  The one rule everything else serves: **the browser's first Model renders the
88
88
  same page the server sent.** The browser's Model is the plan's baseline, by
@@ -104,6 +104,88 @@ Message as Foldkit types them.
104
104
  The code is in three modules, because the server and the browser import
105
105
  different things:
106
106
 
107
+ <!-- docs-check standalone define ssr-app
108
+ import { Effect, Layer, Option, Schema } from 'effect'
109
+ import { Command } from 'foldkit'
110
+ import type { HtmlBuilder } from 'foldkit/html'
111
+ import { defineMessageUnion } from 'foldkit/message'
112
+ import { defineRouteUnion } from 'foldkit/route'
113
+ import { Remote } from 'foldkit-remote'
114
+ import { Projection, Surface } from 'foldkit-surface'
115
+
116
+ const AppRoute = defineRouteUnion({ Home: {}, Post: { id: Schema.String }, NotFound: {} })
117
+ const Model = Schema.Struct({
118
+ route: AppRoute,
119
+ post: Schema.Struct({
120
+ id: Schema.String,
121
+ title: Schema.String,
122
+ body: Schema.String,
123
+ excerpt: Schema.String,
124
+ publishedAt: Schema.String,
125
+ liked: Schema.Boolean,
126
+ }),
127
+ draft: Schema.String,
128
+ menuOpen: Schema.Boolean,
129
+ remote: Remote.Model,
130
+ })
131
+ type Model = typeof Model.Type
132
+ const Modifiers = Schema.Struct({
133
+ shiftKey: Schema.Boolean,
134
+ ctrlKey: Schema.Boolean,
135
+ altKey: Schema.Boolean,
136
+ metaKey: Schema.Boolean,
137
+ })
138
+ const Message = defineMessageUnion({
139
+ ...Remote.messages,
140
+ Liked: { id: Schema.String },
141
+ ChangedDraft: { value: Schema.String },
142
+ Renamed: { id: Schema.String, title: Schema.String },
143
+ Pressed: { key: Schema.String, modifiers: Modifiers },
144
+ })
145
+ type Message = typeof Message.Type
146
+ const initial: Model = {
147
+ route: AppRoute.Post({ id: 'p1' }),
148
+ post: { id: 'p1', title: 'Hello', body: '', excerpt: '', publishedAt: '2026-01-01', liked: false },
149
+ draft: '',
150
+ menuOpen: false,
151
+ remote: Remote.initial,
152
+ }
153
+ const App = Surface.application({ Model, Message, initial, update: (model: Model) => ({ model }) })
154
+ const Data = Remote.make({ model: App.model.remote, entities: [] })
155
+ const PostActions = App.surface('PostActions', {
156
+ params: { id: Schema.String },
157
+ model: ({ model }) => ({ liked: model.post.liked }),
158
+ messages: [Message.Liked],
159
+ })
160
+ const Menu = App.surface('Menu', { model: ({ model }) => ({ open: model.menuOpen }) })
161
+ const Like = App.surface('Like', {
162
+ model: ({ model }) => ({ id: model.post.id }),
163
+ messages: [Message.Liked],
164
+ })
165
+ const PostActionsAt = Surface.when(PostActions, App.model.route, AppRoute.Post, route => ({
166
+ id: route.id,
167
+ }))
168
+ const PostPageAt = Surface.at(Menu, undefined)
169
+ const LoadPreferences = Command.define('LoadPreferences', {
170
+ messages: [Message.ChangedDraft],
171
+ execute: Effect.succeed(Message.ChangedDraft({ value: '' })),
172
+ })
173
+ const config = {
174
+ Model,
175
+ init: () => ({ model: initial }),
176
+ update: (model: Model, _message: Message) => ({ model }),
177
+ view: (model: Model, h: HtmlBuilder<Message>) => ({
178
+ title: model.post.title,
179
+ body: h.p([], [model.draft]),
180
+ }),
181
+ container: null,
182
+ }
183
+ declare const template: string
184
+ declare const buildId: string
185
+ declare const url: string
186
+ declare const request: Request
187
+ -->
188
+
107
189
  ```ts
108
190
  // post.ts, read by both: the plan. Which part of the Model the browser owns;
109
191
  // the rest starts from the baseline, by default the application's initial Model.
@@ -116,6 +198,14 @@ export const Post = SSR.plan(App, {
116
198
  })
117
199
  ```
118
200
 
201
+ <!-- docs-check standalone use ssr-app
202
+ import { SSR as Plans } from 'foldkit-ssr/client'
203
+ const Post = Plans.plan(App, {
204
+ id: 'post',
205
+ state: Projection.pick(App.model.route, App.model.draft),
206
+ })
207
+ -->
208
+
119
209
  ```ts
120
210
  // server.ts, per request.
121
211
  import { Effect } from 'effect'
@@ -125,6 +215,14 @@ const result = await Effect.runPromise(SSR.render(config, Post, { buildId, url:
125
215
  const html = SSR.page(template, result)
126
216
  ```
127
217
 
218
+ <!-- docs-check standalone use ssr-app
219
+ import { SSR as Plans } from 'foldkit-ssr/client'
220
+ const Post = Plans.plan(App, {
221
+ id: 'post',
222
+ state: Projection.pick(App.model.route, App.model.draft),
223
+ })
224
+ -->
225
+
128
226
  ```ts
129
227
  // client.ts, the page's script, instead of Runtime.hydrate.
130
228
  import { SSR } from 'foldkit-ssr/client'
@@ -133,7 +231,7 @@ SSR.hydrate(config, Post, { buildId })
133
231
  ```
134
232
 
135
233
  `foldkit-ssr/client` is the browser's part: `SSR.plan`, `SSR.resume`,
136
- `SSR.hydrate`, `SSR.static`, `SSR.serving`, `Resume`, and the attribute names,
234
+ `SSR.hydrate`, `SSR.static`, `SSR.unbound`, `SSR.serving`, `Resume`, and the attribute names,
137
235
  Foldkit's root stamp (`FOLDKIT_APP_ATTRIBUTE`) among them. It imports nothing
138
236
  of `foldkit/experimental/server`, whose renderer and HTML parser `foldkit-ssr`
139
237
  brings along: about 200 kB minified (60 kB gzipped) off a page's script in the
@@ -168,6 +266,10 @@ The browser does not run `init`, so the Commands it returns would run nowhere.
168
266
  `SSR.render` refuses a plan that would drop them, naming them. Say what the
169
267
  browser runs on load in `boot`:
170
268
 
269
+ <!-- docs-check standalone use ssr-app
270
+ import { SSR } from 'foldkit-ssr'
271
+ -->
272
+
171
273
  ```ts
172
274
  const Post = SSR.plan(App, {
173
275
  id: 'post',
@@ -179,27 +281,36 @@ const Post = SSR.plan(App, {
179
281
  An application assembled with `foldkit-bundle` runs its assembly's startup
180
282
  Commands, which is where a `Mirror.kv` restores what the user saved:
181
283
 
182
- ```ts
284
+ ```ts sketch
183
285
  boot: model => assembly.init(model).commands ?? []
184
286
  ```
185
287
 
186
288
  ### Styles in the first paint
187
289
 
188
290
  A generated page styled with `foldkit-mixins` can ship the CSS its markup uses
189
- in the head, so it is styled before any script runs. `head` is given the rendered
190
- application; `Style.usedIn` returns the CSS of every compiled class the markup
191
- carries, with the global rules (keyframes, `raise`'s depth rules) of the Styles
192
- those classes came from. In the browser, Styles bring their rules as they draw and skip what
193
- this sheet already carries, so nothing is added twice.
291
+ in the head, so it is styled before any script runs. `head` is given the
292
+ rendered application and the compiled classes the render drew; `Style.usedDrawn`
293
+ writes the CSS of those classes, with the global rules (keyframes, `raise`'s
294
+ depth rules) of the Styles they came from, without scanning the HTML. In the
295
+ browser, Styles bring their rules as they draw and skip what this sheet already
296
+ carries, so nothing is added twice.
297
+
298
+ <!-- docs-check
299
+ const result = await Effect.runPromise(SSR.render(config, Post, { buildId, url }))
300
+ -->
194
301
 
195
302
  ```ts
196
303
  import { Style } from 'foldkit-mixins'
197
304
 
198
305
  const html = SSR.page(template, result, {
199
- head: rendered => `<style>${Style.usedIn(rendered.html)}</style>`,
306
+ head: (_rendered, drawn) => `<style>${Style.usedDrawn(drawn)}</style>`,
200
307
  })
201
308
  ```
202
309
 
310
+ The drawn classes are also on the rendered page (`result.drawn`) for a host
311
+ that writes its own head, and `Style.usedIn(rendered.html)` still works for a
312
+ caller holding only the HTML.
313
+
203
314
  With `foldkit-mixins/vite`, the stylesheet is a hashed file, and the page
204
315
  links it from the document's head instead (`renderDocument`'s `head`):
205
316
  `<link rel="stylesheet" href="${href}" data-foldkit-styles-href>`. A link in
@@ -213,11 +324,15 @@ into `index.html` only, never into a page the server renders, so a served
213
324
  page carries the theme's stylesheet here too, beside the classes it draws
214
325
  (`examples/foldkit/ssr/src/renderPage.ts`):
215
326
 
327
+ <!-- docs-check
328
+ declare const stylesheet: string
329
+ -->
330
+
216
331
  ```ts
217
- const styles = (rendered: { readonly html: string }): string =>
218
- `<style>${stylesheet}</style><style>${Style.usedIn(rendered.html)}</style>`
332
+ const styles = (_rendered: { readonly html: string }, drawn: ReadonlySet<string>): string =>
333
+ `<style>${stylesheet}</style><style>${Style.usedDrawn(drawn)}</style>`
219
334
 
220
- SSR.entry(config, plan, { buildId, styles })
335
+ SSR.entry(config, Post, { buildId, styles })
221
336
  ```
222
337
 
223
338
  Without it, every served page flashes unstyled until the script runs. Keep
@@ -227,8 +342,8 @@ again would keep its classes without their rules; `SSR.hydrate` moves them
227
342
  into the document's head before anything adopts the page, whether it resumes
228
343
  or is contained, and the browser's Styles find them there and add nothing
229
344
  twice. A void root holds no children, so styles for one are refused with
230
- `VoidRootWithStyles`, naming the tag. Anything else a head owns (`meta`)
231
- stays with `SSR.generate`.
345
+ `VoidRootWithStyles`, naming the tag. A plan's `meta` rides in the root too,
346
+ for the host to move (`SSR.headed`, under Serving pages).
232
347
 
233
348
  `SSR.generate` takes the same `head`, and answers a `head` that throws `500`,
234
349
  as it does a render that fails. `SSR.entry` takes no `head`: the host owns
@@ -253,6 +368,10 @@ A search result and a link preview read more than Foldkit's `Document`: a
253
368
  description, an image, Open Graph, a post's dates and structured data. The
254
369
  plan's `meta` gives them from the Model:
255
370
 
371
+ <!-- docs-check standalone use ssr-app
372
+ import { SSR } from 'foldkit-ssr'
373
+ -->
374
+
256
375
  ```ts
257
376
  const Post = SSR.plan(App, {
258
377
  id: 'post',
@@ -299,7 +418,7 @@ export default {
299
418
  }
300
419
  ```
301
420
 
302
- ```ts
421
+ ```ts standalone
303
422
  // vite.config.ts, for the dev server and the build id both entries compile in.
304
423
  import { foldkit } from '@foldkit/vite-plugin'
305
424
  import { defineConfig } from 'vite'
@@ -309,7 +428,7 @@ export default defineConfig({
309
428
  })
310
429
  ```
311
430
 
312
- ```ts
431
+ ```ts sketch
313
432
  // entry.server.ts and the browser's entry.ts alike.
314
433
  buildId: import.meta.env.FOLDKIT_BUILD_ID,
315
434
  ```
@@ -349,7 +468,8 @@ the Message is checked against the active Surfaces and `update` runs, so the
349
468
  post starts from the Model the page it came from was drawn with, and one
350
469
  entry, made once, serves every request. A `prepare` that fails is answered
351
470
  `500` and reported; one that would rather draw the page unread recovers
352
- inside its Effect. `POST` is handled only for a plan with a
471
+ inside its Effect. A page the prepared Model says to send elsewhere is a
472
+ `303` ([`redirect`](#sending-a-page-elsewhere-redirect)). `POST` is handled only for a plan with a
353
473
  [server fallback](#forms-that-work-without-scripts). `OPTIONS` is answered
354
474
  `204` and any other method `405`, each with the methods the entry answers in
355
475
  `allow`. A render that fails or throws, `flags` that reject, and a plan the
@@ -363,6 +483,14 @@ the Model. `model` is an `Option`: `some` of the Model the server reached for
363
483
  a rendered page (a posted form's, after `update`), `none` for an answer that
364
484
  rendered nothing (`OPTIONS`, a `405`, a refused post, a `500`).
365
485
 
486
+ <!-- docs-check standalone use ssr-app
487
+ import { SSR } from 'foldkit-ssr'
488
+ const Post = SSR.plan(App, {
489
+ id: 'post',
490
+ state: Projection.pick(App.model.route, App.model.draft),
491
+ })
492
+ -->
493
+
366
494
  ```ts
367
495
  SSR.entry(config, Post, {
368
496
  buildId,
@@ -404,12 +532,37 @@ The page is rendered and resumed as any other; only the response's status
404
532
  changes. A status outside `200`–`599`, a `204`, `205` or `304` that cannot
405
533
  carry the page, or a `status` that throws, is answered `500` and reported.
406
534
 
407
- What the page says of itself (`meta`) and per-page `head` markup are written
408
- into a template's head, which the host owns here: a plan with `meta` is
409
- refused when the entry is made, and served with `SSR.generate` below, which
410
- owns its template.
535
+ What the page says of itself (`meta`) belongs in the head, which the host
536
+ owns here, and link previews and crawlers read only the served head. The
537
+ entry carries a plan's `meta` in the rendered root, between two marker
538
+ comments, and `SSR.headed` wraps the host's document renderer to move it
539
+ before `</head>`:
540
+
541
+ ```ts
542
+ import { injectIntoTemplate, renderDocument as renderShell } from 'foldkit/experimental/server'
543
+
544
+ // A server entry's document renderer, as the Foldkit Vite plugin takes it
545
+ // (export it as `renderDocument`):
546
+ const headedShell = SSR.headed(renderShell)
547
+
548
+ // A host that hands Foldkit a template instead:
549
+ const headedTemplate = SSR.headed((application: Parameters<typeof injectIntoTemplate>[1]) =>
550
+ injectIntoTemplate(template, application),
551
+ )
552
+ ```
553
+
554
+ Each request's page carries its own `meta`, so nothing of one request reaches
555
+ another's document, and `SSR.keptDocuments(SSR.headed(render))` keeps a kept
556
+ page's document with its head. A host that leaves the wrapper out serves the
557
+ `meta` in the body, where nothing reads it: `SSR.hydrate` then removes it,
558
+ reports `HeadNotMoved`, and the head gets it once the page runs. An e2e test
559
+ reading a served page's head is the check before deploying. `SSR.headed`
560
+ takes the markup only from where the entry put it, at the root's end, so
561
+ marker comments a view draws in its own text (a `<style>`) are not moved. A
562
+ root a parser does not keep `<meta>` in (a void element, a table's, `svg`,
563
+ raw text) is refused (`RootRefusesHead`).
411
564
  [foldkit#1448](https://github.com/foldkit/foldkit/issues/1448) asks Foldkit
412
- for a per-request head channel beside the envelope.
565
+ for a per-request head channel, which would retire `SSR.headed`.
413
566
 
414
567
  ### What the host hands the page: `SSR.requestContext`
415
568
 
@@ -420,6 +573,10 @@ bindings, or a reader built from them. `SSR.requestContext` carries it on the
420
573
  request. The host attaches a value, and `renderPage`, given the same request
421
574
  by `handleRequest`, reads it back:
422
575
 
576
+ <!-- docs-check
577
+ const actives = { page: PostActionsAt }
578
+ -->
579
+
423
580
  ```ts
424
581
  import { Effect, Option, type Layer } from 'effect'
425
582
  import type { RemoteClient, RemoteUnauthenticated } from 'foldkit-remote'
@@ -460,6 +617,60 @@ serves. [`examples/auth`](../../examples/auth)'s `src/host.ts` is the whole
460
617
  site behind one handler; its development server, another process, attaches
461
618
  an HTTP reader instead.
462
619
 
620
+ ### Sending a page elsewhere: `redirect`
621
+
622
+ A page the reader may not see (a notebook asked for by a visitor) is answered
623
+ with a `303` to where they belong, decided from the Model `prepare` read as
624
+ them. `redirect: (model, request) => Option<string>` says so, in the entry
625
+ made once:
626
+
627
+ ```text
628
+ GET url -> init -> prepare (read as the reader) -> redirect(model)
629
+ -> some(path): 303, location: path, cache-control: private, no-store
630
+ -> none: render the page from that same Model
631
+ ```
632
+
633
+ <!-- docs-check
634
+ import { Access } from 'foldkit-site'
635
+ declare const accessOf: (model: Model) => Access
636
+ -->
637
+
638
+ ```ts
639
+ export const guarded = SSR.entry(config, Post, {
640
+ buildId,
641
+ prepare: (model, request) =>
642
+ Option.match(PageContext.of(request), {
643
+ onNone: () => Effect.fail(new Error('No reader for this page.')),
644
+ onSome: ({ reader }) => Data.satisfy(model, actives).pipe(Effect.provide(reader)),
645
+ }),
646
+ redirect: model =>
647
+ Access.match(accessOf(model), {
648
+ Denied: ({ url }) => Option.some(url),
649
+ Allowed: () => Option.none(),
650
+ Pending: () => Option.none(),
651
+ }),
652
+ })
653
+ ```
654
+
655
+ `redirect` runs for `GET` and `HEAD`, after `prepare` and before anything is
656
+ rendered, so the decision and the page come from one read; a page sent
657
+ elsewhere never runs its view. A posted form is answered by
658
+ [`answerPost`](#answering-a-post-with-a-redirect), not by `redirect`.
659
+
660
+ - **It is never kept, for anyone.** A redirect is one reader's answer, so it
661
+ says `cache-control: private, no-store` over whatever `headers` set, and
662
+ `cache` never stores it, however public the reads behind it were. The next
663
+ request is decided again.
664
+ - **It carries the entry's `headers`,** given the Model the redirect was
665
+ decided on (a cookie written from it, `vary`); only `cache-control` is the
666
+ entry's own.
667
+ - **It goes nowhere but a path on this origin.** The path must start with a
668
+ single `/` and, resolved against the request's address, keep its origin:
669
+ an absolute URL (even this origin's), `//elsewhere.test`,
670
+ `/\elsewhere.test` (which a browser reads as `//`), a relative path or a
671
+ scheme is answered `500` and reported, as a `redirect` that throws is. The
672
+ `location` written is the path as resolved.
673
+
463
674
  ### Keeping pages: `cache`
464
675
 
465
676
  A page drawn from its URL alone is the same page for everyone who asks for
@@ -486,7 +697,7 @@ export const cached = SSR.entry(config, Post, {
486
697
 
487
698
  Whether a page may be kept is decided from what its render read, not from
488
699
  a declaration. The render is handed a request that records each header
489
- `flags`, `prepare`, `headers` or `status` reads; a page is kept only when
700
+ `flags`, `prepare`, `redirect`, `headers` or `status` reads; a page is kept only when
490
701
  every one of them was absent from the request, so it was drawn from the URL
491
702
  alone. A header read by name (the cart cookie, say) that was absent goes in
492
703
  `vary`, and the kept page serves only requests that lack it too: a request
@@ -509,6 +720,17 @@ The key is the build id and the full URL, so a deploy never serves another
509
720
  build's page (the browser would refuse it anyway, as `OtherBuild`).
510
721
  `CacheStore.workers(caches.default)` keeps pages in the Workers Cache API.
511
722
 
723
+ A page is kept for its freshness, often a minute, so a URL asked again after
724
+ that renders again. `CacheStore.kv(env.CACHE, { keep: '6 hours' })` keeps
725
+ pages in Workers KV and serves each for `keep` after it was kept, past a
726
+ shorter `maxAge`: the page carries when each of its reads was made, and a
727
+ browser whose Remote freshness has a `maxAge`
728
+ (`RemotePolicy.staleWhileRevalidate`) reads again what is past it, so the
729
+ server renders a page once in `keep` instead of once a minute. KV writes a page only on its second
730
+ ask and fails open (`foldkit-remote-server`'s README says how). With
731
+ `keep` it is a `PageCacheStore`, which `cache.store` here takes and
732
+ `serveFetch` refuses: a read's answer carries no age.
733
+
512
734
  The host draws each page into its document, which parses the page again
513
735
  (Foldkit's `injectIntoTemplate`), so a kept page would still cost that on
514
736
  every request. Wrap the server entry's `renderDocument` in
@@ -518,7 +740,7 @@ of assets (the last 32 are held):
518
740
  ```ts
519
741
  import { renderDocument as renderShell, type DocumentRenderer } from 'foldkit/experimental/server'
520
742
 
521
- export const renderDocument: DocumentRenderer = SSR.keptDocuments(renderShell)
743
+ export const renderDocument: DocumentRenderer = SSR.keptDocuments(SSR.headed(renderShell))
522
744
  ```
523
745
 
524
746
  The checker draws a kept page again for each request it serves.
@@ -579,27 +801,6 @@ The Message goes into the starting Model rather than after boot, so a URL
579
801
  mirror does not write the served address back over the real one. A
580
802
  server-rendered page records its path and query, and resumes only there.
581
803
 
582
- Foldkit's Vite plugin prerenders pages through the server entry itself
583
- (`ssr.build.prerender`), so `SSR.entry` cannot tell a build's request from a
584
- visitor's. Name those paths in `prerendered`, and a request for one with no
585
- query records its path alone, as `SSR.generate` does; export the same list
586
- as `prerenderPaths`, which the plugin reads:
587
-
588
- ```ts
589
- export const prerenderPaths = ['/']
590
-
591
- export const { renderPage } = SSR.entry(config, Post, { buildId, prerendered: prerenderPaths })
592
- ```
593
-
594
- A prerendered file the entry was not told of is refused at any other query,
595
- and the reason says so.
596
-
597
- Until the bundle runs, a file shows the state it was recorded with: the
598
- query reaches the Model only when the browser starts. A page whose first
599
- paint depends on its query (a search box filled from `?q=`) is better
600
- rendered per request, which records the query and resumes with nothing
601
- redrawn; `examples/foldkit/domains-plus` prerenders nothing for that reason.
602
-
603
804
  A generated site also wants a sitemap and a `robots.txt` that names it.
604
805
  `SSR.sitemap` takes the pages, with a `modified` date where one is known, and
605
806
  `SSR.robots` the origin:
@@ -628,7 +829,7 @@ The application describes its site in a module (`src/site.ts`) and the plugin
628
829
  evaluates it through a server, so `vite.config.ts` names a file, never
629
830
  application code:
630
831
 
631
- ```ts
832
+ ```ts standalone
632
833
  // vite.config.ts
633
834
  import { foldkit } from '@foldkit/vite-plugin'
634
835
  import { staticSite } from 'foldkit-ssr/vite'
@@ -645,23 +846,44 @@ Model is prepared per page returns its own); `paths` may be a thunk that seeds
645
846
  and lists; `head` is the same `head`; and `sitemap`/`robots` write their files
646
847
  from the generated pages. `files` is the host's layout — `'directory'`
647
848
  (`/about` as `about/index.html`, the default) or `'flat'` (`about.html`, for a
648
- host with clean addresses and no directory indexes):
849
+ host with clean addresses and no directory indexes). `plan` is one plan, or a
850
+ function of the path for a site of more than one application: a path then
851
+ resumes with the plan of the application `config` returns for it, so a site's
852
+ guides and its interactive pages can have Models of their own. A plan function
853
+ that throws fails the build and names the path; the sitemap and robots text
854
+ still list every path:
855
+
856
+ <!-- docs-check standalone use ssr-app
857
+ import { Resume, SSR } from 'foldkit-ssr'
858
+ const Post = SSR.plan(App, {
859
+ id: 'post',
860
+ state: Projection.pick(App.model.route, App.model.draft),
861
+ })
862
+ -->
649
863
 
650
864
  ```ts
651
865
  // src/site.ts
866
+ import { Style } from 'foldkit-mixins'
652
867
  import type { SiteModule } from 'foldkit-ssr/vite'
653
868
  export const site = {
654
869
  origin: 'https://example.com',
655
870
  paths: ['/', '/about'],
656
- config: { Model, init, update, view, container: null, routing },
657
- plan,
658
- head: rendered => `<style>${Style.usedIn(rendered.html)}</style>`,
871
+ config,
872
+ plan: Post,
873
+ head: (_rendered, drawn) => `<style>${Style.usedDrawn(drawn)}</style>`,
659
874
  files: 'directory',
660
875
  sitemap: true,
661
876
  robots: true,
662
877
  } satisfies SiteModule
663
878
  ```
664
879
 
880
+ `staticSite({ site, plugins })` loads the site module with `plugins`: the build
881
+ renders the pages from a Vite server of its own, which has none of the
882
+ application's, so a plugin that changes what a view draws must be passed here
883
+ too. Foldkit's view-identity branding is one: the browser compares the identity
884
+ markers it computes with the page's, and a page drawn without them is rebuilt
885
+ element by element rather than adopted, silently in a production build.
886
+
665
887
  `emit` adds files made from the generated pages, written beside them: what the
666
888
  pages reference and the build must also serve, such as the image variants
667
889
  their `srcset`s name (`foldkit-media`'s `materialize`). It takes the pages and
@@ -675,6 +897,78 @@ emitted)` writes the emitted files as the plugin does. `fileFor(path, layout)` m
675
897
  one path to the file a host serves it from, so a caller writes the files
676
898
  itself; `generateStaticSite` refuses two paths that would claim one file.
677
899
 
900
+ ### Pages rendered once, at build: `prerendered`
901
+
902
+ A page that is the same for every visitor need not be rendered by the
903
+ server at all. Rendered once when the application is built, it is a file
904
+ the host serves before any server code runs: on Workers, a static asset,
905
+ which costs no CPU.
906
+
907
+ Foldkit's Vite plugin prerenders pages through the server entry itself
908
+ (`ssr.build.prerender`), so `SSR.entry` cannot tell a build's request from a
909
+ visitor's. Name those paths in `prerendered`, and export the same list as
910
+ `prerenderPaths`, which the plugin reads:
911
+
912
+ ```ts
913
+ export const prerenderPaths = ['/']
914
+
915
+ export const { renderPage } = SSR.entry(config, Post, { buildId, prerendered: prerenderPaths })
916
+ ```
917
+
918
+ ```ts
919
+ // vite.config.ts
920
+ import { foldkit } from '@foldkit/vite-plugin'
921
+
922
+ foldkit({
923
+ ssr: {
924
+ serverEntry: '/src/entry.server.ts',
925
+ clientEntry: '/src/entry.ts',
926
+ build: { prerender: true },
927
+ },
928
+ })
929
+ ```
930
+
931
+ A file is given to every visitor, so a prerendered page is held to the rule
932
+ `cache` keeps a page by, and stricter on headers, since a file cannot vary:
933
+
934
+ ```text
935
+ render "/" -> every read through pageReader public?
936
+ -> no request header read, not even an absent one?
937
+ -> headers set nothing, status 200?
938
+ -> yes: the page, with no headers of its own, written to a file
939
+ -> no: renderPage rejects naming the read, header or status,
940
+ and the build fails
941
+ ```
942
+
943
+ ```text
944
+ foldkit-ssr: / is prerendered, a file every visitor is given, but it read the
945
+ request's cookie header; render it per request instead (leave it out of prerendered)
946
+ ```
947
+
948
+ A read made other than through `pageReader` is not seen. The rule is checked
949
+ on every render of the path, a request for it in development included, and
950
+ the page cache is not consulted for it.
951
+
952
+ The page is fresh as of the build, and the server never renders it again.
953
+ Its resumed Model says when each read was made, so a browser whose Remote
954
+ freshness has a `maxAge` (`RemotePolicy.staleWhileRevalidate`) reads again,
955
+ at boot, every read older than that. The client refreshes the data through
956
+ Remote, which is cheap; only a deploy renders the page anew.
957
+
958
+ A request for a prerendered path with no query records its path alone, as
959
+ `SSR.generate` does, so the file resumes at `/?q=…` too, and the application
960
+ starts from that URL. A prerendered file the entry was not told of is
961
+ refused at any other query, and the reason says so.
962
+
963
+ Until the bundle runs, a file shows the state it was recorded with: the
964
+ query reaches the Model only when the browser starts. And the host, not the
965
+ entry, decides which requests get the file: Workers static assets match by
966
+ path alone, so a prerendered `/` answers `/?q=…` as well, before the Worker
967
+ runs. A page whose first paint depends on its query (a search box filled from
968
+ `?q=`) is better rendered per request, which records the query and resumes
969
+ with nothing redrawn. `examples/foldkit/domains-plus` prerenders nothing for
970
+ that reason, and because its pages read the cart cookie.
971
+
678
972
  ## Checking what the browser will read
679
973
 
680
974
  The view check sees what the first render shows. A Surface can read a field the
@@ -682,6 +976,10 @@ first view never shows: a like button's state, a menu's contents. Name the
682
976
  Surfaces the browser may activate, and the fields that may start from the
683
977
  baseline on purpose:
684
978
 
979
+ <!-- docs-check standalone use ssr-app
980
+ import { Resume, SSR } from 'foldkit-ssr'
981
+ -->
982
+
685
983
  ```ts
686
984
  const Post = SSR.plan(App, {
687
985
  id: 'post',
@@ -695,13 +993,63 @@ const Post = SSR.plan(App, {
695
993
  ```
696
994
 
697
995
  `SSR.render` then refuses the plan, naming the Surface and the field, when an
698
- active Surface reads a field that is in neither `state` nor `local`, is
699
- activated by one, reads data no part of the plan resumes, or would activate
996
+ active Surface reads a field that is in none of `state`, `restored` or `local`,
997
+ is activated by one, reads data no part of the plan resumes, or would activate
700
998
  differently from the Model the browser starts from. The check runs for the
701
999
  server's Model, because a Surface's reads follow its params.
702
1000
  `SSR.inspect(plan, model)` returns the same findings as data, for a test or a
703
1001
  debugging session: for each Surface, whether it is active, and where each read
704
- comes from, `state`, `local` or `missing`.
1002
+ comes from, `state`, `restored`, `local` or `missing`.
1003
+
1004
+ ### Fields the browser reads again
1005
+
1006
+ A field a URL or cookie mirror owns is one the browser can read for itself, so
1007
+ the envelope need not carry it. Name it in `restored` and give `restore` a
1008
+ function applying the browser's values before the first render:
1009
+
1010
+ <!-- docs-check standalone
1011
+ import { Schema } from 'effect'
1012
+ import { defineMessageUnion } from 'foldkit/message'
1013
+ import { Mirror } from 'foldkit-mirror'
1014
+ import { Projection, Surface } from 'foldkit-surface'
1015
+ import { SSR } from 'foldkit-ssr'
1016
+
1017
+ const Model = Schema.Struct({
1018
+ route: Schema.String,
1019
+ results: Schema.Array(Schema.String),
1020
+ query: Schema.String,
1021
+ tld: Schema.String,
1022
+ })
1023
+ type Model = typeof Model.Type
1024
+ const initial: Model = { route: '/', results: [], query: '', tld: '' }
1025
+ const App = Surface.application({
1026
+ Model,
1027
+ Message: defineMessageUnion({ Searched: {} }),
1028
+ initial,
1029
+ update: (model: Model) => ({ model }),
1030
+ })
1031
+ const SearchInUrl = Mirror.url(App, { name: 'search', fields: [App.model.query, App.model.tld] })
1032
+ const SearchFilters = App.surface('SearchFilters', {
1033
+ model: ({ model }) => ({ query: model.query, tld: model.tld }),
1034
+ })
1035
+ -->
1036
+
1037
+ ```ts
1038
+ const SearchPlan = SSR.plan(App, {
1039
+ id: 'search',
1040
+ state: Projection.pick(App.model.route, App.model.results),
1041
+ restored: [App.model.query, App.model.tld],
1042
+ restore: model => SearchInUrl.reduce(model, window.location.href),
1043
+ surfaces: [Surface.at(SearchFilters, undefined)],
1044
+ })
1045
+ ```
1046
+
1047
+ Each restored path is handed the server's value for the coverage check, since
1048
+ the browser reads the same address or cookie; a path that `state` also sends is
1049
+ refused. The first render differs from the served page only where the browser's
1050
+ values differ from the server's, and Foldkit rebuilds that part, as a
1051
+ navigation would. `restore` runs in the browser alone, before adoption, and may
1052
+ throw; the page is then contained and reported as `Invalid`.
705
1053
 
706
1054
  A `Surface.each` family is one entry of `surfaces`: the envelope carries its
707
1055
  parent's reads with its instances', and coverage inspects each instance by key
@@ -716,6 +1064,10 @@ server read, most of which the page never shows. A **part** is a package's own
716
1064
  contribution to the envelope: it captures what the plan's active Surfaces read,
717
1065
  and restores it in the browser.
718
1066
 
1067
+ <!-- docs-check standalone use ssr-app
1068
+ import { Resume, SSR } from 'foldkit-ssr'
1069
+ -->
1070
+
719
1071
  ```ts
720
1072
  const Post = SSR.plan(App, {
721
1073
  id: 'post',
@@ -739,6 +1091,12 @@ An article body, a product description, highlighted code: a part of the page no
739
1091
  Message changes need not render in the browser at all, and what it reads need
740
1092
  not be sent. Mark it with `SSR.static`:
741
1093
 
1094
+ <!-- docs-check
1095
+ import type { Html } from 'foldkit/html'
1096
+
1097
+ declare const PostActionsView: (model: Model, h: HtmlBuilder<Message>) => Html
1098
+ -->
1099
+
742
1100
  ```ts
743
1101
  const view = (model: Model, h: HtmlBuilder<Message>) => ({
744
1102
  title: 'Post', // not the post's title: the browser does not have it
@@ -764,6 +1122,28 @@ needs that is not in the page, say after a Message shows one, is reported
764
1122
  ([`StaticRegionMissing`](#diagnostics), once per page) and rendered in the
765
1123
  browser.
766
1124
 
1125
+ `ih` is `HtmlBuilder<never>`, so an attribute that binds one of the page's
1126
+ Messages does not compile in it. A Slot's attributes are typed with the page's
1127
+ Message whatever its Mixins add, so a Style looks like a handler to the
1128
+ compiler. Pass them through `SSR.unbound`, which types them as binding nothing
1129
+ and throws, when the region is drawn, on a handler or a Submodel's attribute
1130
+ among them:
1131
+
1132
+ <!-- docs-check
1133
+ import type { SlotBuilder } from 'foldkit-mixins'
1134
+
1135
+ declare const slots: { readonly title: SlotBuilder<Message> }
1136
+ declare const model: Model
1137
+ -->
1138
+
1139
+ ```ts
1140
+ SSR.static('post-title', ih => [ih.h1(SSR.unbound(slots.title.attrs()), [model.post.title])])
1141
+ ```
1142
+
1143
+ Attributes `SSR.unbound` returns fit any builder, so one drawing can serve a
1144
+ region and the live page alike: type it over its builder's Message
1145
+ (`<M>(h: HtmlBuilder<M>) => …`).
1146
+
767
1147
  ### What only the browser has: `prepare`
768
1148
 
769
1149
  The server cannot send what it cannot see. What this browser stored (a
@@ -773,8 +1153,8 @@ rule above still holds, so the first client view is the served page, and
773
1153
  such state is split by whether the view draws it:
774
1154
 
775
1155
  ```text
776
- envelope ──▶ resumed Model ──▶ prepare: what the view does not draw ──▶ Runtime.hydrate adopts the served page
777
- └─▶ a Subscription reads the store ──▶ Message ──▶ update ──▶ drawn
1156
+ envelope ──► resumed Model ──► prepare: what the view does not draw ──► Runtime.hydrate adopts the served page
1157
+ └─► a Subscription reads the store ──► Message ──► update ──► drawn
778
1158
  ```
779
1159
 
780
1160
  `prepare: model => Effect` runs once, on the Model a page resumes, before
@@ -791,6 +1171,34 @@ Remote's durable outbox is the case it was made for. A page that makes
791
1171
  durable writes ([`foldkit-remote`'s outbox](../remote/README.md#a-write-that-outlives-the-page-outbox))
792
1172
  resumes from the outbox's `session`:
793
1173
 
1174
+ <!-- docs-check standalone
1175
+ import { Schema } from 'effect'
1176
+ import type { HtmlBuilder } from 'foldkit/html'
1177
+ import { defineMessageUnion } from 'foldkit/message'
1178
+ import { Remote } from 'foldkit-remote'
1179
+ import { Projection, Surface } from 'foldkit-surface'
1180
+ import { SSR } from 'foldkit-ssr'
1181
+
1182
+ const Model = Schema.Struct({ userId: Schema.String, remote: Remote.Model })
1183
+ type Model = typeof Model.Type
1184
+ const App = Surface.application({
1185
+ Model,
1186
+ Message: defineMessageUnion({ ...Remote.messages }),
1187
+ initial: { userId: 'ada', remote: Remote.initial },
1188
+ update: (model: Model) => ({ model }),
1189
+ })
1190
+ const Data = Remote.make({ model: App.model.remote, entities: [] })
1191
+ const plan = SSR.plan(App, { id: 'outbox', state: Projection.pick(App.model.userId) })
1192
+ const config = {
1193
+ Model,
1194
+ init: () => ({ model: App.initial }),
1195
+ update: (model: Model) => ({ model }),
1196
+ view: (_model: Model, h: HtmlBuilder<never>) => h.p([], []),
1197
+ container: null,
1198
+ }
1199
+ declare const buildId: string
1200
+ -->
1201
+
794
1202
  ```ts
795
1203
  import { outbox } from 'foldkit-remote/outbox'
796
1204
 
@@ -832,15 +1240,19 @@ only when it must, so the first interaction does not wait for the application's
832
1240
  code to start.
833
1241
 
834
1242
  ```text
835
- server each handler ──▶ its Message, encoded ──▶ a marker on the element + an entry in the envelope
1243
+ server each handler ──► its Message, encoded ──► a marker on the element + an entry in the envelope
836
1244
 
837
- browser event ──▶ the markers name its Messages ──▶ queued ──▶ the runtime boots
838
- ──▶ update runs the queue first
1245
+ browser event ──► the markers name its Messages ──► queued ──► the runtime boots
1246
+ ──► update runs the queue first
839
1247
  ```
840
1248
 
841
1249
  It rests on the fact that a Foldkit handler is already a Message value.
842
1250
  `Resume.builder(h)` is `h` that writes those values into the server's markup:
843
1251
 
1252
+ <!-- docs-check standalone use ssr-app
1253
+ import { Resume, SSR } from 'foldkit-ssr'
1254
+ -->
1255
+
844
1256
  ```ts
845
1257
  const view = (model: Model, h: HtmlBuilder<Message>) => {
846
1258
  const rh = Resume.builder(h)
@@ -887,6 +1299,10 @@ const LikeView = Surface.rootView(
887
1299
 
888
1300
  Then say when the runtime starts:
889
1301
 
1302
+ <!-- docs-check standalone use ssr-app
1303
+ import { Resume, SSR } from 'foldkit-ssr'
1304
+ -->
1305
+
890
1306
  ```ts
891
1307
  const Post = SSR.plan(App, {
892
1308
  id: 'post',
@@ -914,6 +1330,10 @@ boots it, so the Model ends where an eager boot would have taken it.
914
1330
  does. `SSR.render` refuses a deferred plan while one would be active,
915
1331
  naming each, until the plan declares it:
916
1332
 
1333
+ <!-- docs-check standalone use ssr-app
1334
+ import { Resume, SSR } from 'foldkit-ssr'
1335
+ -->
1336
+
917
1337
  ```ts
918
1338
  const Post = SSR.plan(App, {
919
1339
  id: 'post',
@@ -928,6 +1348,12 @@ boots it, so the Model ends where an eager boot would have taken it.
928
1348
  `managedResources` in the config given to `SSR.render`, as you would to
929
1349
  Foldkit. `boot` Commands run at boot, so a deferred page's `Mirror.kv`
930
1350
  restore waits for the first interaction.
1351
+ - **Its fields kept.** On a deferred plan, a field whose binding names its
1352
+ typing (a hole-form `OnInput` or `OnChange`; on a checkbox or radio, any
1353
+ named `OnChange`, `OnInput` or `OnClick`) must carry `rh.KeepTyped()`, or
1354
+ `SSR.render` refuses the page (`UnkeptField`), naming each: what is typed
1355
+ into it before boot would be lost at the first render. A page that starts
1356
+ `'now'` has the same gap for a shorter time and is not refused.
931
1357
 
932
1358
  ### Bundles whose code loads on demand
933
1359
 
@@ -936,7 +1362,7 @@ of the boot chunk. Name each in the config's `lazy` list. A sketch, after
936
1362
  `test/lazyFixture.ts`: `Upload` is the lazy bundle, `PlacedUpload` its
937
1363
  placement, and `placements` their `Bundle.assemble`:
938
1364
 
939
- ```ts
1365
+ ```ts sketch
940
1366
  const config = {
941
1367
  Model,
942
1368
  init: () => placements.init({ title: 'Uploads', upload }),
@@ -953,7 +1379,22 @@ const config = {
953
1379
 
954
1380
  The server loads the code before it renders, so the page carries the real
955
1381
  view. The browser loads it before it boots and answers from the markers
956
- meanwhile, whatever `start` says. A binding inside a placement dispatches the
1382
+ meanwhile, whatever `start` says.
1383
+
1384
+ A list loads whole on every page. When each route has code of its own, give
1385
+ `lazy` as a function of the Model instead, and only what the page draws loads:
1386
+
1387
+ ```ts sketch
1388
+ lazy: model => Routing.codeFor(model.route), // Routing = Site.routing({ pages, … })
1389
+ ```
1390
+
1391
+ The server asks it with the Model the page is drawn from (`init`'s, after
1392
+ `SSR.entry`'s `prepare`), and runs `init` once for it; the browser asks it
1393
+ with the resumed Model. The two must name the same bundles, or the render
1394
+ fails with `LazyDependsOnUnsentState`: send in the plan's `state` what `lazy`
1395
+ reads. A page on another route fetches none of this route's code, and
1396
+ `Site.routing`'s `preload` fetches it when the reader points at a link there
1397
+ (`foldkit-site`'s README, "Code split by route"). A binding inside a placement dispatches the
957
1398
  parent's Message, as Foldkit's own handlers do, so the plan's Surface lists the
958
1399
  wrapper variant, `Message.GotUploadMessage`.
959
1400
 
@@ -964,14 +1405,20 @@ later, and hydration re-asserts each field's value to the Model's: what was
964
1405
  typed in between would vanish. A field marked `rh.KeepTyped()` keeps it,
965
1406
  whatever the plan's `start`:
966
1407
 
1408
+ <!-- docs-check
1409
+ declare const h: HtmlBuilder<Message>
1410
+ declare const model: Model
1411
+ const rh = Resume.builder(h)
1412
+ -->
1413
+
967
1414
  ```ts
968
1415
  rh.input([rh.Value(model.draft), rh.OnInput(Message.ChangedDraft), rh.KeepTyped()])
969
1416
  ```
970
1417
 
971
1418
  ```text
972
- parse ──▶ typing (the field holds it) ──▶ script: SSR.hydrate reads the marked fields
973
- ──▶ each changed one becomes its OnInput Message, first in the queue
974
- ──▶ first render adopts the served page ──▶ value and caret put back ──▶ update
1419
+ parse ──► typing (the field holds it) ──► script: SSR.hydrate reads the marked fields
1420
+ ──► each changed one becomes its OnInput Message, first in the queue
1421
+ ──► first render adopts the served page ──► value and caret put back ──► update
975
1422
  ```
976
1423
 
977
1424
  There is no inline script: the field itself holds what was typed, and an
@@ -990,13 +1437,18 @@ bundle is replayed once the bundle's code has loaded.
990
1437
 
991
1438
  Only a field the page can replay may be marked: an `input` that takes text, a
992
1439
  `textarea` or a `select`, built by `rh` (`rh.input`, not `h.input`), with
993
- `OnInput` or `OnChange` given a Message member. The resumable builder marks
1440
+ `OnInput` or `OnChange` given a Message member; or a checkbox or radio, whose
1441
+ `checked` is compared with what the server rendered and replays its `OnChange`
1442
+ (else `OnInput`, else `OnClick`) Message, in either form. A radio the person
1443
+ moved off replays nothing, since the browser sent it no change; the one now
1444
+ checked replays its own. The resumable builder marks
994
1445
  the bindings of the elements it builds; on an element `h` builds, the hole
995
1446
  forms are plain closures to the page and nothing names the Message to replay.
996
1447
  Anything else is refused on the server (`UnkeepableField`), naming the
997
1448
  element. What is not kept: an unmarked field (re-asserted to the served value,
998
1449
  as before); a key press or click before the script (the browser's own, so a
999
- form submitted then posts, which `fallback: 'server'` answers); a page that is
1450
+ form submitted then posts, which `fallback: 'server'` answers; under
1451
+ [the loader](#the-runtime-on-intent-foldkit-ssrloader) a marked one is held); a page that is
1000
1452
  contained, declined or stale; and an IME composition in progress at boot,
1001
1453
  which the first render's reset ends, though its text is kept. A value the
1002
1454
  browser restored into the field on a reload or a history visit is kept like
@@ -1023,6 +1475,66 @@ refused at any query but its own. Markup such a script changes is the
1023
1475
  served page no longer, and Foldkit reconciles it at hydration to the Model's
1024
1476
  first render.
1025
1477
 
1478
+ ### The runtime on intent: `foldkit-ssr/loader`
1479
+
1480
+ `start` defers the runtime's boot, not its code: the entry script still
1481
+ imports the application, so the whole chunk is fetched and evaluated at load.
1482
+ `foldkit-ssr/loader` is an entry script that imports nothing of `effect`,
1483
+ Foldkit or the application (about 2 KB brotli), and runs the chunk when the
1484
+ plan's `start` says:
1485
+
1486
+ ```ts sketch
1487
+ // src/client/loader.ts, the page's entry script
1488
+ import { load } from 'foldkit-ssr/loader'
1489
+
1490
+ load({ runtime: () => import('./entry.js') }) // entry.ts calls SSR.hydrate
1491
+ ```
1492
+
1493
+ ```text
1494
+ load ──► read start from the envelope
1495
+ 'now' ──► run the chunk
1496
+ 'idle' ──► fetch the chunk now ──► idle after load, chunk here: run it
1497
+ 'on-interaction' ──► fetch the chunk now ──► first intent: run it
1498
+ until SSR.hydrate takes over: a marked event ──► held (a submission prevented)
1499
+ SSR.hydrate ──► starts now ──► answers each held event from the markers, once
1500
+ ```
1501
+
1502
+ - **`start` stays the plan's.** The server writes it into the envelope, and
1503
+ the loader adds no policy of its own; the chunk it runs starts at once,
1504
+ since the loader already waited as the plan said.
1505
+ - **Intent** is a pointer over or down, focus, or a key on an element the
1506
+ server marked (a binding of any event, or a kept field), or under
1507
+ `'on-interaction'` a scroll. A pointer crossing unmarked text runs nothing;
1508
+ a reader who only reads is covered by `'idle'`.
1509
+ - **Held, then answered once.** An event of a type the markers name, on a
1510
+ marked element, is held until `SSR.hydrate` claims the loader; a form's
1511
+ submission is prevented while held. `SSR.hydrate` answers each from the
1512
+ markers, as it answers events on a deferred page, so it reaches `update`
1513
+ once. An event on a kept field is not held: the field keeps it in its own
1514
+ state, which `SSR.hydrate` reads.
1515
+ - **Released, never both.** A held event the runtime has not taken 3 s after
1516
+ it happened (`UNTIL_LIMIT_MS`) is released: a submission goes to the
1517
+ browser (`requestSubmit`, with its submitter), so a GET form or a
1518
+ `fallback: 'server'` form still works; anything else is dropped. A chunk
1519
+ that fails to load releases everything at once and holds nothing after,
1520
+ and a page that does not resume (another build, declined, contained)
1521
+ releases what was held as `SSR.hydrate` refuses it.
1522
+ - **Fetched without running.** With `runtimeChunk` from `foldkit-ssr/vite`
1523
+ naming the same module, a client build writes the chunk's address into the
1524
+ loader, which fetches it as it starts, at load and before any idle or intent,
1525
+ with `<link rel="modulepreload">`:
1526
+
1527
+ ```ts sketch
1528
+ plugins: [foldkit({ ssr: { clientEntry: '/src/client/loader.ts', … } }),
1529
+ runtimeChunk({ entry: '/src/client/entry.ts' })]
1530
+ ```
1531
+
1532
+ Fetching is not running: a press before the chunk runs still waits for its
1533
+ evaluation, which a page that evaluates at once (no loader) has begun
1534
+ already. Without it, or under the development server, the chunk is fetched
1535
+ as it runs. A modulepreload fetches that one file; a chunk the runtime shares
1536
+ with another dynamic import is fetched when the runtime runs.
1537
+
1026
1538
  ## Forms that work without scripts
1027
1539
 
1028
1540
  A form whose `OnSubmit` names a Message can be answered by the server, before
@@ -1031,6 +1543,40 @@ server can run it. This example is a to-do list, not the post page: its Model
1031
1543
  holds `draft` and `todos`, its Message `Added({ title })` and `Typed({ value
1032
1544
  })`, and the `TodoList` Surface lists both. The plan opts in:
1033
1545
 
1546
+ <!-- docs-check standalone
1547
+ import { Option, Schema } from 'effect'
1548
+ import type { HtmlBuilder } from 'foldkit/html'
1549
+ import { defineMessageUnion } from 'foldkit/message'
1550
+ import { Projection, Surface } from 'foldkit-surface'
1551
+ import { Resume, SSR } from 'foldkit-ssr'
1552
+
1553
+ const Model = Schema.Struct({
1554
+ draft: Schema.String,
1555
+ todos: Schema.Array(Schema.Struct({ title: Schema.String })),
1556
+ })
1557
+ type Model = typeof Model.Type
1558
+ const Message = defineMessageUnion({ Added: { title: Schema.String }, Typed: { value: Schema.String } })
1559
+ type Message = typeof Message.Type
1560
+ const App = Surface.application({
1561
+ Model,
1562
+ Message,
1563
+ initial: { draft: '', todos: [] },
1564
+ update: (model: Model) => ({ model }),
1565
+ })
1566
+ const TodoList = App.surface('TodoList', {
1567
+ model: ({ model }) => ({ draft: model.draft, todos: model.todos }),
1568
+ messages: [Message.Added, Message.Typed],
1569
+ })
1570
+ const config = {
1571
+ Model,
1572
+ init: () => ({ model: App.initial }),
1573
+ update: (model: Model, _message: Message) => ({ model }),
1574
+ view: (model: Model, h: HtmlBuilder<Message>) => ({ title: 'Todos', body: h.p([], [model.draft]) }),
1575
+ container: null,
1576
+ }
1577
+ declare const buildId: string
1578
+ -->
1579
+
1034
1580
  ```ts
1035
1581
  const Todos = SSR.plan(App, {
1036
1582
  id: 'todos',
@@ -1040,6 +1586,12 @@ const Todos = SSR.plan(App, {
1040
1586
  })
1041
1587
  ```
1042
1588
 
1589
+ <!-- docs-check
1590
+ declare const h: HtmlBuilder<Message>
1591
+ declare const model: Model
1592
+ const rh = Resume.builder(h)
1593
+ -->
1594
+
1043
1595
  ```ts
1044
1596
  rh.form(
1045
1597
  [rh.OnSubmit(Message.Added({ title: model.draft }))],
@@ -1063,9 +1615,9 @@ and one given `Method('post')` posts no Message, which the entry answers
1063
1615
  `400`.
1064
1616
 
1065
1617
  ```text
1066
- POST ──▶ decode the Message ──▶ set the posted fields into it (the typed `title`)
1067
- ──▶ init, prepare, then boot and its Commands ──▶ update, and every Command after it
1068
- ──▶ the page, rendered
1618
+ POST ──► decode the Message ──► set the posted fields into it (the typed `title`)
1619
+ ──► init, prepare, then boot and its Commands ──► update, and every Command after it
1620
+ ──► the page, rendered
1069
1621
  ```
1070
1622
 
1071
1623
  The Message must be one the page's active Surfaces list. Commands run under the
@@ -1111,8 +1663,8 @@ one that orders or sends something. `answerPost: 'redirect'` answers the post
1111
1663
  (Post/Redirect/Get):
1112
1664
 
1113
1665
  ```text
1114
- POST /todos ──▶ update, and its Commands ──▶ 303, Location: /todos, headers(request, some(model))
1115
- GET /todos ──▶ init, prepare ──▶ the page, rendered
1666
+ POST /todos ──► update, and its Commands ──► 303, Location: /todos, headers(request, some(model))
1667
+ GET /todos ──► init, prepare ──► the page, rendered
1116
1668
  ```
1117
1669
 
1118
1670
  ```ts
@@ -1178,7 +1730,7 @@ the first frame shows whatever the server knew when it rendered.
1178
1730
  [example's](../../examples/foldkit/ssr) count, by the same route:
1179
1731
 
1180
1732
  ```text
1181
- request cookie ─▶ flags ─▶ init ─▶ Model.theme ─┬─ view draws it
1733
+ request cookie ─► flags ─► init ─► Model.theme ─┬─ view draws it
1182
1734
  └─ plan.state carries it, so the browser resumes with it
1183
1735
  ```
1184
1736
 
@@ -1242,9 +1794,10 @@ of:
1242
1794
 
1243
1795
  | `reason` | What it means | The fix |
1244
1796
  | -------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------- |
1245
- | `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 |
1797
+ | `ViewDependsOnUnsentState` | The view, or its head, renders differently from the browser's Model | Add the field the message names to `state`, name it `restored` with a `restore`, or stop the view reading it |
1798
+ | `LazyDependsOnUnsentState` | `lazy`, a function of the Model, names other bundles for the browser's Model than for the server's | Add the field it reads to `state`, or stop `lazy` reading it |
1246
1799
  | `UndeclaredStartup` | `init` returned Commands and the plan has no `boot` | Name them in `boot` |
1247
- | `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 |
1800
+ | `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 `restored` or `local`, or list the Message on the Surface |
1248
1801
  | `UnrestorablePart` | A part cannot restore its own capture | A bug in that part |
1249
1802
  | `DuplicateStaticRegion` | Two `SSR.static` regions share an id | Give each its own id |
1250
1803
  | `BindingInStaticRegion` | A handler inside an `SSR.static` region | Move the element out, into a Surface |
@@ -1252,7 +1805,8 @@ of:
1252
1805
  | `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 |
1253
1806
  | `EagerStartRequired` | A deferred plan would start a Subscription or Managed Resource late | Declare it in `deferrable`, or start `'now'` |
1254
1807
  | `VoidRootWithStyles` | `styles` were given for a view whose root is void and holds nothing | Put the styles in the template's head with `SSR.generate`, or return an element root |
1255
- | `UnkeepableField` | `KeepTyped` on an element that holds no typed value, one `h` built rather than `rh`, or with no `OnInput`/`OnChange` given a Message member | Mark only a text `input`, `textarea` or `select` that `rh` builds, and give its binding the Message's member |
1808
+ | `UnkeepableField` | `KeepTyped` on an element that holds nothing typed or ticked, one `h` built rather than `rh`, or with no binding that names its Message | Mark only a text `input`, `textarea`, `select`, checkbox or radio that `rh` builds, and give its binding the Message's member |
1809
+ | `UnkeptField` | A deferred plan has a field whose binding names its typing and no `KeepTyped` | Add `rh.KeepTyped()`, or start `'now'` |
1256
1810
  | `UngeneratablePath` | `SSR.generate` was given a path no file can be served at | Leave out the query and fragment; keep paths to distinct files |
1257
1811
 
1258
1812
  In the browser, `SSR.hydrate` checks in Foldkit's order: the build id first,
@@ -1281,8 +1835,20 @@ page's id. It never waits longer than `UNTIL_LIMIT_MS` (3 s). The CMS site
1281
1835
  waits for the route's read and its Blocks' reads, which its `Site.answered`
1282
1836
  checks with `RemoteData.answered` and `QueryBlock.active(...).answered`:
1283
1837
 
1838
+ <!-- docs-check standalone use ssr-app
1839
+ import { Resume, SSR } from 'foldkit-ssr'
1840
+ const Post = SSR.plan(App, {
1841
+ id: 'post',
1842
+ state: Projection.pick(App.model.route, App.model.draft),
1843
+ })
1844
+ import type { Diagnostic } from 'foldkit-ssr'
1845
+ declare const when: (document: Document) => boolean
1846
+ declare const Site: { readonly answered: (model: Model) => boolean }
1847
+ declare const send: (diagnostic: Diagnostic) => Effect.Effect<void>
1848
+ -->
1849
+
1284
1850
  ```ts
1285
- SSR.hydrate(config, plan, { buildId, when, otherwise: 'render', until: Site.answered })
1851
+ SSR.hydrate(config, Post, { buildId, when, otherwise: 'render', until: Site.answered })
1286
1852
  ```
1287
1853
 
1288
1854
  The served page stays as it was served while it waits: its links are plain
@@ -1310,9 +1876,9 @@ posted form's Commands included. `SSR.generate` reports to the reporter in
1310
1876
  its Effect's context.
1311
1877
 
1312
1878
  ```ts
1313
- SSR.hydrate(config, plan, { buildId, diagnostics: diagnostic => send(diagnostic) })
1879
+ SSR.hydrate(config, Post, { buildId, diagnostics: diagnostic => send(diagnostic) })
1314
1880
 
1315
- SSR.entry(config, plan, {
1881
+ SSR.entry(config, Post, {
1316
1882
  buildId,
1317
1883
  diagnostics: (diagnostic, request) =>
1318
1884
  Effect.logError(`${request.method} ${request.url}: ${diagnostic.message}`),
@@ -1391,6 +1957,13 @@ for a plan, as `Surface.when(PostActions, App.model.route, AppRoute.Post, route
1391
1957
  => ({ id: route.id }))` places one in
1392
1958
  [the coverage example](#checking-what-the-browser-will-read).
1393
1959
 
1960
+ <!-- docs-check standalone
1961
+ import { Schema } from 'effect'
1962
+ import { defineMessageUnion } from 'foldkit/message'
1963
+ import { defineRouteUnion } from 'foldkit/route'
1964
+ import { Remote } from 'foldkit-remote'
1965
+ -->
1966
+
1394
1967
  ```ts
1395
1968
  const AppRoute = defineRouteUnion({ Home: {}, Post: { id: Schema.String }, NotFound: {} })
1396
1969