foldkit-ssr 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -2
- package/dist/{client-XnpTQZHw.d.ts → client-qmdYY-Eb.d.ts} +2 -2
- package/dist/{client-XnpTQZHw.d.ts.map → client-qmdYY-Eb.d.ts.map} +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +1 -1
- package/dist/diagnostics.d.ts +2 -2
- package/dist/diagnostics.js +8 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/index.d.ts +48 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +147 -9
- package/dist/index.js.map +1 -1
- package/dist/keep.d.ts +2 -0
- package/dist/keep.d.ts.map +1 -1
- package/dist/keep.js +36 -7
- package/dist/keep.js.map +1 -1
- package/dist/pageCache-DO0pOgnc.d.ts +80 -0
- package/dist/pageCache-DO0pOgnc.d.ts.map +1 -0
- package/dist/pageCache.d.ts +2 -0
- package/dist/pageCache.js +112 -0
- package/dist/pageCache.js.map +1 -0
- package/dist/{requestContext-D9nsbGSJ.d.ts → requestContext-DmwmQeci.d.ts} +12 -2
- package/dist/requestContext-DmwmQeci.d.ts.map +1 -0
- package/dist/requestContext.d.ts +2 -2
- package/dist/requestContext.js +30 -13
- package/dist/requestContext.js.map +1 -1
- package/dist/{shared-DbupL3vO.d.ts → shared-CJN-m58Z.d.ts} +19 -7
- package/dist/shared-CJN-m58Z.d.ts.map +1 -0
- package/dist/shared.d.ts +1 -1
- package/dist/shared.js +6 -5
- package/dist/shared.js.map +1 -1
- package/dist/vite.d.ts +1 -1
- package/package.json +6 -6
- package/dist/requestContext-D9nsbGSJ.d.ts.map +0 -1
- package/dist/shared-DbupL3vO.d.ts.map +0 -1
package/dist/keep.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keep.js","names":[],"sources":["../src/keep.ts"],"sourcesContent":["/**\n * What is typed before the runtime starts, read from the fields themselves.\n *\n * A field the view marks with `KeepTyped` keeps its typing in the browser's\n * own state (its value, its selection) until the runtime adopts it, and\n * hydration then re-asserts the value the server rendered. The page reads\n * the marked fields when its script runs, turns each changed one into its\n * binding's Message, and after the first render puts the value and the\n * selection back, so the Message that follows finds the field already\n * holding its value and writes nothing.\n */\nimport { Result } from 'effect'\nimport { typedMessage, type DecodedBinding } from './listen.js'\nimport { KEEP_ATTRIBUTE } from './resumable.js'\n\ntype Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n\n/** A marked field and the binding whose Message replays its typing. */\nexport interface KeptField {\n readonly element: Field\n readonly binding: DecodedBinding\n}\n\nconst isField = (element: Element): element is Field =>\n element instanceof HTMLInputElement ||\n element instanceof HTMLTextAreaElement ||\n element instanceof HTMLSelectElement\n\n/**\n * The fields in `root` marked to keep their typing, each with its binding.\n * Refused, with the reason, when a marker names no `OnInput` or `OnChange`\n * binding, or sits on an element that is not a field: the server writes\n * neither, so the page was altered.\n */\nexport const keptFields = (\n root: Element,\n bindings: ReadonlyArray<DecodedBinding>,\n): Result.Result<ReadonlyArray<KeptField>, string> => {\n const kept: Array<KeptField> = []\n for (const element of Array.from(root.querySelectorAll(`[${KEEP_ATTRIBUTE}]`))) {\n const token = element.getAttribute(KEEP_ATTRIBUTE) ?? ''\n const binding = bindings[Number(token)]\n // A binding of either event has a hole: a closure is no binding at all.\n if (\n !/^\\d+$/.test(token) ||\n binding === undefined ||\n (binding.event !== 'input' && binding.event !== 'change')\n ) {\n return Result.fail(\n `the marker ${KEEP_ATTRIBUTE}=\"${token}\" names no input or change binding the page carries`,\n )\n }\n if (!isField(element)) {\n return Result.fail(`the marker ${KEEP_ATTRIBUTE} is on a ${element.localName}, not a field`)\n }\n kept.push({ element, binding })\n }\n return Result.succeed(kept)\n}\n\n/**\n * The value the server rendered into a field: its default, which typing\n * leaves alone. A `select`'s
|
|
1
|
+
{"version":3,"file":"keep.js","names":[],"sources":["../src/keep.ts"],"sourcesContent":["/**\n * What is typed before the runtime starts, read from the fields themselves.\n *\n * A field the view marks with `KeepTyped` keeps its typing in the browser's\n * own state (its value, its selection) until the runtime adopts it, and\n * hydration then re-asserts the value the server rendered. The page reads\n * the marked fields when its script runs, turns each changed one into its\n * binding's Message, and after the first render puts the value and the\n * selection back, so the Message that follows finds the field already\n * holding its value and writes nothing.\n */\nimport { Result } from 'effect'\nimport { typedMessage, type DecodedBinding } from './listen.js'\nimport { KEEP_ATTRIBUTE } from './resumable.js'\n\ntype Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n\n/** A marked field and the binding whose Message replays its typing. */\nexport interface KeptField {\n readonly element: Field\n readonly binding: DecodedBinding\n}\n\nconst isField = (element: Element): element is Field =>\n element instanceof HTMLInputElement ||\n element instanceof HTMLTextAreaElement ||\n element instanceof HTMLSelectElement\n\n/**\n * The fields in `root` marked to keep their typing, each with its binding.\n * Refused, with the reason, when a marker names no `OnInput` or `OnChange`\n * binding, or sits on an element that is not a field: the server writes\n * neither, so the page was altered.\n */\nexport const keptFields = (\n root: Element,\n bindings: ReadonlyArray<DecodedBinding>,\n): Result.Result<ReadonlyArray<KeptField>, string> => {\n const kept: Array<KeptField> = []\n for (const element of Array.from(root.querySelectorAll(`[${KEEP_ATTRIBUTE}]`))) {\n const token = element.getAttribute(KEEP_ATTRIBUTE) ?? ''\n const binding = bindings[Number(token)]\n // A binding of either event has a hole: a closure is no binding at all.\n if (\n !/^\\d+$/.test(token) ||\n binding === undefined ||\n (binding.event !== 'input' && binding.event !== 'change')\n ) {\n return Result.fail(\n `the marker ${KEEP_ATTRIBUTE}=\"${token}\" names no input or change binding the page carries`,\n )\n }\n if (!isField(element)) {\n return Result.fail(`the marker ${KEEP_ATTRIBUTE} is on a ${element.localName}, not a field`)\n }\n kept.push({ element, binding })\n }\n return Result.succeed(kept)\n}\n\n/** Whether an option is disabled by its own attribute or by a disabled `optgroup` around it. */\nconst disabledOption = (option: HTMLOptionElement): boolean =>\n option.disabled || (option.closest('optgroup')?.disabled ?? false)\n\n/** A select's display size: its `size` when it parses above zero, else 4 for `multiple` and 1 otherwise. */\nconst displaySize = (select: HTMLSelectElement): number => {\n const size = select.getAttribute('size')\n const parsed = size === null ? null : /^\\s*(\\d+)\\s*$/.exec(size)\n if (parsed !== null && Number(parsed[1]) > 0) return Number(parsed[1])\n return select.multiple ? 4 : 1\n}\n\n/**\n * The value the server rendered into a field: its default, which typing\n * leaves alone. A `select`'s follows the HTML reset algorithm: the last option\n * marked `selected` wins, else a single-line select takes its first option\n * that is not disabled, through an `optgroup` included.\n */\nconst servedValue = (element: Field): string => {\n if (!(element instanceof HTMLSelectElement)) return element.defaultValue\n const options = Array.from(element.options)\n const chosen =\n options.filter(option => option.defaultSelected).at(-1) ??\n (displaySize(element) === 1 ? options.find(option => !disabledOption(option)) : undefined)\n return chosen?.value ?? ''\n}\n\n/** The indices of a `select`'s options that `chosen` picks, in document order. */\nconst indicesOf = (\n select: HTMLSelectElement,\n chosen: (option: HTMLOptionElement) => boolean,\n): ReadonlyArray<number> =>\n Array.from(select.options).flatMap((option, index) => (chosen(option) ? [index] : []))\n\n/** Whether the field holds something other than what the server rendered. */\nexport const changed = (field: KeptField): boolean => {\n const { element } = field\n // A multiple select holds a set of selections, which its `value`, the first\n // of them, cannot tell apart: compare the whole set with the served one.\n if (element instanceof HTMLSelectElement && element.multiple) {\n const selected = indicesOf(element, option => option.selected)\n const served = indicesOf(element, option => option.defaultSelected)\n return selected.length !== served.length || selected.some((index, at) => index !== served[at])\n }\n return element.value !== servedValue(element)\n}\n\n/** The Messages that carry each changed field's typing, in document order. */\nexport const typedMessages = (fields: ReadonlyArray<KeptField>): ReadonlyArray<unknown> =>\n fields.filter(changed).map(field => typedMessage(field.binding, field.element.value))\n\n/** A changed field's value and selection, as they were just before the runtime started. */\nexport interface Held {\n readonly element: Field\n readonly value: string\n /** A `multiple` select's selected option indices: its `value` names only the first. */\n readonly selected?: readonly number[] | undefined\n readonly selection?: readonly [number, number, 'forward' | 'backward' | 'none'] | undefined\n}\n\n/** Each changed field's state, to put back once hydration has re-asserted the served value. */\nexport const hold = (fields: ReadonlyArray<KeptField>): ReadonlyArray<Held> =>\n fields.filter(changed).map(({ element }) => {\n if (element instanceof HTMLSelectElement) {\n return element.multiple\n ? {\n element,\n value: element.value,\n selected: indicesOf(element, option => option.selected),\n }\n : { element, value: element.value }\n }\n // An input type with no selection (`email`, `number`) reads null.\n const { selectionStart: start, selectionEnd: end } = element\n return {\n element,\n value: element.value,\n ...(start === null || end === null\n ? {}\n : { selection: [start, end, element.selectionDirection ?? 'none'] as const }),\n }\n })\n\n/**\n * Puts each held field back as it was. The first render adopted it, so it is\n * the same element, which the person may still be typing into.\n */\nexport const restore = (held: ReadonlyArray<Held>): void => {\n for (const { element, value, selected, selection } of held) {\n if (element instanceof HTMLSelectElement && selected !== undefined) {\n const chosen = new Set(selected)\n Array.from(element.options).forEach((option, index) => {\n option.selected = chosen.has(index)\n })\n } else {\n element.value = value\n }\n if (selection !== undefined && !(element instanceof HTMLSelectElement)) {\n element.setSelectionRange(...selection)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,WAAW,YACf,mBAAmB,oBACnB,mBAAmB,uBACnB,mBAAmB;;;;;;;AAQrB,MAAa,cACX,MACA,aACoD;CACpD,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,WAAW,MAAM,KAAK,KAAK,iBAAiB,IAAI,eAAe,EAAE,CAAC,GAAG;EAC9E,MAAM,QAAQ,QAAQ,aAAA,wBAA2B,KAAK;EACtD,MAAM,UAAU,SAAS,OAAO,KAAK;EAErC,IACE,CAAC,QAAQ,KAAK,KAAK,KACnB,YAAY,KAAA,KACX,QAAQ,UAAU,WAAW,QAAQ,UAAU,UAEhD,OAAO,OAAO,KACZ,cAAc,eAAe,IAAI,MAAM,oDACzC;EAEF,IAAI,CAAC,QAAQ,OAAO,GAClB,OAA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BAAiB,WAC5B,OAAO,OAAO,OAAO,CAAC,CAAC,KAAI,UAAS,aAAa,MAAM,SAAS,MAAM,QAAQ,KAAK,CAAC;;AAYtF,MAAa,QAAQ,WACnB,OAAO,OAAO,OAAO,CAAC,CAAC,KAAK,EAAE,cAAc;CAC1C,IAAI,mBAAmB,mBACrB,OAAO,QAAQ,WACX;EACE;EACA,OAAO,QAAQ;EACf,UAAU,UAAU,UAAS,WAAU,OAAO,QAAQ;CACxD,IACA;EAAE;EAAS,OAAO,QAAQ;CAAM;CAGtC,MAAM,EAAE,gBAAgB,OAAO,cAAc,QAAQ;CACrD,OAAO;EACL;EACA,OAAO,QAAQ;EACf,GAAI,UAAU,QAAQ,QAAQ,OAC1B,CAAC,IACD,EAAE,WAAW;GAAC;GAAO;GAAK,QAAQ,sBAAsB;EAAM,EAAW;CAC/E;AACF,CAAC;;;;;AAMH,MAAa,WAAW,SAAoC;CAC1D,KAAK,MAAM,EAAE,SAAS,OAAO,UAAU,eAAe,MAAM;EAC1D,IAAI,mBAAmB,qBAAqB,aAAa,KAAA,GAAW;GAClE,MAAM,SAAS,IAAI,IAAI,QAAQ;GAC/B,MAAM,KAAK,QAAQ,OAAO,CAAC,CAAC,SAAS,QAAQ,UAAU;IACrD,OAAO,WAAW,OAAO,IAAI,KAAK;GACpC,CAAC;EACH,OACE,QAAQ,QAAQ;EAElB,IAAI,cAAc,KAAA,KAAa,EAAE,mBAAmB,oBAClD,QAAQ,kBAAkB,GAAG,SAAS;CAE1C;AACF"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { Effect, Option, Schema } from "effect";
|
|
2
|
+
import { RenderedApplication } from "foldkit/experimental/server";
|
|
3
|
+
/** What a render read of its request's headers: names, or every one. */
|
|
4
|
+
interface HeadersRead {
|
|
5
|
+
readonly names: Set<string>;
|
|
6
|
+
all: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* `request` as the render sees it, every header it reads recorded in `read`.
|
|
10
|
+
* A lookup by name records that name; enumerating the headers records all.
|
|
11
|
+
* Everything else is the request's own, so its getters keep their receiver.
|
|
12
|
+
* A request context read of it (`SSR.requestContext`) is the host's request's,
|
|
13
|
+
* and records all: what a host attaches may say who is asking.
|
|
14
|
+
*/
|
|
15
|
+
declare const tracked: (request: Request, read: HeadersRead) => Request;
|
|
16
|
+
/** Whether a page drawn from `read` serves `request`: it carries none of the headers read. */
|
|
17
|
+
declare const fits: (request: Request, vary: ReadonlyArray<string>) => boolean;
|
|
18
|
+
/** A kept page: what the host draws, its status and headers, and the headers it must lack. */
|
|
19
|
+
declare const KeptPage: Schema.Struct<{
|
|
20
|
+
readonly application: Schema.Struct<{
|
|
21
|
+
readonly html: Schema.String;
|
|
22
|
+
readonly title: Schema.String;
|
|
23
|
+
readonly lang: Schema.optionalKey<Schema.String>;
|
|
24
|
+
readonly dir: Schema.optionalKey<Schema.Literals<readonly ["ltr", "rtl", "auto"]>>;
|
|
25
|
+
readonly canonical: Schema.optionalKey<Schema.String>;
|
|
26
|
+
readonly ogUrl: Schema.optionalKey<Schema.String>;
|
|
27
|
+
}>;
|
|
28
|
+
readonly status: Schema.optionalKey<Schema.Number>;
|
|
29
|
+
readonly headers: Schema.$Array<Schema.Tuple<readonly [Schema.String, Schema.String]>>;
|
|
30
|
+
readonly vary: Schema.$Array<Schema.String>;
|
|
31
|
+
}>;
|
|
32
|
+
type KeptPage = typeof KeptPage.Type;
|
|
33
|
+
declare const decodeKept: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => Option.Option<{
|
|
34
|
+
readonly application: {
|
|
35
|
+
readonly html: string;
|
|
36
|
+
readonly title: string;
|
|
37
|
+
readonly lang?: string;
|
|
38
|
+
readonly dir?: "auto" | "ltr" | "rtl";
|
|
39
|
+
readonly canonical?: string;
|
|
40
|
+
readonly ogUrl?: string;
|
|
41
|
+
};
|
|
42
|
+
readonly status?: number;
|
|
43
|
+
readonly headers: readonly (readonly [string, string])[];
|
|
44
|
+
readonly vary: readonly string[];
|
|
45
|
+
}>;
|
|
46
|
+
/** Whether two renders drew the same page: what the host draws, and its status. */
|
|
47
|
+
declare const samePage: (a: {
|
|
48
|
+
readonly application: RenderedApplication;
|
|
49
|
+
readonly status?: number | undefined;
|
|
50
|
+
}, b: {
|
|
51
|
+
readonly application: RenderedApplication;
|
|
52
|
+
readonly status?: number | undefined;
|
|
53
|
+
}, now: number) => boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Where a page is kept: by its build and its full URL, under the request's
|
|
56
|
+
* origin, since the Workers Cache API keys by URL. A deploy's pages never
|
|
57
|
+
* meet another build's.
|
|
58
|
+
*/
|
|
59
|
+
declare const pageKey: (buildId: string, url: string) => Effect.Effect<string>;
|
|
60
|
+
/** The value a `Rendered` result's `headers` gives, none when absent. */
|
|
61
|
+
declare const headerOf: (headers: HeadersInit | undefined, name: string) => Option.Option<string>;
|
|
62
|
+
/** The pages `SSR.entry` serves from its cache, by the object it serves. */
|
|
63
|
+
declare const keptApplications: WeakSet<Readonly<{
|
|
64
|
+
html: string;
|
|
65
|
+
title: string;
|
|
66
|
+
lang?: string;
|
|
67
|
+
dir?: 'ltr' | 'rtl' | 'auto';
|
|
68
|
+
canonical?: string;
|
|
69
|
+
ogUrl?: string;
|
|
70
|
+
}>>;
|
|
71
|
+
/**
|
|
72
|
+
* `render`, remembering the document it drew for each kept page (one
|
|
73
|
+
* `SSR.entry` serves from its `cache`), by the page and the assets: the
|
|
74
|
+
* host draws a page into its document on every request, which parses the
|
|
75
|
+
* page again (`injectIntoTemplate`), so a kept page would cost that much
|
|
76
|
+
* every time it is served. Any other page is drawn as `render` draws it.
|
|
77
|
+
*/
|
|
78
|
+
declare const keptDocuments: <Assets>(render: (application: RenderedApplication, assets: Assets) => string) => (application: RenderedApplication, assets: Assets) => string;
|
|
79
|
+
export { headerOf as a, pageKey as c, fits as i, samePage as l, KeptPage as n, keptApplications as o, decodeKept as r, keptDocuments as s, HeadersRead as t, tracked as u };
|
|
80
|
+
//# sourceMappingURL=pageCache-DO0pOgnc.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pageCache-DO0pOgnc.d.ts","names":[],"sources":["../src/pageCache.ts"],"mappings":";;;UAYiB;WACN,OAAO;EAChB;;;;;;;;;cAUW,UAAO,SAAa,SAAO,MAAQ,gBAAc;;cAkCjD,OAAI,SAAa,SAAO,MAAQ;;cAIhC,UAAQ,OAAA;;;;;;;;;;;;;KAaT,kBAAkB,SAAS;cAE1B,aAAU,gBAAA,qCAAA,iBAAA,OAAA;;;;;;;;;;;;;;cAcV,WAAQ;WACL,aAAa;WAA8B;GAA6B;WACxE,aAAa;WAA8B;GAA6B;;;;;;cAc3E,UAAO,iBAAmB,gBAAgB,OAAO;;cAMjD,WAAQ,SAAa,yBAAuB,iBAAiB,OAAO;;cAIpE,kBAAgB,QAAA;;;;;;;;;;;;;;;cAYhB,gBAAiB,QAAM,SACzB,aAAa,qBAAqB,QAAQ,uBAAiB,aAG/C,qBAAmB,QAAU"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as headerOf, c as pageKey, i as fits, l as samePage, n as KeptPage, o as keptApplications, r as decodeKept, s as keptDocuments, t as HeadersRead, u as tracked } from "./pageCache-DO0pOgnc.js";
|
|
2
|
+
export { HeadersRead, KeptPage, decodeKept, fits, headerOf, keptApplications, keptDocuments, pageKey, samePage, tracked };
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { watchedOf } from "./requestContext.js";
|
|
2
|
+
import { Effect, Option, Schema } from "effect";
|
|
3
|
+
// src/pageCache.ts
|
|
4
|
+
/**
|
|
5
|
+
* What `SSR.entry` needs to keep a rendered page (#428): a request that
|
|
6
|
+
* records which of its headers the render read, and a page as a store keeps
|
|
7
|
+
* it. A page is kept only when every header the render read was absent, so
|
|
8
|
+
* it was drawn from the URL alone and serves every request that also lacks
|
|
9
|
+
* them; the names it read are its `Vary`.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* `request` as the render sees it, every header it reads recorded in `read`.
|
|
13
|
+
* A lookup by name records that name; enumerating the headers records all.
|
|
14
|
+
* Everything else is the request's own, so its getters keep their receiver.
|
|
15
|
+
* A request context read of it (`SSR.requestContext`) is the host's request's,
|
|
16
|
+
* and records all: what a host attaches may say who is asking.
|
|
17
|
+
*/
|
|
18
|
+
const tracked = (request, read) => {
|
|
19
|
+
const headers = new Proxy(request.headers, { get: (target, property) => {
|
|
20
|
+
const value = Reflect.get(target, property, target);
|
|
21
|
+
if (typeof value !== "function") return value;
|
|
22
|
+
if (property === "get" || property === "has") return (name) => {
|
|
23
|
+
read.names.add(name.toLowerCase());
|
|
24
|
+
return value.call(target, name);
|
|
25
|
+
};
|
|
26
|
+
read.all = true;
|
|
27
|
+
return value.bind(target);
|
|
28
|
+
} });
|
|
29
|
+
const watched = new Proxy(request, { get: (target, property) => {
|
|
30
|
+
if (property === "headers") return headers;
|
|
31
|
+
if (property === "clone") read.all = true;
|
|
32
|
+
const value = Reflect.get(target, property, target);
|
|
33
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
34
|
+
} });
|
|
35
|
+
watchedOf().set(watched, {
|
|
36
|
+
original: request,
|
|
37
|
+
readContext: () => {
|
|
38
|
+
read.all = true;
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
return watched;
|
|
42
|
+
};
|
|
43
|
+
/** Whether a page drawn from `read` serves `request`: it carries none of the headers read. */
|
|
44
|
+
const fits = (request, vary) => vary.every((name) => !request.headers.has(name));
|
|
45
|
+
/** A kept page: what the host draws, its status and headers, and the headers it must lack. */
|
|
46
|
+
const KeptPage = Schema.Struct({
|
|
47
|
+
application: Schema.Struct({
|
|
48
|
+
html: Schema.String,
|
|
49
|
+
title: Schema.String,
|
|
50
|
+
lang: Schema.optionalKey(Schema.String),
|
|
51
|
+
dir: Schema.optionalKey(Schema.Literals([
|
|
52
|
+
"ltr",
|
|
53
|
+
"rtl",
|
|
54
|
+
"auto"
|
|
55
|
+
])),
|
|
56
|
+
canonical: Schema.optionalKey(Schema.String),
|
|
57
|
+
ogUrl: Schema.optionalKey(Schema.String)
|
|
58
|
+
}),
|
|
59
|
+
status: Schema.optionalKey(Schema.Number),
|
|
60
|
+
headers: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),
|
|
61
|
+
vary: Schema.Array(Schema.String)
|
|
62
|
+
});
|
|
63
|
+
const decodeKept = Schema.decodeUnknownOption(Schema.fromJsonString(KeptPage));
|
|
64
|
+
const DAY_MS = 864e5;
|
|
65
|
+
/**
|
|
66
|
+
* A page with each time stamped on it as `T`: a run of 13 digits within a
|
|
67
|
+
* day of `now`, as milliseconds since the epoch read now are (a read's
|
|
68
|
+
* `updatedAt` in the resumed Model). A page drawn a moment later is stamped
|
|
69
|
+
* later, and is still the same page.
|
|
70
|
+
*/
|
|
71
|
+
const unstamped = (text, now) => text.replace(/\b\d{13}\b/g, (digits) => Math.abs(Number(digits) - now) < DAY_MS ? "T" : digits);
|
|
72
|
+
/** Whether two renders drew the same page: what the host draws, and its status. */
|
|
73
|
+
const samePage = (a, b, now) => unstamped(JSON.stringify([a.application, a.status ?? 200]), now) === unstamped(JSON.stringify([b.application, b.status ?? 200]), now);
|
|
74
|
+
const hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
75
|
+
/**
|
|
76
|
+
* Where a page is kept: by its build and its full URL, under the request's
|
|
77
|
+
* origin, since the Workers Cache API keys by URL. A deploy's pages never
|
|
78
|
+
* meet another build's.
|
|
79
|
+
*/
|
|
80
|
+
const pageKey = (buildId, url) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${buildId}\n${url}`))).pipe(Effect.map((digest) => `${new URL(url).origin}/__foldkit/cache/page/${hex(digest)}`));
|
|
81
|
+
/** The value a `Rendered` result's `headers` gives, none when absent. */
|
|
82
|
+
const headerOf = (headers, name) => Option.fromNullishOr(headers === void 0 ? null : new Headers(headers).get(name));
|
|
83
|
+
/** The pages `SSR.entry` serves from its cache, by the object it serves. */
|
|
84
|
+
const keptApplications = /* @__PURE__ */ new WeakSet();
|
|
85
|
+
/** The most documents `keptDocuments` holds: each is a whole page's markup. */
|
|
86
|
+
const KEPT_DOCUMENTS = 32;
|
|
87
|
+
/**
|
|
88
|
+
* `render`, remembering the document it drew for each kept page (one
|
|
89
|
+
* `SSR.entry` serves from its `cache`), by the page and the assets: the
|
|
90
|
+
* host draws a page into its document on every request, which parses the
|
|
91
|
+
* page again (`injectIntoTemplate`), so a kept page would cost that much
|
|
92
|
+
* every time it is served. Any other page is drawn as `render` draws it.
|
|
93
|
+
*/
|
|
94
|
+
const keptDocuments = (render) => {
|
|
95
|
+
const drawn = /* @__PURE__ */ new Map();
|
|
96
|
+
return (application, assets) => {
|
|
97
|
+
if (!keptApplications.has(application)) return render(application, assets);
|
|
98
|
+
const key = JSON.stringify([application, assets]);
|
|
99
|
+
const held = drawn.get(key);
|
|
100
|
+
if (held !== void 0) return held;
|
|
101
|
+
const document = render(application, assets);
|
|
102
|
+
drawn.set(key, document);
|
|
103
|
+
for (const oldest of drawn.keys()) {
|
|
104
|
+
if (drawn.size <= KEPT_DOCUMENTS) break;
|
|
105
|
+
drawn.delete(oldest);
|
|
106
|
+
}
|
|
107
|
+
return document;
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
export { KeptPage, decodeKept, fits, headerOf, keptApplications, keptDocuments, pageKey, samePage, tracked };
|
|
111
|
+
|
|
112
|
+
//# sourceMappingURL=pageCache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pageCache.js","names":[],"sources":["../src/pageCache.ts"],"sourcesContent":["/**\n * What `SSR.entry` needs to keep a rendered page (#428): a request that\n * records which of its headers the render read, and a page as a store keeps\n * it. A page is kept only when every header the render read was absent, so\n * it was drawn from the URL alone and serves every request that also lacks\n * them; the names it read are its `Vary`.\n */\nimport { Effect, Option, Schema } from 'effect'\nimport type { RenderedApplication } from 'foldkit/experimental/server'\nimport { watchedOf } from './requestContext.js'\n\n/** What a render read of its request's headers: names, or every one. */\nexport interface HeadersRead {\n readonly names: Set<string>\n all: boolean\n}\n\n/**\n * `request` as the render sees it, every header it reads recorded in `read`.\n * A lookup by name records that name; enumerating the headers records all.\n * Everything else is the request's own, so its getters keep their receiver.\n * A request context read of it (`SSR.requestContext`) is the host's request's,\n * and records all: what a host attaches may say who is asking.\n */\nexport const tracked = (request: Request, read: HeadersRead): Request => {\n const headers = new Proxy(request.headers, {\n get: (target, property) => {\n const value: unknown = Reflect.get(target, property, target)\n if (typeof value !== 'function') return value\n if (property === 'get' || property === 'has') {\n return (name: string) => {\n read.names.add(name.toLowerCase())\n return value.call(target, name)\n }\n }\n read.all = true\n return value.bind(target)\n },\n })\n const watched = new Proxy(request, {\n get: (target, property) => {\n if (property === 'headers') return headers\n // `clone` would hand out a request this one cannot see into.\n if (property === 'clone') read.all = true\n const value: unknown = Reflect.get(target, property, target)\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n watchedOf().set(watched, {\n original: request,\n readContext: () => {\n read.all = true\n },\n })\n return watched\n}\n\n/** Whether a page drawn from `read` serves `request`: it carries none of the headers read. */\nexport const fits = (request: Request, vary: ReadonlyArray<string>): boolean =>\n vary.every(name => !request.headers.has(name))\n\n/** A kept page: what the host draws, its status and headers, and the headers it must lack. */\nexport const KeptPage = Schema.Struct({\n application: Schema.Struct({\n html: Schema.String,\n title: Schema.String,\n lang: Schema.optionalKey(Schema.String),\n dir: Schema.optionalKey(Schema.Literals(['ltr', 'rtl', 'auto'])),\n canonical: Schema.optionalKey(Schema.String),\n ogUrl: Schema.optionalKey(Schema.String),\n }),\n status: Schema.optionalKey(Schema.Number),\n headers: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),\n vary: Schema.Array(Schema.String),\n})\nexport type KeptPage = typeof KeptPage.Type\n\nexport const decodeKept = Schema.decodeUnknownOption(Schema.fromJsonString(KeptPage))\n\nconst DAY_MS = 86_400_000\n\n/**\n * A page with each time stamped on it as `T`: a run of 13 digits within a\n * day of `now`, as milliseconds since the epoch read now are (a read's\n * `updatedAt` in the resumed Model). A page drawn a moment later is stamped\n * later, and is still the same page.\n */\nconst unstamped = (text: string, now: number): string =>\n text.replace(/\\b\\d{13}\\b/g, digits => (Math.abs(Number(digits) - now) < DAY_MS ? 'T' : digits))\n\n/** Whether two renders drew the same page: what the host draws, and its status. */\nexport const samePage = (\n a: { readonly application: RenderedApplication; readonly status?: number | undefined },\n b: { readonly application: RenderedApplication; readonly status?: number | undefined },\n now: number,\n): boolean =>\n unstamped(JSON.stringify([a.application, a.status ?? 200]), now) ===\n unstamped(JSON.stringify([b.application, b.status ?? 200]), now)\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join('')\n\n/**\n * Where a page is kept: by its build and its full URL, under the request's\n * origin, since the Workers Cache API keys by URL. A deploy's pages never\n * meet another build's.\n */\nexport const pageKey = (buildId: string, url: string): Effect.Effect<string> =>\n Effect.promise(() =>\n crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${buildId}\\n${url}`)),\n ).pipe(Effect.map(digest => `${new URL(url).origin}/__foldkit/cache/page/${hex(digest)}`))\n\n/** The value a `Rendered` result's `headers` gives, none when absent. */\nexport const headerOf = (headers: HeadersInit | undefined, name: string): Option.Option<string> =>\n Option.fromNullishOr(headers === undefined ? null : new Headers(headers).get(name))\n\n/** The pages `SSR.entry` serves from its cache, by the object it serves. */\nexport const keptApplications = new WeakSet<RenderedApplication>()\n\n/** The most documents `keptDocuments` holds: each is a whole page's markup. */\nconst KEPT_DOCUMENTS = 32\n\n/**\n * `render`, remembering the document it drew for each kept page (one\n * `SSR.entry` serves from its `cache`), by the page and the assets: the\n * host draws a page into its document on every request, which parses the\n * page again (`injectIntoTemplate`), so a kept page would cost that much\n * every time it is served. Any other page is drawn as `render` draws it.\n */\nexport const keptDocuments = <Assets>(\n render: (application: RenderedApplication, assets: Assets) => string,\n) => {\n const drawn = new Map<string, string>()\n return (application: RenderedApplication, assets: Assets): string => {\n if (!keptApplications.has(application)) return render(application, assets)\n const key = JSON.stringify([application, assets])\n const held = drawn.get(key)\n if (held !== undefined) return held\n const document = render(application, assets)\n drawn.set(key, document)\n for (const oldest of drawn.keys()) {\n if (drawn.size <= KEPT_DOCUMENTS) break\n drawn.delete(oldest)\n }\n return document\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,MAAa,WAAW,SAAkB,SAA+B;CACvE,MAAM,UAAU,IAAI,MAAM,QAAQ,SAAS,EACzC,MAAM,QAAQ,aAAa;EACzB,MAAM,QAAiB,QAAQ,IAAI,QAAQ,UAAU,MAAM;EAC3D,IAAI,OAAO,UAAU,YAAY,OAAO;EACxC,IAAI,aAAa,SAAS,aAAa,OACrC,QAAQ,SAAiB;GACvB,KAAK,MAAM,IAAI,KAAK,YAAY,CAAC;GACjC,OAAO,MAAM,KAAK,QAAQ,IAAI;EAChC;EAEF,KAAK,MAAM;EACX,OAAO,MAAM,KAAK,MAAM;CAC1B,EACF,CAAC;CACD,MAAM,UAAU,IAAI,MAAM,SAAS,EACjC,MAAM,QAAQ,aAAa;EACzB,IAAI,aAAa,WAAW,OAAO;EAEnC,IAAI,aAAa,SAAS,KAAK,MAAM;EACrC,MAAM,QAAiB,QAAQ,IAAI,QAAQ,UAAU,MAAM;EAC3D,OAAO,OAAO,UAAU,aAAa,MAAM,KAAK,MAAM,IAAI;CAC5D,EACF,CAAC;CACD,UAAU,CAAC,CAAC,IAAI,SAAS;EACvB,UAAU;EACV,mBAAmB;GACjB,KAAK,MAAM;EACb;CACF,CAAC;CACD,OAAO;AACT;;AAGA,MAAa,QAAQ,SAAkB,SACrC,KAAK,OAAM,SAAQ,CAAC,QAAQ,QAAQ,IAAI,IAAI,CAAC;;AAG/C,MAAa,WAAW,OAAO,OAAO;CACpC,aAAa,OAAO,OAAO;EACzB,MAAM,OAAO;EACb,OAAO,OAAO;EACd,MAAM,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,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC;;AAGpF,MAAa,mCAAmB,IAAI,QAA6B;;AAGjE,MAAM,iBAAiB;;;;;;;;AASvB,MAAa,iBACX,WACG;CACH,MAAM,wBAAQ,IAAI,IAAoB;CACtC,QAAQ,aAAkC,WAA2B;EACnE,IAAI,CAAC,iBAAiB,IAAI,WAAW,GAAG,OAAO,OAAO,aAAa,MAAM;EACzE,MAAM,MAAM,KAAK,UAAU,CAAC,aAAa,MAAM,CAAC;EAChD,MAAM,OAAO,MAAM,IAAI,GAAG;EAC1B,IAAI,SAAS,KAAA,GAAW,OAAO;EAC/B,MAAM,WAAW,OAAO,aAAa,MAAM;EAC3C,MAAM,IAAI,KAAK,QAAQ;EACvB,KAAK,MAAM,UAAU,MAAM,KAAK,GAAG;GACjC,IAAI,MAAM,QAAQ,gBAAgB;GAClC,MAAM,OAAO,MAAM;EACrB;EACA,OAAO;CACT;AACF"}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import { Option } from "effect";
|
|
2
|
+
/**
|
|
3
|
+
* The request a render that may be kept reads in place of the host's, to the
|
|
4
|
+
* host's, with what to record when the render reads a context of it. On
|
|
5
|
+
* `globalThis`, as the values are, since the Worker's copy of this module
|
|
6
|
+
* may be asked about a request the page bundle's `SSR.entry` made.
|
|
7
|
+
*/
|
|
8
|
+
declare const watchedOf: () => WeakMap<Request, {
|
|
9
|
+
readonly original: Request;
|
|
10
|
+
readonly readContext: () => void;
|
|
11
|
+
}>;
|
|
2
12
|
/** A value of type `C` the host attaches to a request, for its `renderPage` to read. */
|
|
3
13
|
interface RequestContext<C> {
|
|
4
14
|
readonly name: string;
|
|
@@ -17,5 +27,5 @@ interface RequestContext<C> {
|
|
|
17
27
|
* other's values by the name.
|
|
18
28
|
*/
|
|
19
29
|
declare const requestContext: <C>(name: string) => RequestContext<C>;
|
|
20
|
-
export { requestContext as n, RequestContext as t };
|
|
21
|
-
//# sourceMappingURL=requestContext-
|
|
30
|
+
export { requestContext as n, watchedOf as r, RequestContext as t };
|
|
31
|
+
//# sourceMappingURL=requestContext-DmwmQeci.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requestContext-DmwmQeci.d.ts","names":[],"sources":["../src/requestContext.ts"],"mappings":";;;;;;;cAyCa,iBAAS,QAAA;WACD,UAAA;WACG;;;UAIP,eAAe;WACrB;;WAEA,SAAS,SAAS,SAAS,OAAO,MAAM;;;;;;WAMxC,KAAK,SAAS,YAAY,OAAO,OAAO;;;;;;;cAQtC,iBAAkB,GAAC,iBAAiB,eAAe"}
|
package/dist/requestContext.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as requestContext, t as RequestContext } from "./requestContext-
|
|
2
|
-
export { RequestContext, requestContext };
|
|
1
|
+
import { n as requestContext, r as watchedOf, t as RequestContext } from "./requestContext-DmwmQeci.js";
|
|
2
|
+
export { RequestContext, requestContext, watchedOf };
|
package/dist/requestContext.js
CHANGED
|
@@ -11,18 +11,32 @@ import { Option } from "effect";
|
|
|
11
11
|
* with its own copy of this module, so the map lives on `globalThis` under a
|
|
12
12
|
* registered symbol, and a context is known by its name.
|
|
13
13
|
*/
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The map on `globalThis` under `name`'s registered symbol, made the first
|
|
16
|
+
* time it is asked for: every bundle's copy of this module finds the same one.
|
|
17
|
+
*/
|
|
18
|
+
const globalMap = (name) => {
|
|
19
|
+
const key = Symbol.for(name);
|
|
20
|
+
return () => {
|
|
21
|
+
const global = globalThis;
|
|
22
|
+
const held = global[key];
|
|
23
|
+
if (held === void 0) {
|
|
24
|
+
const made = /* @__PURE__ */ new WeakMap();
|
|
25
|
+
global[key] = made;
|
|
26
|
+
return made;
|
|
27
|
+
}
|
|
28
|
+
if (!(held instanceof WeakMap)) throw new Error(`foldkit-ssr: globalThis holds something else under ${String(key)}`);
|
|
29
|
+
return held;
|
|
30
|
+
};
|
|
25
31
|
};
|
|
32
|
+
const valuesOf = globalMap("foldkit-ssr/request-context");
|
|
33
|
+
/**
|
|
34
|
+
* The request a render that may be kept reads in place of the host's, to the
|
|
35
|
+
* host's, with what to record when the render reads a context of it. On
|
|
36
|
+
* `globalThis`, as the values are, since the Worker's copy of this module
|
|
37
|
+
* may be asked about a request the page bundle's `SSR.entry` made.
|
|
38
|
+
*/
|
|
39
|
+
const watchedOf = globalMap("foldkit-ssr/watched-requests");
|
|
26
40
|
/**
|
|
27
41
|
* A request context named `name`. The host and the page each import it from
|
|
28
42
|
* one module, so both agree on `C`; two bundles of that module find each
|
|
@@ -38,11 +52,14 @@ const requestContext = (name) => ({
|
|
|
38
52
|
values.set(request, held);
|
|
39
53
|
return request;
|
|
40
54
|
},
|
|
41
|
-
of: (
|
|
55
|
+
of: (given) => {
|
|
56
|
+
const watched = watchedOf().get(given);
|
|
57
|
+
watched?.readContext();
|
|
58
|
+
const request = watched?.original ?? given;
|
|
42
59
|
const held = valuesOf().get(request);
|
|
43
60
|
return held !== void 0 && held.has(name) ? Option.some(held.get(name)) : Option.none();
|
|
44
61
|
}
|
|
45
62
|
});
|
|
46
|
-
export { requestContext };
|
|
63
|
+
export { requestContext, watchedOf };
|
|
47
64
|
|
|
48
65
|
//# sourceMappingURL=requestContext.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestContext.js","names":[],"sources":["../src/requestContext.ts"],"sourcesContent":["/**\n * A value the host hands `renderPage` with the request. Foldkit's\n * `handleRequest` calls `renderPage(request)` and nothing more, so what the\n * host holds (a Worker's bindings, a reader built from them) rides the\n * request itself: kept in a `WeakMap` keyed by it, which holds nothing past\n * the request's life and never shares one request's value with another.\n *\n * The Worker and the page bundle Vite built are separate module graphs, each\n * with its own copy of this module, so the map lives on `globalThis` under a\n * registered symbol, and a context is known by its name.\n */\nimport { Option } from 'effect'\n\
|
|
1
|
+
{"version":3,"file":"requestContext.js","names":[],"sources":["../src/requestContext.ts"],"sourcesContent":["/**\n * A value the host hands `renderPage` with the request. Foldkit's\n * `handleRequest` calls `renderPage(request)` and nothing more, so what the\n * host holds (a Worker's bindings, a reader built from them) rides the\n * request itself: kept in a `WeakMap` keyed by it, which holds nothing past\n * the request's life and never shares one request's value with another.\n *\n * The Worker and the page bundle Vite built are separate module graphs, each\n * with its own copy of this module, so the map lives on `globalThis` under a\n * registered symbol, and a context is known by its name.\n */\nimport { Option } from 'effect'\n\n/**\n * The map on `globalThis` under `name`'s registered symbol, made the first\n * time it is asked for: every bundle's copy of this module finds the same one.\n */\nconst globalMap = <V>(name: string) => {\n const key = Symbol.for(name)\n return (): WeakMap<Request, V> => {\n const global = globalThis as { [key]?: unknown }\n const held = global[key]\n if (held === undefined) {\n const made = new WeakMap<Request, V>()\n global[key] = made\n return made\n }\n if (!(held instanceof WeakMap))\n throw new Error(`foldkit-ssr: globalThis holds something else under ${String(key)}`)\n return held as WeakMap<Request, V>\n }\n}\n\nconst valuesOf = globalMap<Map<string, unknown>>('foldkit-ssr/request-context')\n\n/**\n * The request a render that may be kept reads in place of the host's, to the\n * host's, with what to record when the render reads a context of it. On\n * `globalThis`, as the values are, since the Worker's copy of this module\n * may be asked about a request the page bundle's `SSR.entry` made.\n */\nexport const watchedOf = globalMap<{\n readonly original: Request\n readonly readContext: () => void\n}>('foldkit-ssr/watched-requests')\n\n/** A value of type `C` the host attaches to a request, for its `renderPage` to read. */\nexport interface RequestContext<C> {\n readonly name: string\n /** Keeps `value` for `request` and returns the request. A second value under this name throws. */\n readonly attach: (request: Request, value: C) => Request\n /**\n * The value the host attached to `request`; none when it attached nothing,\n * as Vite's dev server, which builds its own `Request`, or a host that\n * passed on a copy (`new Request(request)`).\n */\n readonly of: (request: Request) => Option.Option<C>\n}\n\n/**\n * A request context named `name`. The host and the page each import it from\n * one module, so both agree on `C`; two bundles of that module find each\n * other's values by the name.\n */\nexport const requestContext = <C>(name: string): RequestContext<C> => ({\n name,\n attach: (request, value) => {\n const values = valuesOf()\n const held = values.get(request) ?? new Map<string, unknown>()\n if (held.has(name))\n throw new Error(`foldkit-ssr: the request already carries a \"${name}\" context`)\n held.set(name, value)\n values.set(request, held)\n return request\n },\n of: given => {\n const watched = watchedOf().get(given)\n // A context may say who is asking, which a kept page must not depend on.\n watched?.readContext()\n const request = watched?.original ?? given\n const held = valuesOf().get(request)\n return held !== undefined && held.has(name) ? Option.some(held.get(name) as C) : Option.none()\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAM,aAAgB,SAAiB;CACrC,MAAM,MAAM,OAAO,IAAI,IAAI;CAC3B,aAAkC;EAChC,MAAM,SAAS;EACf,MAAM,OAAO,OAAO;EACpB,IAAI,SAAS,KAAA,GAAW;GACtB,MAAM,uBAAO,IAAI,QAAoB;GACrC,OAAO,OAAO;GACd,OAAO;EACT;EACA,IAAI,EAAE,gBAAgB,UACpB,MAAM,IAAI,MAAM,sDAAsD,OAAO,GAAG,GAAG;EACrF,OAAO;CACT;AACF;AAEA,MAAM,WAAW,UAAgC,6BAA6B;;;;;;;AAQ9E,MAAa,YAAY,UAGtB,8BAA8B;;;;;;AAoBjC,MAAa,kBAAqB,UAAqC;CACrE;CACA,SAAS,SAAS,UAAU;EAC1B,MAAM,SAAS,SAAS;EACxB,MAAM,OAAO,OAAO,IAAI,OAAO,qBAAK,IAAI,IAAqB;EAC7D,IAAI,KAAK,IAAI,IAAI,GACf,MAAM,IAAI,MAAM,+CAA+C,KAAK,UAAU;EAChF,KAAK,IAAI,MAAM,KAAK;EACpB,OAAO,IAAI,SAAS,IAAI;EACxB,OAAO;CACT;CACA,KAAI,UAAS;EACX,MAAM,UAAU,UAAU,CAAC,CAAC,IAAI,KAAK;EAErC,SAAS,YAAY;EACrB,MAAM,UAAU,SAAS,YAAY;EACrC,MAAM,OAAO,SAAS,CAAC,CAAC,IAAI,OAAO;EACnC,OAAO,SAAS,KAAA,KAAa,KAAK,IAAI,IAAI,IAAI,OAAO,KAAK,KAAK,IAAI,IAAI,CAAM,IAAI,OAAO,KAAK;CAC/F;AACF"}
|
|
@@ -36,8 +36,18 @@ interface HandlerUnnamed extends Diagnostic {
|
|
|
36
36
|
readonly element: string;
|
|
37
37
|
readonly event: string;
|
|
38
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* A kept page drawn otherwise for the request it served (`SSR.entry`'s
|
|
41
|
+
* `cache.check`): the render read something of the request, or anything
|
|
42
|
+
* else that differs between requests, that the cache could not see. The
|
|
43
|
+
* request was given the page drawn again.
|
|
44
|
+
*/
|
|
45
|
+
interface CachedPageDiffers extends Diagnostic {
|
|
46
|
+
readonly _tag: 'CachedPageDiffers';
|
|
47
|
+
readonly url: string;
|
|
48
|
+
}
|
|
39
49
|
/** Every diagnostic SSR reports. */
|
|
40
|
-
type SsrDiagnostic = PageContained | StaticRegionMissing | BundleUnloaded | PageFailed | HandlerUnnamed;
|
|
50
|
+
type SsrDiagnostic = PageContained | StaticRegionMissing | BundleUnloaded | PageFailed | HandlerUnnamed | CachedPageDiffers;
|
|
41
51
|
declare const pageContained: (reason: PageContained['reason'], detail: string) => PageContained;
|
|
42
52
|
declare const noBuildId: PageContained;
|
|
43
53
|
/** The page's stamped build id, if it has one, is not the client's `client`. */
|
|
@@ -48,6 +58,7 @@ declare const pageFailed: (url: string, cause: Cause.Cause<unknown>) => PageFail
|
|
|
48
58
|
declare const handlerUnnamed: (plan: string, element: string, event: string) => HandlerUnnamed;
|
|
49
59
|
/** `effect` reporting to `report` when one is given, else to the reporter in its context. */
|
|
50
60
|
declare const reportingTo: (report: ReportDiagnostic | undefined) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
61
|
+
declare const cachedPageDiffers: (url: string) => CachedPageDiffers;
|
|
51
62
|
type Region = ReadonlyArray<Html | string>;
|
|
52
63
|
/** An element whose handler for `event` is a function, which the page cannot describe. */
|
|
53
64
|
interface UnnamedHandler {
|
|
@@ -143,10 +154,11 @@ declare const STYLES_MARKER = "foldkit-plus-styles";
|
|
|
143
154
|
*/
|
|
144
155
|
declare const serializeJsonScript: (value: unknown) => string;
|
|
145
156
|
/**
|
|
146
|
-
* The envelope JSON as the stamped root carries it
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
157
|
+
* The envelope JSON as the stamped root carries it, in single quotes so the
|
|
158
|
+
* JSON's own double quotes need no escape. `&` and `'` are escaped, so no
|
|
159
|
+
* string in the Model can break out of the value; `getAttribute` resolves the
|
|
160
|
+
* entities back to exactly the JSON. `serializeJsonScript` has already escaped
|
|
161
|
+
* `<` and the line separators.
|
|
150
162
|
*/
|
|
151
163
|
declare const attributeOf: (json: string) => string;
|
|
152
164
|
/**
|
|
@@ -486,5 +498,5 @@ declare const bindingsAndEvents: <Model, Fields extends Schema.Struct.Fields>(pl
|
|
|
486
498
|
readonly bindings: ReadonlyArray<DecodedBinding>;
|
|
487
499
|
readonly events: ReadonlyArray<string> | undefined;
|
|
488
500
|
}, ResumeRefused>;
|
|
489
|
-
export {
|
|
490
|
-
//# sourceMappingURL=shared-
|
|
501
|
+
export { noBuildId as $, routeOf as A, current as B, metaMarkup as C, projectionsOf as D, plan as E, tagOf as F, HandlerUnnamed as G, within as H, Binding as I, SsrDiagnostic as J, PageContained as K, Region as L, serving as M, startingFrom as N, refuse as O, staticRegion as P, handlerUnnamed as Q, RenderContext as R, metaEntry as S, pathKey as T, BundleUnloaded as U, withContext as V, CachedPageDiffers as W, bundleUnloaded as X, StaticRegionMissing as Y, cachedPageDiffers as Z, arrival as _, PROTOCOL as a, bindingsAndEvents as b, ResumableConfig as c, ResumeRefused as d, otherBuild as et, RouteMatch as f, allowedTags as g, Start as h, Meta as i, staticRegionMissing as it, serializeJsonScript as j, resume as k, ResumePart as l, STYLES_MARKER as m, Loadable as n, pageFailed as nt, PlanSurface as o, STATIC_ATTRIBUTE as p, PageFailed as q, META_ATTRIBUTE as r, reportingTo as rt, RESUME_ATTRIBUTE as s, FOLDKIT_APP_ATTRIBUTE as t, pageContained as tt, ResumePlan as u, attributeOf as v, modelFrom as w, codecOf as x, bindings as y, UnnamedHandler as z };
|
|
502
|
+
//# sourceMappingURL=shared-CJN-m58Z.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shared-CJN-m58Z.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;;;KAIC,gBACR,gBACA,sBACA,iBACA,aACA,iBACA;cAES,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;KCnHpC,SAAS,cAAc;;UAGlB;WACN;WACA;;;;;;;;;UAUM;;WAEN;WACA;WACA;WACA;WACA,OAAO;;WAEP;WACA;;KAGC;WAEG;WACA,SAAS,YAAY;WACrB,YAAY;WACZ,UAAU,MAAM;;WAEhB,YAAY;;EAErB,OAAO;;EAEP;;EAEA;;WAES,UAAU;aACR;aACA;aACA;;;WAGF,SAAS,MAAM;;WAEf,YAAY;;WAGZ;WACA,SAAS,oBAAoB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AAgB,SAAS;WACzB,mBAAmB,SAAS;;WAE5B,YAAY,MAAM;;;;;;WAMlB,OAAO,cAAc;;;UAIf;WACN;WACA,YAAY;WACZ;;;cAcE,eAAgB,OAAK,QACxB,gBAAgB,QAAM;WACZ,OAAO;WAAgB,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAnCnB,OAAA,OAAA,OAAA;EACb,WAAA;EAEK,gBAAA,SAAS;EACN,mBAAA,SAAS;EAEhB,YAAA,MAAM;EAMX,OAAA,cAAc;;aAuBL,OAAA;aAA2B,WAAA;;;;cAIzC,UAAO;;;;;;;;;cAaP,WAAY,OAAO,eAAe,OAAO,OAAO,QAAM,MAC3D,WAAW,OAAO,SAAO,MACzB,YAAU,MACV,SAAO,OACN,UACN,OAAO,OAAO,cAAc,iBAAiB;;;;;cASnC,oBAAqB,OAAO,eAAe,OAAO,OAAO,QAAM,MACpE,WAAW,OAAO,SAAO,MACzB,YAAU,MACV,SAAO,OACN,UACN,OAAO;WAEG,UAAU,cAAc;WACxB,QAAQ;GAEnB"}
|
package/dist/shared.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as routeOf, C as metaMarkup, D as projectionsOf, E as plan, F as tagOf, M as serving, N as startingFrom, O as refuse, P as staticRegion, S as metaEntry, T as pathKey, _ as arrival, a as PROTOCOL, b as bindingsAndEvents, c as ResumableConfig, d as ResumeRefused, f as RouteMatch, g as allowedTags, h as Start, i as Meta, j as serializeJsonScript, k as resume, l as ResumePart, m as STYLES_MARKER, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, v as attributeOf, w as modelFrom, x as codecOf, y as bindings } from "./shared-
|
|
1
|
+
import { A as routeOf, C as metaMarkup, D as projectionsOf, E as plan, F as tagOf, M as serving, N as startingFrom, O as refuse, P as staticRegion, S as metaEntry, T as pathKey, _ as arrival, a as PROTOCOL, b as bindingsAndEvents, c as ResumableConfig, d as ResumeRefused, f as RouteMatch, g as allowedTags, h as Start, i as Meta, j as serializeJsonScript, k as resume, l as ResumePart, m as STYLES_MARKER, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, v as attributeOf, w as modelFrom, x as codecOf, y as bindings } from "./shared-CJN-m58Z.js";
|
|
2
2
|
export { FOLDKIT_APP_ATTRIBUTE, Loadable, META_ATTRIBUTE, Meta, PROTOCOL, PlanSurface, RESUME_ATTRIBUTE, 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 };
|
package/dist/shared.js
CHANGED
|
@@ -40,12 +40,13 @@ const PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
|
|
|
40
40
|
*/
|
|
41
41
|
const serializeJsonScript = (value) => JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(LINE_SEPARATOR, "\\u2028").replaceAll(PARAGRAPH_SEPARATOR, "\\u2029");
|
|
42
42
|
/**
|
|
43
|
-
* The envelope JSON as the stamped root carries it
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
43
|
+
* The envelope JSON as the stamped root carries it, in single quotes so the
|
|
44
|
+
* JSON's own double quotes need no escape. `&` and `'` are escaped, so no
|
|
45
|
+
* string in the Model can break out of the value; `getAttribute` resolves the
|
|
46
|
+
* entities back to exactly the JSON. `serializeJsonScript` has already escaped
|
|
47
|
+
* `<` and the line separators.
|
|
47
48
|
*/
|
|
48
|
-
const attributeOf = (json) => ` ${RESUME_ATTRIBUTE}=
|
|
49
|
+
const attributeOf = (json) => ` ${RESUME_ATTRIBUTE}='${json.replaceAll("&", "&").replaceAll("'", "'")}'`;
|
|
49
50
|
/** Marks each head element a plan's `meta` wrote, so the browser can replace them. */
|
|
50
51
|
const META_ATTRIBUTE = "data-foldkit-meta";
|
|
51
52
|
const attributeText = (text) => text.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|