foldkit-ssr 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -28
- package/dist/{client-BEHlUHBv.d.ts → client-cumvT9XN.d.ts} +2 -2
- package/dist/{client-BEHlUHBv.d.ts.map → client-cumvT9XN.d.ts.map} +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +2 -2
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +1 -1
- package/dist/diagnostics.d.ts +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +41 -12
- package/dist/index.js.map +1 -1
- package/dist/{shared-mQ8CXr-r.d.ts → shared-BuCOwm57.d.ts} +11 -4
- package/dist/{shared-mQ8CXr-r.d.ts.map → shared-BuCOwm57.d.ts.map} +1 -1
- package/dist/shared.d.ts +2 -2
- package/dist/shared.js +3 -1
- package/dist/shared.js.map +1 -1
- package/dist/vite.d.ts +17 -4
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +7 -1
- package/dist/vite.js.map +1 -1
- package/package.json +8 -8
|
@@ -453,9 +453,16 @@ interface ResumableConfig<Model, Message = any> extends ApplicationOptions<Model
|
|
|
453
453
|
* Bundles whose bodies load on demand (`Bundle.lazy`). The server loads
|
|
454
454
|
* them before it renders; the browser loads them before it boots, answering
|
|
455
455
|
* from the markers meanwhile, so a page never shows a bundle's placeholder.
|
|
456
|
+
* A function is asked with the Model the page is drawn from (the server's
|
|
457
|
+
* after `prepare`, the browser's as resumed), so only what that page draws
|
|
458
|
+
* loads: `model => Routing.codeFor(model.route)` (`Site.routing`).
|
|
456
459
|
*/
|
|
457
|
-
readonly lazy?: ReadonlyArray<Loadable> | undefined;
|
|
460
|
+
readonly lazy?: ReadonlyArray<Loadable> | ((model: Model) => ReadonlyArray<Loadable>) | undefined;
|
|
458
461
|
}
|
|
462
|
+
/** The lazy bundles a page drawn from `model` needs loaded. */
|
|
463
|
+
declare const lazyFor: <Model>(config: {
|
|
464
|
+
readonly lazy?: ResumableConfig<Model>['lazy'];
|
|
465
|
+
}, model: Model) => ReadonlyArray<Loadable>;
|
|
459
466
|
/** What `SSR` needs of a lazy bundle: `Bundle.lazy` gives it. */
|
|
460
467
|
interface Loadable {
|
|
461
468
|
readonly name: string;
|
|
@@ -508,7 +515,7 @@ declare const startingFrom: <Model>(config: ResumableConfig<Model>, start: {
|
|
|
508
515
|
subscriptions?: Readonly<Record<string, unknown>> | undefined;
|
|
509
516
|
managedResources?: Readonly<Record<string, unknown>> | undefined;
|
|
510
517
|
resources?: Layer.Layer<never, never, never> | undefined;
|
|
511
|
-
lazy?: ReadonlyArray<Loadable> | undefined;
|
|
518
|
+
lazy?: readonly Loadable[] | ((model: Model) => ReadonlyArray<Loadable>) | undefined;
|
|
512
519
|
init: () => {
|
|
513
520
|
readonly model: Model;
|
|
514
521
|
readonly commands?: ReadonlyArray<unknown> | undefined;
|
|
@@ -533,5 +540,5 @@ declare const bindingsAndEvents: <Model, Fields extends Schema.Struct.Fields>(pl
|
|
|
533
540
|
readonly bindings: ReadonlyArray<DecodedBinding>;
|
|
534
541
|
readonly events: ReadonlyArray<string> | undefined;
|
|
535
542
|
}, ResumeRefused>;
|
|
536
|
-
export {
|
|
537
|
-
//# sourceMappingURL=shared-
|
|
543
|
+
export { StaticRegionMissing as $, refuse as A, Region as B, lazyFor as C, pathKey as D, modelFrom as E, startingFrom as F, within as G, UnnamedHandler as H, staticRegion as I, HandlerUnnamed as J, BundleUnloaded as K, tagOf as L, routeOf as M, serializeJsonScript as N, plan as O, serving as P, SsrDiagnostic as Q, unbound as R, codecOf as S, metaMarkup as T, current as U, RenderContext as V, withContext as W, PageContained as X, HeadNotMoved as Y, PageFailed as Z, allowedTags as _, Meta as a, otherBuild as at, bindings as b, RestoredPlace as c, reportingTo as ct, ResumePlan as d, bundleUnloaded as et, ResumeRefused as f, Start as g, STYLES_MARKER as h, META_ATTRIBUTE as i, noBuildId as it, resume as j, projectionsOf as k, ResumableConfig as l, staticRegionMissing as lt, STATIC_ATTRIBUTE as m, HEAD_MARKER as n, handlerUnnamed as nt, PROTOCOL as o, pageContained as ot, RouteMatch as p, CachedPageDiffers as q, Loadable as r, headNotMoved as rt, PlanSurface as s, pageFailed as st, HEAD_END_MARKER as t, cachedPageDiffers as tt, ResumePart as u, arrival as v, metaEntry as w, bindingsAndEvents as x, attributeOf as y, Binding as z };
|
|
544
|
+
//# sourceMappingURL=shared-BuCOwm57.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-
|
|
1
|
+
{"version":3,"file":"shared-BuCOwm57.d.ts","names":[],"sources":["../src/diagnostics.ts","../src/context.ts","../src/shared.ts"],"mappings":";;;;;;;UAaiB,sBAAsB;WAC5B;;;;;WAKA,qCAAqC;;;UAI/B,4BAA4B;WAClC;WACA;;;UAIM,uBAAuB;WAC7B;WACA;;;UAIM,mBAAmB;WACzB;WACA;WACA,OAAO,MAAM;;;UAIP,uBAAuB;WAC7B;WACA;WACA;WACA;;;;;;;;UASM,0BAA0B;WAChC;WACA;;;;;;;;UASM,qBAAqB;WAC3B;;;KAIC,gBACR,gBACA,sBACA,iBACA,aACA,iBACA,oBACA;cAES,cAAc;cAQd,gBAAa,QAAY,yBAAuB,mBAAmB;cAQnE,WAAW;;cAMX,aAAU,QAAY,OAAO,gBAAc,mBAAmB;cAS9D,sBAAmB,mBAAqB;cAQxC,iBAAc,mBAAqB;cAQnC,aAAU,aAAe,OAAS,MAAM,mBAAiB;cASzD,iBAAc,cAAgB,iBAAiB,kBAAkB;;cAWjE,cAAW,QACb,kCACR,GAAG,GAAG,GAAC,QAAU,OAAO,OAAO,GAAG,GAAG,OAAK,OAAO,OAAO,GAAG,GAAG;cAGpD,oBAAiB,gBAAkB;KCtIpC,SAAS,cAAc;;UAGlB;WACN;WACA;;;;;;;;;UAUM;;WAEN;WACA;WACA;WACA;WACA,OAAO;;WAEP;WACA;;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shared.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { i as RESUME_ATTRIBUTE, n as FOLDKIT_APP_ATTRIBUTE } from "./marks-CX15BwOw.js";
|
|
2
|
-
import { A as
|
|
3
|
-
export { FOLDKIT_APP_ATTRIBUTE, HEAD_END_MARKER, HEAD_MARKER, Loadable, META_ATTRIBUTE, Meta, PROTOCOL, PlanSurface, RESUME_ATTRIBUTE, RestoredPlace, ResumableConfig, ResumePart, ResumePlan, ResumeRefused, RouteMatch, STATIC_ATTRIBUTE, STYLES_MARKER, Start, allowedTags, arrival, attributeOf, bindings, bindingsAndEvents, codecOf, metaEntry, metaMarkup, modelFrom, pathKey, plan, projectionsOf, refuse, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf, unbound };
|
|
2
|
+
import { A as refuse, C as lazyFor, D as pathKey, E as modelFrom, F as startingFrom, I as staticRegion, L as tagOf, M as routeOf, N as serializeJsonScript, O as plan, P as serving, R as unbound, S as codecOf, T as metaMarkup, _ as allowedTags, a as Meta, b as bindings, c as RestoredPlace, d as ResumePlan, f as ResumeRefused, g as Start, h as STYLES_MARKER, i as META_ATTRIBUTE, j as resume, k as projectionsOf, l as ResumableConfig, m as STATIC_ATTRIBUTE, n as HEAD_MARKER, o as PROTOCOL, p as RouteMatch, r as Loadable, s as PlanSurface, t as HEAD_END_MARKER, u as ResumePart, v as arrival, w as metaEntry, x as bindingsAndEvents, y as attributeOf } from "./shared-BuCOwm57.js";
|
|
3
|
+
export { FOLDKIT_APP_ATTRIBUTE, HEAD_END_MARKER, HEAD_MARKER, Loadable, META_ATTRIBUTE, Meta, PROTOCOL, PlanSurface, RESUME_ATTRIBUTE, RestoredPlace, ResumableConfig, ResumePart, ResumePlan, ResumeRefused, RouteMatch, STATIC_ATTRIBUTE, STYLES_MARKER, Start, allowedTags, arrival, attributeOf, bindings, bindingsAndEvents, codecOf, lazyFor, metaEntry, metaMarkup, modelFrom, pathKey, plan, projectionsOf, refuse, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf, unbound };
|
package/dist/shared.js
CHANGED
|
@@ -316,6 +316,8 @@ const serving = () => {
|
|
|
316
316
|
const mode = current()?.mode;
|
|
317
317
|
return mode === "collect" || mode === "replay";
|
|
318
318
|
};
|
|
319
|
+
/** The lazy bundles a page drawn from `model` needs loaded. */
|
|
320
|
+
const lazyFor = (config, model) => typeof config.lazy === "function" ? config.lazy(model) : config.lazy ?? [];
|
|
319
321
|
/**
|
|
320
322
|
* The config without a `Flags` key at all. Deleted, never set to `undefined`:
|
|
321
323
|
* Foldkit's server asks whether `Flags` is defined and its client whether the
|
|
@@ -364,6 +366,6 @@ const bindingsAndEvents = (plan, page, root, model) => {
|
|
|
364
366
|
events: events.success
|
|
365
367
|
});
|
|
366
368
|
};
|
|
367
|
-
export { FOLDKIT_APP_ATTRIBUTE, HEAD_END_MARKER, HEAD_MARKER, META_ATTRIBUTE, PROTOCOL, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, arrival, attributeOf, bindings, bindingsAndEvents, codecOf, metaEntry, metaMarkup, modelFrom, pathKey, plan, projectionsOf, refuse, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf, unbound };
|
|
369
|
+
export { FOLDKIT_APP_ATTRIBUTE, HEAD_END_MARKER, HEAD_MARKER, META_ATTRIBUTE, PROTOCOL, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, arrival, attributeOf, bindings, bindingsAndEvents, codecOf, lazyFor, metaEntry, metaMarkup, modelFrom, pathKey, plan, projectionsOf, refuse, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf, unbound };
|
|
368
370
|
|
|
369
371
|
//# sourceMappingURL=shared.js.map
|
package/dist/shared.js.map
CHANGED
|
@@ -1 +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 {\n inertHtml,\n type Attribute,\n type ChildAttribute,\n type Html,\n type HtmlBuilder,\n} from 'foldkit/html'\nimport type { Ports } from 'foldkit/port'\nimport { fromString } from 'foldkit/url'\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'\nimport { FOLDKIT_APP_ATTRIBUTE, RESUME_ATTRIBUTE } from './marks.js'\n\nexport { FOLDKIT_APP_ATTRIBUTE, RESUME_ATTRIBUTE } from './marks.js'\n\n/** The envelope format this package writes and reads. */\nexport const PROTOCOL = 1\n\n/**\n * The comment a render's `styles` follow in the stamped root. Hydration\n * removes children the view does not draw, so `SSR.hydrate` moves what\n * follows it into the head before adopting the page.\n */\nexport const STYLES_MARKER = 'foldkit-plus-styles'\n\n/**\n * The comments a dynamically served page's head markup (a plan's `meta`)\n * sits between in the stamped root, until the host's `SSR.headed` moves it\n * before `</head>`. Left in the body, `SSR.hydrate` removes it and reports\n * `HeadNotMoved`.\n */\nexport const HEAD_MARKER = 'foldkit-plus-head'\nexport const HEAD_END_MARKER = '/foldkit-plus-head'\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, in single quotes so the\n * JSON's own double quotes need no escape. `&` and `'` are escaped, so no\n * string in the Model can break out of the value; `getAttribute` resolves the\n * entities back to exactly the JSON. `serializeJsonScript` has already escaped\n * `<` and the line separators.\n */\nexport const attributeOf = (json: string): string =>\n ` ${RESUME_ATTRIBUTE}='${json.replaceAll('&', '&').replaceAll(\"'\", ''')}'`\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('&', '&')\n .replaceAll('\"', '"')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\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 * A Model path the browser can read again for itself, such as one a URL or\n * cookie mirror owns, and how to copy the server's value for the coverage\n * check. The envelope leaves the path out.\n */\nexport interface RestoredPlace<Model> {\n readonly path: ReadonlyArray<string>\n readonly copy: (target: Model, source: Model) => 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 /**\n * Model paths the browser reads again before the first render, such as the\n * fields a URL or cookie mirror owns. The envelope leaves them out.\n */\n readonly restored: ReadonlyArray<RestoredPlace<Model>>\n /** The browser's own values for `restored`, read before the first render; never run on the server. */\n readonly restore?: ((model: Model) => Model) | undefined\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 restored?: ReadonlyArray<ModelRef<NoInfer<Model>, any>> | undefined\n readonly restore?: ((model: Model) => 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 const restored = (config.restored ?? []).map(place => {\n const focus = ModelRef.focus(place)\n return {\n path: focus.dependency,\n copy: (target: Model, source: Model) => focus.set(target, focus.get(source)),\n }\n })\n // A path the browser restores is not sent, so a state that still sends it\n // would carry the value twice under two owners.\n const sent = restored.find(({ path }) =>\n config.state.dependencies.some(\n outer =>\n outer.length > 0 &&\n outer.length <= path.length &&\n outer.every((key, index) => path[index] === key),\n ),\n )\n if (sent !== undefined) {\n throw new Error(\n `SSR.plan: \"${sent.path.join('.')}\" is restored by the browser, so the state must not send it`,\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 restored,\n ...(config.restore === undefined ? {} : { restore: config.restore }),\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 // Only the query differs: a static host served a page rendered for one\n // query for another, which only a page recorded for its path survives.\n const served =\n match !== 'path' && pathKey(String(route)) === pathKey(options.route)\n ? `; a page a static host serves for every query must record its path alone: generate it with SSR.generate, or name its path in SSR.entry's prerendered`\n : ''\n return refuse(\n 'Route',\n `the page was ${match === 'path' ? 'generated' : 'rendered'} for ${String(route)}, not ${options.route}${served}`,\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/**\n * The Message telling the application the URL it is at, when the page was\n * recorded for its path alone and the browser is at a query: `init` never ran\n * here, so the application would otherwise never learn the query. None for\n * an application without routing, or a page at no query.\n */\nexport const arrival = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n page: ParentNode,\n href: string,\n): Option.Option<Message> => {\n const routing = config.routing\n if (routing === undefined || new URL(href).search === '') return Option.none()\n const read = readEnvelope(page)\n if (Result.isFailure(read) || read.success.match !== 'path') return Option.none()\n return Option.map(fromString(href), routing.onUrlChange)\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 * A bundle of attributes, such as a Slot's, typed as binding no Message, for a\n * static region's `ih` or any builder. A Slot's attributes are typed with the\n * page's Message whatever its Mixins add, so the type cannot tell a Style from\n * a handler; this checks when it is called instead, and throws on any handler\n * (an `On…` attribute) or a Submodel's attribute, neither of which a static\n * region could run.\n */\nexport const unbound = <Message>(\n attributes: ReadonlyArray<Attribute<Message> | ChildAttribute>,\n): ReadonlyArray<Attribute<never>> =>\n attributes.map(attribute => {\n if (!('_tag' in attribute)) {\n throw new Error(\"SSR.unbound was given a Submodel's attribute, which dispatches a Message\")\n }\n if (attribute._tag.startsWith('On')) {\n throw new Error(`SSR.unbound was given ${attribute._tag}, which binds a Message`)\n }\n // Every variant without the `On` prefix holds no Message, so it is one of `Attribute<never>`'s.\n return attribute as Attribute<never>\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> | undefined },\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.success })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,MAAa,WAAW;;;;;;AAOxB,MAAa,gBAAgB;;;;;;;AAQ7B,MAAa,cAAc;AAC3B,MAAa,kBAAkB;AAE/B,MAAM,iBAAiB,OAAO,aAAa,IAAM;AACjD,MAAM,sBAAsB,OAAO,aAAa,IAAM;;;;;;AAOtD,MAAa,uBAAuB,UAClC,KAAK,UAAU,KAAK,CAAC,CAClB,WAAW,KAAK,SAAS,CAAC,CAC1B,WAAW,gBAAgB,SAAS,CAAC,CACrC,WAAW,qBAAqB,SAAS;;;;;;;;AAS9C,MAAa,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AAM,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
|
+
{"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 {\n inertHtml,\n type Attribute,\n type ChildAttribute,\n type Html,\n type HtmlBuilder,\n} from 'foldkit/html'\nimport type { Ports } from 'foldkit/port'\nimport { fromString } from 'foldkit/url'\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'\nimport { FOLDKIT_APP_ATTRIBUTE, RESUME_ATTRIBUTE } from './marks.js'\n\nexport { FOLDKIT_APP_ATTRIBUTE, RESUME_ATTRIBUTE } from './marks.js'\n\n/** The envelope format this package writes and reads. */\nexport const PROTOCOL = 1\n\n/**\n * The comment a render's `styles` follow in the stamped root. Hydration\n * removes children the view does not draw, so `SSR.hydrate` moves what\n * follows it into the head before adopting the page.\n */\nexport const STYLES_MARKER = 'foldkit-plus-styles'\n\n/**\n * The comments a dynamically served page's head markup (a plan's `meta`)\n * sits between in the stamped root, until the host's `SSR.headed` moves it\n * before `</head>`. Left in the body, `SSR.hydrate` removes it and reports\n * `HeadNotMoved`.\n */\nexport const HEAD_MARKER = 'foldkit-plus-head'\nexport const HEAD_END_MARKER = '/foldkit-plus-head'\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, in single quotes so the\n * JSON's own double quotes need no escape. `&` and `'` are escaped, so no\n * string in the Model can break out of the value; `getAttribute` resolves the\n * entities back to exactly the JSON. `serializeJsonScript` has already escaped\n * `<` and the line separators.\n */\nexport const attributeOf = (json: string): string =>\n ` ${RESUME_ATTRIBUTE}='${json.replaceAll('&', '&').replaceAll(\"'\", ''')}'`\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('&', '&')\n .replaceAll('\"', '"')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\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 * A Model path the browser can read again for itself, such as one a URL or\n * cookie mirror owns, and how to copy the server's value for the coverage\n * check. The envelope leaves the path out.\n */\nexport interface RestoredPlace<Model> {\n readonly path: ReadonlyArray<string>\n readonly copy: (target: Model, source: Model) => 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 /**\n * Model paths the browser reads again before the first render, such as the\n * fields a URL or cookie mirror owns. The envelope leaves them out.\n */\n readonly restored: ReadonlyArray<RestoredPlace<Model>>\n /** The browser's own values for `restored`, read before the first render; never run on the server. */\n readonly restore?: ((model: Model) => Model) | undefined\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 restored?: ReadonlyArray<ModelRef<NoInfer<Model>, any>> | undefined\n readonly restore?: ((model: Model) => 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 const restored = (config.restored ?? []).map(place => {\n const focus = ModelRef.focus(place)\n return {\n path: focus.dependency,\n copy: (target: Model, source: Model) => focus.set(target, focus.get(source)),\n }\n })\n // A path the browser restores is not sent, so a state that still sends it\n // would carry the value twice under two owners.\n const sent = restored.find(({ path }) =>\n config.state.dependencies.some(\n outer =>\n outer.length > 0 &&\n outer.length <= path.length &&\n outer.every((key, index) => path[index] === key),\n ),\n )\n if (sent !== undefined) {\n throw new Error(\n `SSR.plan: \"${sent.path.join('.')}\" is restored by the browser, so the state must not send it`,\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 restored,\n ...(config.restore === undefined ? {} : { restore: config.restore }),\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 // Only the query differs: a static host served a page rendered for one\n // query for another, which only a page recorded for its path survives.\n const served =\n match !== 'path' && pathKey(String(route)) === pathKey(options.route)\n ? `; a page a static host serves for every query must record its path alone: generate it with SSR.generate, or name its path in SSR.entry's prerendered`\n : ''\n return refuse(\n 'Route',\n `the page was ${match === 'path' ? 'generated' : 'rendered'} for ${String(route)}, not ${options.route}${served}`,\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/**\n * The Message telling the application the URL it is at, when the page was\n * recorded for its path alone and the browser is at a query: `init` never ran\n * here, so the application would otherwise never learn the query. None for\n * an application without routing, or a page at no query.\n */\nexport const arrival = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n page: ParentNode,\n href: string,\n): Option.Option<Message> => {\n const routing = config.routing\n if (routing === undefined || new URL(href).search === '') return Option.none()\n const read = readEnvelope(page)\n if (Result.isFailure(read) || read.success.match !== 'path') return Option.none()\n return Option.map(fromString(href), routing.onUrlChange)\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 * A bundle of attributes, such as a Slot's, typed as binding no Message, for a\n * static region's `ih` or any builder. A Slot's attributes are typed with the\n * page's Message whatever its Mixins add, so the type cannot tell a Style from\n * a handler; this checks when it is called instead, and throws on any handler\n * (an `On…` attribute) or a Submodel's attribute, neither of which a static\n * region could run.\n */\nexport const unbound = <Message>(\n attributes: ReadonlyArray<Attribute<Message> | ChildAttribute>,\n): ReadonlyArray<Attribute<never>> =>\n attributes.map(attribute => {\n if (!('_tag' in attribute)) {\n throw new Error(\"SSR.unbound was given a Submodel's attribute, which dispatches a Message\")\n }\n if (attribute._tag.startsWith('On')) {\n throw new Error(`SSR.unbound was given ${attribute._tag}, which binds a Message`)\n }\n // Every variant without the `On` prefix holds no Message, so it is one of `Attribute<never>`'s.\n return attribute as Attribute<never>\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 * A function is asked with the Model the page is drawn from (the server's\n * after `prepare`, the browser's as resumed), so only what that page draws\n * loads: `model => Routing.codeFor(model.route)` (`Site.routing`).\n */\n readonly lazy?: ReadonlyArray<Loadable> | ((model: Model) => ReadonlyArray<Loadable>) | undefined\n}\n\n/** The lazy bundles a page drawn from `model` needs loaded. */\nexport const lazyFor = <Model>(\n config: { readonly lazy?: ResumableConfig<Model>['lazy'] },\n model: Model,\n): ReadonlyArray<Loadable> =>\n typeof config.lazy === 'function' ? config.lazy(model) : (config.lazy ?? [])\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> | undefined },\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.success })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,MAAa,WAAW;;;;;;AAOxB,MAAa,gBAAgB;;;;;;;AAQ7B,MAAa,cAAc;AAC3B,MAAa,kBAAkB;AAE/B,MAAM,iBAAiB,OAAO,aAAa,IAAM;AACjD,MAAM,sBAAsB,OAAO,aAAa,IAAM;;;;;;AAOtD,MAAa,uBAAuB,UAClC,KAAK,UAAU,KAAK,CAAC,CAClB,WAAW,KAAK,SAAS,CAAC,CAC1B,WAAW,gBAAgB,SAAS,CAAC,CACrC,WAAW,qBAAqB,SAAS;;;;;;;;AAS9C,MAAa,eAAe,SAC1B,IAAI,iBAAiB,IAAI,KAAK,WAAW,KAAK,OAAO,CAAC,CAAC,WAAW,KAAK,OAAO,EAAE;;AA0BlF,MAAa,iBAAiB;AAE9B,MAAM,iBAAiB,SACrB,KACG,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,MAAK,QAAQ,CAAC,CACzB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM;;AAG3B,MAAa,cAAc,SAAuB;CAChD,MAAM,OAAO,SAAiB,eAC5B,IAAI,QAAQ,GAAG,eAAe,GAAG,WAAW,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,IAAI,cAAc,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;CACpH,MAAM,SAAS,MAAc,UAC3B,UAAU,KAAA,IACN,CAAC,IACD,CACE,IAAI,QAAQ,CACV,CAAC,QAAQ,IAAI,GACb,CAAC,WAAW,KAAK,CACnB,CAAC,CACH;CACN,MAAM,YAAY,MAAc,UAC9B,UAAU,KAAA,IACN,CAAC,IACD,CACE,IAAI,QAAQ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AI,kBAAkB,MAAM,MAAM,MAAM,KAAK,IAAG,SAAQ,KAAK,QAAQ;AAE9E,MAAM,iBAAiB,OAAO,SAAS,OAAO,MAAM,OAAO,MAAM,CAAC;;;;;AAMlE,MAAa,qBACX,MACA,MACA,MACA,UAOG;CACH,MAAM,SAAS,aAAa,IAAI;CAChC,IAAI,OAAO,UAAU,MAAM,GAAG,OAAO,OAAO,KAAK,OAAO,OAAO;CAC/D,MAAM,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"}
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { d as ResumePlan, l as ResumableConfig } from "./shared-
|
|
1
|
+
import { d as ResumePlan, l as ResumableConfig } from "./shared-BuCOwm57.js";
|
|
2
2
|
import { Head, ResumeUnsafe } from "./index.js";
|
|
3
3
|
import { runtimeChunk } from "./runtimeChunk.js";
|
|
4
4
|
import { Effect, Schema } from "effect";
|
|
5
5
|
import { RenderError } from "foldkit/experimental/server";
|
|
6
|
-
import { Plugin } from "vite";
|
|
6
|
+
import { Plugin, PluginOption } from "vite";
|
|
7
7
|
/** A path the site generates, with the date its sitemap names when it has one. */
|
|
8
8
|
export type SitePath = string | {
|
|
9
9
|
readonly path: string;
|
|
@@ -28,7 +28,13 @@ export declare const fileFor: (path: string, layout: 'directory' | 'flat') => st
|
|
|
28
28
|
*/
|
|
29
29
|
export interface StaticSite<Model, Fields extends Schema.Struct.Fields, Message, Resolved = ResumableConfig<Model, Message>> {
|
|
30
30
|
readonly config: Resolved | ((path: string) => Resolved | Promise<Resolved>);
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* The plan every page resumes with, or a function of the path for a site of
|
|
33
|
+
* more than one application: each path then resumes with the plan of the
|
|
34
|
+
* application `config` returns for it. A function that throws fails the
|
|
35
|
+
* build, naming the path.
|
|
36
|
+
*/
|
|
37
|
+
readonly plan: ResumePlan<Model, Fields> | ((path: string) => ResumePlan<Model, Fields>);
|
|
32
38
|
readonly buildId?: string | undefined;
|
|
33
39
|
readonly origin: string;
|
|
34
40
|
readonly paths: ReadonlyArray<SitePath> | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>);
|
|
@@ -85,7 +91,7 @@ export declare const writeEmitted: (outDir: string, emitted: ReadonlyArray<Emitt
|
|
|
85
91
|
/** A site description as a module exports it, for the plugin to evaluate. */
|
|
86
92
|
export interface SiteModule {
|
|
87
93
|
readonly config: ResumableConfig<any, any> | ((path: string) => ResumableConfig<any, any> | Promise<ResumableConfig<any, any>>);
|
|
88
|
-
readonly plan: ResumePlan<any, any
|
|
94
|
+
readonly plan: ResumePlan<any, any> | ((path: string) => ResumePlan<any, any>);
|
|
89
95
|
readonly buildId?: string | undefined;
|
|
90
96
|
readonly origin: string;
|
|
91
97
|
readonly paths: ReadonlyArray<SitePath> | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>);
|
|
@@ -110,6 +116,13 @@ export declare const staticSite: (options: {
|
|
|
110
116
|
readonly module: string;
|
|
111
117
|
readonly export?: string | undefined;
|
|
112
118
|
};
|
|
119
|
+
/**
|
|
120
|
+
* Vite plugins the site module is loaded with. The build renders the pages
|
|
121
|
+
* from a server of its own, which loads none of the application's: pass the
|
|
122
|
+
* ones that change what a view draws, such as Foldkit's view-identity
|
|
123
|
+
* branding, whose markers the browser compares with the page it adopts.
|
|
124
|
+
*/
|
|
125
|
+
readonly plugins?: PluginOption | undefined;
|
|
113
126
|
/** What `vite build` wrote: defaults to the resolved `build.outDir`. */
|
|
114
127
|
readonly outDir?: string | undefined;
|
|
115
128
|
}) => Plugin;
|
package/dist/vite.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;;;;;;YA0BY;WAA+B;WAAuB;;;;;;;;;qBAarD,UAAO,cAAgB;;;;;;;;;;iBAgBnB,WACf,OACA,eAAe,OAAO,OAAO,QAC7B,SAKA,WAAW,gBAAgB,OAAO;WAEzB,QAAQ,aAAa,iBAAiB,WAAW,QAAQ
|
|
1
|
+
{"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;;;;;;YA0BY;WAA+B;WAAuB;;;;;;;;;qBAarD,UAAO,cAAgB;;;;;;;;;;iBAgBnB,WACf,OACA,eAAe,OAAO,OAAO,QAC7B,SAKA,WAAW,gBAAgB,OAAO;WAEzB,QAAQ,aAAa,iBAAiB,WAAW,QAAQ;;;;;;;WAOzD,MAAM,WAAW,OAAO,YAAY,iBAAiB,WAAW,OAAO;WACvE;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;;;;;qBA2F7B,eAAY,gBACT,SACL,cAAc,iBACtB;;iBAiBc;WACN,QACL,8BACE,iBAAiB,4BAA4B,QAAQ;WAClD,MAAM,yBAAyB,iBAAiB;WAChD;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;;;;;;;;WAO1C,UAAU;;WAEV;MACP"}
|
package/dist/vite.js
CHANGED
|
@@ -60,6 +60,7 @@ const generateStaticSite = (site) => {
|
|
|
60
60
|
const specs = typeof pathsInput === "function" ? yield* Effect.promise(() => Promise.resolve(pathsInput())) : pathsInput;
|
|
61
61
|
const files = site.files ?? "directory";
|
|
62
62
|
const configInput = site.config;
|
|
63
|
+
const planInput = site.plan;
|
|
63
64
|
if (specs.length === 0) throw new Error("foldkit-ssr: the site lists no paths: a site of nothing is a misconfigured paths");
|
|
64
65
|
const claimed = /* @__PURE__ */ new Map();
|
|
65
66
|
for (const spec of specs) {
|
|
@@ -72,7 +73,11 @@ const generateStaticSite = (site) => {
|
|
|
72
73
|
for (const spec of specs) {
|
|
73
74
|
const path = pathOf(spec);
|
|
74
75
|
const config = typeof configInput === "function" ? yield* Effect.promise(async () => configInput(path)) : configInput;
|
|
75
|
-
const
|
|
76
|
+
const plan = typeof planInput === "function" ? yield* Effect.try({
|
|
77
|
+
try: () => planInput(path),
|
|
78
|
+
catch: (cause) => new Error(`foldkit-ssr: the plan for "${path}" failed: ${String(cause)}`, { cause })
|
|
79
|
+
}).pipe(Effect.orDie) : planInput;
|
|
80
|
+
const [page] = yield* SSR.generate(config, plan, {
|
|
76
81
|
buildId,
|
|
77
82
|
template: site.template,
|
|
78
83
|
origin: site.origin,
|
|
@@ -147,6 +152,7 @@ const staticSite = (options) => {
|
|
|
147
152
|
},
|
|
148
153
|
resolve: { conditions },
|
|
149
154
|
ssr: { resolve: { conditions } },
|
|
155
|
+
...options.plugins === void 0 ? {} : { plugins: [options.plugins] },
|
|
150
156
|
optimizeDeps: {
|
|
151
157
|
noDiscovery: true,
|
|
152
158
|
include: []
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +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\nexport { runtimeChunk } from './runtimeChunk.js'\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":";;;;;;;;;;;;;;;;;;AA4BA,MAAM,UAAU,SAA4B,OAAO,SAAS,WAAW,OAAO,KAAK;AACnF,MAAM,cAAc,SAClB,OAAO,SAAS,WAAW,KAAA,IAAY,KAAK;;;;;;;;AAS9C,MAAa,WAAW,MAAc,WAAyC;CAC7E,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I,SAAS,KAAA,KAAa,SAAS,QAAQ,OAAO,SAAS,UACzD,MAAM,IAAI,MACR,gBAAgB,QAAQ,KAAK,OAAO,cAAc,QAAQ,KAAK,UAAU,OAAO,kBAClF;IACF,MAAM,QAAQ,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"}
|
|
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, PluginOption } 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\nexport { runtimeChunk } from './runtimeChunk.js'\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 /**\n * The plan every page resumes with, or a function of the path for a site of\n * more than one application: each path then resumes with the plan of the\n * application `config` returns for it. A function that throws fails the\n * build, naming the path.\n */\n readonly plan: ResumePlan<Model, Fields> | ((path: string) => 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 const planInput = site.plan\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 plan =\n typeof planInput === 'function'\n ? yield* Effect.try({\n try: () => planInput(path),\n catch: cause =>\n new Error(`foldkit-ssr: the plan for \"${path}\" failed: ${String(cause)}`, {\n cause,\n }),\n }).pipe(Effect.orDie)\n : planInput\n const [page] = yield* SSR.generate(config, 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> | ((path: string) => 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 /**\n * Vite plugins the site module is loaded with. The build renders the pages\n * from a server of its own, which loads none of the application's: pass the\n * ones that change what a view draws, such as Foldkit's view-identity\n * branding, whose markers the browser compares with the page it adopts.\n */\n readonly plugins?: PluginOption | 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 ...(options.plugins === undefined ? {} : { plugins: [options.plugins] }),\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":";;;;;;;;;;;;;;;;;;AA4BA,MAAM,UAAU,SAA4B,OAAO,SAAS,WAAW,OAAO,KAAK;AACnF,MAAM,cAAc,SAClB,OAAO,SAAS,WAAW,KAAA,IAAY,KAAK;;;;;;;;AAS9C,MAAa,W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O,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.
|
|
3
|
+
"version": "0.13.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",
|
|
@@ -56,12 +56,12 @@
|
|
|
56
56
|
"foldkit": "^0.170.0"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"foldkit-surface": "0.
|
|
59
|
+
"foldkit-surface": "0.15.0"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
|
-
"@effect/platform-browser": "
|
|
62
|
+
"@effect/platform-browser": "4.1.4",
|
|
63
63
|
"@types/jsdom": "30.0.0",
|
|
64
|
-
"effect": "
|
|
64
|
+
"effect": "4.1.4",
|
|
65
65
|
"esbuild": "0.28.2",
|
|
66
66
|
"foldkit": "0.170.0",
|
|
67
67
|
"jsdom": "30.1.3",
|
|
@@ -69,10 +69,10 @@
|
|
|
69
69
|
"tsdown": "^0.23.1",
|
|
70
70
|
"typescript": "7.0.2",
|
|
71
71
|
"vite": "8.3.5",
|
|
72
|
-
"foldkit-bundle": "0.
|
|
73
|
-
"foldkit-
|
|
74
|
-
"foldkit-mirror": "0.
|
|
75
|
-
"foldkit-
|
|
72
|
+
"foldkit-bundle": "0.14.0",
|
|
73
|
+
"foldkit-remote": "0.27.0",
|
|
74
|
+
"foldkit-mirror": "0.11.0",
|
|
75
|
+
"foldkit-entity": "0.18.0"
|
|
76
76
|
},
|
|
77
77
|
"scripts": {
|
|
78
78
|
"build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
|