foldkit-ssr 0.8.2 → 0.9.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 (50) hide show
  1. package/README.md +203 -69
  2. package/dist/client-F16QT0sc.d.ts +75 -0
  3. package/dist/client-F16QT0sc.d.ts.map +1 -0
  4. package/dist/client.d.ts +5 -0
  5. package/dist/client.js +271 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/context.d.ts +2 -0
  8. package/dist/context.js +21 -0
  9. package/dist/context.js.map +1 -0
  10. package/dist/diagnostics.d.ts +2 -0
  11. package/dist/diagnostics.js +59 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/{index.d.mts → index.d.ts} +18 -7
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/{index.mjs → index.js} +79 -60
  16. package/dist/index.js.map +1 -0
  17. package/dist/listen-zNd0IIAT.d.ts +69 -0
  18. package/dist/listen-zNd0IIAT.d.ts.map +1 -0
  19. package/dist/listen.d.ts +2 -0
  20. package/dist/listen.js +179 -0
  21. package/dist/listen.js.map +1 -0
  22. package/dist/requestContext-D9nsbGSJ.d.ts +21 -0
  23. package/dist/requestContext-D9nsbGSJ.d.ts.map +1 -0
  24. package/dist/requestContext.d.ts +2 -0
  25. package/dist/requestContext.js +48 -0
  26. package/dist/requestContext.js.map +1 -0
  27. package/dist/resumable-BWItJsxF.d.ts +86 -0
  28. package/dist/resumable-BWItJsxF.d.ts.map +1 -0
  29. package/dist/resumable.d.ts +2 -0
  30. package/dist/resumable.js +358 -0
  31. package/dist/resumable.js.map +1 -0
  32. package/dist/{client-DkwAniQQ.d.mts → shared-v1u-OEQI.d.ts} +218 -194
  33. package/dist/shared-v1u-OEQI.d.ts.map +1 -0
  34. package/dist/shared.d.ts +2 -0
  35. package/dist/shared.js +324 -0
  36. package/dist/shared.js.map +1 -0
  37. package/dist/{vite.d.mts → vite.d.ts} +3 -5
  38. package/dist/vite.d.ts.map +1 -0
  39. package/dist/{vite.mjs → vite.js} +3 -4
  40. package/dist/vite.js.map +1 -0
  41. package/package.json +17 -17
  42. package/dist/client-DVG9_3rL.mjs +0 -1113
  43. package/dist/client-DVG9_3rL.mjs.map +0 -1
  44. package/dist/client-DkwAniQQ.d.mts.map +0 -1
  45. package/dist/client.d.mts +0 -2
  46. package/dist/client.mjs +0 -1
  47. package/dist/index.d.mts.map +0 -1
  48. package/dist/index.mjs.map +0 -1
  49. package/dist/vite.d.mts.map +0 -1
  50. package/dist/vite.mjs.map +0 -1
package/dist/shared.js ADDED
@@ -0,0 +1,324 @@
1
+ import { current } from "./context.js";
2
+ import { staticRegionMissing } from "./diagnostics.js";
3
+ import { decodeBindings, readBindings } from "./listen.js";
4
+ import { Effect, Option, Result, Schema, Stream } from "effect";
5
+ import { ModelRef } from "foldkit-surface";
6
+ import { inertHtml } from "foldkit/html";
7
+ // src/shared.ts
8
+ /**
9
+ * What the server and the browser both read: the plan, the envelope as the
10
+ * browser reads it, static regions, and the page's bindings. Nothing here
11
+ * imports Foldkit's server renderer, so `client.ts` can carry all of it.
12
+ */
13
+ /**
14
+ * The attribute Foldkit's server stamps on an application's root, as
15
+ * `foldkit/experimental/server` exports it. Written out here so a page can
16
+ * find its root without that module; a test pins the two together.
17
+ */
18
+ const FOLDKIT_APP_ATTRIBUTE = "data-foldkit-app";
19
+ /**
20
+ * The attribute on the stamped root that carries a page's resume envelope.
21
+ * Foldkit pairs its own handoff the same way: the build id rides on the root
22
+ * beside the app stamp, and the client reads it before adopting anything.
23
+ */
24
+ const RESUME_ATTRIBUTE = "data-foldkit-plus-resume";
25
+ /** The envelope format this package writes and reads. */
26
+ const PROTOCOL = 1;
27
+ const LINE_SEPARATOR = String.fromCharCode(8232);
28
+ const PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
29
+ /**
30
+ * JSON for a script element: `<` is escaped so `<\/script>` in the data ends
31
+ * nothing. U+2028 and U+2029 are escaped too: they are fine in JSON and break a
32
+ * reader that treats the text as JavaScript.
33
+ */
34
+ const serializeJsonScript = (value) => JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(LINE_SEPARATOR, "\\u2028").replaceAll(PARAGRAPH_SEPARATOR, "\\u2029");
35
+ /**
36
+ * The envelope JSON as the stamped root carries it: `serializeJsonScript`
37
+ * already escaped `<` and the line separators, and an attribute must escape
38
+ * `&` and `"` besides, so no string in the Model can break out of the value.
39
+ * `getAttribute` resolves the entities back, which is exactly the JSON.
40
+ */
41
+ const attributeOf = (json) => ` ${RESUME_ATTRIBUTE}="${json.replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}"`;
42
+ /** Marks each head element a plan's `meta` wrote, so the browser can replace them. */
43
+ const META_ATTRIBUTE = "data-foldkit-meta";
44
+ const attributeText = (text) => text.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
45
+ /** The head markup of a `Meta`, every value escaped, one element per line. */
46
+ const metaMarkup = (meta) => {
47
+ const tag = (element, attributes) => `<${element} ${META_ATTRIBUTE} ${attributes.map(([name, value]) => `${name}="${attributeText(value)}"`).join(" ")}>`;
48
+ const named = (name, value) => value === void 0 ? [] : [tag("meta", [["name", name], ["content", value]])];
49
+ const property = (name, value) => value === void 0 ? [] : [tag("meta", [["property", name], ["content", value]])];
50
+ return [
51
+ ...named("description", meta.description),
52
+ ...property("og:title", meta.title),
53
+ ...property("og:description", meta.description),
54
+ ...property("og:type", meta.type),
55
+ ...property("og:site_name", meta.siteName),
56
+ ...property("og:image", meta.image),
57
+ ...meta.description === void 0 && meta.image === void 0 && meta.title === void 0 ? [] : named("twitter:card", meta.image === void 0 ? "summary" : "summary_large_image"),
58
+ ...property("article:published_time", meta.article?.published),
59
+ ...property("article:modified_time", meta.article?.modified),
60
+ ...named("robots", meta.robots),
61
+ ...(meta.alternates ?? []).map(({ hreflang, href }) => tag("link", [
62
+ ["rel", "alternate"],
63
+ ["hreflang", hreflang],
64
+ ["href", href]
65
+ ])),
66
+ ...(meta.jsonLd ?? []).map((data) => `<script ${META_ATTRIBUTE} type="application/ld+json">${serializeJsonScript(data)}<\/script>`)
67
+ ].join("\n");
68
+ };
69
+ /**
70
+ * The Subscription entry that keeps the head's `meta` elements in step with
71
+ * the Model, so a move within the page (another post) changes its
72
+ * description too. It writes the head and sends no Message.
73
+ */
74
+ const metaEntry = (meta) => ({
75
+ dependenciesSchema: Schema.String,
76
+ modelToDependencies: (model) => metaMarkup(meta(model)),
77
+ dependenciesToStream: (markup) => Stream.drain(Stream.fromEffect(Effect.sync(() => {
78
+ const written = document.createElement("template");
79
+ written.innerHTML = markup;
80
+ for (const old of document.head.querySelectorAll(`[${META_ATTRIBUTE}]`)) old.remove();
81
+ document.head.append(written.content);
82
+ })))
83
+ });
84
+ /**
85
+ * What a plan entry resolves to for a Model: the lone projection of a
86
+ * `Surface.at`/`Surface.when` value, or a family's parent first and then each
87
+ * instance. The parent joins so the envelope carries what the instances were
88
+ * discovered through, not just what they read.
89
+ */
90
+ const projectionsOf = (source, model) => {
91
+ if (typeof source.instancesOf === "function") {
92
+ const origin = source;
93
+ const from = source.from;
94
+ return [...from === void 0 ? [] : Option.toArray(from.projectionOf(model)), ...origin.instancesOf(model).map((instance) => instance.projection)];
95
+ }
96
+ return Option.toArray(source.projectionOf(model));
97
+ };
98
+ /** Why a page's resume envelope was refused. */
99
+ var ResumeRefused = class extends Schema.TaggedError()("ResumeRefused", {
100
+ reason: Schema.Literals([
101
+ "Missing",
102
+ "Duplicate",
103
+ "Unreadable",
104
+ "Protocol",
105
+ "Plan",
106
+ "Invalid",
107
+ "Route"
108
+ ]),
109
+ message: Schema.String
110
+ }) {};
111
+ const refuse = (reason, message) => Result.fail(new ResumeRefused({
112
+ reason,
113
+ message
114
+ }));
115
+ /**
116
+ * The slice's Schema as a codec needing no services. A resume plan's state is
117
+ * plain data, so any field that needs one cannot cross a page anyway.
118
+ */
119
+ const codecOf = (schema) => schema;
120
+ /**
121
+ * A resume plan for an application. The baseline defaults to the
122
+ * application's initial Model. It is never written: a writable projection's
123
+ * `set` returns a new Model, so a baseline Foldkit freezes in development is
124
+ * safe to start from.
125
+ *
126
+ * `surfaces` are the Surfaces the browser may activate, and `local` the Model
127
+ * fields allowed to start from the baseline, such as an open menu. Rendering
128
+ * refuses a plan that leaves a Surface's read or activation in neither.
129
+ */
130
+ const plan = (application, config) => {
131
+ const surfaces = config.surfaces ?? [];
132
+ const parts = config.parts ?? [];
133
+ const repeated = parts.find((part, index) => parts.findIndex((p) => p.id === part.id) !== index);
134
+ if (repeated !== void 0) throw new Error(`SSR.plan: two parts of plan "${config.id}" share the id "${repeated.id}"; give one an id of its own`);
135
+ const foreign = surfaces.flatMap((surface) => {
136
+ const from = surface.from;
137
+ return from === void 0 ? [surface] : [surface, from];
138
+ }).find((surface) => application.owner !== void 0 && surface.owner !== application.owner);
139
+ if (foreign !== void 0) throw new Error(`SSR.plan: the Surface "${foreign.name}" belongs to another application than plan "${config.id}"`);
140
+ return {
141
+ id: config.id,
142
+ state: config.state,
143
+ baseline: config.baseline ?? application.initial,
144
+ ...config.boot === void 0 ? {} : { boot: config.boot },
145
+ local: (config.local ?? []).map((place) => ModelRef.focus(place).dependency),
146
+ surfaces,
147
+ parts,
148
+ ...application.Message === void 0 ? {} : { Message: application.Message },
149
+ start: config.start ?? "now",
150
+ deferrable: config.deferrable ?? [],
151
+ ...config.fallback === void 0 ? {} : { fallback: config.fallback },
152
+ ...config.meta === void 0 ? {} : { meta: config.meta },
153
+ ...config.version === void 0 ? {} : { version: config.version }
154
+ };
155
+ };
156
+ /** A path as a `path` match compares it. */
157
+ const pathKey = (route) => {
158
+ const trimmed = (route.split(/[?#]/)[0] ?? "").replace(/\/index\.html$/, "/").replace(/\/+$/, "");
159
+ return trimmed === "" ? "/" : trimmed;
160
+ };
161
+ /**
162
+ * The Model a payload resumes: the baseline with the slice set onto it, then
163
+ * each part restored, in order. Every part the plan names must be there and
164
+ * restore, and no other may be: a page is never half-restored.
165
+ */
166
+ const modelFrom = (plan, payload) => {
167
+ const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state);
168
+ if (Result.isFailure(decoded)) return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`);
169
+ const given = payload.parts ?? {};
170
+ if (typeof given !== "object" || Array.isArray(given)) return Result.fail("the envelope's parts are not an object of parts by id");
171
+ const parts = given;
172
+ const unknown = Object.keys(parts).find((id) => !plan.parts.some((part) => part.id === id));
173
+ if (unknown !== void 0) return Result.fail(`the envelope carries a part "${unknown}" the plan does not name`);
174
+ let model = plan.state.set(plan.baseline, decoded.success);
175
+ for (const part of plan.parts) {
176
+ if (!Object.hasOwn(parts, part.id)) return Result.fail(`the envelope carries no "${part.id}" part`);
177
+ const restored = part.restore(model, parts[part.id]);
178
+ if (Result.isFailure(restored)) return Result.fail(`the "${part.id}" part does not restore: ${restored.failure}`);
179
+ model = restored.success;
180
+ }
181
+ return Result.succeed(model);
182
+ };
183
+ /** The page's envelope, read off its stamped root; refused when there is no root, more than one, no envelope, or not JSON. */
184
+ const readEnvelope = (page) => {
185
+ const roots = page.querySelectorAll(`[${FOLDKIT_APP_ATTRIBUTE}]`);
186
+ if (roots.length === 0) return refuse("Missing", "the page holds no stamped application root");
187
+ if (roots.length > 1) return refuse("Duplicate", `the page holds ${roots.length} stamped application roots`);
188
+ const carried = roots[0]?.getAttribute(RESUME_ATTRIBUTE);
189
+ if (carried === null || carried === void 0) return refuse("Missing", "the page holds no resume envelope");
190
+ try {
191
+ const parsed = JSON.parse(carried);
192
+ return Result.succeed(parsed ?? {});
193
+ } catch (error) {
194
+ return refuse("Unreadable", `the resume envelope is not JSON: ${String(error)}`);
195
+ }
196
+ };
197
+ /**
198
+ * The Model a page resumes from: the baseline with the stamped root's envelope
199
+ * set onto it. Refused, with the reason, when the page holds no stamped root
200
+ * or more than one, when the root carries no envelope or not JSON, when it is
201
+ * not this protocol or this plan, or when the slice does not decode through
202
+ * the plan's Schema. A page is never half-restored.
203
+ */
204
+ const resume = (plan, page, options = {}) => {
205
+ const read = readEnvelope(page);
206
+ if (Result.isFailure(read)) return Result.fail(read.failure);
207
+ const { v, plan: id, state, parts, route, match } = read.success;
208
+ if (v !== 1) return refuse("Protocol", `the envelope is protocol ${String(v)}, not 1`);
209
+ if (id !== plan.id) return refuse("Plan", `the envelope is for plan "${String(id)}", not "${plan.id}"`);
210
+ if (route !== void 0 && options.route !== void 0) {
211
+ if (!(match === "path" ? pathKey(String(route)) === pathKey(options.route) : route === options.route)) return refuse("Route", `the page was ${match === "path" ? "generated" : "rendered"} for ${String(route)}, not ${options.route}`);
212
+ }
213
+ const resumed = modelFrom(plan, {
214
+ state,
215
+ parts
216
+ });
217
+ return Result.isFailure(resumed) ? refuse("Invalid", resumed.failure) : Result.succeed(resumed.success);
218
+ };
219
+ /** The tag a Message value carries, for naming it. */
220
+ const tagOf = (message) => typeof message === "object" && message !== null && "_tag" in message && typeof message._tag === "string" ? message._tag : "an untagged Message";
221
+ /**
222
+ * The Message tags the plan's Surfaces active for `model` may send, which is
223
+ * what a page's bindings may dispatch (the design's rule 3).
224
+ */
225
+ const allowedTags = (plan, model) => new Set(plan.surfaces.flatMap((source) => projectionsOf(source, model).length > 0 ? source.messages : []));
226
+ /** The attribute on a static region's element, naming the region. */
227
+ const STATIC_ATTRIBUTE = "data-foldkit-plus-static";
228
+ const boundary = (id, trusted, children) => inertHtml.div([inertHtml.Attribute(STATIC_ATTRIBUTE, id), ...trusted === void 0 ? [] : [inertHtml.InnerHTML(trusted)]], children);
229
+ /**
230
+ * A region of the page the server owns for the life of the document. It is
231
+ * rendered on the server with the inert builder, so it can dispatch no
232
+ * Message. The browser adopts the server's markup as trusted `InnerHTML` and
233
+ * never runs `render`, so the region reads nothing from the browser's Model
234
+ * and a plan need not send what it reads.
235
+ *
236
+ * A region changes only with a new document. Content a Message should change
237
+ * belongs in a Surface, not here.
238
+ */
239
+ const staticRegion = (id, render) => {
240
+ const now = current();
241
+ if (now?.mode === "resume") {
242
+ const snapshot = now.snapshots.get(id);
243
+ if (snapshot !== void 0) return boundary(id, snapshot, []);
244
+ if (!now.reported.has(id)) {
245
+ now.reported.add(id);
246
+ now.report(staticRegionMissing(id));
247
+ }
248
+ return boundary(id, void 0, render(inertHtml));
249
+ }
250
+ const replayed = now?.mode === "replay" ? now.regions.get(id) : void 0;
251
+ if (replayed !== void 0) return boundary(id, void 0, replayed);
252
+ if (now?.mode !== "collect") return boundary(id, void 0, render(inertHtml));
253
+ const outer = now.region;
254
+ now.region = id;
255
+ try {
256
+ const children = render(inertHtml);
257
+ if (now.regions.has(id)) now.duplicates.add(id);
258
+ else now.regions.set(id, children);
259
+ return boundary(id, void 0, children);
260
+ } finally {
261
+ now.region = outer;
262
+ }
263
+ };
264
+ /**
265
+ * Whether the view call in progress is the server rendering a page, rather than the browser: true
266
+ * through both of `render`'s passes, false while the browser resumes and outside any render. For a
267
+ * view that sends markup it will adopt in the browser rather than draw there, such as
268
+ * `foldkit-richtext-dom`'s editor host, whose placement takes this as `serverRendered`.
269
+ */
270
+ const serving = () => {
271
+ const mode = current()?.mode;
272
+ return mode === "collect" || mode === "replay";
273
+ };
274
+ /**
275
+ * The config without a `Flags` key at all. Deleted, never set to `undefined`:
276
+ * Foldkit's server asks whether `Flags` is defined and its client whether the
277
+ * key exists, so an `undefined` one renders and is then refused.
278
+ */
279
+ const withoutFlags = (config) => {
280
+ const { Flags: _flags, ...rest } = config;
281
+ return rest;
282
+ };
283
+ /** The config whose `init` returns this start, whatever arguments it is given. */
284
+ const startingFrom = (config, start) => ({
285
+ ...withoutFlags(config),
286
+ init: () => start
287
+ });
288
+ /** A route as the envelope records it: the path and the query. */
289
+ const routeOf = (url) => {
290
+ const parsed = new URL(url, "http://localhost");
291
+ return `${parsed.pathname}${parsed.search}`;
292
+ };
293
+ /**
294
+ * The page's bindings, decoded through the plan's Message Schema, kept to the
295
+ * Messages the Surfaces active for `model` may send, and checked against
296
+ * every marker in `root`. Refused, with the reason, when the page carries
297
+ * none, an entry is not one of the application's Messages or one no active
298
+ * Surface lists, or a marker names a binding the page does not carry: a page
299
+ * is answered whole or not at all.
300
+ */
301
+ const bindings = (plan, page, root, model) => Result.map(bindingsAndEvents(plan, page, root, model), (read) => read.bindings);
302
+ const EnvelopeEvents = Schema.optional(Schema.Array(Schema.String));
303
+ /**
304
+ * `bindings`, and the events the envelope says the markers name, if it says:
305
+ * a page from before the envelope listed them leaves `listen` to find them.
306
+ */
307
+ const bindingsAndEvents = (plan, page, root, model) => {
308
+ const parsed = readEnvelope(page);
309
+ if (Result.isFailure(parsed)) return Result.fail(parsed.failure);
310
+ const read = readBindings(parsed.success.bindings ?? []);
311
+ if (Result.isFailure(read)) return refuse("Invalid", `the page's bindings are malformed: ${read.failure}`);
312
+ const encoded = read.success;
313
+ if (encoded.length > 0 && plan.surfaces.length === 0) return refuse("Invalid", "the page has bindings and the plan declares no surfaces to allow them");
314
+ const events = Schema.decodeUnknownResult(EnvelopeEvents)(parsed.success.events);
315
+ if (Result.isFailure(events)) return refuse("Invalid", `the page's events are malformed: ${events.failure.message}`);
316
+ const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model));
317
+ return Result.isFailure(decoded) ? refuse("Invalid", decoded.failure) : Result.succeed({
318
+ bindings: decoded.success,
319
+ events: events.success
320
+ });
321
+ };
322
+ export { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, PROTOCOL, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, allowedTags, attributeOf, bindings, bindingsAndEvents, codecOf, metaEntry, metaMarkup, modelFrom, pathKey, plan, projectionsOf, refuse, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf };
323
+
324
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * What the server and the browser both read: the plan, the envelope as the\n * browser reads it, static regions, and the page's bindings. Nothing here\n * imports Foldkit's server renderer, so `client.ts` can carry all of it.\n */\nimport { Effect, Option, Result, Schema, Stream, type Layer } from 'effect'\nimport type { Runtime } from 'foldkit'\nimport { inertHtml, type Html, type HtmlBuilder } from 'foldkit/html'\nimport type { Ports } from 'foldkit/port'\nimport {\n ModelRef,\n type ActiveSurface,\n type Metadata,\n type ModelPlace,\n type SurfaceSource,\n type WritableProjection,\n} from 'foldkit-surface'\nimport { current, type Region } from './context.js'\nimport { staticRegionMissing } from './diagnostics.js'\nimport { decodeBindings, readBindings, type DecodedBinding } from './listen.js'\n\n/**\n * The attribute Foldkit's server stamps on an application's root, as\n * `foldkit/experimental/server` exports it. Written out here so a page can\n * find its root without that module; a test pins the two together.\n */\nexport const FOLDKIT_APP_ATTRIBUTE = 'data-foldkit-app'\n\n/**\n * The attribute on the stamped root that carries a page's resume envelope.\n * Foldkit pairs its own handoff the same way: the build id rides on the root\n * beside the app stamp, and the client reads it before adopting anything.\n */\nexport const RESUME_ATTRIBUTE = 'data-foldkit-plus-resume'\n\n/** The envelope format this package writes and reads. */\nexport const PROTOCOL = 1\n\nconst LINE_SEPARATOR = String.fromCharCode(0x2028)\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029)\n\n/**\n * JSON for a script element: `<` is escaped so `</script>` in the data ends\n * nothing. U+2028 and U+2029 are escaped too: they are fine in JSON and break a\n * reader that treats the text as JavaScript.\n */\nexport const serializeJsonScript = (value: unknown): string =>\n JSON.stringify(value)\n .replaceAll('<', '\\\\u003c')\n .replaceAll(LINE_SEPARATOR, '\\\\u2028')\n .replaceAll(PARAGRAPH_SEPARATOR, '\\\\u2029')\n\n/**\n * The envelope JSON as the stamped root carries it: `serializeJsonScript`\n * already escaped `<` and the line separators, and an attribute must escape\n * `&` and `\"` besides, so no string in the Model can break out of the value.\n * `getAttribute` resolves the entities back, which is exactly the JSON.\n */\nexport const attributeOf = (json: string): string =>\n ` ${RESUME_ATTRIBUTE}=\"${json.replaceAll('&', '&amp;').replaceAll('\"', '&quot;')}\"`\n\n/**\n * What a page says of itself beyond Foldkit's `Document` (`title`, `lang`,\n * `dir`, `canonical`, `ogUrl`): what a search result and a link preview show.\n * `title` is the preview's title (`og:title`), when it differs from the\n * document's. Dates are ISO 8601 text; `jsonLd` is structured data, each\n * entry written as its own script.\n */\nexport interface Meta {\n readonly description?: string | undefined\n readonly title?: string | undefined\n readonly image?: string | undefined\n readonly type?: 'website' | 'article' | undefined\n readonly siteName?: string | undefined\n readonly article?:\n | { readonly published?: string | undefined; readonly modified?: string | undefined }\n | undefined\n readonly robots?: string | undefined\n readonly alternates?:\n | ReadonlyArray<{ readonly hreflang: string; readonly href: string }>\n | undefined\n readonly jsonLd?: ReadonlyArray<Readonly<Record<string, unknown>>> | undefined\n}\n\n/** Marks each head element a plan's `meta` wrote, so the browser can replace them. */\nexport const META_ATTRIBUTE = 'data-foldkit-meta'\n\nconst attributeText = (text: string): string =>\n text\n .replaceAll('&', '&amp;')\n .replaceAll('\"', '&quot;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n\n/** The head markup of a `Meta`, every value escaped, one element per line. */\nexport const metaMarkup = (meta: Meta): string => {\n const tag = (element: string, attributes: ReadonlyArray<readonly [string, string]>) =>\n `<${element} ${META_ATTRIBUTE} ${attributes.map(([name, value]) => `${name}=\"${attributeText(value)}\"`).join(' ')}>`\n const named = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['name', name],\n ['content', value],\n ]),\n ]\n const property = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['property', name],\n ['content', value],\n ]),\n ]\n return [\n ...named('description', meta.description),\n ...property('og:title', meta.title),\n ...property('og:description', meta.description),\n ...property('og:type', meta.type),\n ...property('og:site_name', meta.siteName),\n ...property('og:image', meta.image),\n ...(meta.description === undefined && meta.image === undefined && meta.title === undefined\n ? []\n : named('twitter:card', meta.image === undefined ? 'summary' : 'summary_large_image')),\n ...property('article:published_time', meta.article?.published),\n ...property('article:modified_time', meta.article?.modified),\n ...named('robots', meta.robots),\n ...(meta.alternates ?? []).map(({ hreflang, href }) =>\n tag('link', [\n ['rel', 'alternate'],\n ['hreflang', hreflang],\n ['href', href],\n ]),\n ),\n ...(meta.jsonLd ?? []).map(\n data =>\n `<script ${META_ATTRIBUTE} type=\"application/ld+json\">${serializeJsonScript(data)}</script>`,\n ),\n ].join('\\n')\n}\n\n/**\n * The Subscription entry that keeps the head's `meta` elements in step with\n * the Model, so a move within the page (another post) changes its\n * description too. It writes the head and sends no Message.\n */\nexport const metaEntry = <Model>(meta: (model: Model) => Meta) => ({\n dependenciesSchema: Schema.String,\n modelToDependencies: (model: Model) => metaMarkup(meta(model)),\n dependenciesToStream: (markup: string) =>\n Stream.drain(\n Stream.fromEffect(\n Effect.sync(() => {\n const written = document.createElement('template')\n written.innerHTML = markup\n for (const old of document.head.querySelectorAll(`[${META_ATTRIBUTE}]`)) old.remove()\n document.head.append(written.content)\n }),\n ),\n ),\n})\n\n/** One entry of a resume plan's `surfaces`: a lone Surface, or a `Surface.each` family. */\nexport type PlanSurface<Model> = ActiveSurface<Model> | SurfaceSource<Model>\n\n/**\n * What a plan entry resolves to for a Model: the lone projection of a\n * `Surface.at`/`Surface.when` value, or a family's parent first and then each\n * instance. The parent joins so the envelope carries what the instances were\n * discovered through, not just what they read.\n */\nexport const projectionsOf = <Model>(\n source: PlanSurface<Model>,\n model: Model,\n): ReadonlyArray<{ readonly metadata: Metadata }> => {\n if (typeof (source as Partial<SurfaceSource<Model>>).instancesOf === 'function') {\n const origin = source as SurfaceSource<Model>\n const from = (source as { readonly from?: ActiveSurface<Model> }).from\n const parent = from === undefined ? [] : Option.toArray(from.projectionOf(model))\n return [...parent, ...origin.instancesOf(model).map(instance => instance.projection)]\n }\n return Option.toArray((source as ActiveSurface<Model>).projectionOf(model))\n}\n\n/**\n * Which part of the Model the browser owns, and what it starts from.\n *\n * `state` is a writable projection of that part, from `Projection.pick` or\n * `Projection.compose`. `baseline` is the Model the browser sets it onto, by\n * default the application's own initial Model. `boot` names the Commands the\n * browser runs on load, since `init` does not run there.\n */\nexport interface ResumePlan<Model, Fields extends Schema.Struct.Fields, Commands = unknown> {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline: Model\n readonly boot?: ((model: Model) => Commands) | undefined\n /** Model paths allowed to start from the baseline, as each place's focus gives them. */\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n /** The Surfaces the browser may activate, which the plan must cover. */\n readonly surfaces: ReadonlyArray<PlanSurface<Model>>\n /** State another package owns, each captured and restored by that package. */\n readonly parts: ReadonlyArray<ResumePart<Model>>\n /** The application's Message Schema, which encodes the page's bindings. */\n readonly Message?: Schema.Top | undefined\n /**\n * When the browser boots the runtime: `now` on load, `idle` when the browser\n * is idle or on the first interaction, `on-interaction` on the first only.\n * Until then the page answers events from its bindings and queues the\n * Messages, which the runtime runs through `update` before any other.\n */\n readonly start: Start\n /** Subscription and Managed Resource keys that may start late (decision 10). */\n readonly deferrable: ReadonlyArray<string>\n /**\n * `server`: a form whose `OnSubmit` names a Message also posts it to the\n * page's own URL, and `SSR.handle` runs `update` there, so the form works\n * with scripts off or not yet loaded.\n */\n readonly fallback?: 'server' | undefined\n /**\n * What the page says of itself, from the Model: rendered into the head on\n * the server, checked like the view, and kept in step in the browser.\n */\n readonly meta?: ((model: Model) => Meta) | undefined\n /**\n * The data the page was built from, for the browser's freshness check: a\n * Remote cursor, a revision number, anything the check compares. Unset\n * when the page has no age.\n */\n readonly version?: unknown | undefined\n}\n\nexport type Start = 'now' | 'idle' | 'on-interaction'\n\n/**\n * A package's contribution to the envelope, for state the plan's slice cannot\n * carry, such as Remote's normalized store. On the server `capture` takes what\n * the active Surfaces' projections read and returns it as JSON; in the browser\n * `restore` sets it onto the Model, or says why it cannot. A part owns its\n * encoding: this package only carries the value.\n *\n * `covers` names the metadata keys whose reads the part resumes, so the\n * coverage check counts those reads as sent. `Remote.resume(Data)` is one.\n */\nexport interface ResumePart<Model> {\n readonly id: string\n readonly covers: ReadonlyArray<string>\n readonly capture: (\n model: Model,\n projections: ReadonlyArray<{ readonly metadata: Metadata }>,\n ) => unknown\n readonly restore: (model: Model, value: unknown) => Result.Result<Model, string>\n /**\n * Whether a Subscription or Managed Resource entry of this part's package\n * may start late, when a deferred boot is asked for. A part knows its own\n * entries; nothing is deferrable by default.\n */\n readonly deferrable?: ((key: string, entry: unknown) => boolean) | undefined\n}\n\n/** Why a page's resume envelope was refused. */\nexport class ResumeRefused extends Schema.TaggedError<ResumeRefused>()('ResumeRefused', {\n reason: Schema.Literals([\n 'Missing',\n 'Duplicate',\n 'Unreadable',\n 'Protocol',\n 'Plan',\n 'Invalid',\n 'Route',\n ]),\n message: Schema.String,\n}) {}\n\nexport const refuse = (reason: ResumeRefused['reason'], message: string) =>\n Result.fail(new ResumeRefused({ reason, message }))\n\n/**\n * The slice's Schema as a codec needing no services. A resume plan's state is\n * plain data, so any field that needs one cannot cross a page anyway.\n */\nexport const codecOf = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>\n schema as unknown as Schema.Codec<Schema.Struct.Type<Fields>, unknown>\n\n/**\n * A resume plan for an application. The baseline defaults to the\n * application's initial Model. It is never written: a writable projection's\n * `set` returns a new Model, so a baseline Foldkit freezes in development is\n * safe to start from.\n *\n * `surfaces` are the Surfaces the browser may activate, and `local` the Model\n * fields allowed to start from the baseline, such as an open menu. Rendering\n * refuses a plan that leaves a Surface's read or activation in neither.\n */\nexport const plan = <Model, Fields extends Schema.Struct.Fields, Commands = unknown>(\n application: {\n readonly initial: Model\n readonly owner?: object\n readonly Message?: Schema.Top | undefined\n },\n config: {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline?: Model | undefined\n readonly boot?: ((model: Model) => Commands) | undefined\n readonly local?: ReadonlyArray<ModelPlace<NoInfer<Model>>> | undefined\n readonly surfaces?: ReadonlyArray<PlanSurface<Model>> | undefined\n readonly parts?: ReadonlyArray<ResumePart<Model>> | undefined\n readonly start?: Start | undefined\n readonly deferrable?: ReadonlyArray<string> | undefined\n readonly fallback?: 'server' | undefined\n readonly meta?: ((model: Model) => Meta) | undefined\n readonly version?: unknown | undefined\n },\n): ResumePlan<Model, Fields, Commands> => {\n const surfaces = config.surfaces ?? []\n const parts = config.parts ?? []\n const repeated = parts.find((part, index) => parts.findIndex(p => p.id === part.id) !== index)\n if (repeated !== undefined) {\n throw new Error(\n `SSR.plan: two parts of plan \"${config.id}\" share the id \"${repeated.id}\"; give one an id of its own`,\n )\n }\n // A family joins its parent's requirements with its instances', so the\n // parent's application is checked too: a family smuggling another\n // application's Surface is refused here, not at its reads.\n const entered = surfaces.flatMap(surface => {\n const from = (surface as { readonly from?: PlanSurface<Model> }).from\n return from === undefined ? [surface] : [surface, from]\n })\n const foreign = entered.find(\n surface => application.owner !== undefined && surface.owner !== application.owner,\n )\n if (foreign !== undefined) {\n throw new Error(\n `SSR.plan: the Surface \"${foreign.name}\" belongs to another application than plan \"${config.id}\"`,\n )\n }\n return {\n id: config.id,\n state: config.state,\n baseline: config.baseline ?? application.initial,\n ...(config.boot === undefined ? {} : { boot: config.boot }),\n local: (config.local ?? []).map(place => ModelRef.focus(place).dependency),\n surfaces,\n parts,\n ...(application.Message === undefined ? {} : { Message: application.Message }),\n start: config.start ?? 'now',\n deferrable: config.deferrable ?? [],\n ...(config.fallback === undefined ? {} : { fallback: config.fallback }),\n ...(config.meta === undefined ? {} : { meta: config.meta }),\n ...(config.version === undefined ? {} : { version: config.version }),\n }\n}\n\n/**\n * How a page's recorded route is compared with the browser's. `full` compares\n * path and query. `path` compares the path alone, ignoring a trailing slash or\n * `index.html`, for a page generated as a file: a static host serves one file\n * for every query, and for `/about` and `/about/` alike.\n */\nexport type RouteMatch = 'full' | 'path'\n\n/** A path as a `path` match compares it. */\nexport const pathKey = (route: string): string => {\n const path = route.split(/[?#]/)[0] ?? ''\n const trimmed = path.replace(/\\/index\\.html$/, '/').replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n/**\n * The Model a payload resumes: the baseline with the slice set onto it, then\n * each part restored, in order. Every part the plan names must be there and\n * restore, and no other may be: a page is never half-restored.\n */\nexport const modelFrom = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: { readonly state: unknown; readonly parts?: unknown },\n): Result.Result<Model, string> => {\n const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state)\n if (Result.isFailure(decoded)) {\n return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`)\n }\n const given = payload.parts ?? {}\n if (typeof given !== 'object' || Array.isArray(given)) {\n return Result.fail(\"the envelope's parts are not an object of parts by id\")\n }\n const parts = given as Readonly<Record<string, unknown>>\n const unknown = Object.keys(parts).find(id => !plan.parts.some(part => part.id === id))\n if (unknown !== undefined) {\n return Result.fail(`the envelope carries a part \"${unknown}\" the plan does not name`)\n }\n let model = plan.state.set(plan.baseline, decoded.success)\n for (const part of plan.parts) {\n if (!Object.hasOwn(parts, part.id))\n return Result.fail(`the envelope carries no \"${part.id}\" part`)\n const restored = part.restore(model, parts[part.id])\n if (Result.isFailure(restored)) {\n return Result.fail(`the \"${part.id}\" part does not restore: ${restored.failure}`)\n }\n model = restored.success\n }\n return Result.succeed(model)\n}\n\n/** The page's envelope, read off its stamped root; refused when there is no root, more than one, no envelope, or not JSON. */\nconst readEnvelope = (\n page: ParentNode,\n): Result.Result<Readonly<Record<string, unknown>>, ResumeRefused> => {\n const roots = page.querySelectorAll(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (roots.length === 0) return refuse('Missing', 'the page holds no stamped application root')\n if (roots.length > 1) {\n return refuse('Duplicate', `the page holds ${roots.length} stamped application roots`)\n }\n const carried = roots[0]?.getAttribute(RESUME_ATTRIBUTE)\n if (carried === null || carried === undefined) {\n return refuse('Missing', 'the page holds no resume envelope')\n }\n try {\n const parsed: unknown = JSON.parse(carried)\n return Result.succeed((parsed ?? {}) as Readonly<Record<string, unknown>>)\n } catch (error) {\n return refuse('Unreadable', `the resume envelope is not JSON: ${String(error)}`)\n }\n}\n\n/**\n * The Model a page resumes from: the baseline with the stamped root's envelope\n * set onto it. Refused, with the reason, when the page holds no stamped root\n * or more than one, when the root carries no envelope or not JSON, when it is\n * not this protocol or this plan, or when the slice does not decode through\n * the plan's Schema. A page is never half-restored.\n */\nexport const resume = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n options: { readonly route?: string | undefined } = {},\n): Result.Result<Model, ResumeRefused> => {\n const read = readEnvelope(page)\n if (Result.isFailure(read)) return Result.fail(read.failure)\n const parsed = read.success\n const { v, plan: id, state, parts, route, match } = parsed\n if (v !== PROTOCOL) {\n return refuse('Protocol', `the envelope is protocol ${String(v)}, not ${PROTOCOL}`)\n }\n if (id !== plan.id) {\n return refuse('Plan', `the envelope is for plan \"${String(id)}\", not \"${plan.id}\"`)\n }\n // The route the Model was made for. The runtime never reports the URL at\n // boot, so a page resumed on another route would show one and be on the\n // other.\n if (route !== undefined && options.route !== undefined) {\n const matches =\n match === 'path' ? pathKey(String(route)) === pathKey(options.route) : route === options.route\n if (!matches) {\n return refuse(\n 'Route',\n `the page was ${match === 'path' ? 'generated' : 'rendered'} for ${String(route)}, not ${options.route}`,\n )\n }\n }\n const resumed = modelFrom(plan, { state, parts })\n return Result.isFailure(resumed)\n ? refuse('Invalid', resumed.failure)\n : Result.succeed(resumed.success)\n}\n\n/** The tag a Message value carries, for naming it. */\nexport const tagOf = (message: unknown): string =>\n typeof message === 'object' &&\n message !== null &&\n '_tag' in message &&\n typeof message._tag === 'string'\n ? message._tag\n : 'an untagged Message'\n\n/**\n * The Message tags the plan's Surfaces active for `model` may send, which is\n * what a page's bindings may dispatch (the design's rule 3).\n */\nexport const allowedTags = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlySet<string> =>\n new Set(\n plan.surfaces.flatMap(source =>\n projectionsOf(source, model).length > 0 ? source.messages : [],\n ),\n )\n\n/** The attribute on a static region's element, naming the region. */\nexport const STATIC_ATTRIBUTE = 'data-foldkit-plus-static'\n\nconst boundary = (id: string, trusted: string | undefined, children: Region): Html =>\n inertHtml.div(\n [\n inertHtml.Attribute(STATIC_ATTRIBUTE, id),\n ...(trusted === undefined ? [] : [inertHtml.InnerHTML(trusted)]),\n ],\n children,\n )\n\n/**\n * A region of the page the server owns for the life of the document. It is\n * rendered on the server with the inert builder, so it can dispatch no\n * Message. The browser adopts the server's markup as trusted `InnerHTML` and\n * never runs `render`, so the region reads nothing from the browser's Model\n * and a plan need not send what it reads.\n *\n * A region changes only with a new document. Content a Message should change\n * belongs in a Surface, not here.\n */\nexport const staticRegion = (id: string, render: (ih: HtmlBuilder<never>) => Region): Html => {\n const now = current()\n if (now?.mode === 'resume') {\n const snapshot = now.snapshots.get(id)\n if (snapshot !== undefined) return boundary(id, snapshot, [])\n if (!now.reported.has(id)) {\n now.reported.add(id)\n now.report(staticRegionMissing(id))\n }\n return boundary(id, undefined, render(inertHtml))\n }\n const replayed = now?.mode === 'replay' ? now.regions.get(id) : undefined\n if (replayed !== undefined) return boundary(id, undefined, replayed)\n if (now?.mode !== 'collect') return boundary(id, undefined, render(inertHtml))\n const outer = now.region\n now.region = id\n try {\n const children = render(inertHtml)\n if (now.regions.has(id)) now.duplicates.add(id)\n else now.regions.set(id, children)\n return boundary(id, undefined, children)\n } finally {\n now.region = outer\n }\n}\n\n/**\n * Whether the view call in progress is the server rendering a page, rather than the browser: true\n * through both of `render`'s passes, false while the browser resumes and outside any render. For a\n * view that sends markup it will adopt in the browser rather than draw there, such as\n * `foldkit-richtext-dom`'s editor host, whose placement takes this as `serverRendered`.\n */\nexport const serving = (): boolean => {\n const mode = current()?.mode\n return mode === 'collect' || mode === 'replay'\n}\n\n/**\n * The `makeApplication` options `SSR` hands to Foldkit as they are, typed as\n * Foldkit types them.\n */\ntype ApplicationOptions<Model, Message> = Partial<\n Pick<\n Runtime.RoutingApplicationConfig<Model, Message, never, never, Ports | undefined>,\n | 'routing'\n | 'ports'\n | 'crash'\n | 'slow'\n | 'viewTransition'\n | 'freezeModel'\n | 'preserveScroll'\n | 'devTools'\n >\n>\n\n/**\n * The part of a Foldkit application config a server render and a resumed\n * client need. The full `makeApplication` config fits, whichever of its four\n * shapes, and its callbacks (`routing`'s, say) are typed from `update`'s\n * Message as Foldkit types them.\n */\nexport interface ResumableConfig<Model, Message = any> extends ApplicationOptions<Model, Message> {\n readonly Model: Schema.Codec<Model, any, unknown, unknown>\n readonly init: (...args: ReadonlyArray<any>) => {\n readonly model: Model\n readonly commands?: ReadonlyArray<{ readonly name: string }> | undefined\n }\n readonly update: (model: Model, message: Message) => { readonly model: Model }\n readonly view: (model: Model, h: any) => unknown\n readonly container: HTMLElement | null\n readonly Flags?: unknown\n readonly subscriptions?: Readonly<Record<string, unknown>> | undefined\n readonly managedResources?: Readonly<Record<string, unknown>> | undefined\n /** The services Commands need, as Foldkit's runtime provides them. */\n readonly resources?: Layer.Layer<never, never, never> | undefined\n /**\n * Bundles whose bodies load on demand (`Bundle.lazy`). The server loads\n * them before it renders; the browser loads them before it boots, answering\n * from the markers meanwhile, so a page never shows a bundle's placeholder.\n */\n readonly lazy?: ReadonlyArray<Loadable> | undefined\n}\n\n/** What `SSR` needs of a lazy bundle: `Bundle.lazy` gives it. */\nexport interface Loadable {\n readonly name: string\n readonly load: () => Promise<void>\n readonly isLoaded: () => boolean\n}\n\n/**\n * The config without a `Flags` key at all. Deleted, never set to `undefined`:\n * Foldkit's server asks whether `Flags` is defined and its client whether the\n * key exists, so an `undefined` one renders and is then refused.\n */\nconst withoutFlags = <Config extends { readonly Flags?: unknown }>(config: Config) => {\n const { Flags: _flags, ...rest } = config\n return rest\n}\n\n/** The config whose `init` returns this start, whatever arguments it is given. */\nexport const startingFrom = <Model>(\n config: ResumableConfig<Model>,\n start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> },\n) => ({ ...withoutFlags(config), init: () => start })\n\n/** A route as the envelope records it: the path and the query. */\nexport const routeOf = (url: string): string => {\n const parsed = new URL(url, 'http://localhost')\n return `${parsed.pathname}${parsed.search}`\n}\n\n/**\n * The page's bindings, decoded through the plan's Message Schema, kept to the\n * Messages the Surfaces active for `model` may send, and checked against\n * every marker in `root`. Refused, with the reason, when the page carries\n * none, an entry is not one of the application's Messages or one no active\n * Surface lists, or a marker names a binding the page does not carry: a page\n * is answered whole or not at all.\n */\nexport const bindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<ReadonlyArray<DecodedBinding>, ResumeRefused> =>\n Result.map(bindingsAndEvents(plan, page, root, model), read => read.bindings)\n\nconst EnvelopeEvents = Schema.optional(Schema.Array(Schema.String))\n\n/**\n * `bindings`, and the events the envelope says the markers name, if it says:\n * a page from before the envelope listed them leaves `listen` to find them.\n */\nexport const bindingsAndEvents = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<\n {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n ResumeRefused\n> => {\n const parsed = readEnvelope(page)\n if (Result.isFailure(parsed)) return Result.fail(parsed.failure)\n const read = readBindings(parsed.success.bindings ?? [])\n if (Result.isFailure(read)) {\n return refuse('Invalid', `the page's bindings are malformed: ${read.failure}`)\n }\n const encoded = read.success\n if (encoded.length > 0 && plan.surfaces.length === 0) {\n return refuse(\n 'Invalid',\n 'the page has bindings and the plan declares no surfaces to allow them',\n )\n }\n const events = Schema.decodeUnknownResult(EnvelopeEvents)(parsed.success.events)\n if (Result.isFailure(events)) {\n return refuse('Invalid', `the page's events are malformed: ${events.failure.message}`)\n }\n const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model))\n return Result.isFailure(decoded)\n ? refuse('Invalid', decoded.failure)\n : Result.succeed({ bindings: decoded.success, events: events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,OAAO,aAAa,OAAO,QAAQ,YAAY,CAAC,CAAC;CACvD,IAAI,OAAO,UAAU,IAAI,GACvB,OAAO,OAAO,WAAW,sCAAsC,KAAK,SAAS;CAE/E,MAAM,UAAU,KAAK;CACrB,IAAI,QAAQ,SAAS,KAAK,KAAK,SAAS,WAAW,GACjD,OAAO,OACL,WACA,uEACF;CAEF,MAAM,SAAS,OAAO,oBAAoB,cAAc,CAAC,CAAC,OAAO,QAAQ,MAAM;CAC/E,IAAI,OAAO,UAAU,MAAM,GACzB,OAAO,OAAO,WAAW,oCAAoC,OAAO,QAAQ,SAAS;CAEvF,MAAM,UAAU,eAAe,KAAK,SAAS,SAAS,MAAM,YAAY,MAAM,KAAK,CAAC;CACpF,OAAO,OAAO,UAAU,OAAO,IAC3B,OAAO,WAAW,QAAQ,OAAO,IACjC,OAAO,QAAQ;EAAE,UAAU,QAAQ;EAAS,QAAQ,OAAO;CAAQ,CAAC;AAC1E"}
@@ -1,9 +1,8 @@
1
- import { f as ResumePlan, u as ResumableConfig } from "./client-DkwAniQQ.mjs";
2
- import { Head, ResumeUnsafe } from "./index.mjs";
1
+ import { c as ResumableConfig, u as ResumePlan } from "./shared-v1u-OEQI.js";
2
+ import { Head, ResumeUnsafe } from "./index.js";
3
3
  import { Effect, Schema } from "effect";
4
4
  import { RenderError } from "foldkit/experimental/server";
5
5
  import { Plugin } from "vite";
6
- //#region src/vite.d.ts
7
6
  /** A path the site generates, with the date its sitemap names when it has one. */
8
7
  export type SitePath = string | {
9
8
  readonly path: string;
@@ -113,6 +112,5 @@ export declare const staticSite: (options: {
113
112
  /** What `vite build` wrote: defaults to the resolved `build.outDir`. */
114
113
  readonly outDir?: string | undefined;
115
114
  }) => Plugin;
116
- //#endregion
117
115
  export type { Head };
118
- //# sourceMappingURL=vite.d.mts.map
116
+ //# sourceMappingURL=vite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;;;;;YAwBY;WAA+B;WAAuB;;;;;;;;;qBAarD,UAAO,cAAgB;;;;;;;;;;iBAgBnB,WACf,OACA,eAAe,OAAO,OAAO,QAC7B,SAKA,WAAW,gBAAgB,OAAO;WAEzB,QAAQ,aAAa,iBAAiB,WAAW,QAAQ;WACzD,MAAM,WAAW,OAAO;WACxB;WACA;WACA,OACL,cAAc,mBACP,cAAc,YAAY,QAAQ,cAAc;WAClD;WACA,OAAO;WACP,UAAU;WACV;WACA;WACA;;;;;;WAMA,SACH,OAAO,cAAc,eAAe,QAAQ,cAAc;;;iBAKjD;WACN;WACA,UAAU;;;iBAIJ;WACN;WACA;WACA;WACA;;;iBAIM;WACN,OAAO,cAAc;WACrB;WACA;WACA,SAAS,cAAc;;;;;;;qBAQrB,eAAY,SACd,cAAc,cAAY,OAC5B,0BACN,cAAc;;;;;;;qBAqBJ,qBAAsB,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,MACpF,WAAW,OAAO,QAAQ,aAC/B,OAAO,OAAO,WAAW,cAAc;;;;;qBAgF7B,eAAY,gBACT,SACL,cAAc,iBACtB;;iBAiBc;WACN,QACL,8BACE,iBAAiB,4BAA4B,QAAQ;WAClD,MAAM;WACN;WACA;WACA,OACL,cAAc,mBACP,cAAc,YAAY,QAAQ,cAAc;WAClD,aAAa;WACb,OAAO;WACP,UAAU;WACV;WACA;WACA;WACA,SACH,OAAO,cAAc,eAAe,QAAQ,cAAc;;;;;;;;;qBAcrD,aAAU;;WAEZ;aAAiB;aAAyB;;;WAE1C;MACP"}
@@ -1,8 +1,8 @@
1
- import { SSR } from "./index.mjs";
1
+ import { SSR } from "./index.js";
2
2
  import { Effect } from "effect";
3
3
  import { access, mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, isAbsolute, join, resolve } from "node:path";
5
- //#region src/vite.ts
5
+ // src/vite.ts
6
6
  /**
7
7
  * `foldkit-ssr/vite`: the static half of a build, as a Vite plugin. After
8
8
  * Vite writes the client bundle, `staticSite` renders every path with
@@ -180,7 +180,6 @@ const staticSite = (options) => {
180
180
  }
181
181
  };
182
182
  };
183
- //#endregion
184
183
  export { checkEmitted, fileFor, generateStaticSite, staticSite, writeEmitted };
185
184
 
186
- //# sourceMappingURL=vite.mjs.map
185
+ //# sourceMappingURL=vite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["/**\n * `foldkit-ssr/vite`: the static half of a build, as a Vite plugin. After\n * Vite writes the client bundle, `staticSite` renders every path with\n * `SSR.generate` and writes each page where a static host serves its\n * address, with the sitemap and `robots.txt` beside them. It owns no build:\n * it runs as a `closeBundle` step on the application's own client build,\n * with the application's own template.\n *\n * The application describes its site in a module the plugin evaluates\n * through a server (workspace packages resolve to source, as the build\n * does), so `vite.config.ts` names a file, never application code.\n */\nimport { access, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { Effect, Schema } from 'effect'\nimport type { RenderError } from 'foldkit/experimental/server'\nimport type { Plugin } from 'vite'\nimport { SSR, type Head, type ResumeUnsafe } from './index.js'\nimport type { ResumableConfig, ResumePlan } from './shared.js'\n\n/** What a page adds to its head, given what it rendered: for site descriptions. */\nexport type { Head }\n\n/** A path the site generates, with the date its sitemap names when it has one. */\nexport type SitePath = string | { readonly path: string; readonly modified?: string | undefined }\n\nconst pathOf = (spec: SitePath): string => (typeof spec === 'string' ? spec : spec.path)\nconst modifiedOf = (spec: SitePath): string | undefined =>\n typeof spec === 'string' ? undefined : spec.modified\n\n/**\n * The file a static host serves for a path. `directory` is the package's\n * own layout (`/about` as `about/index.html`); `flat` writes `about.html`,\n * for hosts with clean addresses and no directory indexes. `generate`\n * refuses what is not servable (a query, a fragment, an unresolvable\n * address) before this maps it, so this maps and never validates.\n */\nexport const fileFor = (path: string, layout: 'directory' | 'flat'): string => {\n const trimmed = path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n if (trimmed === '') return 'index.html'\n if (layout === 'flat') return trimmed.endsWith('.html') ? trimmed : `${trimmed}.html`\n return trimmed.endsWith('.html') ? trimmed : `${trimmed}/index.html`\n}\n\n/**\n * What a static site is: everything `SSR.generate` takes, plus where its\n * pages land. `config` may read the path (a site whose Model is prepared\n * per page satisfies and returns its own config for it); `paths` may close\n * over what the site serves (a thunk that seeds and lists, evaluated when\n * the build runs). `template` is the built shell the pages are rendered\n * into; `files` is the host's layout; `sitemap` and `robots` write their\n * files from the generated pages; `emit` adds files of its own made from them.\n */\nexport interface StaticSite<\n Model,\n Fields extends Schema.Struct.Fields,\n Message,\n // Unconstrained on purpose: a site's config carries its own services (a\n // Remote layer, flags), which no bound here could name without threading\n // the whole service graph through. The narrowed call still checks: a\n // config that is not a config or a function of a path fails where used.\n Resolved = ResumableConfig<Model, Message>,\n> {\n readonly config: Resolved | ((path: string) => Resolved | Promise<Resolved>)\n readonly plan: ResumePlan<Model, Fields>\n readonly buildId?: string | undefined\n readonly origin: string\n readonly paths:\n | ReadonlyArray<SitePath>\n | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>)\n readonly template: string\n readonly head?: Head | undefined\n readonly flags?: ((path: string) => unknown) | undefined\n readonly files?: 'directory' | 'flat' | undefined\n readonly sitemap?: boolean | undefined\n readonly robots?: boolean | undefined\n /**\n * Files made from the generated pages, written beside them: what the pages\n * reference and the build must also serve, such as the image variants\n * their `srcset`s name (`foldkit-media`'s `materialize`).\n */\n readonly emit?:\n | ((pages: ReadonlyArray<BuiltPage>) => Promise<ReadonlyArray<EmittedFile>>)\n | undefined\n}\n\n/** A file `emit` adds: its path in the output, and its contents. */\nexport interface EmittedFile {\n readonly file: string\n readonly contents: Uint8Array | string\n}\n\n/** One generated page, with the file the host serves it from. */\nexport interface BuiltPage {\n readonly path: string\n readonly file: string\n readonly html: string\n readonly modified?: string | undefined\n}\n\n/** What a static site build produced: its pages, and its sitemap and robots text. */\nexport interface BuiltSite {\n readonly pages: ReadonlyArray<BuiltPage>\n readonly sitemap?: string | undefined\n readonly robots?: string | undefined\n readonly emitted: ReadonlyArray<EmittedFile>\n}\n\n/**\n * The files `emit` returned, refused when one would land outside the output\n * (an absolute path, a `..`) or on a file the build writes itself: a page,\n * the sitemap, robots, or another emitted file.\n */\nexport const checkEmitted = (\n emitted: ReadonlyArray<EmittedFile>,\n taken: ReadonlyArray<string>,\n): ReadonlyArray<EmittedFile> => {\n const claimed = new Set(taken)\n for (const { file } of emitted) {\n const segments = file.split(/[\\\\/]/)\n if (file === '' || /^([a-zA-Z]:|[\\\\/])/.test(file) || segments.includes('..')) {\n throw new Error(`foldkit-ssr: emit returned \"${file}\", which is not a path inside the output`)\n }\n if (claimed.has(file)) {\n throw new Error(`foldkit-ssr: emit returned \"${file}\", which the build already writes`)\n }\n claimed.add(file)\n }\n return emitted\n}\n\n/**\n * Renders a static site: every path through `SSR.generate`, one page per\n * path in order, with the sitemap and robots text the options ask for. A\n * build id must never be a secret, and two deployments must never share\n * one; empty is refused with the deployment's name missing.\n */\nexport const generateStaticSite = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n site: StaticSite<Model, Fields, Message>,\n): Effect.Effect<BuiltSite, RenderError | ResumeUnsafe> => {\n const buildId = site.buildId ?? process.env.FOLDKIT_BUILD_ID ?? ''\n if (buildId === '') {\n throw new Error(\n 'set FOLDKIT_BUILD_ID to the deployment this build belongs to, the same value `vite build` saw',\n )\n }\n return Effect.gen(function* () {\n // Read into locals first: a call inside the thunks below would lose the\n // narrowing of a property access.\n const pathsInput = site.paths\n const specs =\n typeof pathsInput === 'function'\n ? yield* Effect.promise(() => Promise.resolve(pathsInput()))\n : pathsInput\n const files = site.files ?? 'directory'\n const configInput = site.config\n if (specs.length === 0) {\n throw new Error(\n 'foldkit-ssr: the site lists no paths: a site of nothing is a misconfigured paths',\n )\n }\n // Two specs may name one file (`/about` and `/about/`, or a `.html`\n // path beside its directory twin): `generate` sees one path at a time\n // and cannot catch it, so the collision is refused before rendering.\n const claimed = new Map<string, string>()\n for (const spec of specs) {\n const file = fileFor(pathOf(spec), files)\n const other = claimed.get(file)\n if (other !== undefined) {\n throw new Error(\n `foldkit-ssr: \"${pathOf(spec)}\" and \"${other}\" would both be written to ${file}`,\n )\n }\n claimed.set(file, pathOf(spec))\n }\n const pages: Array<BuiltPage> = []\n for (const spec of specs) {\n const path = pathOf(spec)\n const config =\n typeof configInput === 'function'\n ? yield* Effect.promise(async () => configInput(path))\n : configInput\n const [page] = yield* SSR.generate(config, site.plan, {\n buildId,\n template: site.template,\n origin: site.origin,\n paths: [path] as const,\n ...(site.flags === undefined ? {} : { flags: site.flags }),\n ...(site.head === undefined ? {} : { head: site.head }),\n })\n pages.push({\n path,\n file: fileFor(path, files),\n html: page.html,\n ...(modifiedOf(spec) === undefined ? {} : { modified: modifiedOf(spec) }),\n })\n }\n const emitInput = site.emit\n const emitted =\n emitInput === undefined\n ? []\n : checkEmitted(yield* Effect.promise(() => emitInput(pages)), [\n ...pages.map(page => page.file),\n ...(site.sitemap === true ? ['sitemap.xml'] : []),\n ...(site.robots === true ? ['robots.txt'] : []),\n ])\n return {\n pages,\n ...(site.sitemap === true ? { sitemap: SSR.sitemap(pages, { origin: site.origin }) } : {}),\n ...(site.robots === true ? { robots: SSR.robots({ origin: site.origin }) } : {}),\n emitted,\n }\n })\n}\n\n/**\n * Writes what `emit` returned into `outDir`, refusing a file the client\n * build already wrote there: a file from `public/` is not emit's to replace.\n */\nexport const writeEmitted = async (\n outDir: string,\n emitted: ReadonlyArray<EmittedFile>,\n): Promise<void> => {\n for (const { file, contents } of emitted) {\n const target = join(outDir, file)\n if (\n await access(target).then(\n () => true,\n () => false,\n )\n ) {\n throw new Error(`foldkit-ssr: emit returned \"${file}\", which the client build already wrote`)\n }\n await mkdir(dirname(target), { recursive: true })\n await writeFile(target, contents)\n }\n}\n\n/** A site description as a module exports it, for the plugin to evaluate. */\nexport interface SiteModule {\n readonly config:\n | ResumableConfig<any, any>\n | ((path: string) => ResumableConfig<any, any> | Promise<ResumableConfig<any, any>>)\n readonly plan: ResumePlan<any, any>\n readonly buildId?: string | undefined\n readonly origin: string\n readonly paths:\n | ReadonlyArray<SitePath>\n | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>)\n readonly template?: ((built: string) => string) | undefined\n readonly head?: Head | undefined\n readonly flags?: ((path: string) => unknown) | undefined\n readonly files?: 'directory' | 'flat' | undefined\n readonly sitemap?: boolean | undefined\n readonly robots?: boolean | undefined\n readonly emit?:\n | ((pages: ReadonlyArray<BuiltPage>) => Promise<ReadonlyArray<EmittedFile>>)\n | undefined\n}\n\n/** Workspace packages resolve to their source, so the site builds as edited. */\nconst conditions = ['foldkit-plus:source']\n\n/**\n * A static site as a Vite plugin: after the client bundle is written, the\n * site module is evaluated, every path is rendered into the built shell,\n * and the pages land in the output beside the sitemap and robots text.\n * The config names the module, never application code, so nothing resolves\n * through a stale build.\n */\nexport const staticSite = (options: {\n /** The site description's module, root-relative (`/src/site.ts`), and its export. */\n readonly site: { readonly module: string; readonly export?: string | undefined }\n /** What `vite build` wrote: defaults to the resolved `build.outDir`. */\n readonly outDir?: string | undefined\n}): Plugin => {\n let outDir = options.outDir ?? 'dist'\n let root = process.cwd()\n return {\n name: 'foldkit-ssr',\n apply: 'build',\n configResolved(config) {\n // The site module resolves against the application, not this process:\n // the test runs from the workspace root while the site lives elsewhere.\n root = config.root\n // An explicit outDir reads as Vite reads it: against the root.\n outDir =\n options.outDir === undefined\n ? isAbsolute(config.build.outDir)\n ? config.build.outDir\n : resolve(config.root, config.build.outDir)\n : isAbsolute(options.outDir)\n ? options.outDir\n : resolve(config.root, options.outDir)\n },\n async closeBundle() {\n // No dev server runs during a build: one of its own, closed after.\n // `vite` loads only here, never by a page: a build without it fails\n // naming the package, not with a resolution error.\n const { createServer } = await import('vite').catch(() => {\n throw new Error(\"foldkit-ssr/vite needs the 'vite' package: add it where the build runs\")\n })\n const server = await createServer({\n configFile: false,\n root,\n logLevel: 'error',\n appType: 'custom',\n server: { middlewareMode: true, hmr: false },\n resolve: { conditions },\n ssr: { resolve: { conditions } },\n optimizeDeps: { noDiscovery: true, include: [] },\n })\n try {\n const exported = await server.ssrLoadModule(options.site.module)\n const site = exported[options.site.export ?? 'site'] as SiteModule\n if (site === undefined || site === null || typeof site !== 'object')\n throw new Error(\n `foldkit-ssr: ${options.site.module} exports no ${options.site.export ?? 'site'} site description`,\n )\n const shell = join(outDir, 'index.html')\n let built: string\n try {\n built = await readFile(shell, 'utf8')\n } catch {\n // Rollup runs closeBundle after a failed client build too: name\n // the missing shell instead of its ENOENT.\n throw new Error(\n `foldkit-ssr: no built index.html at ${shell}: the client build failed or outDir is wrong`,\n )\n }\n const result = await Effect.runPromise(\n generateStaticSite({\n ...site,\n template: site.template?.(built) ?? built,\n }),\n )\n for (const page of result.pages) {\n const file = join(outDir, page.file)\n await mkdir(dirname(file), { recursive: true })\n await writeFile(file, page.html)\n }\n if (result.sitemap !== undefined)\n await writeFile(join(outDir, 'sitemap.xml'), result.sitemap)\n if (result.robots !== undefined) await writeFile(join(outDir, 'robots.txt'), result.robots)\n await writeEmitted(outDir, result.emitted)\n console.log(\n `foldkit-ssr: generated ${result.pages.length} pages${result.sitemap === undefined ? '' : ', a sitemap'}${result.robots === undefined ? '' : ' and robots.txt'}${result.emitted.length === 0 ? '' : ` and ${result.emitted.length} emitted files`} into ${outDir}`,\n )\n } finally {\n await server.close()\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,MAAM,UAAU,SAA4B,OAAO,SAAS,WAAW,OAAO,KAAK;AACnF,MAAM,cAAc,SAClB,OAAO,SAAS,WAAW,KAAA,IAAY,KAAK;;;;;;;;AAS9C,MAAa,WAAW,MAAc,WAAyC;CAC7E,MAAM,UAAU,KAAK,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAC3D,IAAI,YAAY,IAAI,OAAO;CAC3B,IAAI,WAAW,QAAQ,OAAO,QAAQ,SAAS,OAA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,KAAK,QAAQ,YAAY;IACvC,IAAI;IACJ,IAAI;KACF,QAAQ,MAAM,SAAS,OAAO,MAAM;IACtC,QAAQ;KAGN,MAAM,IAAI,MACR,uCAAuC,MAAM,6CAC/C;IACF;IACA,MAAM,SAAS,MAAM,OAAO,WAC1B,mBAAmB;KACjB,GAAG;KACH,UAAU,KAAK,WAAW,KAAK,KAAK;IACtC,CAAC,CACH;IACA,KAAK,MAAM,QAAQ,OAAO,OAAO;KAC/B,MAAM,OAAO,KAAK,QAAQ,KAAK,IAAI;KACnC,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;KAC9C,MAAM,UAAU,MAAM,KAAK,IAAI;IACjC;IACA,IAAI,OAAO,YAAY,KAAA,GACrB,MAAM,UAAU,KAAK,QAAQ,aAAa,GAAG,OAAO,OAAO;IAC7D,IAAI,OAAO,WAAW,KAAA,GAAW,MAAM,UAAU,KAAK,QAAQ,YAAY,GAAG,OAAO,MAAM;IAC1F,MAAM,aAAa,QAAQ,OAAO,OAAO;IACzC,QAAQ,IACN,0BAA0B,OAAO,MAAM,OAAO,QAAQ,OAAO,YAAY,KAAA,IAAY,KAAK,gBAAgB,OAAO,WAAW,KAAA,IAAY,KAAK,oBAAoB,OAAO,QAAQ,WAAW,IAAI,KAAK,QAAQ,OAAO,QAAQ,OAAO,gBAAgB,QAAQ,QAC5P;GACF,UAAU;IACR,MAAM,OAAO,MAAM;GACrB;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-ssr",
3
- "version": "0.8.2",
3
+ "version": "0.9.0",
4
4
  "description": "Server rendering for Foldkit Plus: render once on the server, hand the Model over, and hydrate without rerunning init.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -27,18 +27,18 @@
27
27
  "exports": {
28
28
  ".": {
29
29
  "foldkit-plus:source": "./src/index.ts",
30
- "types": "./dist/index.d.mts",
31
- "import": "./dist/index.mjs"
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
32
  },
33
33
  "./client": {
34
34
  "foldkit-plus:source": "./src/client.ts",
35
- "types": "./dist/client.d.mts",
36
- "import": "./dist/client.mjs"
35
+ "types": "./dist/client.d.ts",
36
+ "import": "./dist/client.js"
37
37
  },
38
38
  "./vite": {
39
39
  "foldkit-plus:source": "./src/vite.ts",
40
- "types": "./dist/vite.d.mts",
41
- "import": "./dist/vite.mjs"
40
+ "types": "./dist/vite.d.ts",
41
+ "import": "./dist/vite.js"
42
42
  }
43
43
  },
44
44
  "files": [
@@ -47,27 +47,27 @@
47
47
  "LICENSE"
48
48
  ],
49
49
  "peerDependencies": {
50
- "effect": "^4.0.0",
51
- "foldkit": "^0.169.0"
50
+ "effect": "^4.1.0",
51
+ "foldkit": "^0.170.0"
52
52
  },
53
53
  "dependencies": {
54
- "foldkit-surface": "0.10.2"
54
+ "foldkit-surface": "0.11.0"
55
55
  },
56
56
  "devDependencies": {
57
- "@effect/platform-browser": "^4.0.5",
57
+ "@effect/platform-browser": "^4.1.0",
58
58
  "@types/jsdom": "30.0.0",
59
- "effect": "^4.0.5",
59
+ "effect": "^4.1.0",
60
60
  "esbuild": "0.28.2",
61
- "foldkit": "0.169.0",
61
+ "foldkit": "0.170.0",
62
62
  "jsdom": "30.1.3",
63
63
  "playwright-core": "1.64.1",
64
64
  "tsdown": "^0.23.1",
65
65
  "typescript": "7.0.2",
66
66
  "vite": "8.3.5",
67
- "foldkit-bundle": "0.8.1",
68
- "foldkit-mirror": "0.6.3",
69
- "foldkit-entity": "0.11.0",
70
- "foldkit-remote": "0.19.0"
67
+ "foldkit-bundle": "0.9.0",
68
+ "foldkit-mirror": "0.7.0",
69
+ "foldkit-remote": "0.22.0",
70
+ "foldkit-entity": "0.14.0"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "tsdown",