foldkit-ssr 0.9.0 → 0.11.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 (52) hide show
  1. package/README.md +402 -36
  2. package/dist/{client-F16QT0sc.d.ts → client-qmdYY-Eb.d.ts} +15 -5
  3. package/dist/client-qmdYY-Eb.d.ts.map +1 -0
  4. package/dist/client.d.ts +5 -5
  5. package/dist/client.js +126 -54
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js +12 -0
  9. package/dist/context.js.map +1 -1
  10. package/dist/diagnostics.d.ts +2 -2
  11. package/dist/diagnostics.js +8 -1
  12. package/dist/diagnostics.js.map +1 -1
  13. package/dist/index.d.ts +127 -25
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +317 -59
  16. package/dist/index.js.map +1 -1
  17. package/dist/keep.d.ts +36 -0
  18. package/dist/keep.d.ts.map +1 -0
  19. package/dist/keep.js +109 -0
  20. package/dist/keep.js.map +1 -0
  21. package/dist/{listen-zNd0IIAT.d.ts → listen-DaUPRKVR.d.ts} +4 -2
  22. package/dist/listen-DaUPRKVR.d.ts.map +1 -0
  23. package/dist/listen.d.ts +2 -2
  24. package/dist/listen.js +31 -23
  25. package/dist/listen.js.map +1 -1
  26. package/dist/pageCache-DO0pOgnc.d.ts +80 -0
  27. package/dist/pageCache-DO0pOgnc.d.ts.map +1 -0
  28. package/dist/pageCache.d.ts +2 -0
  29. package/dist/pageCache.js +112 -0
  30. package/dist/pageCache.js.map +1 -0
  31. package/dist/{requestContext-D9nsbGSJ.d.ts → requestContext-DmwmQeci.d.ts} +12 -2
  32. package/dist/requestContext-DmwmQeci.d.ts.map +1 -0
  33. package/dist/requestContext.d.ts +2 -2
  34. package/dist/requestContext.js +30 -13
  35. package/dist/requestContext.js.map +1 -1
  36. package/dist/{resumable-BWItJsxF.d.ts → resumable-BPN_qQHU.d.ts} +33 -12
  37. package/dist/resumable-BPN_qQHU.d.ts.map +1 -0
  38. package/dist/resumable.d.ts +2 -2
  39. package/dist/resumable.js +51 -8
  40. package/dist/resumable.js.map +1 -1
  41. package/dist/{shared-v1u-OEQI.d.ts → shared-CJN-m58Z.d.ts} +37 -10
  42. package/dist/shared-CJN-m58Z.d.ts.map +1 -0
  43. package/dist/shared.d.ts +2 -2
  44. package/dist/shared.js +31 -7
  45. package/dist/shared.js.map +1 -1
  46. package/dist/vite.d.ts +1 -1
  47. package/package.json +9 -9
  48. package/dist/client-F16QT0sc.d.ts.map +0 -1
  49. package/dist/listen-zNd0IIAT.d.ts.map +0 -1
  50. package/dist/requestContext-D9nsbGSJ.d.ts.map +0 -1
  51. package/dist/resumable-BWItJsxF.d.ts.map +0 -1
  52. package/dist/shared-v1u-OEQI.d.ts.map +0 -1
package/README.md CHANGED
@@ -70,6 +70,9 @@ and the checks that the browser can start from it.
70
70
  state of its own, and every change after boot goes through `update`.
71
71
  - **Data belongs to its package.** Remote's store crosses through Remote's own
72
72
  part (`Remote.resume`), which decides what to capture.
73
+ - **What the browser stored stays the browser's.** The server cannot read a
74
+ queue kept in `localStorage`, so it is never in the page: it joins after
75
+ the first frame ([`prepare`](#what-only-the-browser-has-prepare)).
73
76
 
74
77
  ## The mental model
75
78
 
@@ -197,9 +200,15 @@ const html = SSR.page(template, result, {
197
200
  })
198
201
  ```
199
202
 
203
+ With `foldkit-mixins/vite`, the stylesheet is a hashed file, and the page
204
+ links it from the document's head instead (`renderDocument`'s `head`):
205
+ `<link rel="stylesheet" href="${href}" data-foldkit-styles-href>`. A link in
206
+ the head is fetched before the first paint; `styles`, below, is written as the
207
+ root's last children, so a large page paints unstyled until it has all arrived.
208
+
200
209
  A served page has no template head to write to, so `SSR.render`, `SSR.entry`
201
210
  and `SSR.handle` take the same function as `styles` instead, carried as the
202
- rendered root's last child. `foldkit-mixins/foundations` writes the theme
211
+ rendered root's last children. `foldkit-mixins/foundations` writes the theme
203
212
  into `index.html` only, never into a page the server renders, so a served
204
213
  page carries the theme's stylesheet here too, beside the classes it draws
205
214
  (`examples/foldkit/ssr/src/renderPage.ts`):
@@ -212,10 +221,14 @@ SSR.entry(config, plan, { buildId, styles })
212
221
  ```
213
222
 
214
223
  Without it, every served page flashes unstyled until the script runs. Keep
215
- `styles` to `<style>`: hydration adopts the nodes around it and drops it on
216
- its first patch, and the browser's Styles skip what it already carries. A void root holds no children, so styles for one are
217
- refused with `VoidRootWithStyles`, naming the tag. Anything a head owns
218
- (`meta`, links) stays with `SSR.generate`.
224
+ `styles` to `<style>` and stylesheet `<link>`s. The view does not draw them,
225
+ so hydration would remove them from the root, and a page that never renders
226
+ again would keep its classes without their rules; `SSR.hydrate` moves them
227
+ into the document's head before anything adopts the page, whether it resumes
228
+ or is contained, and the browser's Styles find them there and add nothing
229
+ 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`.
219
232
 
220
233
  `SSR.generate` takes the same `head`, and answers a `head` that throws `500`,
221
234
  as it does a render that fails. `SSR.entry` takes no `head`: the host owns
@@ -328,25 +341,68 @@ so a Model serialized by another deployment is never decoded. Asking Foldkit
328
341
  to expose that id is [proposal 4](../../docs/upstream-foldkit-ssr.md#proposal-4-expose-the-compiled-build-id).
329
342
 
330
343
  `GET` and `HEAD` render the page for the request's URL; an application with
331
- Flags passes `flags: request => ...`. `POST` is handled only for a plan with a
344
+ Flags passes `flags: request => ...`. `prepare: (model, request) => Effect`
345
+ turns the Model `init` gave into the one the page is rendered from, for what
346
+ must be read before the render (`Data.satisfy`, [below](#what-the-host-hands-the-page-ssrrequestcontext))
347
+ or taken from the request (a cookie). It runs for a posted form too, before
348
+ the Message is checked against the active Surfaces and `update` runs, so the
349
+ post starts from the Model the page it came from was drawn with, and one
350
+ entry, made once, serves every request. A `prepare` that fails is answered
351
+ `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
332
353
  [server fallback](#forms-that-work-without-scripts). `OPTIONS` is answered
333
354
  `204` and any other method `405`, each with the methods the entry answers in
334
355
  `allow`. A render that fails or throws, `flags` that reject, and a plan the
335
356
  render refuses are answered `500` with the reason reported
336
357
  ([`PageFailed`](#diagnostics)), never with a page the browser could not resume.
337
358
 
338
- `headers: request => ...` rides on the `Rendered` result, set over the host's
339
- own: a cache policy for a page that is one visitor's, or the CORS answer to a
340
- preflight, which reaches the entry and not the host.
359
+ `headers: (request, model) => ...` is set over the host's own on every
360
+ answer: a cache policy for a page that is one visitor's, the CORS answer to a
361
+ preflight, which reaches the entry and not the host, or a cookie written from
362
+ the Model. `model` is an `Option`: `some` of the Model the server reached for
363
+ a rendered page (a posted form's, after `update`), `none` for an answer that
364
+ rendered nothing (`OPTIONS`, a `405`, a refused post, a `500`).
365
+
366
+ ```ts
367
+ SSR.entry(config, Post, {
368
+ buildId,
369
+ headers: (_request, model) => ({
370
+ 'cache-control': 'private, no-store',
371
+ vary: 'cookie',
372
+ ...Option.match(model, {
373
+ onNone: () => ({}),
374
+ onSome: ({ post }) => ({
375
+ 'set-cookie': `last-read=${encodeURIComponent(post.id)}; Path=/; SameSite=Lax`,
376
+ }),
377
+ }),
378
+ }),
379
+ })
380
+ ```
381
+
382
+ A `headers` that throws is answered `500`, as a failed render is, and so is
383
+ one that sets what is not the application's to set: a name or value `Headers`
384
+ refuses (a value holding CR or LF cannot smuggle a second header in), a
385
+ header that frames the response (`content-length`, `transfer-encoding`,
386
+ `connection` and their kin), or `location`. A value from the Model still
387
+ needs encoding for its header, as `encodeURIComponent` does here: a cookie's
388
+ value holds no `;` or `,`.
389
+
390
+ Every rendered page is answered `200` unless `status: (model, request) =>
391
+ ...` says otherwise. It is given the Model the server reached, which already
392
+ says which route it is, so a not-found page is answered `404` without parsing
393
+ the URL twice:
341
394
 
342
395
  ```ts
343
396
  SSR.entry(config, Post, {
344
397
  buildId,
345
- headers: () => ({ 'cache-control': 'private, no-store', vary: 'cookie' }),
398
+ status: model =>
399
+ AppRoute.match(model.route, { Home: () => 200, Post: () => 200, NotFound: () => 404 }),
346
400
  })
347
401
  ```
348
402
 
349
- A `headers` that throws is answered `500`, as a failed render is.
403
+ The page is rendered and resumed as any other; only the response's status
404
+ changes. A status outside `200`–`599`, a `204`, `205` or `304` that cannot
405
+ carry the page, or a `status` that throws, is answered `500` and reported.
350
406
 
351
407
  What the page says of itself (`meta`) and per-page `head` markup are written
352
408
  into a template's head, which the host owns here: a plan with `meta` is
@@ -366,7 +422,6 @@ by `handleRequest`, reads it back:
366
422
 
367
423
  ```ts
368
424
  import { Effect, Option, type Layer } from 'effect'
369
- import { Responded } from 'foldkit/experimental/server'
370
425
  import type { RemoteClient, RemoteUnauthenticated } from 'foldkit-remote'
371
426
  import { SSR } from 'foldkit-ssr'
372
427
 
@@ -378,19 +433,15 @@ export const PageContext = SSR.requestContext<{
378
433
  // The host, a Worker's fetch say:
379
434
  // pages.fetch(PageContext.attach(request, { reader: pageReader(page)(request, env) }))
380
435
 
381
- // The server entry. `actives` is the record `Data.wiring` takes.
382
- export const renderPage = (request: Request) =>
383
- Option.match(PageContext.of(request), {
384
- onNone: async () => Responded(new Response('No reader for this page.', { status: 500 })),
385
- onSome: async ({ reader }) => {
386
- const model = await Effect.runPromise(
387
- Data.satisfy(App.initial, actives).pipe(Effect.provide(reader)),
388
- )
389
- return SSR.entry({ ...config, init: () => ({ model }) }, Post, { buildId }).renderPage(
390
- request,
391
- )
392
- },
393
- })
436
+ // The server entry, made once. `actives` is the record `Data.wiring` takes.
437
+ export const { renderPage } = SSR.entry(config, Post, {
438
+ buildId,
439
+ prepare: (model, request) =>
440
+ Option.match(PageContext.of(request), {
441
+ onNone: () => Effect.fail(new Error('No reader for this page.')),
442
+ onSome: ({ reader }) => Data.satisfy(model, actives).pipe(Effect.provide(reader)),
443
+ }),
444
+ })
394
445
  ```
395
446
 
396
447
  The value is kept for that request alone, in a `WeakMap` on `globalThis`
@@ -409,6 +460,87 @@ serves. [`examples/auth`](../../examples/auth)'s `src/host.ts` is the whole
409
460
  site behind one handler; its development server, another process, attaches
410
461
  an HTTP reader instead.
411
462
 
463
+ ### Keeping pages: `cache`
464
+
465
+ A page drawn from its URL alone is the same page for everyone who asks for
466
+ that URL, and drawing it again costs the same every time. With `cache`, the
467
+ entry keeps such a page and answers the next request for it from a store:
468
+
469
+ ```text
470
+ GET url -> kept for this build and url, and the request lacks every header it read?
471
+ -> yes: the kept page
472
+ -> no: render, watching what the render reads
473
+ every read public, every header it read absent, no cookie set, 200?
474
+ -> keep it, cache-control: public, max-age=…, vary: <headers read>
475
+ -> otherwise cache-control: private, no-store
476
+ ```
477
+
478
+ ```ts
479
+ import { CacheStore } from 'foldkit-surface'
480
+
481
+ export const cached = SSR.entry(config, Post, {
482
+ buildId,
483
+ cache: { store: CacheStore.memory(), maxAge: '60 seconds' },
484
+ })
485
+ ```
486
+
487
+ Whether a page may be kept is decided from what its render read, not from
488
+ 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
490
+ every one of them was absent from the request, so it was drawn from the URL
491
+ alone. A header read by name (the cart cookie, say) that was absent goes in
492
+ `vary`, and the kept page serves only requests that lack it too: a request
493
+ with that cookie is drawn for itself, and is never kept. Reading every
494
+ header, cloning the request, or reading an `SSR.requestContext` (which may
495
+ say who is asking) keeps nothing. Handing the request itself to `fetch` or
496
+ `new Request` fails the render, since the platform cannot read the watched
497
+ request.
498
+
499
+ Reads count through `foldkit-remote-server`'s `pageReader`, which notes each
500
+ one (`PageReads`): the page is kept only when every read was public, for the
501
+ shortest of `maxAge` and their freshness, tagged with the rows they hold. A
502
+ write `serveFetch` answers purges, from the same store, the pages holding a
503
+ row it names. A read made other than through `pageReader` is not seen, so
504
+ `maxAge` is all that bounds it. A page whose `headers` set a cookie or a
505
+ `cache-control` of their own, one not `200`, and every post, are not kept;
506
+ an unkept page says `private, no-store` unless `headers` said otherwise.
507
+
508
+ The key is the build id and the full URL, so a deploy never serves another
509
+ build's page (the browser would refuse it anyway, as `OtherBuild`).
510
+ `CacheStore.workers(caches.default)` keeps pages in the Workers Cache API.
511
+
512
+ The host draws each page into its document, which parses the page again
513
+ (Foldkit's `injectIntoTemplate`), so a kept page would still cost that on
514
+ every request. Wrap the server entry's `renderDocument` in
515
+ `SSR.keptDocuments` and the document of a kept page is drawn once per set
516
+ of assets (the last 32 are held):
517
+
518
+ ```ts
519
+ import { renderDocument as renderShell, type DocumentRenderer } from 'foldkit/experimental/server'
520
+
521
+ export const renderDocument: DocumentRenderer = SSR.keptDocuments(renderShell)
522
+ ```
523
+
524
+ The checker draws a kept page again for each request it serves.
525
+ `cache.check` does so on every request a kept page serves, and where the
526
+ two differ reports `CachedPageDiffers` and answers with the page drawn
527
+ again: a development mode. Times stamped on the page (13 digits within a day
528
+ of now, as a read's `updatedAt`) are not compared. `SSR.checkCache(make,
529
+ requests)` is the same, for a test: `make` builds the entry from the
530
+ `cache` and `diagnostics` it is given, and each request is answered twice;
531
+ it rejects a difference, or a set of requests that kept no page. Give it
532
+ requests from more than one reader, a visitor's and one with a cookie:
533
+
534
+ ```ts
535
+ export const checked = SSR.checkCache(
536
+ options => SSR.entry(config, Post, { buildId, ...options }),
537
+ [
538
+ () => new Request('https://example.com/posts/1'),
539
+ () => new Request('https://example.com/posts/1', { headers: { cookie: 'session=abc' } }),
540
+ ],
541
+ )
542
+ ```
543
+
412
544
  ### At build time
413
545
 
414
546
  ```ts
@@ -437,8 +569,36 @@ a tuple, so `const [home, about] = pages` needs no check.
437
569
 
438
570
  A static host serves one file for every query, and for `/about` and `/about/`
439
571
  alike, so a generated page records its path alone: `/about?ref=mail` resumes
440
- the page generated for `/about`, and `/other` is refused. A server-rendered page
441
- records its path and query, and resumes only there.
572
+ the page generated for `/about`, and `/other` is refused. The page was made
573
+ without the query, and `init` does not run in the browser, so an application
574
+ with `routing` starts from the resumed Model given `routing.onUrlChange` of
575
+ the URL it is at, as from a navigation, and starts at once whatever its
576
+ `start`: one that reads the query (a search box in `?q=`) shows it, and the
577
+ part of the page that differs is redrawn; one that does not changes nothing.
578
+ The Message goes into the starting Model rather than after boot, so a URL
579
+ mirror does not write the served address back over the real one. A
580
+ server-rendered page records its path and query, and resumes only there.
581
+
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.
442
602
 
443
603
  A generated site also wants a sitemap and a `robots.txt` that names it.
444
604
  `SSR.sitemap` takes the pages, with a `modified` date where one is known, and
@@ -604,6 +764,57 @@ needs that is not in the page, say after a Message shows one, is reported
604
764
  ([`StaticRegionMissing`](#diagnostics), once per page) and rendered in the
605
765
  browser.
606
766
 
767
+ ### What only the browser has: `prepare`
768
+
769
+ The server cannot send what it cannot see. What this browser stored (a
770
+ queue of writes kept in `localStorage` or IndexedDB) and what this page
771
+ load mints (an id its writes are named by) exist only in the browser. The
772
+ rule above still holds, so the first client view is the served page, and
773
+ such state is split by whether the view draws it:
774
+
775
+ ```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
778
+ ```
779
+
780
+ `prepare: model => Effect` runs once, on the Model a page resumes, before
781
+ anything is adopted, and the runtime starts when it succeeds. Keep it to
782
+ what no view draws. What the view draws arrives after, as a Message,
783
+ reduced over whatever the Model is by then. A `prepare` that changes what is
784
+ drawn makes the first client view differ from the served page: Foldkit
785
+ rebuilds every element that differs, and a development build warns that the
786
+ server DOM did not match. It must not fail, as `when` must not throw. A page
787
+ drawn afresh (no served page, or `otherwise: 'render'`) starts from `init`,
788
+ as it would without a server render, and does not run it.
789
+
790
+ Remote's durable outbox is the case it was made for. A page that makes
791
+ durable writes ([`foldkit-remote`'s outbox](../remote/README.md#a-write-that-outlives-the-page-outbox))
792
+ resumes from the outbox's `session`:
793
+
794
+ ```ts
795
+ import { outbox } from 'foldkit-remote/outbox'
796
+
797
+ const durable = outbox(Data, { key: model => `outbox:${model.userId}`, scope: model => model.userId })
798
+
799
+ SSR.hydrate(config, plan, { buildId, prepare: durable.session })
800
+ ```
801
+
802
+ - **The server's page holds none of the queue.** `Remote.resume` carries no
803
+ outbox, and the server has no store to read.
804
+ - **`durable.session` mints the page's id and reads nothing.** A durable
805
+ write made before the queue is read is queued at once, not refused.
806
+ - **The queue arrives through the outbox's own Subscription.** It reads the
807
+ store after the first frame and sends `OutboxRead`, which keeps any write
808
+ made before it and saves it with the rest. The unsent writes then join the
809
+ page, and every tab on the key shows them.
810
+ - **Not `durable.restore`.** As `prepare`, it would read the store before
811
+ adoption and show the queue in a first view the server did not draw. As
812
+ the config's `flags`, it never runs: a resumed page does not run `init`.
813
+
814
+ [`examples/reference`](../../examples/reference) does this on Workers: a
815
+ note added while the server is out of reach survives a reload of the
816
+ Worker's page, shows in a second tab, and is sent once the server answers.
817
+
607
818
  ### Markup the browser adopts: `SSR.serving`
608
819
 
609
820
  `SSR.serving()` is true while the view call in progress is the server rendering a page (both
@@ -651,9 +862,10 @@ const view = (model: Model, h: HtmlBuilder<Message>) => {
651
862
  }
652
863
  ```
653
864
 
654
- `rh` differs from `h` in one place: `OnInput`, `OnChange`, `OnKeyDown` and
865
+ `rh` differs from `h` in two places: `OnInput`, `OnChange`, `OnKeyDown` and
655
866
  `OnKeyUp` also take a Message's own constructor, and the event fills the field
656
- it leaves open. The types check it where it is written: the member must be one
867
+ it leaves open; and `KeepTyped` marks a field whose early typing is kept
868
+ ([below](#typing-before-the-script-arrives)). The types check it where it is written: the member must be one
657
869
  of the view's Messages, and leave exactly one string field, or exactly `key`
658
870
  and `modifiers`. A closure still works. It is not data, so the page cannot
659
871
  answer that event itself and boots on it instead, letting the live page answer.
@@ -745,6 +957,72 @@ meanwhile, whatever `start` says. A binding inside a placement dispatches the
745
957
  parent's Message, as Foldkit's own handlers do, so the plan's Surface lists the
746
958
  wrapper variant, `Message.GotUploadMessage`.
747
959
 
960
+ ### Typing before the script arrives
961
+
962
+ A served page is editable as soon as it is parsed, but its script comes
963
+ later, and hydration re-asserts each field's value to the Model's: what was
964
+ typed in between would vanish. A field marked `rh.KeepTyped()` keeps it,
965
+ whatever the plan's `start`:
966
+
967
+ ```ts
968
+ rh.input([rh.Value(model.draft), rh.OnInput(Message.ChangedDraft), rh.KeepTyped()])
969
+ ```
970
+
971
+ ```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
975
+ ```
976
+
977
+ There is no inline script: the field itself holds what was typed, and an
978
+ `OnInput` Message carries the whole value, so the value when the script runs
979
+ says all the keystrokes would. A page with a Content Security Policy needs no
980
+ nonce for it. When the script runs, `SSR.hydrate` reads each marked field
981
+ whose value differs from what the server rendered and turns it into the
982
+ field's `OnInput` Message (else its `OnChange`), with the hole filled. These
983
+ go ahead of anything the page answers afterwards, once each, in document
984
+ order, so a page that waits to boot replays the early typing first. The first
985
+ render starts from the resumed Model, so it adopts every node and resets the
986
+ field; the field's value and selection are put back as it commits, and the
987
+ Message then finds the field already holding its value and writes nothing.
988
+ The caret stays where it was, and focus never moves. A field inside a lazy
989
+ bundle is replayed once the bundle's code has loaded.
990
+
991
+ Only a field the page can replay may be marked: an `input` that takes text, a
992
+ `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
994
+ the bindings of the elements it builds; on an element `h` builds, the hole
995
+ forms are plain closures to the page and nothing names the Message to replay.
996
+ Anything else is refused on the server (`UnkeepableField`), naming the
997
+ element. What is not kept: an unmarked field (re-asserted to the served value,
998
+ 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
1000
+ contained, declined or stale; and an IME composition in progress at boot,
1001
+ which the first render's reset ends, though its text is kept. A value the
1002
+ browser restored into the field on a reload or a history visit is kept like
1003
+ typing, since it is what the field shows.
1004
+
1005
+ `KeepTyped` answers the typing as soon as the script runs, not before. Until
1006
+ the bundle is parsed no code of the application is in the page, so nothing
1007
+ but the field changes: the address stays, and text derived from the query (a
1008
+ heading, pending results) shows what the server rendered. When the script
1009
+ runs, the replayed Message is the first `update` sees, and the page draws its
1010
+ effects as it would any Message's. Typing is the interaction a page started
1011
+ `'idle'` or `'on-interaction'` waits for, so such a page starts at once when
1012
+ something was typed before its script; only a lazy bundle still loading
1013
+ holds the queue undrawn.
1014
+
1015
+ Answering sooner takes code that runs before the bundle, which only an inline
1016
+ script can be. `foldkit-ssr` writes none: it would need a Content Security
1017
+ Policy nonce and a second copy of the field's behaviour in plain DOM code. An
1018
+ application that keeps one (upstream's foldkit-domains writes `?q=` and fills
1019
+ its pending cards from one) may write the address only on a page recorded for
1020
+ its path alone (`SSR.generate`, or `SSR.entry`'s `prerendered`), which, opened
1021
+ at another query, starts from that URL; a page rendered per request is
1022
+ refused at any query but its own. Markup such a script changes is the
1023
+ served page no longer, and Foldkit reconciles it at hydration to the Model's
1024
+ first render.
1025
+
748
1026
  ## Forms that work without scripts
749
1027
 
750
1028
  A form whose `OnSubmit` names a Message can be answered by the server, before
@@ -778,11 +1056,15 @@ A form that need not work without scripts sends `Added()` and reads
778
1056
 
779
1057
  With scripts on, nothing changes: the page answers the submit and the form
780
1058
  never posts. Without them, the server wrote the form to post the Message to the
781
- page's own URL, and `SSR.entry` hands that post to `SSR.handle`:
1059
+ page's own URL, and `SSR.entry` hands that post to `SSR.handle`. A form given
1060
+ its own `Method` is left as the view draws it, with no Message field: a
1061
+ search form is `rh.Method('get')` and sends its named fields as the address,
1062
+ and one given `Method('post')` posts no Message, which the entry answers
1063
+ `400`.
782
1064
 
783
1065
  ```text
784
1066
  POST ──▶ decode the Message ──▶ set the posted fields into it (the typed `title`)
785
- ──▶ init, then boot and its Commands ──▶ update, and every Command after it
1067
+ ──▶ init, prepare, then boot and its Commands ──▶ update, and every Command after it
786
1068
  ──▶ the page, rendered
787
1069
  ```
788
1070
 
@@ -805,7 +1087,14 @@ A form a cookie session authorizes is a cross-site request forgery target,
805
1087
  and a form cannot carry a CSRF header. `SSR.entry`'s `origins` names the
806
1088
  origins a form may be posted from; a post whose `Origin` (every browser sends
807
1089
  one on a `POST`) is not among them is answered `403` before its body is read
808
- or `flags` and `resources` run. A page served with `Referrer-Policy:
1090
+ or `flags` and `resources` run. `origins: 'same-origin'` takes a post from
1091
+ the origin the request was addressed to and no other, for a site whose
1092
+ address the entry cannot know when it is made (a dev server's port). It
1093
+ compares with the request's own URL, so **behind a proxy that terminates TLS
1094
+ or rewrites the host** (nginx, Fly, Render), where the server sees
1095
+ `http://host` and the browser sends `Origin: https://host`, every post is
1096
+ refused `403`. There, pass the public origin, `origins:
1097
+ ['https://example.com']`, never `'same-origin'`. A page served with `Referrer-Policy:
809
1098
  no-referrer` posts `Origin: null` even to its own site; such a post, or one
810
1099
  with no `Origin` at all, is taken when its Fetch Metadata `Sec-Fetch-Site`,
811
1100
  which no page or form can set, says `same-origin`, and refused without it. A plan with a server fallback requires `origins`, since a post
@@ -813,6 +1102,72 @@ runs `flags`, the config's `resources` and its own as whoever the cookie says
813
1102
  posted: an entry made without them throws. An entry of your own that calls
814
1103
  `SSR.handle` checks `Origin` itself.
815
1104
 
1105
+ ### Answering a post with a redirect
1106
+
1107
+ The page a post renders sits at the address the form posted to, so a reload
1108
+ asks to post again. That is harmless for an idempotent Message and wrong for
1109
+ one that orders or sends something. `answerPost: 'redirect'` answers the post
1110
+ `303` to the same address instead, and the browser asks for it with a `GET`
1111
+ (Post/Redirect/Get):
1112
+
1113
+ ```text
1114
+ POST /todos ──▶ update, and its Commands ──▶ 303, Location: /todos, headers(request, some(model))
1115
+ GET /todos ──▶ init, prepare ──▶ the page, rendered
1116
+ ```
1117
+
1118
+ ```ts
1119
+ SSR.entry(config, Todos, {
1120
+ buildId,
1121
+ origins: ['https://example.com'],
1122
+ answerPost: 'redirect',
1123
+ // What the post changed has to outlive it: the next request starts from `init`.
1124
+ headers: (_request, model) =>
1125
+ Option.match(model, {
1126
+ onNone: () => ({}),
1127
+ onSome: ({ todos }) => ({
1128
+ 'set-cookie': `todos=${encodeURIComponent(JSON.stringify(todos))}; Path=/; HttpOnly; SameSite=Lax`,
1129
+ }),
1130
+ }),
1131
+ })
1132
+ ```
1133
+
1134
+ The `Location` is the posted address's path and query, relative, so the
1135
+ browser resolves it against the address it posted to and it can name no
1136
+ other origin, whatever `Host` the request claimed. The `GET` starts from
1137
+ `init` and `prepare`, so whatever the post changed reaches it only through
1138
+ what `headers` wrote (a cookie) or a store of the application's; `prepare`
1139
+ reads it back. The page shows nothing else of the post: a message about its
1140
+ outcome is a one-shot cookie the application writes and `prepare` reads. A
1141
+ refused post is still a `400`, and a failing Command a `500`.
1142
+
1143
+ ### A whole page without scripts
1144
+
1145
+ A form that posts is one part of a page that works with JavaScript off. The
1146
+ rest is the application's, and
1147
+ [`examples/foldkit/domains-plus`](../../examples/foldkit/domains-plus) does
1148
+ all of it; [Pages that work without JavaScript](../../docs/progressive-enhancement.md)
1149
+ is the guide. What the port needed from this package:
1150
+
1151
+ - **Render what is shown.** `SSR.render` fetches nothing, so read first, in
1152
+ `prepare` (`Data.satisfy`); send the reading
1153
+ Surfaces' data with `parts: [Remote.resume(Data)]` and list the Surfaces
1154
+ in `surfaces`, so the browser reads none of it again.
1155
+ - **Give a GET form its method.** With a fallback, a form `rh` builds whose
1156
+ `OnSubmit` names a Message posts it; a search or filter form is a GET of
1157
+ the address the URL mirror reads, and `rh.Method('get')` leaves it one.
1158
+ - **Draw the plain controls on both sides.** Show them under
1159
+ `@media (scripting: none)` and hide the scripted ones there; a control in
1160
+ `<noscript>` is not drawn by the view, and the page would not be the one
1161
+ the browser renders first.
1162
+ - **Keep state between posts yourself.** A post starts from `init`, so what
1163
+ must outlive it lives in a cookie the entry reads in `prepare`, validated
1164
+ as it is read, and `headers(request, model)` writes it back from the Model
1165
+ the post reached. With that, answer posts with a redirect
1166
+ (`answerPost: 'redirect'`), so a reload does not post again.
1167
+ - **Wait for the takeover in a scripted test.** The served page works on its
1168
+ own, so a click before boot posts. The root loses `data-foldkit-plus-resume`
1169
+ as the page boots.
1170
+
816
1171
  ## A reader's preferences in the first frame
817
1172
 
818
1173
  A theme, a light or dark choice, a density: a reader expects the page to open
@@ -897,6 +1252,7 @@ of:
897
1252
  | `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 |
898
1253
  | `EagerStartRequired` | A deferred plan would start a Subscription or Managed Resource late | Declare it in `deferrable`, or start `'now'` |
899
1254
  | `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 |
900
1256
  | `UngeneratablePath` | `SSR.generate` was given a path no file can be served at | Leave out the query and fragment; keep paths to distinct files |
901
1257
 
902
1258
  In the browser, `SSR.hydrate` checks in Foldkit's order: the build id first,
@@ -978,10 +1334,19 @@ In a test, `Diagnostics.collect()` gives a reporter and the array it fills.
978
1334
  - **A resumable page leans on two Foldkit behaviours,** each pinned by a test
979
1335
  here and by Foldkit's own: the first patch removes attributes the browser's
980
1336
  view does not assert, and a control's value is re-asserted to the Model's.
1337
+ What the server wrote for the browser's script alone (the envelope, the
1338
+ markers, a placement's slot, a fallback form's method and hidden field) is
1339
+ taken off as the page boots, before Foldkit records the served page, so a
1340
+ development build does not report it as markup the view disagrees with.
981
1341
  It does not depend on `Runtime.hydrate` rendering its first frame before
982
1342
  it returns, which Foldkit does today without promising it: until that
983
1343
  frame commits (`Render.afterCommit`), the page keeps answering from its
984
1344
  markers and sends the live page what only it can answer.
1345
+ - **A kept field is written twice at boot.** Hydration re-asserts the served
1346
+ value, and the page writes the typed one back with its selection, in the
1347
+ same task, so nothing paints between. The write ends an IME composition
1348
+ in progress; leaving a changed control alone is
1349
+ [proposal 6](../../docs/upstream-foldkit-ssr.md#proposal-6-leave-a-control-the-person-changed-alone-at-hydration).
985
1350
  - **Development is not production.** Under Vite's dev server, Foldkit's model
986
1351
  preservation restores the previous Model after a reload and skips adoption.
987
1352
  - **A closure handler makes its event wait for boot.** `SSR.render`'s result
@@ -999,8 +1364,8 @@ In a test, `Diagnostics.collect()` gives a reporter and the array it fills.
999
1364
  as a `Result`. `SSR.render` carries it on the stamped root, beside Foldkit's
1000
1365
  own stamps; the JSON escapes `<` as Foldkit escapes its Flags, and U+2028
1001
1366
  and U+2029, and the attribute escapes `&` and `"` besides, so no string in
1002
- the Model can break out of the value. Hydration drops the attribute on its
1003
- first patch, so the browser reads it before it boots.
1367
+ the Model can break out of the value. The browser reads it, then takes the
1368
+ attribute off as the page boots.
1004
1369
  - **`SSR.inspect(plan, model)`**: the plan's coverage as data.
1005
1370
  - **`Resume.bindings(plan, document, root, model)`** decodes and checks a
1006
1371
  page's bindings, and **`Resume.listen(root, { bindings, onAnswer, events? })`**
@@ -1012,7 +1377,8 @@ In a test, `Diagnostics.collect()` gives a reporter and the array it fills.
1012
1377
  - **Attribute names**, for tools and tests: `RESUME_ATTRIBUTE` (the envelope
1013
1378
  on the stamped root), `STATIC_ATTRIBUTE`, `BINDING_ATTRIBUTE` (a prefix,
1014
1379
  followed by the event), `SLOT_ATTRIBUTE` (a placement's root while the server
1015
- renders) and `FALLBACK_FIELD` (the posted Message).
1380
+ renders), `KEEP_ATTRIBUTE` (a kept field, naming the binding that replays
1381
+ it) and `FALLBACK_FIELD` (the posted Message).
1016
1382
 
1017
1383
  ## The application in these examples
1018
1384
 
@@ -1026,7 +1392,7 @@ for a plan, as `Surface.when(PostActions, App.model.route, AppRoute.Post, route
1026
1392
  [the coverage example](#checking-what-the-browser-will-read).
1027
1393
 
1028
1394
  ```ts
1029
- const AppRoute = defineRouteUnion({ Home: {}, Post: { id: Schema.String } })
1395
+ const AppRoute = defineRouteUnion({ Home: {}, Post: { id: Schema.String }, NotFound: {} })
1030
1396
 
1031
1397
  const Model = Schema.Struct({
1032
1398
  route: AppRoute,
@@ -1,7 +1,7 @@
1
- import { o as listen } from "./listen-zNd0IIAT.js";
2
- import { m as view, p as builder } from "./resumable-BWItJsxF.js";
3
- import { A as serving, D as resume, M as staticRegion, _ as bindings, c as ResumableConfig, u as ResumePlan, w as plan } from "./shared-v1u-OEQI.js";
4
- import { Schema } from "effect";
1
+ import { o as listen } from "./listen-DaUPRKVR.js";
2
+ import { g as view, h as builder } from "./resumable-BPN_qQHU.js";
3
+ import { E as plan, M as serving, P as staticRegion, c as ResumableConfig, k as resume, u as ResumePlan, y as bindings } from "./shared-CJN-m58Z.js";
4
+ import { Effect, Schema } from "effect";
5
5
  import { Diagnostic as Diagnostic$1, Diagnostics as Diagnostics$1, ReportDiagnostic, ReportDiagnostic as ReportDiagnostic$1 } from "foldkit-surface";
6
6
  /**
7
7
  * Starts the browser from the page's resumed Model, without running `init`.
@@ -45,6 +45,16 @@ declare const hydrate: <Model, Fields extends Schema.Struct.Fields, Message = an
45
45
  * throw, as `when`.
46
46
  */
47
47
  readonly fresh?: ((version: unknown) => boolean) | undefined;
48
+ /**
49
+ * What only this browser adds to the resumed Model before it is adopted,
50
+ * and the view does not draw: a session minted for this page load (an
51
+ * outbox's `session`). Run once, for a page that resumes; the runtime
52
+ * starts when it succeeds. What the view draws, such as a queue read from
53
+ * storage, arrives after, as a Message: here it would make the first
54
+ * client view differ from the served page. Must not fail, as `when` must
55
+ * not throw.
56
+ */
57
+ readonly prepare?: ((model: Model) => Effect.Effect<Model>) | undefined;
48
58
  /**
49
59
  * Where what the page met goes: a page contained rather than resumed, a
50
60
  * static region the server's page lacked, a lazy bundle that did not
@@ -72,4 +82,4 @@ declare const SSR: {
72
82
  serving: typeof serving;
73
83
  };
74
84
  export { SSR as a, Resume as i, Diagnostics$1 as n, UNTIL_LIMIT_MS as o, ReportDiagnostic$1 as r, Diagnostic$1 as t };
75
- //# sourceMappingURL=client-F16QT0sc.d.ts.map
85
+ //# sourceMappingURL=client-qmdYY-Eb.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-qmdYY-Eb.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;;;;;;;;;;;cAgFM,UAAW,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,QAChE,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;WAEpB;;;;;;;WAOA,SAAS,MAAM;;;;;;;WAOf;;;;;;;;WAQA,UAAU,OAAO;;;;;;;;WAQjB,UAAU;;;;;;;;;;WAUV,YAAY,OAAO,UAAU,OAAO,OAAO;;;;;;;;WAQ3C,cAAc;;;cA8Md;;cAuKA;;;;;;;cAGA"}
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { n as DecodedBinding } from "./listen-zNd0IIAT.js";
2
- import { a as FALLBACK_FIELD, l as ResumableBuilder, n as BINDING_ATTRIBUTE, u as SLOT_ATTRIBUTE } from "./resumable-BWItJsxF.js";
3
- import { G as SsrDiagnostic, H as HandlerUnnamed, K as StaticRegionMissing, L as UnnamedHandler, U as PageContained, V as BundleUnloaded, W as PageFailed, c as ResumableConfig, d as ResumeRefused, i as Meta, l as ResumePart, m as Start, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, x as metaMarkup } from "./shared-v1u-OEQI.js";
4
- import { a as SSR, i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-F16QT0sc.js";
5
- export { BINDING_ATTRIBUTE, type BundleUnloaded, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
1
+ import { n as DecodedBinding } from "./listen-DaUPRKVR.js";
2
+ import { a as FALLBACK_FIELD, d as SLOT_ATTRIBUTE, n as BINDING_ATTRIBUTE, s as KEEP_ATTRIBUTE, u as ResumableBuilder } from "./resumable-BPN_qQHU.js";
3
+ import { C as metaMarkup, G as HandlerUnnamed, J as SsrDiagnostic, K as PageContained, U as BundleUnloaded, W as CachedPageDiffers, Y as StaticRegionMissing, c as ResumableConfig, d as ResumeRefused, h as Start, i as Meta, l as ResumePart, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, q as PageFailed, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, z as UnnamedHandler } from "./shared-CJN-m58Z.js";
4
+ import { a as SSR, i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-qmdYY-Eb.js";
5
+ export { BINDING_ATTRIBUTE, type BundleUnloaded, type CachedPageDiffers, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, KEEP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };