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/client.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { withContext } from "./context.js";
2
2
  import { bundleUnloaded, noBuildId, otherBuild, pageContained, reportingTo } from "./diagnostics.js";
3
- import { BINDING_ATTRIBUTE, FALLBACK_FIELD, SLOT_ATTRIBUTE, builder, view } from "./resumable.js";
3
+ import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, SLOT_ATTRIBUTE, builder, view } from "./resumable.js";
4
4
  import { listen } from "./listen.js";
5
- import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, bindings, bindingsAndEvents, metaEntry, metaMarkup, plan, resume, routeOf, serving, startingFrom, staticRegion } from "./shared.js";
5
+ import { hold, keptFields, restore, typedMessages } from "./keep.js";
6
+ import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, arrival, bindings, bindingsAndEvents, metaEntry, metaMarkup, plan, resume, routeOf, serving, startingFrom, staticRegion } from "./shared.js";
6
7
  import { Effect, Option, Result, Schema, Stream } from "effect";
7
8
  import { hydrate, makeApplication, run } from "foldkit/runtime";
8
9
  import * as Render from "foldkit/render";
@@ -45,6 +46,7 @@ const hydrate$1 = (config, plan, options) => {
45
46
  }
46
47
  };
47
48
  const root = document.querySelector(`[${FOLDKIT_APP_ATTRIBUTE}]`);
49
+ if (root !== null) keepStyles(root);
48
50
  const declined = options.when !== void 0 && !options.when(document);
49
51
  const stale = options.fresh !== void 0 && !options.fresh(plan.version);
50
52
  if (root === null) {
@@ -82,59 +84,124 @@ const hydrate$1 = (config, plan, options) => {
82
84
  contain();
83
85
  return;
84
86
  }
85
- const model = resumed.success;
86
- const commands = plan.boot?.(model) ?? [];
87
- const resuming = {
88
- mode: "resume",
89
- snapshots: snapshotsOf(root),
90
- reported: /* @__PURE__ */ new Set(),
91
- report
92
- };
93
- const answered = [];
94
- const apply = config.update;
95
- const update = (current, message) => {
96
- const handingOver = message === HANDOVER;
97
- if (answered.length === 0) return handingOver ? { model: current } : apply(current, message);
98
- const returned = [];
99
- for (const next of [...answered.splice(0), ...handingOver ? [] : [message]]) {
100
- const step = apply(current, next);
101
- current = step.model;
102
- returned.push(...step.commands ?? []);
103
- }
104
- return {
105
- model: current,
106
- commands: returned
87
+ const adoptFrom = (model) => {
88
+ const arrived = arrival(config, document, window.location.href);
89
+ const bootCommands = (started) => plan.boot?.(started) ?? [];
90
+ const resuming = {
91
+ mode: "resume",
92
+ snapshots: snapshotsOf(root),
93
+ reported: /* @__PURE__ */ new Set(),
94
+ report
107
95
  };
108
- };
109
- const boot = (entries = {}) => hydrate(makeApplication({
110
- ...withContext(startingFrom({
111
- ...config,
112
- update
113
- }, {
114
- model,
115
- commands
116
- }), resuming),
117
- container: root,
118
- subscriptions: {
119
- ...config.subscriptions,
120
- ...entries
96
+ const answered = [];
97
+ const apply = config.update;
98
+ const update = (current, message) => {
99
+ const handingOver = message === HANDOVER;
100
+ if (answered.length === 0) return handingOver ? { model: current } : apply(current, message);
101
+ const returned = [];
102
+ for (const next of [...answered.splice(0), ...handingOver ? [] : [message]]) {
103
+ const step = apply(current, next);
104
+ current = step.model;
105
+ returned.push(...step.commands ?? []);
106
+ }
107
+ return {
108
+ model: current,
109
+ commands: returned
110
+ };
111
+ };
112
+ const startOf = () => Option.match(arrived, {
113
+ onNone: () => ({
114
+ model,
115
+ commands: bootCommands(model)
116
+ }),
117
+ onSome: (message) => {
118
+ const step = apply(model, message);
119
+ return {
120
+ model: step.model,
121
+ commands: [...bootCommands(step.model), ...step.commands ?? []]
122
+ };
123
+ }
124
+ });
125
+ const boot = (entries = {}) => {
126
+ unmark(root);
127
+ return hydrate(makeApplication({
128
+ ...withContext(startingFrom({
129
+ ...config,
130
+ update
131
+ }, startOf()), resuming),
132
+ container: root,
133
+ subscriptions: {
134
+ ...config.subscriptions,
135
+ ...entries
136
+ }
137
+ }), { buildId: options.buildId });
138
+ };
139
+ const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
140
+ const start = Option.isSome(arrived) ? "now" : plan.start;
141
+ const eager = start === "now" && pending.length === 0;
142
+ if (eager && root.querySelector(`[data-foldkit-plus-keep]`) === null) {
143
+ boot();
144
+ return;
121
145
  }
122
- }), { buildId: options.buildId });
123
- const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
124
- if (plan.start === "now" && pending.length === 0) {
125
- boot();
126
- return;
127
- }
128
- const decoded = bindingsAndEvents(plan, document, root, model);
129
- if (Result.isFailure(decoded)) {
130
- report(pageContained(decoded.failure.reason, decoded.failure.message));
131
- contain();
132
- return;
146
+ const decoded = bindingsAndEvents(plan, document, root, model);
147
+ if (Result.isFailure(decoded)) {
148
+ report(pageContained(decoded.failure.reason, decoded.failure.message));
149
+ contain();
150
+ return;
151
+ }
152
+ const kept = keptFields(root, decoded.success.bindings);
153
+ if (Result.isFailure(kept)) {
154
+ report(pageContained("Invalid", kept.failure));
155
+ contain();
156
+ return;
157
+ }
158
+ answered.push(...typedMessages(kept.success));
159
+ if (eager && answered.length === 0) {
160
+ boot();
161
+ return;
162
+ }
163
+ const typed = answered.length > 0 ? "now" : start;
164
+ deferBoot(root, decoded.success, typed, {
165
+ boot,
166
+ answered
167
+ }, pending, report, kept.success);
168
+ };
169
+ const prepare = options.prepare;
170
+ if (prepare === void 0) adoptFrom(resumed.success);
171
+ else Effect.runPromise(prepare(resumed.success)).then(adoptFrom);
172
+ };
173
+ /**
174
+ * Takes out of the served page what the server wrote for this script to read
175
+ * and no view draws: the envelope, each binding's and kept field's marker,
176
+ * each placement's slot, and each form's fallback (its `method` and hidden
177
+ * fields). Left in, each is in what Foldkit records of the served page and
178
+ * gone after its first patch, so Foldkit reconciles every such element, and
179
+ * a development build reports that the server's markup and the view
180
+ * disagree. Run as the page boots, so a form submitted before then still
181
+ * posts.
182
+ */
183
+ const unmark = (root) => {
184
+ root.removeAttribute(RESUME_ATTRIBUTE);
185
+ for (const element of [root, ...root.querySelectorAll("*")]) for (const name of element.getAttributeNames()) if (name.startsWith("data-foldkit-plus-on-") || name === "data-foldkit-plus-keep" || name === "data-foldkit-plus-slot") element.removeAttribute(name);
186
+ for (const field of root.querySelectorAll(`input[type="hidden"][name="${FALLBACK_FIELD}"]`)) {
187
+ const form = field.parentElement;
188
+ form?.removeAttribute("method");
189
+ form?.querySelector(`:scope > input[type="hidden"][name="${FALLBACK_DEPTH_FIELD}"]`)?.remove();
190
+ field.remove();
133
191
  }
134
- deferBoot(root, decoded.success, plan.start, {
135
- boot,
136
- answered
137
- }, pending, report);
192
+ };
193
+ /**
194
+ * Moves what a render's `styles` put in the root into the head, before
195
+ * anything adopts the page: the view does not draw it, so hydration would
196
+ * remove it, and a page that never renders again would lose the rules its
197
+ * classes need. Whatever adopts the page next finds them in the head.
198
+ */
199
+ const keepStyles = (root) => {
200
+ const marker = Array.from(root.childNodes).find((node) => node.nodeType === Node.COMMENT_NODE && node.nodeValue === "foldkit-plus-styles");
201
+ if (marker === void 0) return;
202
+ for (let next = marker.nextSibling; next !== null; next = marker.nextSibling) if (next instanceof Element) document.head.append(next);
203
+ else next.remove();
204
+ marker.remove();
138
205
  };
139
206
  /** The longest a served page stays in view while a fresh application waits for `until`. */
140
207
  const UNTIL_LIMIT_MS = 3e3;
@@ -190,10 +257,13 @@ const HANDOVER = Object.freeze({ _tag: "foldkit-ssr/Handover" });
190
257
  * `hydrate` returns, which Foldkit does today, or else when a handover
191
258
  * Subscription entry starts, after `Render.afterCommit`. When lazy bundles
192
259
  * must load first, the boot waits for them and the page keeps answering.
260
+ * Each kept field the person changed is put back, value and selection, as
261
+ * the first render commits, since that render re-asserts the served value.
193
262
  */
194
- const deferBoot = (root, decoded, start, runtime, pending, report) => {
263
+ const deferBoot = (root, decoded, start, runtime, pending, report, kept) => {
195
264
  const unanswered = [];
196
265
  let phase = "waiting";
266
+ let held = [];
197
267
  const stop = listen(root, {
198
268
  bindings: decoded.bindings,
199
269
  ...decoded.events === void 0 ? {} : { events: decoded.events },
@@ -218,6 +288,7 @@ const deferBoot = (root, decoded, start, runtime, pending, report) => {
218
288
  const handOver = () => {
219
289
  if (phase === "live") return;
220
290
  phase = "live";
291
+ restore(held);
221
292
  stop();
222
293
  for (const { event, element } of unanswered.splice(0)) {
223
294
  const Ctor = event.constructor;
@@ -226,6 +297,7 @@ const deferBoot = (root, decoded, start, runtime, pending, report) => {
226
297
  };
227
298
  const commit = () => {
228
299
  phase = "starting";
300
+ held = hold(kept);
229
301
  runtime.boot({ "foldkit-ssr.handover": {
230
302
  dependenciesSchema: Schema.Null,
231
303
  modelToDependencies: () => null,
@@ -266,6 +338,6 @@ const SSR = {
266
338
  static: staticRegion,
267
339
  serving
268
340
  };
269
- export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
341
+ export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, KEEP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
270
342
 
271
343
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["hydrate","Diagnostics","adopt"],"sources":["../src/client.ts"],"sourcesContent":["/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Option, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { withContext, type RenderContext } from './context.js'\nimport {\n bundleUnloaded,\n noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport { builder, view } from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n /**\n * Where what the page met goes: a page contained rather than resumed, a\n * static region the server's page lacked, a lazy bundle that did not\n * load. Each is reported before or apart from the runtime, so its\n * resources' reporter is not in effect. Omitted, Effect's log: the\n * browser's console.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): void => {\n const report = (diagnostic: SsrDiagnostic): void => {\n Effect.runFork(reportingTo(options.diagnostics)(Diagnostics.report(diagnostic)))\n }\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n // The type says a string, but `import.meta.env` is `any`: with the variable\n // unset the id arrives undefined, and Foldkit, given none, takes its own\n // compiled id, which matches the page, so the baseline was adopted in silence.\n if (typeof options.buildId !== 'string') {\n report(noBuildId)\n contain()\n return\n }\n const served = root.getAttribute(BUILD_ATTRIBUTE)\n if (served !== options.buildId) {\n report(otherBuild(Option.fromNullOr(served), options.buildId))\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n report(pageContained(resumed.failure.reason, resumed.failure.message))\n contain()\n return\n }\n const model = resumed.success\n const commands = (plan.boot?.(model) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n report,\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n const boot = (entries: Readonly<Record<string, unknown>> = {}) =>\n adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, { model, commands }), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n if (plan.start === 'now' && pending.length === 0) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n report(pageContained(decoded.failure.reason, decoded.failure.message))\n contain()\n return\n }\n deferBoot(root, decoded.success, plan.start, { boot, answered }, pending, report)\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport const UNTIL_LIMIT_MS = 3000\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n report: (diagnostic: SsrDiagnostic) => void,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n const stop = listen(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n report(bundleUnloaded(error))\n commit()\n })\n }\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n/** The diagnostics channel `hydrate` reports into, re-exported so a page needs no other import. */\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport type {\n BundleUnloaded,\n HandlerUnnamed,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;;;;;;AA2CA,MAAM,eAAe,SACnB,IAAI,IACF,MAAM,KAAK,KAAK,iBAAiB,IAAI,iBAAiB,EAAE,IAAG,YAAW,CACpE,QAAQ,aAAA,0BAA6B,KAAK,IAC1C,QAAQ,SACV,CAAC,CACH;;;;;;AAOF,MAAM,kBAAkB;;;;;;;;;;;AAYxB,MAAMA,aACJ,QACA,MACA,YAyCS;CACT,MAAM,UAAU,eAAoC;EAClD,OAAO,QAAQ,YAAY,QAAQ,WAAW,CAAC,CAACC,cAAY,OAAO,UAAU,CAAC,CAAC;CACjF;CACA,MAAM,WAAW,KAAK;CACtB,IAAI,aAAa,KAAA,GACf,SAAS;EACP,GAAG;EACH,eAAe;GAAE,GAAG,OAAO;GAAe,oBAAoB,UAAU,QAAQ;EAAE;CACpF;CAEF,MAAM,OAAO,SAAS,cAA2B,IAAI,sBAAsB,EAAE;CAI7E,MAAM,WAAW,QAAQ,SAAS,KAAA,KAAa,CAAC,QAAQ,KAAK,QAAQ;CACrE,MAAM,QAAQ,QAAQ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,iBAAiB;EACrB,IAAI,UAAU,QAAQ;EACtB,QAAQ;EACR,KAAK;EACL,KAAK,MAAM,EAAE,OAAO,aAAa,WAAW,OAAO,CAAC,GAAG;GACrD,MAAM,OAAO,MAAM;GACnB,QAAQ,cAAc,IAAI,KAAK,MAAM,MAAM,KAAK,CAAC;EACnD;CACF;CACA,MAAM,eAAe;EACnB,QAAQ;EACR,QAAQ,KAAK,EACX,wBAAwB;GACtB,oBAAoB,OAAO;GAC3B,2BAA2B;GAG3B,4BACE,OAAO,WACL,OAAO,GACL,OAAO,QACL,KAAK,aAAA,kBAAkC,IAAI,OAAO,cAAc,OAAO,MACvE,OAAO,KAAK,QAAQ,CACtB,GACA,QACF,CACF;EACJ,EACF,CAAC;EACD,IAAI,CAAC,KAAK,aAAA,kBAAkC,GAAG,SAAS;CAC1D;CACA,MAAM,iBAAiB;EACrB,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,IAAI,QAAQ,WAAW,GAAG;GACxB,OAAO;GACP;EACF;EACA,QAAa,IAAI,QAAQ,KAAI,WAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,UAAmB;GACtF,OAAO,eAAe,KAAK,CAAC;GAC5B,OAAO;EACT,CAAC;CACH;CACA,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;AAAQ"}
1
+ {"version":3,"file":"client.js","names":["hydrate","Diagnostics","adopt"],"sources":["../src/client.ts"],"sourcesContent":["/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Option, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { withContext, type RenderContext } from './context.js'\nimport {\n bundleUnloaded,\n noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { hold, keptFields, restore, typedMessages, type Held, type KeptField } from './keep.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport {\n BINDING_ATTRIBUTE,\n FALLBACK_DEPTH_FIELD,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n builder,\n view,\n} from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n STYLES_MARKER,\n arrival,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n /**\n * What only this browser adds to the resumed Model before it is adopted,\n * and the view does not draw: a session minted for this page load (an\n * outbox's `session`). Run once, for a page that resumes; the runtime\n * starts when it succeeds. What the view draws, such as a queue read from\n * storage, arrives after, as a Message: here it would make the first\n * client view differ from the served page. Must not fail, as `when` must\n * not throw.\n */\n readonly prepare?: ((model: Model) => Effect.Effect<Model>) | undefined\n /**\n * Where what the page met goes: a page contained rather than resumed, a\n * static region the server's page lacked, a lazy bundle that did not\n * load. Each is reported before or apart from the runtime, so its\n * resources' reporter is not in effect. Omitted, Effect's log: the\n * browser's console.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): void => {\n const report = (diagnostic: SsrDiagnostic): void => {\n Effect.runFork(reportingTo(options.diagnostics)(Diagnostics.report(diagnostic)))\n }\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (root !== null) keepStyles(root)\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n // The type says a string, but `import.meta.env` is `any`: with the variable\n // unset the id arrives undefined, and Foldkit, given none, takes its own\n // compiled id, which matches the page, so the baseline was adopted in silence.\n if (typeof options.buildId !== 'string') {\n report(noBuildId)\n contain()\n return\n }\n const served = root.getAttribute(BUILD_ATTRIBUTE)\n if (served !== options.buildId) {\n report(otherBuild(Option.fromNullOr(served), options.buildId))\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n report(pageContained(resumed.failure.reason, resumed.failure.message))\n contain()\n return\n }\n const adoptFrom = (model: Model): void => {\n // A page recorded for its path, opened at a query: the application learns\n // the URL, as from a navigation, and the page starts now, since what it\n // shows is not yet the address.\n const arrived = arrival(config, document, window.location.href)\n const bootCommands = (started: Model): ReadonlyArray<unknown> =>\n (plan.boot?.(started) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n report,\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n // The URL goes into the Model the runtime starts from, not into `answered`:\n // Subscriptions start from that Model before any Message lands, and a URL\n // mirror among them would write the served address back over the real one.\n // The first render then differs from the served page where the URL does, and\n // Foldkit rebuilds that part, as a navigation would redraw it. Applied at\n // boot, once any lazy bundle's `update` has loaded. The boot Commands are\n // planned from the Model the runtime actually starts with, so one derived\n // from the route or query sees the address the page arrived at.\n const startOf = () =>\n Option.match(arrived, {\n onNone: () => ({ model, commands: bootCommands(model) }),\n onSome: message => {\n const step = apply(model, message) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n return {\n model: step.model,\n commands: [...bootCommands(step.model), ...(step.commands ?? [])],\n }\n },\n })\n const boot = (entries: Readonly<Record<string, unknown>> = {}) => {\n unmark(root)\n return adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, startOf()), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n }\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n const start = Option.isSome(arrived) ? 'now' : plan.start\n const eager = start === 'now' && pending.length === 0\n if (eager && root.querySelector(`[${KEEP_ATTRIBUTE}]`) === null) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n report(pageContained(decoded.failure.reason, decoded.failure.message))\n contain()\n return\n }\n const kept = keptFields(root, decoded.success.bindings)\n if (Result.isFailure(kept)) {\n report(pageContained('Invalid', kept.failure))\n contain()\n return\n }\n // What was typed before this script ran, first in the queue: everything the\n // page answers from here on happened after it.\n answered.push(...typedMessages(kept.success))\n if (eager && answered.length === 0) {\n boot()\n return\n }\n // Typing is an interaction, whenever it happened: a page that waits for\n // one starts now, so what was typed is answered as soon as the script runs.\n const typed = answered.length > 0 ? 'now' : start\n deferBoot(root, decoded.success, typed, { boot, answered }, pending, report, kept.success)\n }\n const prepare = options.prepare\n if (prepare === undefined) adoptFrom(resumed.success)\n else void Effect.runPromise(prepare(resumed.success)).then(adoptFrom)\n}\n\n/**\n * Takes out of the served page what the server wrote for this script to read\n * and no view draws: the envelope, each binding's and kept field's marker,\n * each placement's slot, and each form's fallback (its `method` and hidden\n * fields). Left in, each is in what Foldkit records of the served page and\n * gone after its first patch, so Foldkit reconciles every such element, and\n * a development build reports that the server's markup and the view\n * disagree. Run as the page boots, so a form submitted before then still\n * posts.\n */\nconst unmark = (root: Element): void => {\n root.removeAttribute(RESUME_ATTRIBUTE)\n for (const element of [root, ...root.querySelectorAll('*')]) {\n for (const name of element.getAttributeNames()) {\n if (name.startsWith(BINDING_ATTRIBUTE) || name === KEEP_ATTRIBUTE || name === SLOT_ATTRIBUTE)\n element.removeAttribute(name)\n }\n }\n for (const field of root.querySelectorAll(`input[type=\"hidden\"][name=\"${FALLBACK_FIELD}\"]`)) {\n const form = field.parentElement\n form?.removeAttribute('method')\n form?.querySelector(`:scope > input[type=\"hidden\"][name=\"${FALLBACK_DEPTH_FIELD}\"]`)?.remove()\n field.remove()\n }\n}\n\n/**\n * Moves what a render's `styles` put in the root into the head, before\n * anything adopts the page: the view does not draw it, so hydration would\n * remove it, and a page that never renders again would lose the rules its\n * classes need. Whatever adopts the page next finds them in the head.\n */\nconst keepStyles = (root: Element): void => {\n const marker = Array.from(root.childNodes).find(\n node => node.nodeType === Node.COMMENT_NODE && node.nodeValue === STYLES_MARKER,\n )\n if (marker === undefined) return\n for (let next = marker.nextSibling; next !== null; next = marker.nextSibling) {\n if (next instanceof Element) document.head.append(next)\n else next.remove()\n }\n marker.remove()\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport const UNTIL_LIMIT_MS = 3000\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n * Each kept field the person changed is put back, value and selection, as\n * the first render commits, since that render re-asserts the served value.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n report: (diagnostic: SsrDiagnostic) => void,\n kept: ReadonlyArray<KeptField>,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n // The kept fields as the person left them, which the first render resets.\n let held: ReadonlyArray<Held> = []\n const stop = listen(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n // Before the queue runs, so its Messages find the fields holding their values.\n restore(held)\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n held = hold(kept)\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n report(bundleUnloaded(error))\n commit()\n })\n }\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n/** The diagnostics channel `hydrate` reports into, re-exported so a page needs no other import. */\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport type {\n BundleUnloaded,\n CachedPageDiffers,\n HandlerUnnamed,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuDA,MAAM,eAAe,SACnB,IAAI,IACF,MAAM,KAAK,KAAK,iBAAiB,IAAI,iBAAiB,EAAE,IAAG,YAAW,CACpE,QAAQ,aAAA,0BAA6B,KAAK,IAC1C,QAAQ,SACV,CAAC,CACH;;;;;;AAOF,MAAM,kBAAkB;;;;;;;;;;;AAYxB,MAAMA,aACJ,QACA,MACA,YAmDS;CACT,MAAM,UAAU,eAAoC;EAClD,OAAO,QAAQ,YAAY,QAAQ,WAAW,CAAC,CAACC,cAAY,OAAO,UAAU,CAAC,CAAC;CACjF;CACA,MAAM,WAAW,KAAK;CACtB,IAAI,aAAa,KAAA,GACf,SAAS;EACP,GAAG;EACH,eAAe;GAAE,GAAG,OAAO;GAAe,oBAAoB,UAAU,QAAQ;EAAE;CACpF;CAEF,MAAM,OAAO,SAAS,cAA2B,IAAI,sBAAsB,EAAE;CAC7E,IAAI,SAAS,MAAM,WAAW,IAAI;CAIlC,MAAM,WAAW,QAAQ,SAAS,KAAA,KAAa,CAAC,QAAQ,KAAK,QAAQ;CACrE,MAAM,QAAQ,QAAQ,UAAU,KAAA,KAAa,CAAC,QAAQ,MAAM,KAAK,OAAO;CACxE,IAAI,SAAS,MAAM;EACjB,IAAI,gBAAgB,MAAe,CAAC;EACpC;CACF;CACA,MAAM,WAAW,UACf,gBAAgB;EAAE,GAAG,aAAa,QAAQ,KAAK;EAAG,WAAW;CAAK,CAAU;CAG9E,MAAM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O,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;AAAQ"}
package/dist/context.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { B as within, F as Region, I as RenderContext, L as UnnamedHandler, P as Binding, R as current, z as withContext } from "./shared-v1u-OEQI.js";
1
+ import { B as current, H as within, I as Binding, L as Region, R as RenderContext, V as withContext, z as UnnamedHandler } from "./shared-CJN-m58Z.js";
2
2
  export { Binding, Region, RenderContext, UnnamedHandler, current, withContext, within };
package/dist/context.js CHANGED
@@ -2,13 +2,25 @@
2
2
  let context;
3
3
  /** The context of the view call in progress, if any. */
4
4
  const current = () => context;
5
+ /**
6
+ * Set on `globalThis` while the server renders a page, under a registered
7
+ * symbol so a view's packages find it from another bundle: a memoized
8
+ * drawing (`foldkit-mixins`' SlotView) is drawn afresh then, since one kept
9
+ * from another pass or request carries that render's markers and none of
10
+ * this one's bindings.
11
+ */
12
+ const SERVER_RENDER = Symbol.for("foldkit-plus.serverRender");
5
13
  const within = (next, run) => {
6
14
  const previous = context;
15
+ const global = globalThis;
16
+ const rendering = global[SERVER_RENDER];
7
17
  context = next;
18
+ global[SERVER_RENDER] = next.mode === "collect" || next.mode === "replay";
8
19
  try {
9
20
  return run();
10
21
  } finally {
11
22
  context = previous;
23
+ global[SERVER_RENDER] = rendering;
12
24
  }
13
25
  };
14
26
  /** The config whose view runs inside `next`. */
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * The render context: what the page's server-owned parts do, set around one\n * synchronous call of the view. `SSR.static` reads it to decide whether a\n * region renders, replays, or adopts the server's markup, and the resumable\n * builder reads it to decide whether to mark the bindings it builds. With no\n * context, as in a client-only render, both behave as ordinary view code.\n *\n * - `collect`: the server's render. Each region runs once and is kept, and\n * each binding is recorded in render order.\n * - `replay`: the server's second render, from the browser's Model. Each\n * region is the one already rendered, so it never reads the browser's Model;\n * bindings are recorded again, to be compared with the first render's.\n * - `resume`: the browser. Each region is the markup the server left in the\n * page, and its render never runs; no binding is marked.\n */\nimport type { Html } from 'foldkit/html'\nimport type { StaticRegionMissing } from './diagnostics.js'\n\nexport type Region = ReadonlyArray<Html | string>\n\n/** An element whose handler for `event` is a function, which the page cannot describe. */\nexport interface UnnamedHandler {\n readonly element: string\n readonly event: string\n}\n\n/**\n * An element's binding as the server's render records it, before encoding:\n * the Foldkit attribute and its DOM event, the element for diagnostics, and\n * the Message it causes. For a Message with a hole, `message` is the Message\n * with the hole filled by a placeholder, and `hole` names the fields the event\n * fills.\n */\nexport interface Binding {\n /** Foldkit's attribute, whose tag says what the handler does beside dispatching. */\n readonly attribute: string\n readonly event: string\n readonly element: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n /** How many placement wrappers enclose the hole's fields: `message` is entered that many times. */\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\nexport type RenderContext =\n | {\n readonly mode: 'collect'\n readonly regions: Map<string, Region>\n readonly duplicates: Set<string>\n readonly bindings: Array<Binding>\n /** Encodes a form's Message for its no-script fallback; absent when the plan has none. */\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n /** Lifts a Message of the view in progress to the application's, through each enclosing placement. */\n wrap: (message: unknown) => unknown\n /** How many placements enclose the view in progress. */\n depth: number\n /** The static region whose render is in progress, if any. */\n region: string | undefined\n /** Handlers met inside a static region, which the server alone renders. */\n readonly inStatic: Array<{\n readonly region: string\n readonly element: string\n readonly event: string\n }>\n /** Each element and event marked `*`: a handler the page cannot name. */\n readonly unnamed: Array<UnnamedHandler>\n }\n | {\n readonly mode: 'replay'\n readonly regions: ReadonlyMap<string, Region>\n readonly bindings: Array<Binding>\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n wrap: (message: unknown) => unknown\n depth: number\n }\n | {\n readonly mode: 'resume'\n readonly snapshots: ReadonlyMap<string, string>\n /** The regions already reported missing, so each is reported once. */\n readonly reported: Set<string>\n readonly report: (diagnostic: StaticRegionMissing) => void\n }\n\nlet context: RenderContext | undefined\n\n/** The context of the view call in progress, if any. */\nexport const current = (): RenderContext | undefined => context\n\nexport const within = <A>(next: RenderContext, run: () => A): A => {\n const previous = context\n context = next\n try {\n return run()\n } finally {\n context = previous\n }\n}\n\n/** The config whose view runs inside `next`. */\nexport const withContext = <Config extends { readonly view: (model: any, h: any) => unknown }>(\n config: Config,\n next: RenderContext,\n): Config => ({\n ...config,\n view: (model: unknown, h: unknown) => within(next, () => config.view(model, h)),\n})\n"],"mappings":";AAoFA,IAAI;;AAGJ,MAAa,gBAA2C;AAExD,MAAa,UAAa,MAAqB,QAAoB;CACjE,MAAM,WAAW;CACjB,UAAU;CACV,IAAI;EACF,OAAO,IAAI;CACb,UAAU;EACR,UAAU;CACZ;AACF;;AAGA,MAAa,eACX,QACA,UACY;CACZ,GAAG;CACH,OAAO,OAAgB,MAAe,OAAO,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC;AAChF"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * The render context: what the page's server-owned parts do, set around one\n * synchronous call of the view. `SSR.static` reads it to decide whether a\n * region renders, replays, or adopts the server's markup, and the resumable\n * builder reads it to decide whether to mark the bindings it builds. With no\n * context, as in a client-only render, both behave as ordinary view code.\n *\n * - `collect`: the server's render. Each region runs once and is kept, and\n * each binding is recorded in render order.\n * - `replay`: the server's second render, from the browser's Model. Each\n * region is the one already rendered, so it never reads the browser's Model;\n * bindings are recorded again, to be compared with the first render's.\n * - `resume`: the browser. Each region is the markup the server left in the\n * page, and its render never runs; no binding is marked.\n */\nimport type { Html } from 'foldkit/html'\nimport type { StaticRegionMissing } from './diagnostics.js'\n\nexport type Region = ReadonlyArray<Html | string>\n\n/** An element whose handler for `event` is a function, which the page cannot describe. */\nexport interface UnnamedHandler {\n readonly element: string\n readonly event: string\n}\n\n/**\n * An element's binding as the server's render records it, before encoding:\n * the Foldkit attribute and its DOM event, the element for diagnostics, and\n * the Message it causes. For a Message with a hole, `message` is the Message\n * with the hole filled by a placeholder, and `hole` names the fields the event\n * fills.\n */\nexport interface Binding {\n /** Foldkit's attribute, whose tag says what the handler does beside dispatching. */\n readonly attribute: string\n readonly event: string\n readonly element: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n /** How many placement wrappers enclose the hole's fields: `message` is entered that many times. */\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\nexport type RenderContext =\n | {\n readonly mode: 'collect'\n readonly regions: Map<string, Region>\n readonly duplicates: Set<string>\n readonly bindings: Array<Binding>\n /** Encodes a form's Message for its no-script fallback; absent when the plan has none. */\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n /** Lifts a Message of the view in progress to the application's, through each enclosing placement. */\n wrap: (message: unknown) => unknown\n /** How many placements enclose the view in progress. */\n depth: number\n /** The static region whose render is in progress, if any. */\n region: string | undefined\n /** Handlers met inside a static region, which the server alone renders. */\n readonly inStatic: Array<{\n readonly region: string\n readonly element: string\n readonly event: string\n }>\n /** Each element and event marked `*`: a handler the page cannot name. */\n readonly unnamed: Array<UnnamedHandler>\n /** Why each `KeepTyped` field met cannot be replayed, one line each. */\n readonly unkeepable: Array<string>\n }\n | {\n readonly mode: 'replay'\n readonly regions: ReadonlyMap<string, Region>\n readonly bindings: Array<Binding>\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n wrap: (message: unknown) => unknown\n depth: number\n }\n | {\n readonly mode: 'resume'\n readonly snapshots: ReadonlyMap<string, string>\n /** The regions already reported missing, so each is reported once. */\n readonly reported: Set<string>\n readonly report: (diagnostic: StaticRegionMissing) => void\n }\n\nlet context: RenderContext | undefined\n\n/** The context of the view call in progress, if any. */\nexport const current = (): RenderContext | undefined => context\n\n/**\n * Set on `globalThis` while the server renders a page, under a registered\n * symbol so a view's packages find it from another bundle: a memoized\n * drawing (`foldkit-mixins`' SlotView) is drawn afresh then, since one kept\n * from another pass or request carries that render's markers and none of\n * this one's bindings.\n */\nconst SERVER_RENDER = Symbol.for('foldkit-plus.serverRender')\n\nexport const within = <A>(next: RenderContext, run: () => A): A => {\n const previous = context\n const global = globalThis as Record<symbol, unknown>\n const rendering = global[SERVER_RENDER]\n context = next\n global[SERVER_RENDER] = next.mode === 'collect' || next.mode === 'replay'\n try {\n return run()\n } finally {\n context = previous\n global[SERVER_RENDER] = rendering\n }\n}\n\n/** The config whose view runs inside `next`. */\nexport const withContext = <Config extends { readonly view: (model: any, h: any) => unknown }>(\n config: Config,\n next: RenderContext,\n): Config => ({\n ...config,\n view: (model: unknown, h: unknown) => within(next, () => config.view(model, h)),\n})\n"],"mappings":";AAsFA,IAAI;;AAGJ,MAAa,gBAA2C;;;;;;;;AASxD,MAAM,gBAAgB,OAAO,IAAI,2BAA2B;AAE5D,MAAa,UAAa,MAAqB,QAAoB;CACjE,MAAM,WAAW;CACjB,MAAM,SAAS;CACf,MAAM,YAAY,OAAO;CACzB,UAAU;CACV,OAAO,iBAAiB,KAAK,SAAS,aAAa,KAAK,SAAS;CACjE,IAAI;EACF,OAAO,IAAI;CACb,UAAU;EACR,UAAU;EACV,OAAO,iBAAiB;CAC1B;AACF;;AAGA,MAAa,eACX,QACA,UACY;CACZ,GAAG;CACH,OAAO,OAAgB,MAAe,OAAO,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC;AAChF"}
@@ -1,2 +1,2 @@
1
- import { $ as reportingTo, G as SsrDiagnostic, H as HandlerUnnamed, J as handlerUnnamed, K as StaticRegionMissing, Q as pageFailed, U as PageContained, V as BundleUnloaded, W as PageFailed, X as otherBuild, Y as noBuildId, Z as pageContained, et as staticRegionMissing, q as bundleUnloaded } from "./shared-v1u-OEQI.js";
2
- export { BundleUnloaded, HandlerUnnamed, PageContained, PageFailed, SsrDiagnostic, StaticRegionMissing, bundleUnloaded, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
1
+ import { $ as noBuildId, G as HandlerUnnamed, J as SsrDiagnostic, K as PageContained, Q as handlerUnnamed, U as BundleUnloaded, W as CachedPageDiffers, X as bundleUnloaded, Y as StaticRegionMissing, Z as cachedPageDiffers, et as otherBuild, it as staticRegionMissing, nt as pageFailed, q as PageFailed, rt as reportingTo, tt as pageContained } from "./shared-CJN-m58Z.js";
2
+ export { BundleUnloaded, CachedPageDiffers, HandlerUnnamed, PageContained, PageFailed, SsrDiagnostic, StaticRegionMissing, bundleUnloaded, cachedPageDiffers, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
@@ -54,6 +54,13 @@ const handlerUnnamed = (plan, element, event) => ({
54
54
  });
55
55
  /** `effect` reporting to `report` when one is given, else to the reporter in its context. */
56
56
  const reportingTo = (report) => (effect) => report === void 0 ? effect : Effect.provideService(effect, Diagnostics.Reporter, report);
57
- export { bundleUnloaded, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
57
+ const cachedPageDiffers = (url) => ({
58
+ _tag: "CachedPageDiffers",
59
+ source,
60
+ level: "error",
61
+ message: `the page kept for ${url} was drawn otherwise for a request it served, so something the render read is not the URL alone; find what in flags, prepare, headers, status or the view differs between requests`,
62
+ url
63
+ });
64
+ export { bundleUnloaded, cachedPageDiffers, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
58
65
 
59
66
  //# sourceMappingURL=diagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What SSR meets and keeps going past: a page the browser contains rather\n * than resumes, a static region or lazy bundle it draws without, a request\n * answered 500, and a handler that keeps a page from answering before boot.\n * Each is reported through `Diagnostics.report`, by default to the log.\n */\nimport { Cause, Effect, Option } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ResumeRefused } from './shared.js'\n\nconst source = 'foldkit-ssr'\n\n/** A served page the browser contained instead of resuming: it stays in view, inert, and no runtime starts. */\nexport interface PageContained extends Diagnostic {\n readonly _tag: 'PageContained'\n /**\n * `NoBuildId` when `SSR.hydrate` was given none, `OtherBuild` when the page\n * names another deployment; otherwise why the envelope was refused.\n */\n readonly reason: 'NoBuildId' | 'OtherBuild' | ResumeRefused['reason']\n}\n\n/** A static region the browser asked for that the server's page did not hold, rendered in the browser. */\nexport interface StaticRegionMissing extends Diagnostic {\n readonly _tag: 'StaticRegionMissing'\n readonly region: string\n}\n\n/** A lazy bundle whose bodies did not load; the runtime boots without them. */\nexport interface BundleUnloaded extends Diagnostic {\n readonly _tag: 'BundleUnloaded'\n readonly error: unknown\n}\n\n/** A request answered 500: its `headers` threw, or its page could not be rendered. */\nexport interface PageFailed extends Diagnostic {\n readonly _tag: 'PageFailed'\n readonly url: string\n readonly cause: Cause.Cause<unknown>\n}\n\n/** A handler the page cannot name, so its event waits for the live runtime. Reported once per process. */\nexport interface HandlerUnnamed extends Diagnostic {\n readonly _tag: 'HandlerUnnamed'\n readonly plan: string\n readonly element: string\n readonly event: string\n}\n\n/** Every diagnostic SSR reports. */\nexport type SsrDiagnostic =\n | PageContained\n | StaticRegionMissing\n | BundleUnloaded\n | PageFailed\n | HandlerUnnamed\n\nexport const pageContained = (reason: PageContained['reason'], detail: string): PageContained => ({\n _tag: 'PageContained',\n source,\n level: 'error',\n message: `the page cannot resume, so it is contained: ${detail}`,\n reason,\n})\n\nexport const noBuildId: PageContained = pageContained(\n 'NoBuildId',\n \"SSR.hydrate was given no build id, so it cannot tell this page from another deployment's. Pass the id the server stamped: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID (or `foldkit({ buildId })`) so that `import.meta.env.FOLDKIT_BUILD_ID` is defined in the client too.\",\n)\n\n/** The page's stamped build id, if it has one, is not the client's `client`. */\nexport const otherBuild = (served: Option.Option<string>, client: string): PageContained =>\n pageContained(\n 'OtherBuild',\n `it was served by ${Option.match(served, {\n onNone: () => 'no known deployment',\n onSome: id => `deployment \"${id}\"`,\n })}, but this client belongs to deployment \"${client}\". If both came from one build, they were given different ids: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID in the build's environment, or once in vite.config.ts before \\`foldkit()\\` reads it (\\`process.env.FOLDKIT_BUILD_ID ??= randomUUID()\\`). Otherwise serve the page from the running deployment.`,\n )\n\nexport const staticRegionMissing = (region: string): StaticRegionMissing => ({\n _tag: 'StaticRegionMissing',\n source,\n level: 'error',\n message: `the static region \"${region}\" is not in the server's page, so it is rendered in the browser`,\n region,\n})\n\nexport const bundleUnloaded = (error: unknown): BundleUnloaded => ({\n _tag: 'BundleUnloaded',\n source,\n level: 'error',\n message: `a bundle's bodies did not load, and the page boots without them: ${String(error)}`,\n error,\n})\n\nexport const pageFailed = (url: string, cause: Cause.Cause<unknown>): PageFailed => ({\n _tag: 'PageFailed',\n source,\n level: 'error',\n message: `${url} was answered 500: ${Cause.pretty(cause)}`,\n url,\n cause,\n})\n\nexport const handlerUnnamed = (plan: string, element: string, event: string): HandlerUnnamed => ({\n _tag: 'HandlerUnnamed',\n source,\n level: 'warning',\n message: `plan \"${plan}\": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,\n plan,\n element,\n event,\n})\n\n/** `effect` reporting to `report` when one is given, else to the reporter in its context. */\nexport const reportingTo =\n (report: ReportDiagnostic | undefined) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n report === undefined ? effect : Effect.provideService(effect, Diagnostics.Reporter, report)\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;AA+Cf,MAAa,iBAAiB,QAAiC,YAAmC;CAChG,MAAM;CACN;CACA,OAAO;CACP,SAAS,+CAA+C;CACxD;AACF;AAEA,MAAa,YAA2B,cACtC,aACA,gRACF;;AAGA,MAAa,cAAc,QAA+B,WACxD,cACE,cACA,oBAAoB,OAAO,MAAM,QAAQ;CACvC,cAAc;CACd,SAAQ,OAAM,eAAe,GAAG;AAClC,CAAC,EAAE,2CAA2C,OAAO,8SACvD;AAEF,MAAa,uBAAuB,YAAyC;CAC3E,MAAM;CACN;CACA,OAAO;CACP,SAAS,sBAAsB,OAAO;CACtC;AACF;AAEA,MAAa,kBAAkB,WAAoC;CACjE,MAAM;CACN;CACA,OAAO;CACP,SAAS,oEAAoE,OAAO,KAAK;CACzF;AACF;AAEA,MAAa,cAAc,KAAa,WAA6C;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,IAAI,qBAAqB,MAAM,OAAO,KAAK;CACvD;CACA;AACF;AAEA,MAAa,kBAAkB,MAAc,SAAiB,WAAmC;CAC/F,MAAM;CACN;CACA,OAAO;CACP,SAAS,SAAS,KAAK,KAAK,QAAQ,WAAW,MAAM;CACrD;CACA;CACA;AACF;;AAGA,MAAa,eACV,YACS,WACR,WAAW,KAAA,IAAY,SAAS,OAAO,eAAe,QAAQ,YAAY,UAAU,MAAM"}
1
+ {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What SSR meets and keeps going past: a page the browser contains rather\n * than resumes, a static region or lazy bundle it draws without, a request\n * answered 500, and a handler that keeps a page from answering before boot.\n * Each is reported through `Diagnostics.report`, by default to the log.\n */\nimport { Cause, Effect, Option } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ResumeRefused } from './shared.js'\n\nconst source = 'foldkit-ssr'\n\n/** A served page the browser contained instead of resuming: it stays in view, inert, and no runtime starts. */\nexport interface PageContained extends Diagnostic {\n readonly _tag: 'PageContained'\n /**\n * `NoBuildId` when `SSR.hydrate` was given none, `OtherBuild` when the page\n * names another deployment; otherwise why the envelope was refused.\n */\n readonly reason: 'NoBuildId' | 'OtherBuild' | ResumeRefused['reason']\n}\n\n/** A static region the browser asked for that the server's page did not hold, rendered in the browser. */\nexport interface StaticRegionMissing extends Diagnostic {\n readonly _tag: 'StaticRegionMissing'\n readonly region: string\n}\n\n/** A lazy bundle whose bodies did not load; the runtime boots without them. */\nexport interface BundleUnloaded extends Diagnostic {\n readonly _tag: 'BundleUnloaded'\n readonly error: unknown\n}\n\n/** A request answered 500: its `headers` threw, or its page could not be rendered. */\nexport interface PageFailed extends Diagnostic {\n readonly _tag: 'PageFailed'\n readonly url: string\n readonly cause: Cause.Cause<unknown>\n}\n\n/** A handler the page cannot name, so its event waits for the live runtime. Reported once per process. */\nexport interface HandlerUnnamed extends Diagnostic {\n readonly _tag: 'HandlerUnnamed'\n readonly plan: string\n readonly element: string\n readonly event: string\n}\n\n/**\n * A kept page drawn otherwise for the request it served (`SSR.entry`'s\n * `cache.check`): the render read something of the request, or anything\n * else that differs between requests, that the cache could not see. The\n * request was given the page drawn again.\n */\nexport interface CachedPageDiffers extends Diagnostic {\n readonly _tag: 'CachedPageDiffers'\n readonly url: string\n}\n\n/** Every diagnostic SSR reports. */\nexport type SsrDiagnostic =\n | PageContained\n | StaticRegionMissing\n | BundleUnloaded\n | PageFailed\n | HandlerUnnamed\n | CachedPageDiffers\n\nexport const pageContained = (reason: PageContained['reason'], detail: string): PageContained => ({\n _tag: 'PageContained',\n source,\n level: 'error',\n message: `the page cannot resume, so it is contained: ${detail}`,\n reason,\n})\n\nexport const noBuildId: PageContained = pageContained(\n 'NoBuildId',\n \"SSR.hydrate was given no build id, so it cannot tell this page from another deployment's. Pass the id the server stamped: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID (or `foldkit({ buildId })`) so that `import.meta.env.FOLDKIT_BUILD_ID` is defined in the client too.\",\n)\n\n/** The page's stamped build id, if it has one, is not the client's `client`. */\nexport const otherBuild = (served: Option.Option<string>, client: string): PageContained =>\n pageContained(\n 'OtherBuild',\n `it was served by ${Option.match(served, {\n onNone: () => 'no known deployment',\n onSome: id => `deployment \"${id}\"`,\n })}, but this client belongs to deployment \"${client}\". If both came from one build, they were given different ids: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID in the build's environment, or once in vite.config.ts before \\`foldkit()\\` reads it (\\`process.env.FOLDKIT_BUILD_ID ??= randomUUID()\\`). Otherwise serve the page from the running deployment.`,\n )\n\nexport const staticRegionMissing = (region: string): StaticRegionMissing => ({\n _tag: 'StaticRegionMissing',\n source,\n level: 'error',\n message: `the static region \"${region}\" is not in the server's page, so it is rendered in the browser`,\n region,\n})\n\nexport const bundleUnloaded = (error: unknown): BundleUnloaded => ({\n _tag: 'BundleUnloaded',\n source,\n level: 'error',\n message: `a bundle's bodies did not load, and the page boots without them: ${String(error)}`,\n error,\n})\n\nexport const pageFailed = (url: string, cause: Cause.Cause<unknown>): PageFailed => ({\n _tag: 'PageFailed',\n source,\n level: 'error',\n message: `${url} was answered 500: ${Cause.pretty(cause)}`,\n url,\n cause,\n})\n\nexport const handlerUnnamed = (plan: string, element: string, event: string): HandlerUnnamed => ({\n _tag: 'HandlerUnnamed',\n source,\n level: 'warning',\n message: `plan \"${plan}\": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,\n plan,\n element,\n event,\n})\n\n/** `effect` reporting to `report` when one is given, else to the reporter in its context. */\nexport const reportingTo =\n (report: ReportDiagnostic | undefined) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n report === undefined ? effect : Effect.provideService(effect, Diagnostics.Reporter, report)\n\nexport const cachedPageDiffers = (url: string): CachedPageDiffers => ({\n _tag: 'CachedPageDiffers',\n source,\n level: 'error',\n message: `the page kept for ${url} was drawn otherwise for a request it served, so something the render read is not the URL alone; find what in flags, prepare, headers, status or the view differs between requests`,\n url,\n})\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;AA2Df,MAAa,iBAAiB,QAAiC,YAAmC;CAChG,MAAM;CACN;CACA,OAAO;CACP,SAAS,+CAA+C;CACxD;AACF;AAEA,MAAa,YAA2B,cACtC,aACA,gRACF;;AAGA,MAAa,cAAc,QAA+B,WACxD,cACE,cACA,oBAAoB,OAAO,MAAM,QAAQ;CACvC,cAAc;CACd,SAAQ,OAAM,eAAe,GAAG;AAClC,CAAC,EAAE,2CAA2C,OAAO,8SACvD;AAEF,MAAa,uBAAuB,YAAyC;CAC3E,MAAM;CACN;CACA,OAAO;CACP,SAAS,sBAAsB,OAAO;CACtC;AACF;AAEA,MAAa,kBAAkB,WAAoC;CACjE,MAAM;CACN;CACA,OAAO;CACP,SAAS,oEAAoE,OAAO,KAAK;CACzF;AACF;AAEA,MAAa,cAAc,KAAa,WAA6C;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,IAAI,qBAAqB,MAAM,OAAO,KAAK;CACvD;CACA;AACF;AAEA,MAAa,kBAAkB,MAAc,SAAiB,WAAmC;CAC/F,MAAM;CACN;CACA,OAAO;CACP,SAAS,SAAS,KAAK,KAAK,QAAQ,WAAW,MAAM;CACrD;CACA;CACA;AACF;;AAGA,MAAa,eACV,YACS,WACR,WAAW,KAAA,IAAY,SAAS,OAAO,eAAe,QAAQ,YAAY,UAAU,MAAM;AAE9F,MAAa,qBAAqB,SAAoC;CACpE,MAAM;CACN;CACA,OAAO;CACP,SAAS,qBAAqB,IAAI;CAClC;AACF"}