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/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { withContext } from "./context.js";
2
- import { handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.js";
3
- import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, SLOT_ATTRIBUTE } from "./resumable.js";
4
- import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, allowedTags, attributeOf, codecOf, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf } from "./shared.js";
2
+ import { cachedPageDiffers, handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.js";
3
+ import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, SLOT_ATTRIBUTE } from "./resumable.js";
4
+ import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, attributeOf, codecOf, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf } from "./shared.js";
5
5
  import { Diagnostics, Resume, SSR as SSR$1, UNTIL_LIMIT_MS } from "./client.js";
6
6
  import { requestContext } from "./requestContext.js";
7
+ import { decodeKept, fits, headerOf, keptApplications, keptDocuments, pageKey, samePage, tracked } from "./pageCache.js";
7
8
  import { Cause, Context, Effect, Exit, Layer, Option, Result, Schema } from "effect";
8
- import { Diagnostics as Diagnostics$1, Metadata } from "foldkit-surface";
9
+ import { CacheStore, Diagnostics as Diagnostics$1, Metadata, PageReads, cachePolicy, maxAgeSeconds, shorterPolicy } from "foldkit-surface";
9
10
  import { FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, renderToString } from "foldkit/experimental/server";
10
11
  // src/index.ts
11
12
  /**
@@ -63,9 +64,8 @@ const envelopeOf = (resume, payload, options) => serializeJsonScript({
63
64
  * Foldkit's own app and build stamps. `injectIntoTemplate` accepts the
64
65
  * envelope there, as part of the root, and refuses it beside the root, so a
65
66
  * page the host injects carries the handover without the entry owning the
66
- * template. Hydration adopts the server's nodes around it and drops the
67
- * attribute on its first patch, so the browser reads the envelope before it
68
- * boots.
67
+ * template. The browser reads the envelope, then takes the attribute off
68
+ * as the page boots, before Foldkit adopts the server's nodes around it.
69
69
  */
70
70
  const withEnvelopeAttribute = (html, json) => {
71
71
  const stamp = "data-foldkit-app=\"";
@@ -97,10 +97,11 @@ const isInRootTag = (html, at) => {
97
97
  return true;
98
98
  };
99
99
  /**
100
- * The rendered markup with `extra` as the root's last child, so the first
101
- * paint is styled before any script runs where no template head can take it.
102
- * A void root holds no children: styles for one are refused, naming the tag,
103
- * rather than served where no browser could keep them.
100
+ * The rendered markup with `extra` as the root's last children, after the
101
+ * styles marker, so the first paint is styled before any script runs where no
102
+ * template head can take it; `SSR.hydrate` moves them into the head. A void
103
+ * root holds no children: styles for one are refused, naming the tag, rather
104
+ * than served where no browser could keep them.
104
105
  */
105
106
  const withInRoot = (html, extra) => {
106
107
  const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1];
@@ -109,7 +110,7 @@ const withInRoot = (html, extra) => {
109
110
  reason: "VoidRootWithStyles",
110
111
  message: `styles need a root element that can hold them, but the view returned <${tag ?? "?"}>: put the styles in the template's head with SSR.generate, or return an element root`
111
112
  }));
112
- return Result.succeed(`${html.slice(0, at)}${extra}${html.slice(at)}`);
113
+ return Result.succeed(`${html.slice(0, at)}<!--${STYLES_MARKER}-->${extra}${html.slice(at)}`);
113
114
  };
114
115
  /**
115
116
  * The Model the browser will start from when the server's Model is `model`:
@@ -234,7 +235,8 @@ var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
234
235
  "EagerStartRequired",
235
236
  "UndeclaredSurfaces",
236
237
  "BindingInStaticRegion",
237
- "VoidRootWithStyles"
238
+ "VoidRootWithStyles",
239
+ "UnkeepableField"
238
240
  ]),
239
241
  message: Schema.String
240
242
  }) {};
@@ -243,6 +245,45 @@ const unlistedBindings = (plan, model, bindings) => {
243
245
  const allowed = allowedTags(plan, model);
244
246
  return bindings.filter((binding) => !allowed.has(tagOf(binding.message))).map((binding) => `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`);
245
247
  };
248
+ /**
249
+ * Whether `at` starts an attribute inside the start tag opened before it.
250
+ * A marker in a text node follows that tag's `>`, and one inside another
251
+ * attribute's value has its quotes escaped (`&quot;`), so only a marker
252
+ * between a tag's `<` and a `>` outside a quoted value is an attribute.
253
+ */
254
+ const opensAttribute = (html, at) => {
255
+ if (at === 0 || !/[ \t\r\n]/.test(html[at - 1])) return false;
256
+ const open = html.lastIndexOf("<", at);
257
+ if (open === -1 || html.startsWith("<!--", open)) return false;
258
+ let quote;
259
+ for (let index = open + 1; index < at; index++) {
260
+ const char = html[index];
261
+ if (quote !== void 0) {
262
+ if (char === quote) quote = void 0;
263
+ } else if (char === "\"" || char === "'") quote = char;
264
+ else if (char === ">") return false;
265
+ }
266
+ return quote === void 0;
267
+ };
268
+ /**
269
+ * A line for each `KeepTyped` the render drew on an element the resumable
270
+ * builder did not build, whose marker still holds its server-render value:
271
+ * nothing marks which binding replays such a field, so every browser would
272
+ * refuse the page. Only a marker that is an attribute counts: ordinary text
273
+ * can spell the same characters.
274
+ */
275
+ const unplacedKeeps = (html) => {
276
+ const marker = `${KEEP_ATTRIBUTE}="?"`;
277
+ const found = [];
278
+ for (let at = html.indexOf(marker); at !== -1; at = html.indexOf(marker, at + 1)) {
279
+ if (!opensAttribute(html, at)) continue;
280
+ const open = html.lastIndexOf("<", at);
281
+ const tag = /^<([A-Za-z][A-Za-z0-9._-]*)/.exec(html.slice(open))?.[1] ?? "an element";
282
+ const id = /\sid="([^"]*)"/.exec(html.slice(open, html.indexOf(">", at)))?.[1];
283
+ found.push(`KeepTyped on ${id === void 0 ? tag : `${tag}#${id}`}, which Resume.builder did not build, so nothing marks the binding its typing replays as: build the element with the resumable builder (rh.input), not h`);
284
+ }
285
+ return found;
286
+ };
246
287
  /** Loads every lazy bundle's bodies, so the view renders whole. */
247
288
  const loadLazy = (config) => Effect.promise(() => Promise.all((config.lazy ?? []).map((bundle) => bundle.load())));
248
289
  /** Foldkit's own Flags script, which a resumed page never carries. */
@@ -313,7 +354,7 @@ const eagerEntries = (config, plan, model) => {
313
354
  * Foldkit would rebuild that part of the page silently, so this is the one
314
355
  * place it shows.
315
356
  */
316
- const render = (config, plan, options) => renderMatching(config, plan, options, "full");
357
+ const render = (config, plan, options) => Effect.map(renderMatching(config, plan, options, "full"), (served) => served.page);
317
358
  const renderMatching = (config, plan, options, match) => Effect.gen(function* () {
318
359
  yield* loadLazy(config);
319
360
  let served;
@@ -323,6 +364,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
323
364
  const browserBindings = [];
324
365
  const inStatic = [];
325
366
  const unnamed = [];
367
+ const unkeepable = [];
326
368
  const fallback = fallbackEncoder(plan);
327
369
  const capturing = withContext({
328
370
  ...config,
@@ -337,9 +379,11 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
337
379
  depth: 0,
338
380
  region: void 0,
339
381
  inStatic,
340
- unnamed
382
+ unnamed,
383
+ unkeepable
341
384
  });
342
385
  const full = yield* renderToString(capturing, options);
386
+ unkeepable.push(...unplacedKeeps(full.html));
343
387
  if (duplicates.size > 0) return yield* new ResumeUnsafe({
344
388
  reason: "DuplicateStaticRegion",
345
389
  message: `two static regions share the id ${[...duplicates].map((id) => `"${id}"`).join(", ")}: the browser could adopt only one`
@@ -348,6 +392,10 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
348
392
  reason: "BindingInStaticRegion",
349
393
  message: `a static region is the server's alone, and these would never run: ${inStatic.map(({ region, element, event }) => `a ${event} handler on ${element} in "${region}"`).join(", ")}. What a Message changes belongs in a Surface`
350
394
  });
395
+ if (unkeepable.length > 0) return yield* new ResumeUnsafe({
396
+ reason: "UnkeepableField",
397
+ message: `the page cannot keep what is typed into these fields before it boots:\n- ${unkeepable.join("\n- ")}`
398
+ });
351
399
  const started = served;
352
400
  const commands = started.commands ?? [];
353
401
  if (commands.length > 0 && plan.boot === void 0) return yield* new ResumeUnsafe({
@@ -409,13 +457,16 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
409
457
  const styled = options.styles === void 0 ? Result.succeed(rendered.html) : withInRoot(rendered.html, options.styles(rendered));
410
458
  if (Result.isFailure(styled)) return yield* styled.failure;
411
459
  return {
412
- rendered: {
413
- ...rendered,
414
- html: withEnvelopeAttribute(styled.success, envelope)
460
+ page: {
461
+ rendered: {
462
+ ...rendered,
463
+ html: withEnvelopeAttribute(styled.success, envelope)
464
+ },
465
+ meta,
466
+ envelope,
467
+ unnamed
415
468
  },
416
- meta,
417
- envelope,
418
- unnamed
469
+ model: started.model
419
470
  };
420
471
  });
421
472
  /**
@@ -551,7 +602,7 @@ const generate = (config, plan, options) => Effect.gen(function* () {
551
602
  buildId: options.buildId,
552
603
  url: new URL(path, options.origin).href,
553
604
  ...options.flags === void 0 ? {} : { flags: options.flags(path) }
554
- }, "path").pipe(Effect.tap((result) => reportUnnamed(config, plan, result.unnamed)), Effect.map((result) => ({
605
+ }, "path").pipe(Effect.map((served) => served.page), Effect.tap((result) => reportUnnamed(config, plan, result.unnamed)), Effect.map((result) => ({
555
606
  path,
556
607
  file: fileOf(path),
557
608
  html: page(options.template, result, { head: options.head })
@@ -564,15 +615,18 @@ const generate = (config, plan, options) => Effect.gen(function* () {
564
615
  * served by Node and Workers alike.
565
616
  *
566
617
  * `GET` and `HEAD` render the page against the plan, with the request's URL
567
- * and, when the application has Flags, `flags(request)`. `POST` goes to
618
+ * and, when the application has Flags, `flags(request)`; `prepare(model,
619
+ * request)` turns the Model `init` gave into the one rendered, a read made
620
+ * before the render (`Data.satisfy`). `POST` goes to
568
621
  * `SSR.handle` when the plan has a server fallback, and is answered `400` when
569
622
  * the post is unusable. `OPTIONS` is answered `204`, and any other method
570
623
  * `405`, each with the methods the entry answers in `allow` (`handleRequest`
571
624
  * passes every method through). A render that fails, or a plan the render
572
625
  * refuses, is answered `500` with the reason reported (`diagnostics`), never with a page the
573
- * browser cannot resume. `headers(request)` rides on the `Rendered` result, so
574
- * Foldkit's `toResponse` sets it over its own on the page: a cache policy, or
575
- * a CORS answer to a preflight.
626
+ * browser cannot resume. `headers(request, model)` is set over Foldkit's own
627
+ * on every answer: a cache policy, a CORS answer to a preflight, or a cookie
628
+ * written from the Model a post reached. `status(model, request)` gives a page
629
+ * its status from that Model, `404` for a route not found.
576
630
  *
577
631
  * The page is answered as `Rendered`: the rendered application carries the
578
632
  * envelope in its root, so the host injects it into its own template with
@@ -586,30 +640,56 @@ const generate = (config, plan, options) => Effect.gen(function* () {
586
640
  * `meta` is refused when the entry is made, and served with `SSR.generate`.
587
641
  */
588
642
  const entry = (config, plan, options) => {
643
+ const cache = Option.map(Option.fromUndefinedOr(options.cache), (given) => ({
644
+ ...given,
645
+ policy: cachePolicy(given)
646
+ }));
589
647
  if (plan.meta !== void 0) throw new Error(`foldkit-ssr: plan "${plan.id}" says what the page says of itself (meta), which is written into the template's head, and the template is the host's: serve it with SSR.generate, not SSR.entry`);
590
- for (const origin of options.origins ?? []) if (!URL.canParse(origin) || new URL(origin).origin !== origin) throw new Error(`foldkit-ssr: ${JSON.stringify(origin)} in origins is not an origin`);
648
+ const listed = options.origins === "same-origin" ? [] : options.origins ?? [];
649
+ for (const origin of listed) if (!URL.canParse(origin) || new URL(origin).origin !== origin) throw new Error(`foldkit-ssr: ${JSON.stringify(origin)} in origins is not an origin`);
650
+ if (options.answerPost !== void 0 && plan.fallback !== "server") throw new Error(`foldkit-ssr: plan "${plan.id}" has no server fallback, so no form is posted to answer (answerPost)`);
591
651
  if (plan.fallback === "server" && options.origins === void 0) throw new Error(`foldkit-ssr: plan "${plan.id}" handles posted forms, which run as whoever posted; name the origins a form may be posted from (origins)`);
592
- const origins = new Set(options.origins ?? []);
652
+ for (const path of options.prerendered ?? []) if (!path.startsWith("/") || /[?#]/.test(path)) throw new Error(`foldkit-ssr: "${path}" in prerendered is not a path a file can be served at: start it with / and leave out any query or fragment`);
653
+ const prerendered = new Set((options.prerendered ?? []).map(pathKey));
654
+ const matchOf = (url) => {
655
+ const route = routeOf(url);
656
+ return !route.includes("?") && prerendered.has(pathKey(route)) ? "path" : "full";
657
+ };
658
+ const origins = new Set(listed);
659
+ const originsOf = (request) => options.origins === "same-origin" ? /* @__PURE__ */ new Set([new URL(request.url).origin]) : origins;
593
660
  const allow = plan.fallback === "server" ? "GET, HEAD, POST, OPTIONS" : "GET, HEAD, OPTIONS";
594
661
  const merge = (response, extra) => {
595
662
  for (const name of new Set(extra.keys())) response.headers.delete(name);
596
663
  extra.forEach((value, name) => response.headers.append(name, value));
597
664
  return response;
598
665
  };
599
- const answer = async (request) => {
666
+ const headersOf = (request, model) => {
667
+ if (options.headers === void 0) return void 0;
668
+ const headers = new Headers(options.headers(request, model));
669
+ for (const name of headers.keys()) if (ENTRY_HEADERS.has(name)) throw new Error(`headers set ${name}, which the entry writes and an application may not`);
670
+ return headers;
671
+ };
672
+ /**
673
+ * One request answered. `watched`, for a render that may be kept, records
674
+ * what the render read of the request's headers and through `pageReader`.
675
+ */
676
+ const answer = async (given, watched) => {
677
+ const request = watched === void 0 ? given : tracked(given, watched.read);
600
678
  const method = request.method.toUpperCase();
601
679
  const posting = method === "POST" && plan.fallback === "server";
602
680
  const { diagnostics } = options;
603
- const reporting = reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request));
604
- const headersOf = options.headers;
605
- let extra;
606
- if (headersOf !== void 0) try {
607
- extra = new Headers(headersOf(request));
608
- } catch (error) {
609
- await Effect.runPromise(reporting(Diagnostics$1.report(pageFailed(request.url, Cause.die(error)))));
610
- return Responded(plainText(500, "The page could not be rendered."));
611
- }
612
- const responded = (response) => Responded(extra === void 0 ? response : merge(response, extra));
681
+ const reported = reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, given));
682
+ const reporting = (effect) => reported(watched === void 0 ? effect : Effect.provideService(effect, PageReads, Option.some((read) => watched.reads.push(read))));
683
+ const responded = async (response, { reported = false } = {}) => {
684
+ let extra;
685
+ try {
686
+ extra = headersOf(request, Option.none());
687
+ } catch (error) {
688
+ if (!reported) await Effect.runPromise(reporting(Diagnostics$1.report(pageFailed(request.url, Cause.die(error)))));
689
+ return Responded(plainText(500, "The page could not be rendered."));
690
+ }
691
+ return Responded(extra === void 0 ? response : merge(response, extra));
692
+ };
613
693
  if (method === "OPTIONS") return responded(new Response(null, {
614
694
  status: 204,
615
695
  headers: { allow }
@@ -618,37 +698,193 @@ const entry = (config, plan, options) => {
618
698
  status: 405,
619
699
  headers: { allow }
620
700
  }));
621
- if (posting && !postedFrom(request, origins)) return responded(plainText(403, "The form was not posted from this site."));
701
+ if (posting && !postedFrom(request, originsOf(request))) return responded(plainText(403, "The form was not posted from this site."));
622
702
  const flagsOf = options.flags;
703
+ const statusOf = options.status;
704
+ const { prepare } = options;
623
705
  const styled = options.styles === void 0 ? {} : { styles: options.styles };
624
706
  const exit = await Effect.runPromiseExit(Effect.gen(function* () {
625
707
  const flags = flagsOf === void 0 ? void 0 : yield* Effect.tryPromise(async () => flagsOf(request));
626
708
  const flagged = flagsOf === void 0 ? {} : { flags };
627
- if (posting) return yield* handle(request, config, plan, {
709
+ const prepared = prepare === void 0 ? {} : { prepare };
710
+ const post = () => ({
628
711
  buildId: options.buildId,
629
712
  ...flagged,
630
713
  ...styled,
714
+ ...prepared,
631
715
  ...options.resources === void 0 ? {} : { resources: options.resources(request) }
632
716
  });
633
- return yield* render(config, plan, {
717
+ if (posting && options.answerPost === "redirect") {
718
+ const model = yield* postedModel(request, config, plan, post());
719
+ const extra = yield* Effect.sync(() => headersOf(request, Option.some(model)));
720
+ const redirect = new Response(null, {
721
+ status: 303,
722
+ headers: { location: sameAddress(request.url) }
723
+ });
724
+ return Responded(extra === void 0 ? redirect : merge(redirect, extra));
725
+ }
726
+ const served = posting ? yield* handleServed(request, config, plan, post()) : yield* renderMatching(prepare === void 0 ? config : yield* preparedStart(request, config, {
727
+ url: request.url,
728
+ ...flagged
729
+ }, prepare), plan, {
634
730
  buildId: options.buildId,
635
731
  url: request.url,
636
732
  ...flagged,
637
733
  ...styled
734
+ }, matchOf(request.url));
735
+ const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)));
736
+ const status = Option.map(Option.fromUndefinedOr(statusOf), (of) => of(served.model, request));
737
+ const unanswerable = Option.filter(status, (given) => !Number.isInteger(given) || given < 200 || given > 599 || given === 204 || given === 205 || given === 304);
738
+ if (Option.isSome(unanswerable)) return yield* Effect.die(/* @__PURE__ */ new Error(`status gave ${unanswerable.value} for the page, which is no status for a page with a body`));
739
+ yield* reportUnnamed(config, plan, served.page.unnamed);
740
+ return Rendered(served.page.rendered, {
741
+ ...extra === void 0 ? {} : { headers: extra },
742
+ ...Option.match(status, {
743
+ onNone: () => ({}),
744
+ onSome: (status) => ({ status })
745
+ })
638
746
  });
639
747
  }).pipe(reporting));
640
748
  if (Exit.isFailure(exit)) {
641
749
  const refused = Cause.findErrorOption(exit.cause).pipe(Option.filter((error) => error instanceof FallbackRefused));
642
750
  if (Option.isSome(refused)) return responded(plainText(400, `The form could not be handled: ${refused.value.message}`));
643
751
  await Effect.runPromise(reporting(Diagnostics$1.report(pageFailed(request.url, exit.cause))));
644
- return responded(plainText(500, "The page could not be rendered."));
752
+ return responded(plainText(500, "The page could not be rendered."), { reported: true });
753
+ }
754
+ return exit.value;
755
+ };
756
+ if (Option.isNone(cache)) return { renderPage: (request) => answer(request) };
757
+ const { store, check, policy } = cache.value;
758
+ const reportTo = (request) => {
759
+ const { diagnostics } = options;
760
+ return reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request));
761
+ };
762
+ /** A page no store may keep for another request: its own `cache-control` stands. */
763
+ const unkept = (result) => {
764
+ if (result._tag !== "Rendered" || Option.isSome(headerOf(result.headers, "cache-control"))) return result;
765
+ const headers = new Headers(result.headers);
766
+ headers.set("cache-control", "private, no-store");
767
+ return Rendered(result.application, {
768
+ ...result,
769
+ headers
770
+ });
771
+ };
772
+ /** The page as a store keeps it, when nothing it was drawn from was the request's own. */
773
+ const keepable = (request, result, watched) => {
774
+ if (result._tag !== "Rendered" || (result.status ?? 200) !== 200 || watched.read.all) return Option.none();
775
+ if (![...watched.read.names].every((name) => !request.headers.has(name))) return Option.none();
776
+ if (Option.isSome(headerOf(result.headers, "set-cookie")) || Option.isSome(headerOf(result.headers, "cache-control"))) return Option.none();
777
+ let shortest = policy;
778
+ const tags = /* @__PURE__ */ new Set();
779
+ for (const read of watched.reads) {
780
+ if (read._tag === "Private") return Option.none();
781
+ shortest = shorterPolicy(shortest, read.policy);
782
+ for (const tag of read.tags) tags.add(tag);
783
+ }
784
+ const vary = [...watched.read.names].sort();
785
+ const headers = new Headers(result.headers);
786
+ headers.set("cache-control", `public, max-age=${maxAgeSeconds(shortest)}`);
787
+ if (vary.length > 0) headers.set("vary", vary.join(", "));
788
+ return Option.some({
789
+ page: {
790
+ application: result.application,
791
+ ...result.status === void 0 ? {} : { status: result.status },
792
+ headers: [...headers],
793
+ vary
794
+ },
795
+ maxAge: shortest,
796
+ tags: [...tags]
797
+ });
798
+ };
799
+ const served = (page) => {
800
+ keptApplications.add(page.application);
801
+ return Rendered(page.application, {
802
+ ...page.status === void 0 ? {} : { status: page.status },
803
+ headers: page.headers.map(([name, value]) => [name, value])
804
+ });
805
+ };
806
+ const renderPage = async (request) => {
807
+ const method = request.method.toUpperCase();
808
+ if (method !== "GET" && method !== "HEAD") return unkept(await answer(request));
809
+ const key = await Effect.runPromise(pageKey(options.buildId, request.url));
810
+ const kept = Option.filter(Option.flatMap(await Effect.runPromise(store.match(key)), decodeKept), (page) => fits(request, page.vary));
811
+ if (Option.isSome(kept)) {
812
+ if (check !== true) return served(kept.value);
813
+ const again = await answer(request);
814
+ if (again._tag === "Rendered" && samePage(again, kept.value, Date.now())) return served(kept.value);
815
+ await Effect.runPromise(reportTo(request)(Diagnostics$1.report(cachedPageDiffers(request.url))));
816
+ return unkept(again);
645
817
  }
646
- await Effect.runPromise(reporting(reportUnnamed(config, plan, exit.value.unnamed)));
647
- return extra === void 0 ? Rendered(exit.value.rendered) : Rendered(exit.value.rendered, { headers: extra });
818
+ const watched = {
819
+ read: {
820
+ names: /* @__PURE__ */ new Set(),
821
+ all: false
822
+ },
823
+ reads: []
824
+ };
825
+ const result = await answer(request, watched);
826
+ return Option.match(keepable(request, result, watched), {
827
+ onNone: () => unkept(result),
828
+ onSome: ({ page, maxAge, tags }) => Effect.runPromise(Effect.as(store.put(key, JSON.stringify(page), {
829
+ maxAge: maxAge.maxAge,
830
+ tags
831
+ }), served(page)))
832
+ });
648
833
  };
649
- return { renderPage: answer };
834
+ return { renderPage };
835
+ };
836
+ /**
837
+ * The page cache's checker, for a test: builds the entry with `make`, given a
838
+ * store in memory and `check`, and answers each request twice, so a page
839
+ * kept for one request is drawn again for every later one it serves.
840
+ * Rejects naming each page drawn otherwise for a request it served, and
841
+ * when no page was kept, which would check nothing. Give requests that
842
+ * differ in who asks (a visitor's, and one with someone's cookie); each is a
843
+ * function, since a request is read once.
844
+ */
845
+ const checkCache = async (make, requests) => {
846
+ const store = CacheStore.memory();
847
+ const differs = [];
848
+ const entry = make({
849
+ cache: {
850
+ store,
851
+ maxAge: "1 hour",
852
+ check: true
853
+ },
854
+ diagnostics: (diagnostic) => Effect.sync(() => {
855
+ if (diagnostic._tag === "CachedPageDiffers") differs.push(diagnostic.message);
856
+ })
857
+ });
858
+ for (const _round of [1, 2]) for (const request of requests) await entry.renderPage(request());
859
+ if (differs.length > 0) throw new Error(differs.join("\n"));
860
+ if (store.size() === 0) throw new Error("SSR.checkCache: no page was kept, so nothing was checked");
861
+ };
862
+ /**
863
+ * Where a post's answer sends the browser: the address it posted to, its path
864
+ * and query alone. Relative, so the browser resolves it against that address
865
+ * and it names no other origin, whatever `Host` the request claimed; leading
866
+ * slashes collapse to one, since `//elsewhere.test/` would name another host.
867
+ */
868
+ const sameAddress = (url) => {
869
+ const { pathname, search } = new URL(url);
870
+ return `${pathname.replace(/^\/+/, "/")}${search}`;
650
871
  };
651
872
  /**
873
+ * What `headers` may not set: what frames the response, which the host's
874
+ * server writes, and `location`, which only the entry writes.
875
+ */
876
+ const ENTRY_HEADERS = /* @__PURE__ */ new Set([
877
+ "connection",
878
+ "content-length",
879
+ "keep-alive",
880
+ "location",
881
+ "proxy-connection",
882
+ "te",
883
+ "trailer",
884
+ "transfer-encoding",
885
+ "upgrade"
886
+ ]);
887
+ /**
652
888
  * Whether a post came from one of `origins`, by what the browser sends and no
653
889
  * page or form can set: its `Origin`, or, where that is missing or opaque
654
890
  * (`Origin: null`, which a page served with `Referrer-Policy: no-referrer`
@@ -729,7 +965,11 @@ const startOf = (config, options) => Effect.gen(function* () {
729
965
  let started;
730
966
  yield* renderToString({
731
967
  ...config,
732
- init: (...args) => started = config.init(...args)
968
+ init: (...args) => started = config.init(...args),
969
+ view: (_model, h) => ({
970
+ title: "",
971
+ body: h.div([], [])
972
+ })
733
973
  }, {
734
974
  buildId: "x",
735
975
  ...options
@@ -737,15 +977,34 @@ const startOf = (config, options) => Effect.gen(function* () {
737
977
  return started;
738
978
  });
739
979
  /**
980
+ * The config a request starts from: `init`'s answer, its Model prepared. A
981
+ * failed `prepare` is a defect, answered 500 and reported as a failed render.
982
+ */
983
+ const preparedStart = (request, config, options, prepare) => Effect.gen(function* () {
984
+ const started = yield* startOf(config, options);
985
+ const model = yield* Effect.orDie(prepare(started.model, request));
986
+ return startingFrom(config, {
987
+ ...started,
988
+ model
989
+ });
990
+ });
991
+ /**
740
992
  * Answers a form posted by a page rendered with `fallback: 'server'`: the
741
993
  * posted Message is decoded through the plan's Message Schema, with posted
742
994
  * fields of the same names as its own overriding them, and must be one the
743
995
  * Surfaces active for the request's Model may send. The server then rebuilds
744
- * the Model the browser had, `init` and then the plan's `boot` with every
996
+ * the Model the browser had, `init`, `prepare` and then the plan's `boot` with every
745
997
  * Command it leads to, runs `update` with the Message and every Command that
746
998
  * follows, and renders the result as a fresh page.
747
999
  */
748
- const handle = (request, config, plan, options) => Effect.scoped(Effect.gen(function* () {
1000
+ const handle = (request, config, plan, options) => Effect.map(handleServed(request, config, plan, options), (served) => served.page);
1001
+ const handleServed = (request, config, plan, options) => Effect.flatMap(postedModel(request, config, plan, options), (model) => renderMatching(startingFrom(config, { model }), plan, {
1002
+ buildId: options.buildId,
1003
+ url: request.url,
1004
+ ...options.styles === void 0 ? {} : { styles: options.styles }
1005
+ }, "full"));
1006
+ /** The Model a posted form reaches: its Message decoded and checked, then `update` and its Commands. */
1007
+ const postedModel = (request, config, plan, options) => Effect.scoped(Effect.gen(function* () {
749
1008
  if (plan.fallback !== "server" || plan.Message === void 0) return yield* refuseFallback("NoFallback", `plan "${plan.id}" has no server fallback`);
750
1009
  const form = yield* Effect.tryPromise({
751
1010
  try: () => request.formData(),
@@ -787,16 +1046,13 @@ const handle = (request, config, plan, options) => Effect.scoped(Effect.gen(func
787
1046
  url: request.url,
788
1047
  ...options
789
1048
  });
790
- if (!allowedTags(plan, started.model).has(tagOf(message))) return yield* refuseFallback("Unlisted", `the posted ${tagOf(message)} is not one an active Surface lists in its messages`);
791
- const boot = plan.boot?.(started.model) ?? [];
1049
+ const { prepare } = options;
1050
+ const start = prepare === void 0 ? started.model : yield* Effect.orDie(prepare(started.model, request));
1051
+ if (!allowedTags(plan, start).has(tagOf(message))) return yield* refuseFallback("Unlisted", `the posted ${tagOf(message)} is not one an active Surface lists in its messages`);
1052
+ const boot = plan.boot?.(start) ?? [];
792
1053
  const post = options.resources === void 0 ? Context.empty() : yield* Layer.build(options.resources);
793
- const booted = yield* fold(config, post, started.model, [], boot);
794
- const model = yield* fold(config, post, booted, [message], []);
795
- return yield* render(startingFrom(config, { model }), plan, {
796
- buildId: options.buildId,
797
- url: request.url,
798
- ...options.styles === void 0 ? {} : { styles: options.styles }
799
- });
1054
+ const booted = yield* fold(config, post, start, [], boot);
1055
+ return yield* fold(config, post, booted, [message], []);
800
1056
  }));
801
1057
  const SSR = {
802
1058
  plan,
@@ -810,12 +1066,14 @@ const SSR = {
810
1066
  serving,
811
1067
  generate,
812
1068
  entry,
1069
+ checkCache,
1070
+ keptDocuments,
813
1071
  handle,
814
1072
  serializeJsonScript,
815
1073
  sitemap,
816
1074
  robots,
817
1075
  requestContext
818
1076
  };
819
- export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, FallbackRefused, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
1077
+ export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, FallbackRefused, KEEP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
820
1078
 
821
1079
  //# sourceMappingURL=index.js.map