@rsc-kit/core 0.30.54 → 0.31.1

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/dist/csp.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ /** What `rscKit({ contentSecurityPolicy })` accepts. */
2
+ export interface ContentSecurityPolicyOptions {
3
+ /**
4
+ * The policy, one entry per directive: `{ 'img-src': ["'self'", 'data:'] }`.
5
+ * Left out, `default-src 'self'; base-uri 'self'; object-src 'none';
6
+ * style-src-attr 'unsafe-inline'`.
7
+ */
8
+ directives?: Record<string, string | readonly string[]>;
9
+ /** Sent as Content-Security-Policy-Report-Only: reported, never enforced. */
10
+ reportOnly?: boolean;
11
+ }
12
+ /** The policy as the build hands it to the host. */
13
+ export interface ContentSecurityPolicy {
14
+ directives: [string, string[]][];
15
+ reportOnly: boolean;
16
+ }
17
+ /** What a document's own inline code hashes to, as CSP source expressions. */
18
+ export interface InlineHashes {
19
+ scripts: string[];
20
+ styles: string[];
21
+ }
22
+ export declare const DEFAULT_DIRECTIVES: Record<string, string[]>;
23
+ /**
24
+ * The policy, checked. Refused at build, never trimmed at runtime: a policy
25
+ * quietly not sent is a security header missing from every page.
26
+ */
27
+ export declare function normaliseContentSecurityPolicy(raw: ContentSecurityPolicyOptions | undefined): ContentSecurityPolicy | undefined;
28
+ /**
29
+ * The policy as `vite dev` sends it: the same one, so what it would refuse in
30
+ * production is refused while you work, plus what only development needs.
31
+ *
32
+ * - `'unsafe-eval'` in script-src. React's development build evaluates code
33
+ * for its debugging features (owner stacks, server logs replayed in the
34
+ * browser) and says so in the console when it cannot. Never in a build.
35
+ * - The dev server's origin, when the page is served from another one (a
36
+ * backend in front, `devOrigin`): its modules, styles and fonts load from
37
+ * there, and its HMR socket connects there.
38
+ *
39
+ * Every page renders per request in dev, so every page is allowed by its
40
+ * nonce, where a build hashes the pages it stores. Vite's own inline styles -
41
+ * a CSS update, the error overlay - take the nonce from a
42
+ * `<meta property="csp-nonce">` the page's boot script writes.
43
+ */
44
+ export declare function devContentSecurityPolicy(policy: ContentSecurityPolicy, options?: {
45
+ origin?: string;
46
+ }): ContentSecurityPolicy;
47
+ /** The header the policy goes out as. */
48
+ export declare function policyHeaderName(policy: ContentSecurityPolicy): string;
49
+ /**
50
+ * The policy with what the document needs added: its hashes, and a nonce for
51
+ * a response that streams.
52
+ *
53
+ * Added only where the policy restricts scripts (or styles) at all - a
54
+ * script-src, or a default-src it falls back to. A policy that says nothing
55
+ * about scripts allows every one, and a script-src with hashes in it would
56
+ * take that away. And never where the author wrote 'unsafe-inline': a hash or
57
+ * nonce beside it switches it off, which is the opposite of what they asked.
58
+ */
59
+ export declare function policyValue(policy: ContentSecurityPolicy, extra?: {
60
+ hashes?: InlineHashes | null;
61
+ nonce?: string | null;
62
+ for?: "header" | "meta";
63
+ }): string;
64
+ /**
65
+ * The policy as a `<meta>`, for a page a host serves as a file and the engine
66
+ * never answers - a static export. Without the directives only a header can
67
+ * carry, and none at all for a report-only policy, which a `<meta>` cannot be.
68
+ */
69
+ export declare function policyMeta(policy: ContentSecurityPolicy, hashes: InlineHashes): string;
70
+ /**
71
+ * The document with its policy in `<head>`: after the charset, which must
72
+ * stay inside the first 1024 bytes, and ahead of every script and style the
73
+ * policy judges.
74
+ */
75
+ export declare function withPolicyMeta(html: string, meta: string): string;
76
+ /**
77
+ * The hash of every inline script and style in a document: what a policy
78
+ * must name for the document to run as written. A script with a `src` is the
79
+ * policy's origin rules' to judge, and a data block - JSON, a type no browser
80
+ * runs - is not judged at all.
81
+ */
82
+ export declare function inlineHashes(html: string): Promise<InlineHashes>;
83
+ /** A nonce: 128 random bits, base64. New for every response that streams. */
84
+ export declare function newNonce(): string;
package/dist/csp.js ADDED
@@ -0,0 +1,264 @@
1
+ // A Content-Security-Policy that allows the page's own inline code and nothing
2
+ // else, on every host - a process, a Worker, a function, an edge, a bucket.
3
+ //
4
+ // The author names the policy; the engine adds what only it knows: the inline
5
+ // scripts and styles each document carries. Two ways, and which one is decided
6
+ // by whether the body is known before the headers leave:
7
+ //
8
+ // - A body that is whole first - a page the build stored, a kept page, a
9
+ // shell - gets the hash of each inline script and style in it. The same
10
+ // bytes for everyone, so the same header for everyone, and a cache may
11
+ // share both.
12
+ // - A body that streams - a page rendered per request, the holes resumed
13
+ // after a shell - gets a nonce, new for each response, which React puts on
14
+ // every script it writes. A shell's own scripts are already hashed, so a
15
+ // stored shell stays the same bytes for everyone.
16
+ //
17
+ // The payload a document carries is data blocks (see inlineFlight.ts), which
18
+ // no policy judges, so a nonce is needed only for what React writes as a
19
+ // stream fills in: `$RC("B:1","S:1")` and its like, which differ by the shape
20
+ // of each render and which no hash can know in advance. A nonce is never put
21
+ // on anything a cache may share: it would be a secret given to everyone.
22
+ //
23
+ // Nothing here imports `node:` anything: it runs where the host runs.
24
+ export const DEFAULT_DIRECTIVES = {
25
+ "default-src": ["'self'"],
26
+ "base-uri": ["'self'"],
27
+ "object-src": ["'none'"],
28
+ // A style={{...}} React rendered on the server is a style attribute, which
29
+ // no hash or nonce can allow. An attribute cannot run code.
30
+ "style-src-attr": ["'unsafe-inline'"],
31
+ };
32
+ /**
33
+ * Directives a `<meta>` policy cannot carry: a browser ignores them there and
34
+ * says so in the console. Only a header delivers them.
35
+ */
36
+ const HEADER_ONLY = new Set(["frame-ancestors", "report-uri", "report-to", "sandbox"]);
37
+ /**
38
+ * The policy, checked. Refused at build, never trimmed at runtime: a policy
39
+ * quietly not sent is a security header missing from every page.
40
+ */
41
+ export function normaliseContentSecurityPolicy(raw) {
42
+ if (raw === undefined)
43
+ return undefined;
44
+ const fail = (why) => {
45
+ throw new Error(`[rsc-kit] contentSecurityPolicy: ${why}`);
46
+ };
47
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
48
+ fail("an object, as in { directives: { 'img-src': [\"'self'\", 'data:'] } }.");
49
+ for (const key of Object.keys(raw)) {
50
+ if (key !== "directives" && key !== "reportOnly")
51
+ fail(`${JSON.stringify(key)} is not an option. It takes directives and reportOnly.`);
52
+ }
53
+ if (raw.reportOnly !== undefined && typeof raw.reportOnly !== "boolean")
54
+ fail("reportOnly is true or false.");
55
+ const given = raw.directives ?? DEFAULT_DIRECTIVES;
56
+ if (given === null || typeof given !== "object" || Array.isArray(given))
57
+ fail("directives is an object of directive names to sources.");
58
+ const directives = [];
59
+ const seen = new Set();
60
+ for (const [rawName, value] of Object.entries(given)) {
61
+ const name = rawName.toLowerCase();
62
+ if (!/^[a-z][a-z-]*$/.test(name))
63
+ fail(`${JSON.stringify(rawName)} is not a directive name.`);
64
+ if (seen.has(name))
65
+ fail(`${name} is named twice.`);
66
+ seen.add(name);
67
+ const list = typeof value === "string" ? value.split(/\s+/) : Array.isArray(value) ? [...value] : fail(`${name} takes a string or a list of sources.`);
68
+ const sources = list.map((source) => {
69
+ if (typeof source !== "string")
70
+ fail(`${name} takes a string or a list of sources.`);
71
+ return source.trim();
72
+ }).filter(Boolean);
73
+ for (const source of sources) {
74
+ if (/[\s;,]/.test(source))
75
+ fail(`${name}: ${JSON.stringify(source)} is not one source. Give each its own entry.`);
76
+ if (/^'nonce-/i.test(source))
77
+ fail(`${name}: a nonce written into the config is the same on every response, which is no nonce at all. The engine adds one to each response that streams.`);
78
+ }
79
+ directives.push([name, sources]);
80
+ }
81
+ return { directives, reportOnly: raw.reportOnly === true };
82
+ }
83
+ /**
84
+ * The policy as `vite dev` sends it: the same one, so what it would refuse in
85
+ * production is refused while you work, plus what only development needs.
86
+ *
87
+ * - `'unsafe-eval'` in script-src. React's development build evaluates code
88
+ * for its debugging features (owner stacks, server logs replayed in the
89
+ * browser) and says so in the console when it cannot. Never in a build.
90
+ * - The dev server's origin, when the page is served from another one (a
91
+ * backend in front, `devOrigin`): its modules, styles and fonts load from
92
+ * there, and its HMR socket connects there.
93
+ *
94
+ * Every page renders per request in dev, so every page is allowed by its
95
+ * nonce, where a build hashes the pages it stores. Vite's own inline styles -
96
+ * a CSS update, the error overlay - take the nonce from a
97
+ * `<meta property="csp-nonce">` the page's boot script writes.
98
+ */
99
+ export function devContentSecurityPolicy(policy, options = {}) {
100
+ const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));
101
+ const fallback = map.get("default-src");
102
+ const origin = options.origin ? new URL(options.origin).origin : "";
103
+ const socket = origin ? origin.replace(/^http/, "ws") : "";
104
+ // Only to a directive the policy has: one it leaves out falls back to
105
+ // default-src, which gets the same. One the author closed with 'none' stays
106
+ // closed: dev adds what it needs, never what the author refused.
107
+ const plus = (name, sources) => {
108
+ const list = map.get(name);
109
+ if (!list || list.some((source) => /^'none'$/i.test(source)))
110
+ return;
111
+ for (const source of sources)
112
+ if (!list.includes(source))
113
+ list.push(source);
114
+ };
115
+ // A script-src copied from default-src, as policyValue would, so eval has
116
+ // somewhere to go; a policy restricting no scripts already allows it.
117
+ if (!map.has("script-src") && fallback)
118
+ map.set("script-src", [...fallback]);
119
+ plus("script-src", ["'unsafe-eval'"]);
120
+ if (origin) {
121
+ for (const name of ["default-src", "script-src", "script-src-elem", "style-src", "style-src-elem", "font-src", "img-src"]) {
122
+ plus(name, [origin]);
123
+ }
124
+ if (!map.has("connect-src") && fallback)
125
+ map.set("connect-src", [...fallback]);
126
+ plus("connect-src", [origin, socket]);
127
+ }
128
+ return { ...policy, directives: [...map] };
129
+ }
130
+ /** The header the policy goes out as. */
131
+ export function policyHeaderName(policy) {
132
+ return policy.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
133
+ }
134
+ /**
135
+ * The policy with what the document needs added: its hashes, and a nonce for
136
+ * a response that streams.
137
+ *
138
+ * Added only where the policy restricts scripts (or styles) at all - a
139
+ * script-src, or a default-src it falls back to. A policy that says nothing
140
+ * about scripts allows every one, and a script-src with hashes in it would
141
+ * take that away. And never where the author wrote 'unsafe-inline': a hash or
142
+ * nonce beside it switches it off, which is the opposite of what they asked.
143
+ */
144
+ export function policyValue(policy, extra = {}) {
145
+ const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));
146
+ const nonce = extra.nonce ? `'nonce-${extra.nonce}'` : null;
147
+ const add = (kind, hashes) => {
148
+ const own = `${kind}-src`;
149
+ const fallback = map.get("default-src");
150
+ if (!map.has(own) && fallback)
151
+ map.set(own, [...fallback]);
152
+ for (const name of [own, `${own}-elem`]) {
153
+ const sources = map.get(name);
154
+ if (!sources)
155
+ continue;
156
+ if (sources.some((source) => /^'(unsafe-inline|none)'$/i.test(source)))
157
+ continue;
158
+ for (const source of [...hashes, ...(nonce ? [nonce] : [])]) {
159
+ if (!sources.includes(source))
160
+ sources.push(source);
161
+ }
162
+ }
163
+ };
164
+ add("script", extra.hashes?.scripts ?? []);
165
+ add("style", extra.hashes?.styles ?? []);
166
+ return [...map]
167
+ .filter(([name]) => extra.for !== "meta" || !HEADER_ONLY.has(name))
168
+ .map(([name, sources]) => (sources.length ? `${name} ${sources.join(" ")}` : name))
169
+ .join("; ");
170
+ }
171
+ /**
172
+ * The policy as a `<meta>`, for a page a host serves as a file and the engine
173
+ * never answers - a static export. Without the directives only a header can
174
+ * carry, and none at all for a report-only policy, which a `<meta>` cannot be.
175
+ */
176
+ export function policyMeta(policy, hashes) {
177
+ if (policy.reportOnly)
178
+ return "";
179
+ const value = policyValue(policy, { hashes, for: "meta" }).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
180
+ return `<meta http-equiv="Content-Security-Policy" content="${value}">`;
181
+ }
182
+ /**
183
+ * The document with its policy in `<head>`: after the charset, which must
184
+ * stay inside the first 1024 bytes, and ahead of every script and style the
185
+ * policy judges.
186
+ */
187
+ export function withPolicyMeta(html, meta) {
188
+ if (!meta)
189
+ return html;
190
+ const charset = /<meta\s[^>]*charset[^>]*>/i.exec(html);
191
+ if (charset && charset.index < 1024) {
192
+ const at = charset.index + charset[0].length;
193
+ return html.slice(0, at) + meta + html.slice(at);
194
+ }
195
+ const head = /<head\b[^>]*>/i.exec(html);
196
+ if (!head)
197
+ return html;
198
+ const at = head.index + head[0].length;
199
+ return html.slice(0, at) + meta + html.slice(at);
200
+ }
201
+ const ATTRIBUTES = `((?:[^>"']|"[^"]*"|'[^']*')*)`;
202
+ const SCRIPT = new RegExp(`<script\\b${ATTRIBUTES}>([\\s\\S]*?)</script\\s*>`, "gi");
203
+ const STYLE = new RegExp(`<style\\b${ATTRIBUTES}>([\\s\\S]*?)</style\\s*>`, "gi");
204
+ /** The types a browser runs, or that a policy judges as a script anyway. */
205
+ const RUN = new Set([
206
+ "",
207
+ "module",
208
+ "text/javascript",
209
+ "application/javascript",
210
+ "text/ecmascript",
211
+ "application/ecmascript",
212
+ "importmap",
213
+ "speculationrules",
214
+ ]);
215
+ function attribute(attributes, name) {
216
+ const match = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+))`, "i").exec(attributes);
217
+ if (match)
218
+ return match[1] ?? match[2] ?? match[3] ?? "";
219
+ return new RegExp(`(?:^|\\s)${name}(?:\\s|$)`, "i").test(attributes) ? "" : null;
220
+ }
221
+ async function sha256(text) {
222
+ // The parser normalises line breaks before a browser hashes the element's text.
223
+ const bytes = new TextEncoder().encode(text.replace(/\r\n?/g, "\n"));
224
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
225
+ let binary = "";
226
+ for (const byte of digest)
227
+ binary += String.fromCharCode(byte);
228
+ return `'sha256-${btoa(binary)}'`;
229
+ }
230
+ /**
231
+ * The hash of every inline script and style in a document: what a policy
232
+ * must name for the document to run as written. A script with a `src` is the
233
+ * policy's origin rules' to judge, and a data block - JSON, a type no browser
234
+ * runs - is not judged at all.
235
+ */
236
+ export async function inlineHashes(html) {
237
+ const scripts = new Set();
238
+ const styles = new Set();
239
+ for (const [, attributes, body] of html.matchAll(SCRIPT)) {
240
+ if (attribute(attributes, "src") !== null)
241
+ continue;
242
+ if (!RUN.has((attribute(attributes, "type") ?? "").trim().toLowerCase()))
243
+ continue;
244
+ if (body === "")
245
+ continue;
246
+ scripts.add(await sha256(body));
247
+ }
248
+ // Scripts out first: a style tag written inside a script's text is not one.
249
+ for (const [, , body] of html.replace(SCRIPT, "").matchAll(STYLE)) {
250
+ if (body === "")
251
+ continue;
252
+ styles.add(await sha256(body));
253
+ }
254
+ return { scripts: [...scripts].sort(), styles: [...styles].sort() };
255
+ }
256
+ /** A nonce: 128 random bits, base64. New for every response that streams. */
257
+ export function newNonce() {
258
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
259
+ let binary = "";
260
+ for (const byte of bytes)
261
+ binary += String.fromCharCode(byte);
262
+ return btoa(binary);
263
+ }
264
+ //# sourceMappingURL=csp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"csp.js","sourceRoot":"","sources":["../src/csp.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,yDAAyD;AACzD,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,kBAAkB;AAClB,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,EAAE;AACF,6EAA6E;AAC7E,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,yEAAyE;AACzE,EAAE;AACF,sEAAsE;AA0BtE,MAAM,CAAC,MAAM,kBAAkB,GAA6B;IAC1D,aAAa,EAAE,CAAC,QAAQ,CAAC;IACzB,UAAU,EAAE,CAAC,QAAQ,CAAC;IACtB,YAAY,EAAE,CAAC,QAAQ,CAAC;IACxB,2EAA2E;IAC3E,4DAA4D;IAC5D,gBAAgB,EAAE,CAAC,iBAAiB,CAAC;CACtC,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC,CAAC;AAEvF;;;GAGG;AACH,MAAM,UAAU,8BAA8B,CAC5C,GAA6C;IAE7C,IAAI,GAAG,KAAK,SAAS;QA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AO,EAAE,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AACtE,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,QAAQ;IACtB,MAAM,KAAK,GAAG,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC;IACzD,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IAE9D,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC","sourcesContent":["// A Content-Security-Policy that allows the page's own inline code and nothing\n// else, on every host - a process, a Worker, a function, an edge, a bucket.\n//\n// The author names the policy; the engine adds what only it knows: the inline\n// scripts and styles each document carries. Two ways, and which one is decided\n// by whether the body is known before the headers leave:\n//\n// - A body that is whole first - a page the build stored, a kept page, a\n// shell - gets the hash of each inline script and style in it. The same\n// bytes for everyone, so the same header for everyone, and a cache may\n// share both.\n// - A body that streams - a page rendered per request, the holes resumed\n// after a shell - gets a nonce, new for each response, which React puts on\n// every script it writes. A shell's own scripts are already hashed, so a\n// stored shell stays the same bytes for everyone.\n//\n// The payload a document carries is data blocks (see inlineFlight.ts), which\n// no policy judges, so a nonce is needed only for what React writes as a\n// stream fills in: `$RC(\"B:1\",\"S:1\")` and its like, which differ by the shape\n// of each render and which no hash can know in advance. A nonce is never put\n// on anything a cache may share: it would be a secret given to everyone.\n//\n// Nothing here imports `node:` anything: it runs where the host runs.\n\n/** What `rscKit({ contentSecurityPolicy })` accepts. */\nexport interface ContentSecurityPolicyOptions {\n /**\n * The policy, one entry per directive: `{ 'img-src': [\"'self'\", 'data:'] }`.\n * Left out, `default-src 'self'; base-uri 'self'; object-src 'none';\n * style-src-attr 'unsafe-inline'`.\n */\n directives?: Record<string, string | readonly string[]>;\n /** Sent as Content-Security-Policy-Report-Only: reported, never enforced. */\n reportOnly?: boolean;\n}\n\n/** The policy as the build hands it to the host. */\nexport interface ContentSecurityPolicy {\n directives: [string, string[]][];\n reportOnly: boolean;\n}\n\n/** What a document's own inline code hashes to, as CSP source expressions. */\nexport interface InlineHashes {\n scripts: string[];\n styles: string[];\n}\n\nexport const DEFAULT_DIRECTIVES: Record<string, string[]> = {\n \"default-src\": [\"'self'\"],\n \"base-uri\": [\"'self'\"],\n \"object-src\": [\"'none'\"],\n // A style={{...}} React rendered on the server is a style attribute, which\n // no hash or nonce can allow. An attribute cannot run code.\n \"style-src-attr\": [\"'unsafe-inline'\"],\n};\n\n/**\n * Directives a `<meta>` policy cannot carry: a browser ignores them there and\n * says so in the console. Only a header delivers them.\n */\nconst HEADER_ONLY = new Set([\"frame-ancestors\", \"report-uri\", \"report-to\", \"sandbox\"]);\n\n/**\n * The policy, checked. Refused at build, never trimmed at runtime: a policy\n * quietly not sent is a security header missing from every page.\n */\nexport function normaliseContentSecurityPolicy(\n raw: ContentSecurityPolicyOptions | undefined,\n): ContentSecurityPolicy | undefined {\n if (raw === undefined) return undefined;\n\n const fail = (why: string): never => {\n throw new Error(`[rsc-kit] contentSecurityPolicy: ${why}`);\n };\n\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw))\n fail(\"an object, as in { directives: { 'img-src': [\\\"'self'\\\", 'data:'] } }.\");\n\n for (const key of Object.keys(raw)) {\n if (key !== \"directives\" && key !== \"reportOnly\") fail(`${JSON.stringify(key)} is not an option. It takes directives and reportOnly.`);\n }\n\n if (raw.reportOnly !== undefined && typeof raw.reportOnly !== \"boolean\") fail(\"reportOnly is true or false.\");\n\n const given = raw.directives ?? DEFAULT_DIRECTIVES;\n\n if (given === null || typeof given !== \"object\" || Array.isArray(given))\n fail(\"directives is an object of directive names to sources.\");\n\n const directives: [string, string[]][] = [];\n const seen = new Set<string>();\n\n for (const [rawName, value] of Object.entries(given)) {\n const name = rawName.toLowerCase();\n\n if (!/^[a-z][a-z-]*$/.test(name)) fail(`${JSON.stringify(rawName)} is not a directive name.`);\n if (seen.has(name)) fail(`${name} is named twice.`);\n seen.add(name);\n\n const list = typeof value === \"string\" ? value.split(/\\s+/) : Array.isArray(value) ? [...value] : fail(`${name} takes a string or a list of sources.`);\n const sources = list.map((source) => {\n if (typeof source !== \"string\") fail(`${name} takes a string or a list of sources.`);\n\n return source.trim();\n }).filter(Boolean);\n\n for (const source of sources) {\n if (/[\\s;,]/.test(source)) fail(`${name}: ${JSON.stringify(source)} is not one source. Give each its own entry.`);\n if (/^'nonce-/i.test(source))\n fail(`${name}: a nonce written into the config is the same on every response, which is no nonce at all. The engine adds one to each response that streams.`);\n }\n\n directives.push([name, sources]);\n }\n\n return { directives, reportOnly: raw.reportOnly === true };\n}\n\n/**\n * The policy as `vite dev` sends it: the same one, so what it would refuse in\n * production is refused while you work, plus what only development needs.\n *\n * - `'unsafe-eval'` in script-src. React's development build evaluates code\n * for its debugging features (owner stacks, server logs replayed in the\n * browser) and says so in the console when it cannot. Never in a build.\n * - The dev server's origin, when the page is served from another one (a\n * backend in front, `devOrigin`): its modules, styles and fonts load from\n * there, and its HMR socket connects there.\n *\n * Every page renders per request in dev, so every page is allowed by its\n * nonce, where a build hashes the pages it stores. Vite's own inline styles -\n * a CSS update, the error overlay - take the nonce from a\n * `<meta property=\"csp-nonce\">` the page's boot script writes.\n */\nexport function devContentSecurityPolicy(\n policy: ContentSecurityPolicy,\n options: { origin?: string } = {},\n): ContentSecurityPolicy {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const fallback = map.get(\"default-src\");\n const origin = options.origin ? new URL(options.origin).origin : \"\";\n const socket = origin ? origin.replace(/^http/, \"ws\") : \"\";\n // Only to a directive the policy has: one it leaves out falls back to\n // default-src, which gets the same. One the author closed with 'none' stays\n // closed: dev adds what it needs, never what the author refused.\n const plus = (name: string, sources: string[]) => {\n const list = map.get(name);\n\n if (!list || list.some((source) => /^'none'$/i.test(source))) return;\n\n for (const source of sources) if (!list.includes(source)) list.push(source);\n };\n\n // A script-src copied from default-src, as policyValue would, so eval has\n // somewhere to go; a policy restricting no scripts already allows it.\n if (!map.has(\"script-src\") && fallback) map.set(\"script-src\", [...fallback]);\n\n plus(\"script-src\", [\"'unsafe-eval'\"]);\n\n if (origin) {\n for (const name of [\"default-src\", \"script-src\", \"script-src-elem\", \"style-src\", \"style-src-elem\", \"font-src\", \"img-src\"]) {\n plus(name, [origin]);\n }\n\n if (!map.has(\"connect-src\") && fallback) map.set(\"connect-src\", [...fallback]);\n\n plus(\"connect-src\", [origin, socket]);\n }\n\n return { ...policy, directives: [...map] };\n}\n\n/** The header the policy goes out as. */\nexport function policyHeaderName(policy: ContentSecurityPolicy): string {\n return policy.reportOnly ? \"Content-Security-Policy-Report-Only\" : \"Content-Security-Policy\";\n}\n\n/**\n * The policy with what the document needs added: its hashes, and a nonce for\n * a response that streams.\n *\n * Added only where the policy restricts scripts (or styles) at all - a\n * script-src, or a default-src it falls back to. A policy that says nothing\n * about scripts allows every one, and a script-src with hashes in it would\n * take that away. And never where the author wrote 'unsafe-inline': a hash or\n * nonce beside it switches it off, which is the opposite of what they asked.\n */\nexport function policyValue(\n policy: ContentSecurityPolicy,\n extra: { hashes?: InlineHashes | null; nonce?: string | null; for?: \"header\" | \"meta\" } = {},\n): string {\n const map = new Map(policy.directives.map(([name, sources]) => [name, [...sources]]));\n const nonce = extra.nonce ? `'nonce-${extra.nonce}'` : null;\n\n const add = (kind: \"script\" | \"style\", hashes: readonly string[]) => {\n const own = `${kind}-src`;\n const fallback = map.get(\"default-src\");\n\n if (!map.has(own) && fallback) map.set(own, [...fallback]);\n\n for (const name of [own, `${own}-elem`]) {\n const sources = map.get(name);\n\n if (!sources) continue;\n if (sources.some((source) => /^'(unsafe-inline|none)'$/i.test(source))) continue;\n\n for (const source of [...hashes, ...(nonce ? [nonce] : [])]) {\n if (!sources.includes(source)) sources.push(source);\n }\n }\n };\n\n add(\"script\", extra.hashes?.scripts ?? []);\n add(\"style\", extra.hashes?.styles ?? []);\n\n return [...map]\n .filter(([name]) => extra.for !== \"meta\" || !HEADER_ONLY.has(name))\n .map(([name, sources]) => (sources.length ? `${name} ${sources.join(\" \")}` : name))\n .join(\"; \");\n}\n\n/**\n * The policy as a `<meta>`, for a page a host serves as a file and the engine\n * never answers - a static export. Without the directives only a header can\n * carry, and none at all for a report-only policy, which a `<meta>` cannot be.\n */\nexport function policyMeta(policy: ContentSecurityPolicy, hashes: InlineHashes): string {\n if (policy.reportOnly) return \"\";\n\n const value = policyValue(policy, { hashes, for: \"meta\" }).replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n\n return `<meta http-equiv=\"Content-Security-Policy\" content=\"${value}\">`;\n}\n\n/**\n * The document with its policy in `<head>`: after the charset, which must\n * stay inside the first 1024 bytes, and ahead of every script and style the\n * policy judges.\n */\nexport function withPolicyMeta(html: string, meta: string): string {\n if (!meta) return html;\n\n const charset = /<meta\\s[^>]*charset[^>]*>/i.exec(html);\n\n if (charset && charset.index < 1024) {\n const at = charset.index + charset[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n }\n\n const head = /<head\\b[^>]*>/i.exec(html);\n\n if (!head) return html;\n\n const at = head.index + head[0].length;\n\n return html.slice(0, at) + meta + html.slice(at);\n}\n\nconst ATTRIBUTES = `((?:[^>\"']|\"[^\"]*\"|'[^']*')*)`;\nconst SCRIPT = new RegExp(`<script\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</script\\\\s*>`, \"gi\");\nconst STYLE = new RegExp(`<style\\\\b${ATTRIBUTES}>([\\\\s\\\\S]*?)</style\\\\s*>`, \"gi\");\n\n/** The types a browser runs, or that a policy judges as a script anyway. */\nconst RUN = new Set([\n \"\",\n \"module\",\n \"text/javascript\",\n \"application/javascript\",\n \"text/ecmascript\",\n \"application/ecmascript\",\n \"importmap\",\n \"speculationrules\",\n]);\n\nfunction attribute(attributes: string, name: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s\"'=<>\\`]+))`, \"i\").exec(attributes);\n\n if (match) return match[1] ?? match[2] ?? match[3] ?? \"\";\n\n return new RegExp(`(?:^|\\\\s)${name}(?:\\\\s|$)`, \"i\").test(attributes) ? \"\" : null;\n}\n\nasync function sha256(text: string): Promise<string> {\n // The parser normalises line breaks before a browser hashes the element's text.\n const bytes = new TextEncoder().encode(text.replace(/\\r\\n?/g, \"\\n\"));\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes));\n let binary = \"\";\n\n for (const byte of digest) binary += String.fromCharCode(byte);\n\n return `'sha256-${btoa(binary)}'`;\n}\n\n/**\n * The hash of every inline script and style in a document: what a policy\n * must name for the document to run as written. A script with a `src` is the\n * policy's origin rules' to judge, and a data block - JSON, a type no browser\n * runs - is not judged at all.\n */\nexport async function inlineHashes(html: string): Promise<InlineHashes> {\n const scripts = new Set<string>();\n const styles = new Set<string>();\n\n for (const [, attributes, body] of html.matchAll(SCRIPT)) {\n if (attribute(attributes, \"src\") !== null) continue;\n if (!RUN.has((attribute(attributes, \"type\") ?? \"\").trim().toLowerCase())) continue;\n if (body === \"\") continue;\n\n scripts.add(await sha256(body));\n }\n\n // Scripts out first: a style tag written inside a script's text is not one.\n for (const [, , body] of html.replace(SCRIPT, \"\").matchAll(STYLE)) {\n if (body === \"\") continue;\n\n styles.add(await sha256(body));\n }\n\n return { scripts: [...scripts].sort(), styles: [...styles].sort() };\n}\n\n/** A nonce: 128 random bits, base64. New for every response that streams. */\nexport function newNonce(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n let binary = \"\";\n\n for (const byte of bytes) binary += String.fromCharCode(byte);\n\n return btoa(binary);\n}\n"]}
@@ -28,11 +28,12 @@ export declare const MAX_STATIC = 200;
28
28
  * prefetch, a refresh - carries X-RSC, and an action is a POST, which an edge
29
29
  * never answers from a shell anyway.
30
30
  */
31
- export declare function edgeMarker(build: string, shells: string[], statics: string[]): {
31
+ export declare function edgeMarker(build: string, shells: string[], statics: string[], nonceShells?: string[]): {
32
32
  v: number;
33
33
  build: string;
34
34
  shells: string[];
35
35
  static: string[];
36
+ nonceShells?: string[] | undefined;
36
37
  bypass: {
37
38
  headers: string[];
38
39
  };
@@ -27,8 +27,18 @@ export const MAX_STATIC = 200;
27
27
  * prefetch, a refresh - carries X-RSC, and an action is a POST, which an edge
28
28
  * never answers from a shell anyway.
29
29
  */
30
- export function edgeMarker(build, shells, statics) {
31
- return { v: 2, build, shells, static: statics, bypass: { headers: ['X-RSC'] } };
30
+ export function edgeMarker(build, shells, statics, nonceShells) {
31
+ return {
32
+ v: 2,
33
+ build,
34
+ shells,
35
+ static: statics,
36
+ // Under a Content-Security-Policy: shells whose holes need a nonce, for an
37
+ // edge that mints one (Edge-Accept: nonce). An edge that does not reads
38
+ // only `shells`, which is then empty, and sends these pages to the origin.
39
+ ...(nonceShells ? { nonceShells } : {}),
40
+ bypass: { headers: ['X-RSC'] },
41
+ };
32
42
  }
33
43
  /**
34
44
  * The patterns, `/` for the index, `[name]` for one segment and a final
@@ -1 +1 @@
1
- {"version":3,"file":"edgeShells.js","sourceRoot":"","sources":["../src/edgeShells.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,sDAAsD;AACtD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAA;AAC7B,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,CAAA;AAClC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAA;AAE7B;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,MAAgB,EAAE,OAAiB;IAC3E,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,OAAO,CAAC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AAG,CAAC,CAAA;IAE5B,KAAK,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;QACvC,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;QACxD,CAAC;QAED,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS;YAAE,OAAO,KAAK,CAAA;QACvC,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC;YAAE,OAAO,KAAK,CAAA;IAC7E,CAAC;IAED,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAA;AACpC,CAAC","sourcesContent":["/**\n * The pages an edge may serve without the app, for `.output/edge.json` - the\n * marker of the edge contract, which an edge reads the same way for every\n * framework that implements it: `shells`, the url patterns of the PPR pages\n * it may answer from a cached shell, and `static`, the paths of the pages it\n * may answer whole.\n *\n * An edge in front of the app asks one question of each request - may I\n * answer this? - and answers it from a list it was handed at deploy time. Reading\n * `rsc-static/` for it does not work: a guarded page has a shell on disk too,\n * served from a cache it skips its guard; `_team_` cannot say whether it was a\n * parameter or a folder of that name; and the layout is ours to change.\n *\n * So the list is the build's, by the same rule the page endpoint applies: a\n * page with a shell, on a route with no middleware - neither a `middleware.ts`\n * above it nor the host's `export const middleware`. The endpoint refuses\n * exactly those, so the list and the origin cannot disagree.\n */\n\nimport type { RouteSegment } from './manifest.js'\n\n/** What an edge is promised, and what it can hold. */\nexport const MAX_SHELLS = 200\nexport const MAX_SHELL_BYTES = 200\n/** The same again for `static`, on top of `shells`' count. */\nexport const MAX_STATIC = 200\n\n/**\n * The marker. `bypass` names this framework's own requests on a page's path\n * that are not a visitor's document: every payload fetch - a navigation, a\n * prefetch, a refresh - carries X-RSC, and an action is a POST, which an edge\n * never answers from a shell anyway.\n */\nexport function edgeMarker(build: string, shells: string[], statics: string[]) {\n return { v: 2, build, shells, static: statics, bypass: { headers: ['X-RSC'] } }\n}\n\nexport interface ShellRoute {\n component: string\n segments: RouteSegment[]\n middleware?: readonly string[]\n hostMiddleware?: readonly string[]\n}\n\n/**\n * The patterns, `/` for the index, `[name]` for one segment and a final\n * `[...name]` for one or more - and what was left out of the list, and why,\n * for the build to say.\n */\nexport function edgeShells(\n results: readonly { type: string; component: string }[],\n routes: readonly ShellRoute[],\n): { shells: string[]; left: string[] } {\n const byComponent = new Map(routes.map((route) => [route.component, route]))\n const shells: string[] = []\n const left: string[] = []\n\n for (const component of new Set(results.filter((r) => r.type === 'shell').map((r) => r.component))) {\n const route = byComponent.get(component)\n\n if (!route) continue\n if (route.middleware?.length || route.hostMiddleware?.length) continue\n\n // Bound from the request's host, which a path pattern cannot say: the\n // same pattern would match every tenant's page on every domain.\n if (route.segments.some((segment) => segment.type === 'host')) continue\n\n const pattern = patternOf(route.segments)\n\n if (pattern === null) continue\n\n if (new TextEncoder().encode(pattern).length > MAX_SHELL_BYTES) {\n left.push(`${pattern.slice(0, 60)}… is over ${MAX_SHELL_BYTES} bytes`)\n continue\n }\n\n if (!shells.includes(pattern)) shells.push(pattern)\n }\n\n // Over the cap, the deepest are the ones not listed: an edge that does not\n // know a page is a PPR page sends it to the origin, which answers it\n // correctly, and the shallow pages are the ones most visited.\n if (shells.length > MAX_SHELLS) {\n shells.sort((a, b) => depth(a) - depth(b) || (a < b ? -1 : 1))\n left.push(`${shells.length - MAX_SHELLS} past the shallowest ${MAX_SHELLS}`)\n shells.length = MAX_SHELLS\n }\n\n shells.sort()\n\n return { shells, left }\n}\n\n/**\n * A route's segments as the edge matches them, or null when it cannot: a\n * catch-all anywhere but last, or a name that is itself bracketed - an\n * optional catch-all, `[[...name]]`, matches no url at all.\n */\nfunction patternOf(segments: readonly RouteSegment[]): string | null {\n const parts: string[] = []\n\n for (const [index, segment] of segments.entries()) {\n // Not a path an edge can match: the contract has no empty, `.` or `..`\n // segment, and a name with a slash would be two.\n if (['', '.', '..'].includes(segment.value) || segment.value.includes('/')) return null\n if (segment.type === 'static') parts.push(segment.value)\n else if (segment.value.includes('[') || segment.value.includes(']')) return null\n else if (segment.type === 'catchAll') {\n if (index !== segments.length - 1) return null\n parts.push(`[...${segment.value}]`)\n } else parts.push(`[${segment.value}]`)\n }\n\n return '/' + parts.join('/')\n}\n\nfunction depth(pattern: string): number {\n return pattern === '/' ? 0 : pattern.split('/').length - 1\n}\n\n/**\n * The pages an edge may answer whole: frozen, so the document is the same for\n * every visitor until the next build, with no guard of either kind and not\n * bound from the host - and listed as the paths the build rendered, since\n * `static` takes no patterns: a pattern would ask the edge for paths that\n * were never rendered. A frozen redirect is not here: it has no document.\n *\n * A path a listed shell's pattern also matches is left out, so no path is\n * two things to the edge.\n */\nexport function edgeStatic(\n results: readonly { type: string; component: string; url: string }[],\n routes: readonly ShellRoute[],\n shells: readonly string[],\n): { static: string[]; left: string[] } {\n const byComponent = new Map(routes.map((route) => [route.component, route]))\n const statics: string[] = []\n const left: string[] = []\n\n for (const result of results) {\n if (result.type !== 'frozen') continue\n\n const route = byComponent.get(result.component)\n\n if (!route) continue\n if (route.middleware?.length || route.hostMiddleware?.length) continue\n if (route.segments.some((segment) => segment.type === 'host')) continue\n\n const path = contractPath(result.url)\n\n if (path === null) continue\n\n if (new TextEncoder().encode(path).length > MAX_SHELL_BYTES) {\n left.push(`${path.slice(0, 60)}… is over ${MAX_SHELL_BYTES} bytes`)\n continue\n }\n\n if (shells.some((pattern) => matchesPattern(pattern, path))) continue\n if (!statics.includes(path)) statics.push(path)\n }\n\n if (statics.length > MAX_STATIC) {\n statics.sort((a, b) => depth(a) - depth(b) || (a < b ? -1 : 1))\n left.push(`${statics.length - MAX_STATIC} static past the shallowest ${MAX_STATIC}`)\n statics.length = MAX_STATIC\n }\n\n statics.sort()\n\n return { static: statics, left }\n}\n\n/**\n * Why pages an edge could otherwise have served were kept out: the outermost\n * middleware above each, with how many pages it guards. A root middleware -\n * the usual home of security headers - guards every page and empties both\n * lists, correctly, and an empty edge.json with no reason given reads as a\n * bug. So the build names the file.\n */\nexport function edgeGuarded(\n results: readonly { type: string; component: string }[],\n routes: readonly ShellRoute[],\n): string[] {\n const byComponent = new Map(routes.map((route) => [route.component, route]))\n const counts = new Map<string, number>()\n\n for (const result of results) {\n if (result.type !== 'frozen' && result.type !== 'shell') continue\n\n const route = byComponent.get(result.component)\n const guard = route?.middleware?.[0] ?? (route?.hostMiddleware?.length ? `the host's ${route.hostMiddleware[0]}` : null)\n\n if (guard) counts.set(guard, (counts.get(guard) ?? 0) + 1)\n }\n\n return [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([guard, n]) => `${guard} (${n})`)\n}\n\n/**\n * A rendered url as the contract lists it - absolute, decoded once, no query\n * - or null when it has no such form: an empty, `.` or `..` segment, or one\n * holding a `/` once decoded.\n */\nexport function contractPath(url: string): string | null {\n const path = url.split(/[?#]/)[0]\n\n if (!path.startsWith('/')) return null\n if (path === '/') return path\n\n const parts: string[] = []\n\n for (const raw of path.slice(1).split('/')) {\n let part: string\n\n try {\n part = decodeURIComponent(raw)\n } catch {\n return null\n }\n\n if (['', '.', '..'].includes(part) || part.includes('/') || /[?#]/.test(part)) return null\n parts.push(part)\n }\n\n return '/' + parts.join('/')\n}\n\n/** A marker pattern against a path: `[name]` is one segment, a final `[...name]` one or more. */\nexport function matchesPattern(pattern: string, path: string): boolean {\n const want = pattern.split('/')\n const have = path.split('/')\n\n for (const [i, part] of want.entries()) {\n if (i === want.length - 1 && /^\\[\\.\\.\\..+\\]$/.test(part)) {\n return have.length > i && have.slice(i).every(Boolean)\n }\n\n if (have[i] === undefined) return false\n if (/^\\[.+\\]$/.test(part) ? have[i] === '' : part !== have[i]) return false\n }\n\n return want.length === have.length\n}\n"]}
1
+ {"version":3,"file":"edgeShells.js","sourceRoot":"","sources":["../src/edgeShells.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,sDAAsD;AACtD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAA;AAC7B,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,CAAA;AAClC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAA;AAE7B;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,MAAgB,EAAE,OAAiB,EAAE,WAAsB;IACnG,OAAO;QACL,CAAC,EAAE,CAAC;QACJ,KAAK;QACL,MAAM;QACN,MAAM,EAAE,OAAO;QACf,2EAA2E;QAC3E,wEAAwE;QACxE,2EAA2E;QAC3E,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,OAAO,CAAC,EAAE;KAC/B,CAAA;AACH,CAAC;AASD;;;;GAIG;AACH,MAAM,UAAU,UAAU,CACxB,OAAuD,EACvD,MAA6B;IAE7B,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC,CAAA;IAC5E,MAAM,MAAM,GAAa,EAAE,CAAA;IAC3B,MAAM,IAAI,GAAa,EAAE,CAAA;IAEzB,KAAK,MAAM,SAAS,IAAI,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CA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,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC;YAAE,OAAO,KAAK,CAAA;IAC7E,CAAC;IAED,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAA;AACpC,CAAC","sourcesContent":["/**\n * The pages an edge may serve without the app, for `.output/edge.json` - the\n * marker of the edge contract, which an edge reads the same way for every\n * framework that implements it: `shells`, the url patterns of the PPR pages\n * it may answer from a cached shell, and `static`, the paths of the pages it\n * may answer whole.\n *\n * An edge in front of the app asks one question of each request - may I\n * answer this? - and answers it from a list it was handed at deploy time. Reading\n * `rsc-static/` for it does not work: a guarded page has a shell on disk too,\n * served from a cache it skips its guard; `_team_` cannot say whether it was a\n * parameter or a folder of that name; and the layout is ours to change.\n *\n * So the list is the build's, by the same rule the page endpoint applies: a\n * page with a shell, on a route with no middleware - neither a `middleware.ts`\n * above it nor the host's `export const middleware`. The endpoint refuses\n * exactly those, so the list and the origin cannot disagree.\n */\n\nimport type { RouteSegment } from './manifest.js'\n\n/** What an edge is promised, and what it can hold. */\nexport const MAX_SHELLS = 200\nexport const MAX_SHELL_BYTES = 200\n/** The same again for `static`, on top of `shells`' count. */\nexport const MAX_STATIC = 200\n\n/**\n * The marker. `bypass` names this framework's own requests on a page's path\n * that are not a visitor's document: every payload fetch - a navigation, a\n * prefetch, a refresh - carries X-RSC, and an action is a POST, which an edge\n * never answers from a shell anyway.\n */\nexport function edgeMarker(build: string, shells: string[], statics: string[], nonceShells?: string[]) {\n return {\n v: 2,\n build,\n shells,\n static: statics,\n // Under a Content-Security-Policy: shells whose holes need a nonce, for an\n // edge that mints one (Edge-Accept: nonce). An edge that does not reads\n // only `shells`, which is then empty, and sends these pages to the origin.\n ...(nonceShells ? { nonceShells } : {}),\n bypass: { headers: ['X-RSC'] },\n }\n}\n\nexport interface ShellRoute {\n component: string\n segments: RouteSegment[]\n middleware?: readonly string[]\n hostMiddleware?: readonly string[]\n}\n\n/**\n * The patterns, `/` for the index, `[name]` for one segment and a final\n * `[...name]` for one or more - and what was left out of the list, and why,\n * for the build to say.\n */\nexport function edgeShells(\n results: readonly { type: string; component: string }[],\n routes: readonly ShellRoute[],\n): { shells: string[]; left: string[] } {\n const byComponent = new Map(routes.map((route) => [route.component, route]))\n const shells: string[] = []\n const left: string[] = []\n\n for (const component of new Set(results.filter((r) => r.type === 'shell').map((r) => r.component))) {\n const route = byComponent.get(component)\n\n if (!route) continue\n if (route.middleware?.length || route.hostMiddleware?.length) continue\n\n // Bound from the request's host, which a path pattern cannot say: the\n // same pattern would match every tenant's page on every domain.\n if (route.segments.some((segment) => segment.type === 'host')) continue\n\n const pattern = patternOf(route.segments)\n\n if (pattern === null) continue\n\n if (new TextEncoder().encode(pattern).length > MAX_SHELL_BYTES) {\n left.push(`${pattern.slice(0, 60)}… is over ${MAX_SHELL_BYTES} bytes`)\n continue\n }\n\n if (!shells.includes(pattern)) shells.push(pattern)\n }\n\n // Over the cap, the deepest are the ones not listed: an edge that does not\n // know a page is a PPR page sends it to the origin, which answers it\n // correctly, and the shallow pages are the ones most visited.\n if (shells.length > MAX_SHELLS) {\n shells.sort((a, b) => depth(a) - depth(b) || (a < b ? -1 : 1))\n left.push(`${shells.length - MAX_SHELLS} past the shallowest ${MAX_SHELLS}`)\n shells.length = MAX_SHELLS\n }\n\n shells.sort()\n\n return { shells, left }\n}\n\n/**\n * A route's segments as the edge matches them, or null when it cannot: a\n * catch-all anywhere but last, or a name that is itself bracketed - an\n * optional catch-all, `[[...name]]`, matches no url at all.\n */\nfunction patternOf(segments: readonly RouteSegment[]): string | null {\n const parts: string[] = []\n\n for (const [index, segment] of segments.entries()) {\n // Not a path an edge can match: the contract has no empty, `.` or `..`\n // segment, and a name with a slash would be two.\n if (['', '.', '..'].includes(segment.value) || segment.value.includes('/')) return null\n if (segment.type === 'static') parts.push(segment.value)\n else if (segment.value.includes('[') || segment.value.includes(']')) return null\n else if (segment.type === 'catchAll') {\n if (index !== segments.length - 1) return null\n parts.push(`[...${segment.value}]`)\n } else parts.push(`[${segment.value}]`)\n }\n\n return '/' + parts.join('/')\n}\n\nfunction depth(pattern: string): number {\n return pattern === '/' ? 0 : pattern.split('/').length - 1\n}\n\n/**\n * The pages an edge may answer whole: frozen, so the document is the same for\n * every visitor until the next build, with no guard of either kind and not\n * bound from the host - and listed as the paths the build rendered, since\n * `static` takes no patterns: a pattern would ask the edge for paths that\n * were never rendered. A frozen redirect is not here: it has no document.\n *\n * A path a listed shell's pattern also matches is left out, so no path is\n * two things to the edge.\n */\nexport function edgeStatic(\n results: readonly { type: string; component: string; url: string }[],\n routes: readonly ShellRoute[],\n shells: readonly string[],\n): { static: string[]; left: string[] } {\n const byComponent = new Map(routes.map((route) => [route.component, route]))\n const statics: string[] = []\n const left: string[] = []\n\n for (const result of results) {\n if (result.type !== 'frozen') continue\n\n const route = byComponent.get(result.component)\n\n if (!route) continue\n if (route.middleware?.length || route.hostMiddleware?.length) continue\n if (route.segments.some((segment) => segment.type === 'host')) continue\n\n const path = contractPath(result.url)\n\n if (path === null) continue\n\n if (new TextEncoder().encode(path).length > MAX_SHELL_BYTES) {\n left.push(`${path.slice(0, 60)}… is over ${MAX_SHELL_BYTES} bytes`)\n continue\n }\n\n if (shells.some((pattern) => matchesPattern(pattern, path))) continue\n if (!statics.includes(path)) statics.push(path)\n }\n\n if (statics.length > MAX_STATIC) {\n statics.sort((a, b) => depth(a) - depth(b) || (a < b ? -1 : 1))\n left.push(`${statics.length - MAX_STATIC} static past the shallowest ${MAX_STATIC}`)\n statics.length = MAX_STATIC\n }\n\n statics.sort()\n\n return { static: statics, left }\n}\n\n/**\n * Why pages an edge could otherwise have served were kept out: the outermost\n * middleware above each, with how many pages it guards. A root middleware -\n * the usual home of security headers - guards every page and empties both\n * lists, correctly, and an empty edge.json with no reason given reads as a\n * bug. So the build names the file.\n */\nexport function edgeGuarded(\n results: readonly { type: string; component: string }[],\n routes: readonly ShellRoute[],\n): string[] {\n const byComponent = new Map(routes.map((route) => [route.component, route]))\n const counts = new Map<string, number>()\n\n for (const result of results) {\n if (result.type !== 'frozen' && result.type !== 'shell') continue\n\n const route = byComponent.get(result.component)\n const guard = route?.middleware?.[0] ?? (route?.hostMiddleware?.length ? `the host's ${route.hostMiddleware[0]}` : null)\n\n if (guard) counts.set(guard, (counts.get(guard) ?? 0) + 1)\n }\n\n return [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([guard, n]) => `${guard} (${n})`)\n}\n\n/**\n * A rendered url as the contract lists it - absolute, decoded once, no query\n * - or null when it has no such form: an empty, `.` or `..` segment, or one\n * holding a `/` once decoded.\n */\nexport function contractPath(url: string): string | null {\n const path = url.split(/[?#]/)[0]\n\n if (!path.startsWith('/')) return null\n if (path === '/') return path\n\n const parts: string[] = []\n\n for (const raw of path.slice(1).split('/')) {\n let part: string\n\n try {\n part = decodeURIComponent(raw)\n } catch {\n return null\n }\n\n if (['', '.', '..'].includes(part) || part.includes('/') || /[?#]/.test(part)) return null\n parts.push(part)\n }\n\n return '/' + parts.join('/')\n}\n\n/** A marker pattern against a path: `[name]` is one segment, a final `[...name]` one or more. */\nexport function matchesPattern(pattern: string, path: string): boolean {\n const want = pattern.split('/')\n const have = path.split('/')\n\n for (const [i, part] of want.entries()) {\n if (i === want.length - 1 && /^\\[\\.\\.\\..+\\]$/.test(part)) {\n return have.length > i && have.slice(i).every(Boolean)\n }\n\n if (have[i] === undefined) return false\n if (/^\\[.+\\]$/.test(part) ? have[i] === '' : part !== have[i]) return false\n }\n\n return want.length === have.length\n}\n"]}
package/dist/export.js CHANGED
@@ -17,6 +17,7 @@
17
17
  // out/docs/index.rsc
18
18
  // out/assets/… the browser bundle
19
19
  import { pathKey } from './prerender.js';
20
+ import { inlineHashes, policyMeta, withPolicyMeta } from './csp.js';
20
21
  export class NotExportable extends Error {
21
22
  refused;
22
23
  constructor(refused) {
@@ -107,7 +108,19 @@ export async function exportSite(options) {
107
108
  pages++;
108
109
  continue;
109
110
  }
110
- await copy(`${key}.html`, `${dir}index.html`);
111
+ // A file host sends no header the engine wrote, so the policy travels in
112
+ // the page: a <meta> with this page's own hashes. A host that can set
113
+ // headers may send the stricter one too; a browser enforces both.
114
+ const policy = manifest.build?.contentSecurityPolicy;
115
+ if (policy) {
116
+ const html = await read(`${key}.html`);
117
+ if (html === null)
118
+ throw new Error(`Nothing to export at ${key}.html. Prerender and export must read the same output.`);
119
+ await write(`${dir}index.html`, withPolicyMeta(html, policyMeta(policy, await inlineHashes(html))));
120
+ }
121
+ else {
122
+ await copy(`${key}.html`, `${dir}index.html`);
123
+ }
111
124
  await copy(`${key}.flight`, `${dir}${payloadName}`);
112
125
  // One file per depth a client might already hold, addressed by name
113
126
  // because a file server cannot vary on a header. Without these every
@@ -1 +1 @@
1
- {"version":3,"file":"export.js","sourceRoot":"","sources":["../src/export.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,EAAE;AACF,8EAA8E;AAC9E,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,4EAA4E;AAC5E,wBAAwB;AACxB,EAAE;AACF,wEAAwE;AACxE,4EAA4E;AAC5E,+BAA+B;AAC/B,EAAE;AACF,gCAAgC;AAChC,kBAAkB;AAClB,oCAAoC;AACpC,uBAAuB;AACvB,iDAAiD;AAEjD,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAmCxC,MAAM,OAAO,aAAc,SAAQ,KAAK;IACV,OAAO;IAAnC,YAA4B,OAA0B;QACpD,KAAK,CACH,0FAA0F;YACxF,iCAAiC;YACjC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;YAC7E,6EAA6E,CAChF,CAAA;uBANyB,OAAO;QAOjC,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;IAED,MAAM,MAAM,EAAE,EAAE,CAAA;IAEhB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAA;AAC3B,CAAC","sourcesContent":["// Writing the whole site out as files, for a host that only serves files.\n//\n// Everything a server was doing has to have happened already, which makes the\n// refusals the important part. A site exported with a route missing, or with a\n// shell nothing will ever fill, does not fail at build time and does not fail\n// on load — it serves a page that sits there, or a 404 for a url that worked\n// yesterday. So anything that is not fully static stops the export and says\n// which routes and why.\n//\n// Layout is a directory per route with an index inside it, so urls stay\n// extensionless, and the Flight payload sits beside it under a filename the\n// client was built to ask for.\n//\n// out/index.html /\n// out/index.rsc\n// out/docs/index.html /docs\n// out/docs/index.rsc\n// out/assets/… the browser bundle\n\nimport { pathKey } from './prerender.js'\nimport type { PrerenderResult } from './prerender.js'\nimport type { RouteManifest } from './manifest.js'\n\nexport interface ExportOptions {\n /** What prerender() decided, so this can refuse what it cannot serve. */\n results: PrerenderResult[]\n /** Reads what prerender() wrote. `prerenderedFrom` in `@rsc-kit/core/files`. */\n read: (name: string) => Promise<string | null> | string | null\n /**\n * Writes the site, keyed by its url path — `docs/index.html`, not an\n * absolute one. `writeTo` in `@rsc-kit/core/files` puts those under a\n * directory; a deploy that uploads straight to a bucket writes keys.\n */\n write: (path: string, contents: string) => Promise<void> | void\n /** The route table, for what the build decided about payload urls. */\n manifest: RouteManifest\n /**\n * Brings the browser bundle along, if this export has to carry it.\n *\n * A callback rather than a directory pair: copying a tree of built files is\n * a filesystem operation by nature, and a deploy that uploads them has its\n * own tooling for it. `copyAssets` in `@rsc-kit/core/files` does the local one.\n */\n assets?: () => Promise<void> | void\n /**\n * Export anyway, leaving out whatever is not static.\n *\n * The result is a site with holes in it, which is sometimes what you want\n * while moving an app towards being exportable. It is never the default,\n * because the holes are 404s at urls that worked before.\n */\n force?: boolean\n}\n\nexport class NotExportable extends Error {\n constructor(public readonly refused: PrerenderResult[]) {\n super(\n 'This site cannot be exported as it is. A static host runs nothing, so these routes have ' +\n 'no way to finish rendering:\\n\\n' +\n refused.map((r) => ` ${r.url} — ${r.reason ?? describe(r.type)}`).join('\\n') +\n '\\n\\nMake them static, or pass force to export the rest and leave these out.',\n )\n this.name = 'NotExportable'\n }\n}\n\nfunction describe(type: PrerenderResult['type']): string {\n if (type === 'shell') {\n // Worth spelling out: a shell looks like a working page in the build\n // output, and on a static host it is a page that loads and stays empty.\n return 'only a shell was stored, and nothing on a static host will fill it'\n }\n\n return 'failed to render'\n}\n\nexport async function exportSite(options: ExportOptions): Promise<{ pages: number; refused: PrerenderResult[] }> {\n const { results, read, write, manifest, assets, force = false } = options\n\n // A guarded route is frozen on purpose — the content is the same for\n // everyone allowed to see it — but the guard runs when the page is served,\n // and a static host serves without running anything. Exporting one publishes\n // the page to whoever asks, which is the opposite of what the guard said.\n const guarded = new Set(\n (manifest.routes as { component: string; middleware?: string[]; hostMiddleware?: string[] }[])\n // The host's middleware too: `export const middleware = ['auth']` is a\n // guard a static host cannot run either.\n .filter((route) => route.middleware?.length || route.hostMiddleware?.length)\n .map((route) => route.component),\n )\n\n const refused = results\n .filter((r) => r.type !== 'frozen' || guarded.has(r.component))\n .map((r) =>\n r.type === 'frozen' && guarded.has(r.component)\n ? { ...r, reason: 'guarded, and a static host has nothing to run the guard' }\n : r,\n )\n\n if (refused.length > 0 && !force) throw new NotExportable(refused)\n\n // The client has to ask for payloads by url, because a static host cannot\n // read the header that would otherwise select one. That is decided by the\n // build, so a site exported from a server build ships a client asking the\n // wrong way — every navigation silently falls back to a full page load.\n const payloadName = manifest.build?.payloadName\n\n if (!payloadName) {\n throw new Error(\n 'This build was made for a server, so its client asks for payloads with a header rather ' +\n \"than by url. Build with output: 'export' before exporting.\",\n )\n }\n\n const copy = async (name: string, into: string) => {\n const contents = await read(name)\n\n // Missing where the results said it would be: the prerender output and the\n // results it returned disagree, which is not something to paper over with\n // a half-written site.\n if (contents === null) {\n throw new Error(`Nothing to export at ${name}. Prerender and export must read the same output.`)\n }\n\n await write(into, contents)\n }\n\n let pages = 0\n\n for (const result of results) {\n if (result.type !== 'frozen') continue\n\n // Frozen, but guarded: refused above, and left out here too. Forcing an\n // export leaves out what is refused - and a guarded page written anyway\n // was the page published to whoever asked, with the build saying it had\n // been left out.\n if (guarded.has(result.component)) continue\n\n const key = pathKey(result.url)\n // The root is the out dir itself; everything else is a directory with an\n // index, so /docs stays /docs rather than becoming /docs.html.\n const dir = key === 'index' ? '' : `${key}/`\n\n // A route that only redirects is frozen as its answer rather than as a\n // page, so there is no .html to copy — and reaching for one threw, which\n // is why exporting an app with a redirect in it failed outright.\n //\n // A meta refresh because it is the one redirect every static host performs\n // without being configured; `_redirects` and its equivalents are per-host\n // files this has no business writing. The canonical link is what keeps a\n // crawler pointed at the destination rather than at this page.\n const redirect = await read(`${key}.redirect.json`)\n\n if (redirect !== null) {\n const { location } = JSON.parse(redirect) as { status: number; location: string }\n const escaped = location.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;')\n\n await write(\n `${dir}index.html`,\n `<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">` +\n `<meta http-equiv=\"refresh\" content=\"0; url=${escaped}\">` +\n `<link rel=\"canonical\" href=\"${escaped}\">` +\n `<title>Redirecting</title></head>` +\n `<body><a href=\"${escaped}\">${escaped}</a></body></html>\\n`,\n )\n\n pages++\n continue\n }\n\n await copy(`${key}.html`, `${dir}index.html`)\n await copy(`${key}.flight`, `${dir}${payloadName}`)\n\n // One file per depth a client might already hold, addressed by name\n // because a file server cannot vary on a header. Without these every\n // navigation is a whole document, which replaces the root and unmounts\n // the pages retained behind it — so going back does not restore the form\n // you were filling in.\n for (let depth = 1; ; depth++) {\n const variant = await read(`${key}.seg${depth}.flight`)\n\n if (variant === null) break\n\n await write(`${dir}${payloadName.replace(/^index\\./, `index.seg${depth}.`)}`, variant)\n }\n\n pages++\n }\n\n await assets?.()\n\n return { pages, refused }\n}\n\n\n"]}
1
+ {"version":3,"file":"export.js","sourceRoot":"","sources":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,EAAE,CAAA;IACT,CAAC;IAED,MAAM,MAAM,EAAE,EAAE,CAAA;IAEhB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAA;AAC3B,CAAC","sourcesContent":["// Writing the whole site out as files, for a host that only serves files.\n//\n// Everything a server was doing has to have happened already, which makes the\n// refusals the important part. A site exported with a route missing, or with a\n// shell nothing will ever fill, does not fail at build time and does not fail\n// on load — it serves a page that sits there, or a 404 for a url that worked\n// yesterday. So anything that is not fully static stops the export and says\n// which routes and why.\n//\n// Layout is a directory per route with an index inside it, so urls stay\n// extensionless, and the Flight payload sits beside it under a filename the\n// client was built to ask for.\n//\n// out/index.html /\n// out/index.rsc\n// out/docs/index.html /docs\n// out/docs/index.rsc\n// out/assets/… the browser bundle\n\nimport { pathKey } from './prerender.js'\nimport type { PrerenderResult } from './prerender.js'\nimport type { RouteManifest } from './manifest.js'\nimport { inlineHashes, policyMeta, withPolicyMeta } from './csp.js'\n\nexport interface ExportOptions {\n /** What prerender() decided, so this can refuse what it cannot serve. */\n results: PrerenderResult[]\n /** Reads what prerender() wrote. `prerenderedFrom` in `@rsc-kit/core/files`. */\n read: (name: string) => Promise<string | null> | string | null\n /**\n * Writes the site, keyed by its url path — `docs/index.html`, not an\n * absolute one. `writeTo` in `@rsc-kit/core/files` puts those under a\n * directory; a deploy that uploads straight to a bucket writes keys.\n */\n write: (path: string, contents: string) => Promise<void> | void\n /** The route table, for what the build decided about payload urls. */\n manifest: RouteManifest\n /**\n * Brings the browser bundle along, if this export has to carry it.\n *\n * A callback rather than a directory pair: copying a tree of built files is\n * a filesystem operation by nature, and a deploy that uploads them has its\n * own tooling for it. `copyAssets` in `@rsc-kit/core/files` does the local one.\n */\n assets?: () => Promise<void> | void\n /**\n * Export anyway, leaving out whatever is not static.\n *\n * The result is a site with holes in it, which is sometimes what you want\n * while moving an app towards being exportable. It is never the default,\n * because the holes are 404s at urls that worked before.\n */\n force?: boolean\n}\n\nexport class NotExportable extends Error {\n constructor(public readonly refused: PrerenderResult[]) {\n super(\n 'This site cannot be exported as it is. A static host runs nothing, so these routes have ' +\n 'no way to finish rendering:\\n\\n' +\n refused.map((r) => ` ${r.url} — ${r.reason ?? describe(r.type)}`).join('\\n') +\n '\\n\\nMake them static, or pass force to export the rest and leave these out.',\n )\n this.name = 'NotExportable'\n }\n}\n\nfunction describe(type: PrerenderResult['type']): string {\n if (type === 'shell') {\n // Worth spelling out: a shell looks like a working page in the build\n // output, and on a static host it is a page that loads and stays empty.\n return 'only a shell was stored, and nothing on a static host will fill it'\n }\n\n return 'failed to render'\n}\n\nexport async function exportSite(options: ExportOptions): Promise<{ pages: number; refused: PrerenderResult[] }> {\n const { results, read, write, manifest, assets, force = false } = options\n\n // A guarded route is frozen on purpose — the content is the same for\n // everyone allowed to see it — but the guard runs when the page is served,\n // and a static host serves without running anything. Exporting one publishes\n // the page to whoever asks, which is the opposite of what the guard said.\n const guarded = new Set(\n (manifest.routes as { component: string; middleware?: string[]; hostMiddleware?: string[] }[])\n // The host's middleware too: `export const middleware = ['auth']` is a\n // guard a static host cannot run either.\n .filter((route) => route.middleware?.length || route.hostMiddleware?.length)\n .map((route) => route.component),\n )\n\n const refused = results\n .filter((r) => r.type !== 'frozen' || guarded.has(r.component))\n .map((r) =>\n r.type === 'frozen' && guarded.has(r.component)\n ? { ...r, reason: 'guarded, and a static host has nothing to run the guard' }\n : r,\n )\n\n if (refused.length > 0 && !force) throw new NotExportable(refused)\n\n // The client has to ask for payloads by url, because a static host cannot\n // read the header that would otherwise select one. That is decided by the\n // build, so a site exported from a server build ships a client asking the\n // wrong way — every navigation silently falls back to a full page load.\n const payloadName = manifest.build?.payloadName\n\n if (!payloadName) {\n throw new Error(\n 'This build was made for a server, so its client asks for payloads with a header rather ' +\n \"than by url. Build with output: 'export' before exporting.\",\n )\n }\n\n const copy = async (name: string, into: string) => {\n const contents = await read(name)\n\n // Missing where the results said it would be: the prerender output and the\n // results it returned disagree, which is not something to paper over with\n // a half-written site.\n if (contents === null) {\n throw new Error(`Nothing to export at ${name}. Prerender and export must read the same output.`)\n }\n\n await write(into, contents)\n }\n\n let pages = 0\n\n for (const result of results) {\n if (result.type !== 'frozen') continue\n\n // Frozen, but guarded: refused above, and left out here too. Forcing an\n // export leaves out what is refused - and a guarded page written anyway\n // was the page published to whoever asked, with the build saying it had\n // been left out.\n if (guarded.has(result.component)) continue\n\n const key = pathKey(result.url)\n // The root is the out dir itself; everything else is a directory with an\n // index, so /docs stays /docs rather than becoming /docs.html.\n const dir = key === 'index' ? '' : `${key}/`\n\n // A route that only redirects is frozen as its answer rather than as a\n // page, so there is no .html to copy — and reaching for one threw, which\n // is why exporting an app with a redirect in it failed outright.\n //\n // A meta refresh because it is the one redirect every static host performs\n // without being configured; `_redirects` and its equivalents are per-host\n // files this has no business writing. The canonical link is what keeps a\n // crawler pointed at the destination rather than at this page.\n const redirect = await read(`${key}.redirect.json`)\n\n if (redirect !== null) {\n const { location } = JSON.parse(redirect) as { status: number; location: string }\n const escaped = location.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;')\n\n await write(\n `${dir}index.html`,\n `<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">` +\n `<meta http-equiv=\"refresh\" content=\"0; url=${escaped}\">` +\n `<link rel=\"canonical\" href=\"${escaped}\">` +\n `<title>Redirecting</title></head>` +\n `<body><a href=\"${escaped}\">${escaped}</a></body></html>\\n`,\n )\n\n pages++\n continue\n }\n\n // A file host sends no header the engine wrote, so the policy travels in\n // the page: a <meta> with this page's own hashes. A host that can set\n // headers may send the stricter one too; a browser enforces both.\n const policy = manifest.build?.contentSecurityPolicy\n\n if (policy) {\n const html = await read(`${key}.html`)\n\n if (html === null) throw new Error(`Nothing to export at ${key}.html. Prerender and export must read the same output.`)\n\n await write(`${dir}index.html`, withPolicyMeta(html, policyMeta(policy, await inlineHashes(html))))\n } else {\n await copy(`${key}.html`, `${dir}index.html`)\n }\n await copy(`${key}.flight`, `${dir}${payloadName}`)\n\n // One file per depth a client might already hold, addressed by name\n // because a file server cannot vary on a header. Without these every\n // navigation is a whole document, which replaces the root and unmounts\n // the pages retained behind it — so going back does not restore the form\n // you were filling in.\n for (let depth = 1; ; depth++) {\n const variant = await read(`${key}.seg${depth}.flight`)\n\n if (variant === null) break\n\n await write(`${dir}${payloadName.replace(/^index\\./, `index.seg${depth}.`)}`, variant)\n }\n\n pages++\n }\n\n await assets?.()\n\n return { pages, refused }\n}\n\n\n"]}