@rsc-kit/core 0.30.54 → 0.31.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.
@@ -1,5 +1,14 @@
1
- /** The script that declares the payload is coming, and what the page is built from. */
1
+ /** The block that declares the payload is coming, and what the page is built from. */
2
2
  export declare function inlineFlightStart(layouts: string): string;
3
+ /**
4
+ * Hands each block to `self.__rsc_f` once the parser has finished it, in
5
+ * document order: the ones already parsed when it runs, then each one added
6
+ * after. Part of the boot script, so it runs before the runtime that reads
7
+ * the queue, and on every page: a page whose payload is a file has no blocks
8
+ * and this does nothing. Stops at DOMContentLoaded, when the document - and
9
+ * so the payload - is complete.
10
+ */
11
+ export declare const READ_BLOCKS: string;
3
12
  /**
4
13
  * The HTML with the payload interleaved, and an end marker once both have
5
14
  * finished. `prelude` - the declaration - goes after the first flush, never
@@ -4,10 +4,17 @@
4
4
  // It used to be a second request - and a second render of the whole page, its
5
5
  // reads and its queries, a moment after the document's render had made exactly
6
6
  // that tree. Now the render's payload is written into the document as it
7
- // streams, a script per chunk between React's HTML, and the runtime reads it
7
+ // streams, a block per chunk between React's HTML, and the runtime reads it
8
8
  // from there. One render per visit, nothing held anywhere, and the slow parts
9
9
  // of the page stream in the payload the moment they do in the HTML.
10
10
  //
11
+ // A block is data, not code: `<script type="application/json" data-rsc>`,
12
+ // which a browser never runs and a Content-Security-Policy never judges. The
13
+ // chunks are the visitor's own data, so as scripts no policy short of
14
+ // 'unsafe-inline' or a nonce could allow them - and a nonce is impossible on
15
+ // a page a cache shares. READ_BLOCKS, in the boot script every page carries,
16
+ // hands each block to the runtime's queue as the parser finishes it.
17
+ //
11
18
  // React writes its HTML in pieces that can end mid-tag, but always all the
12
19
  // pieces of one flush in the same task. So a payload chunk is written on the
13
20
  // next task, never between two pieces of one flush. (The rsc-html-stream
@@ -15,10 +22,36 @@
15
22
  //
16
23
  // Read in the browser by js/inlinePayload.ts.
17
24
  const encoder = new TextEncoder();
18
- /** The script that declares the payload is coming, and what the page is built from. */
25
+ /** One chunk of the payload, as data. */
26
+ const BLOCK = '<script type="application/json" data-rsc>';
27
+ /**
28
+ * What ends every write that ends in a block. The reader takes a block once
29
+ * the parser has moved past it - once it has a next sibling - since until
30
+ * then its text may still be arriving. A block written just before the
31
+ * stream waits on a slow hole would otherwise sit unread until the hole came.
32
+ */
33
+ const PAST = "<!---->";
34
+ /** The block that declares the payload is coming, and what the page is built from. */
19
35
  export function inlineFlightStart(layouts) {
20
- return `<script>self.__rsc_f=self.__rsc_f||[];self.__rsc_l=${script(layouts)}</script>`;
36
+ return `<script type="application/json" data-rsc="l">${script(layouts)}</script>${PAST}`;
21
37
  }
38
+ /**
39
+ * Hands each block to `self.__rsc_f` once the parser has finished it, in
40
+ * document order: the ones already parsed when it runs, then each one added
41
+ * after. Part of the boot script, so it runs before the runtime that reads
42
+ * the queue, and on every page: a page whose payload is a file has no blocks
43
+ * and this does nothing. Stops at DOMContentLoaded, when the document - and
44
+ * so the payload - is complete.
45
+ */
46
+ export const READ_BLOCKS = "(function(){var d=document,p=[];" +
47
+ "function r(){for(var s;(s=p[0])&&(s.nextSibling||d.readyState!=='loading');){p.shift();" +
48
+ "var v=JSON.parse(s.textContent),q=self.__rsc_f=self.__rsc_f||[];" +
49
+ "if(s.getAttribute('data-rsc')==='l')self.__rsc_l=v;else q.push(v)}}" +
50
+ "function a(n){n.nodeName==='SCRIPT'&&n.hasAttribute('data-rsc')&&p.push(n)}" +
51
+ "d.querySelectorAll('script[data-rsc]').forEach(a);" +
52
+ "var o=new MutationObserver(function(m){for(var i=0;i<m.length;i++)m[i].addedNodes.forEach(a);r()});" +
53
+ "o.observe(d,{childList:true,subtree:true});" +
54
+ "d.addEventListener('DOMContentLoaded',function(){o.disconnect();r()});r()})();";
22
55
  /**
23
56
  * The HTML with the payload interleaved, and an end marker once both have
24
57
  * finished. `prelude` - the declaration - goes after the first flush, never
@@ -41,12 +74,12 @@ export function inlineFlight(html, flight, prelude = "") {
41
74
  if (closed)
42
75
  return;
43
76
  if (pending.length) {
44
- controller.enqueue(encoder.encode(pending.join("")));
77
+ controller.enqueue(encoder.encode(pending.join("") + PAST));
45
78
  pending = [];
46
79
  }
47
80
  if (flightDone && htmlDone) {
48
81
  closed = true;
49
- controller.enqueue(encoder.encode("<script>self.__rsc_f.push(null)</script>"));
82
+ controller.enqueue(encoder.encode(`${BLOCK}null</script>${PAST}`));
50
83
  controller.close();
51
84
  }
52
85
  };
@@ -73,13 +106,13 @@ export function inlineFlight(html, flight, prelude = "") {
73
106
  const { done, value } = await flightReader.read();
74
107
  if (done)
75
108
  break;
76
- pending.push(`<script>self.__rsc_f.push(${chunk(value)})</script>`);
109
+ pending.push(`${BLOCK}${chunk(value)}</script>`);
77
110
  later();
78
111
  }
79
112
  // A character split across the last two chunks would be held here.
80
113
  const tail = decoder.decode();
81
114
  if (tail)
82
- pending.push(`<script>self.__rsc_f.push(${script(tail)})</script>`);
115
+ pending.push(`${BLOCK}${script(tail)}</script>`);
83
116
  flightDone = true;
84
117
  later();
85
118
  };
@@ -112,11 +145,14 @@ export function inlineFlight(html, flight, prelude = "") {
112
145
  let binary = "";
113
146
  for (const byte of value)
114
147
  binary += String.fromCharCode(byte);
115
- return `{b:${script(btoa(binary))}}`;
148
+ return `{"b":${script(btoa(binary))}}`;
116
149
  }
117
150
  }
118
151
  }
119
- /** A string literal safe inside a <script>: no way to close the element or open a comment. */
152
+ /**
153
+ * A JSON string safe inside a <script>: no way to close the element or open a
154
+ * comment. JSON, because the reader parses it: a block is never run.
155
+ */
120
156
  function script(text) {
121
157
  return JSON.stringify(text)
122
158
  .replace(/</g, "\\u003c")
@@ -1 +1 @@
1
- {"version":3,"file":"inlineFlight.js","sourceRoot":"","sources":["../src/inlineFlight.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,+EAA+E;AAC/E,yEAAyE;AACzE,6EAA6E;AAC7E,8EAA8E;A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AE9D,OAAO,MAAM,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC;QACvC,CAAC;IACH,CAAC;AACH,CAAC;AAED,8FAA8F;AAC9F,SAAS,MAAM,CAAC,IAAY;IAC1B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;SACxB,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC;SACxB,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACnC,CAAC","sourcesContent":["// The page's payload, streamed inside its own document.\n//\n// Hydrating server components needs the serialised tree as well as the HTML.\n// It used to be a second request - and a second render of the whole page, its\n// reads and its queries, a moment after the document's render had made exactly\n// that tree. Now the render's payload is written into the document as it\n// streams, a script per chunk between React's HTML, and the runtime reads it\n// from there. One render per visit, nothing held anywhere, and the slow parts\n// of the page stream in the payload the moment they do in the HTML.\n//\n// React writes its HTML in pieces that can end mid-tag, but always all the\n// pieces of one flush in the same task. So a payload chunk is written on the\n// next task, never between two pieces of one flush. (The rsc-html-stream\n// package does the same.)\n//\n// Read in the browser by js/inlinePayload.ts.\n\nconst encoder = new TextEncoder();\n\n/** The script that declares the payload is coming, and what the page is built from. */\nexport function inlineFlightStart(layouts: string): string {\n return `<script>self.__rsc_f=self.__rsc_f||[];self.__rsc_l=${script(layouts)}</script>`;\n}\n\n/**\n * The HTML with the payload interleaved, and an end marker once both have\n * finished. `prelude` - the declaration - goes after the first flush, never\n * ahead of the HTML: in front of the doctype it would put the page in quirks\n * mode.\n */\nexport function inlineFlight(\n html: ReadableStream<Uint8Array>,\n flight: ReadableStream<Uint8Array>,\n prelude = \"\",\n): ReadableStream<Uint8Array> {\n const htmlReader = html.getReader();\n const flightReader = flight.getReader();\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n let pending: string[] = prelude ? [prelude] : [];\n let scheduled: ReturnType<typeof setTimeout> | null = null;\n let flightDone = false;\n let htmlDone = false;\n let closed = false;\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n const flush = () => {\n scheduled = null;\n\n if (closed) return;\n if (pending.length) {\n controller.enqueue(encoder.encode(pending.join(\"\")));\n pending = [];\n }\n if (flightDone && htmlDone) {\n closed = true;\n controller.enqueue(encoder.encode(\"<script>self.__rsc_f.push(null)</script>\"));\n controller.close();\n }\n };\n // After the task React is flushing in, so never between its pieces.\n const later = () => {\n scheduled ??= setTimeout(flush, 0);\n };\n\n const readHtml = async () => {\n for (;;) {\n const { done, value } = await htmlReader.read();\n\n if (done) break;\n if (!closed) controller.enqueue(value);\n // Anything the payload had waiting goes after this flush, not in it.\n if (pending.length) later();\n }\n htmlDone = true;\n later();\n };\n\n const readFlight = async () => {\n for (;;) {\n const { done, value } = await flightReader.read();\n\n if (done) break;\n pending.push(`<script>self.__rsc_f.push(${chunk(value)})</script>`);\n later();\n }\n // A character split across the last two chunks would be held here.\n const tail = decoder.decode();\n\n if (tail) pending.push(`<script>self.__rsc_f.push(${script(tail)})</script>`);\n flightDone = true;\n later();\n };\n\n const fail = (error: unknown) => {\n if (closed) return;\n closed = true;\n void htmlReader.cancel(error).catch(() => {});\n void flightReader.cancel(error).catch(() => {});\n controller.error(error);\n };\n\n readHtml().catch(fail);\n readFlight().catch(fail);\n },\n cancel(reason) {\n closed = true;\n if (scheduled) clearTimeout(scheduled);\n void htmlReader.cancel(reason).catch(() => {});\n void flightReader.cancel(reason).catch(() => {});\n },\n });\n\n // Text as a string, which compresses with the page. A chunk that is not\n // UTF-8 - a typed array in the payload - goes as base64.\n function chunk(value: Uint8Array): string {\n try {\n return script(decoder.decode(value, { stream: true }));\n } catch {\n let binary = \"\";\n\n for (const byte of value) binary += String.fromCharCode(byte);\n\n return `{b:${script(btoa(binary))}}`;\n }\n }\n}\n\n/** A string literal safe inside a <script>: no way to close the element or open a comment. */\nfunction script(text: string): string {\n return JSON.stringify(text)\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028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B,CAAC;QACD,MAAM,CAAC,MAAM;YACX,MAAM,GAAG,IAAI,CAAC;YACd,IAAI,SAAS;gBAAE,YAAY,CAAC,SAAS,CAAC,CAAC;YACvC,KAAK,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAC/C,KAAK,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QACnD,CAAC;KACF,CAAC,CAAC;IAEH,wEAAwE;IACxE,yDAAyD;IACzD,SAAS,KAAK,CAAC,KAAiB;QAC9B,IAAI,CAAC;YACH,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACzD,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,MAAM,GAAG,EAAE,CAAC;YAEhB,KAAK,MAAM,IAAI,IAAI,KAAK;gBAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;YAE9D,OAAO,QAAQ,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC;QACzC,CAAC;IACH,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,SAAS,MAAM,CAAC,IAAY;IAC1B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;SACxB,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC;SACxB,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACnC,CAAC","sourcesContent":["// The page's payload, streamed inside its own document.\n//\n// Hydrating server components needs the serialised tree as well as the HTML.\n// It used to be a second request - and a second render of the whole page, its\n// reads and its queries, a moment after the document's render had made exactly\n// that tree. Now the render's payload is written into the document as it\n// streams, a block per chunk between React's HTML, and the runtime reads it\n// from there. One render per visit, nothing held anywhere, and the slow parts\n// of the page stream in the payload the moment they do in the HTML.\n//\n// A block is data, not code: `<script type=\"application/json\" data-rsc>`,\n// which a browser never runs and a Content-Security-Policy never judges. The\n// chunks are the visitor's own data, so as scripts no policy short of\n// 'unsafe-inline' or a nonce could allow them - and a nonce is impossible on\n// a page a cache shares. READ_BLOCKS, in the boot script every page carries,\n// hands each block to the runtime's queue as the parser finishes it.\n//\n// React writes its HTML in pieces that can end mid-tag, but always all the\n// pieces of one flush in the same task. So a payload chunk is written on the\n// next task, never between two pieces of one flush. (The rsc-html-stream\n// package does the same.)\n//\n// Read in the browser by js/inlinePayload.ts.\n\nconst encoder = new TextEncoder();\n\n/** One chunk of the payload, as data. */\nconst BLOCK = '<script type=\"application/json\" data-rsc>';\n\n/**\n * What ends every write that ends in a block. The reader takes a block once\n * the parser has moved past it - once it has a next sibling - since until\n * then its text may still be arriving. A block written just before the\n * stream waits on a slow hole would otherwise sit unread until the hole came.\n */\nconst PAST = \"<!---->\";\n\n/** The block that declares the payload is coming, and what the page is built from. */\nexport function inlineFlightStart(layouts: string): string {\n return `<script type=\"application/json\" data-rsc=\"l\">${script(layouts)}</script>${PAST}`;\n}\n\n/**\n * Hands each block to `self.__rsc_f` once the parser has finished it, in\n * document order: the ones already parsed when it runs, then each one added\n * after. Part of the boot script, so it runs before the runtime that reads\n * the queue, and on every page: a page whose payload is a file has no blocks\n * and this does nothing. Stops at DOMContentLoaded, when the document - and\n * so the payload - is complete.\n */\nexport const READ_BLOCKS =\n \"(function(){var d=document,p=[];\" +\n \"function r(){for(var s;(s=p[0])&&(s.nextSibling||d.readyState!=='loading');){p.shift();\" +\n \"var v=JSON.parse(s.textContent),q=self.__rsc_f=self.__rsc_f||[];\" +\n \"if(s.getAttribute('data-rsc')==='l')self.__rsc_l=v;else q.push(v)}}\" +\n \"function a(n){n.nodeName==='SCRIPT'&&n.hasAttribute('data-rsc')&&p.push(n)}\" +\n \"d.querySelectorAll('script[data-rsc]').forEach(a);\" +\n \"var o=new MutationObserver(function(m){for(var i=0;i<m.length;i++)m[i].addedNodes.forEach(a);r()});\" +\n \"o.observe(d,{childList:true,subtree:true});\" +\n \"d.addEventListener('DOMContentLoaded',function(){o.disconnect();r()});r()})();\";\n\n/**\n * The HTML with the payload interleaved, and an end marker once both have\n * finished. `prelude` - the declaration - goes after the first flush, never\n * ahead of the HTML: in front of the doctype it would put the page in quirks\n * mode.\n */\nexport function inlineFlight(\n html: ReadableStream<Uint8Array>,\n flight: ReadableStream<Uint8Array>,\n prelude = \"\",\n): ReadableStream<Uint8Array> {\n const htmlReader = html.getReader();\n const flightReader = flight.getReader();\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n let pending: string[] = prelude ? [prelude] : [];\n let scheduled: ReturnType<typeof setTimeout> | null = null;\n let flightDone = false;\n let htmlDone = false;\n let closed = false;\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n const flush = () => {\n scheduled = null;\n\n if (closed) return;\n if (pending.length) {\n controller.enqueue(encoder.encode(pending.join(\"\") + PAST));\n pending = [];\n }\n if (flightDone && htmlDone) {\n closed = true;\n controller.enqueue(encoder.encode(`${BLOCK}null</script>${PAST}`));\n controller.close();\n }\n };\n // After the task React is flushing in, so never between its pieces.\n const later = () => {\n scheduled ??= setTimeout(flush, 0);\n };\n\n const readHtml = async () => {\n for (;;) {\n const { done, value } = await htmlReader.read();\n\n if (done) break;\n if (!closed) controller.enqueue(value);\n // Anything the payload had waiting goes after this flush, not in it.\n if (pending.length) later();\n }\n htmlDone = true;\n later();\n };\n\n const readFlight = async () => {\n for (;;) {\n const { done, value } = await flightReader.read();\n\n if (done) break;\n pending.push(`${BLOCK}${chunk(value)}</script>`);\n later();\n }\n // A character split across the last two chunks would be held here.\n const tail = decoder.decode();\n\n if (tail) pending.push(`${BLOCK}${script(tail)}</script>`);\n flightDone = true;\n later();\n };\n\n const fail = (error: unknown) => {\n if (closed) return;\n closed = true;\n void htmlReader.cancel(error).catch(() => {});\n void flightReader.cancel(error).catch(() => {});\n controller.error(error);\n };\n\n readHtml().catch(fail);\n readFlight().catch(fail);\n },\n cancel(reason) {\n closed = true;\n if (scheduled) clearTimeout(scheduled);\n void htmlReader.cancel(reason).catch(() => {});\n void flightReader.cancel(reason).catch(() => {});\n },\n });\n\n // Text as a string, which compresses with the page. A chunk that is not\n // UTF-8 - a typed array in the payload - goes as base64.\n function chunk(value: Uint8Array): string {\n try {\n return script(decoder.decode(value, { stream: true }));\n } catch {\n let binary = \"\";\n\n for (const byte of value) binary += String.fromCharCode(byte);\n\n return `{\"b\":${script(btoa(binary))}}`;\n }\n }\n}\n\n/**\n * A JSON string safe inside a <script>: no way to close the element or open a\n * comment. JSON, because the reader parses it: a block is never run.\n */\nfunction script(text: string): string {\n return JSON.stringify(text)\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n"]}
@@ -1,9 +1,10 @@
1
1
  // The payload a document carries for itself - see ../inlineFlight.ts.
2
2
  //
3
3
  // The server writes each chunk of the render's payload into the document as a
4
- // script, `self.__rsc_f.push(chunk)`, and a null once it has finished. This
5
- // turns those into the stream the runtime decodes, as if it had fetched it:
6
- // what arrived before the runtime ran, then each chunk as it is parsed.
4
+ // data block, and a null once it has finished; the boot script's reader
5
+ // (READ_BLOCKS) pushes each onto `self.__rsc_f` as the parser finishes it.
6
+ // This turns those into the stream the runtime decodes, as if it had fetched
7
+ // it: what arrived before the runtime ran, then each chunk as it is parsed.
7
8
  /**
8
9
  * The document's own payload as a response, or null when it carries none -
9
10
  * a page from a file the build wrote, a server that writes none - and the
@@ -1 +1 @@
1
- {"version":3,"file":"inlinePayload.js","sourceRoot":"","sources":["../../src/js/inlinePayload.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AAQxE;;;;GAIG;AACH,MAAM,UAAU,aAAa;I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AAC;YACX,CAAC,CAAC;YAEF,qEAAqE;YACrE,qEAAqE;YACrE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAElC,IAAI,QAAQ,CAAC,UAAU,KAAK,SAAS;gBAAE,QAAQ,CAAC,gBAAgB,CAAC,kBAAkB,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;;gBAC1G,QAAQ,EAAE,CAAC;QAClB,CAAC;KACF,CAAC,CAAC;IAEH,MAAM,OAAO,GAA2B,EAAE,cAAc,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,GAAG,EAAE,CAAC;IAE3G,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ;QAAE,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC;IAExE,OAAO,CAAC,CAAC,OAAO,CAAC;IAEjB,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AACzC,CAAC","sourcesContent":["// The payload a document carries for itself - see ../inlineFlight.ts.\n//\n// The server writes each chunk of the render's payload into the document as a\n// script, `self.__rsc_f.push(chunk)`, and a null once it has finished. This\n// turns those into the stream the runtime decodes, as if it had fetched it:\n// what arrived before the runtime ran, then each chunk as it is parsed.\n\ninterface Queue {\n push(chunk: unknown): number;\n length: number;\n [index: number]: unknown;\n}\n\n/**\n * The document's own payload as a response, or null when it carries none -\n * a page from a file the build wrote, a server that writes none - and the\n * runtime fetches it, as it always did.\n */\nexport function inlinePayload(): Response | null {\n const w = window as unknown as { __rsc_f?: Queue; __rsc_l?: string };\n const queue = w.__rsc_f;\n\n if (!queue || typeof queue.push !== \"function\") return null;\n\n const encoder = new TextEncoder();\n const bytes = (chunk: unknown): Uint8Array =>\n typeof chunk === \"string\"\n ? encoder.encode(chunk)\n : Uint8Array.from(atob((chunk as { b: string }).b), (c) => c.charCodeAt(0));\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n let ended = false;\n const take = (chunk: unknown) => {\n if (ended) return;\n if (chunk === null) {\n ended = true;\n controller.close();\n\n return;\n }\n controller.enqueue(bytes(chunk));\n };\n\n for (let i = 0; i < queue.length; i++) take(queue[i]);\n queue.length = 0;\n queue.push = (chunk: unknown) => {\n take(chunk);\n\n return 0;\n };\n\n // A document cut off before the server's end marker: what arrived is\n // all there is, and the decoder is told so rather than left waiting.\n const finished = () => take(null);\n\n if (document.readyState === \"loading\") document.addEventListener(\"DOMContentLoaded\", finished, { once: true });\n else finished();\n },\n });\n\n const headers: Record<string, string> = { \"Content-Type\": \"text/x-component\", \"X-RSC-Segment-Depth\": \"0\" };\n\n if (typeof w.__rsc_l === \"string\") headers[\"X-RSC-Layouts\"] = w.__rsc_l;\n\n delete w.__rsc_l;\n\n return new Response(body, { headers });\n}\n"]}
1
+ {"version":3,"file":"inlinePayload.js","sourceRoot":"","sources":["../../src/js/inlinePayload.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,EAAE;AACF,8EAA8E;AAC9E,wEAAwE;AACxE,2EAA2E;AAC3E,6EAA6E;AAC7E,4EAA4E;AAQ5E;;;;GAIG;AACH,MAAM,UAAU,aAAa;IAC3B,MAAM,CAAC,GAAG,MAA0D,CAAC;IACrE,MAAM,KAAK,GAAG,CAAC,CAAC,OAAO,CAAC;IAExB,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC;IAE5D,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,MAAM,KAAK,GAAG,CAAC,KAAc,EAAc,EAAE,CAC3C,OAAO,KAAK,KAAK,QAAQ;QACvB,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC;QACvB,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAE,KAAuB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,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,OAAO,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC;IAExE,OAAO,CAAC,CAAC,OAAO,CAAC;IAEjB,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;AACzC,CAAC","sourcesContent":["// The payload a document carries for itself - see ../inlineFlight.ts.\n//\n// The server writes each chunk of the render's payload into the document as a\n// data block, and a null once it has finished; the boot script's reader\n// (READ_BLOCKS) pushes each onto `self.__rsc_f` as the parser finishes it.\n// This turns those into the stream the runtime decodes, as if it had fetched\n// it: what arrived before the runtime ran, then each chunk as it is parsed.\n\ninterface Queue {\n push(chunk: unknown): number;\n length: number;\n [index: number]: unknown;\n}\n\n/**\n * The document's own payload as a response, or null when it carries none -\n * a page from a file the build wrote, a server that writes none - and the\n * runtime fetches it, as it always did.\n */\nexport function inlinePayload(): Response | null {\n const w = window as unknown as { __rsc_f?: Queue; __rsc_l?: string };\n const queue = w.__rsc_f;\n\n if (!queue || typeof queue.push !== \"function\") return null;\n\n const encoder = new TextEncoder();\n const bytes = (chunk: unknown): Uint8Array =>\n typeof chunk === \"string\"\n ? encoder.encode(chunk)\n : Uint8Array.from(atob((chunk as { b: string }).b), (c) => c.charCodeAt(0));\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n let ended = false;\n const take = (chunk: unknown) => {\n if (ended) return;\n if (chunk === null) {\n ended = true;\n controller.close();\n\n return;\n }\n controller.enqueue(bytes(chunk));\n };\n\n for (let i = 0; i < queue.length; i++) take(queue[i]);\n queue.length = 0;\n queue.push = (chunk: unknown) => {\n take(chunk);\n\n return 0;\n };\n\n // A document cut off before the server's end marker: what arrived is\n // all there is, and the decoder is told so rather than left waiting.\n const finished = () => take(null);\n\n if (document.readyState === \"loading\") document.addEventListener(\"DOMContentLoaded\", finished, { once: true });\n else finished();\n },\n });\n\n const headers: Record<string, string> = { \"Content-Type\": \"text/x-component\", \"X-RSC-Segment-Depth\": \"0\" };\n\n if (typeof w.__rsc_l === \"string\") headers[\"X-RSC-Layouts\"] = w.__rsc_l;\n\n delete w.__rsc_l;\n\n return new Response(body, { headers });\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { ContentSecurityPolicy } from "./csp.js";
1
2
  export interface RouteSegment {
2
3
  /**
3
4
  * `host`: a `[name]` directory at the top of app/. Bound from the request's
@@ -149,6 +150,11 @@ export interface RouteManifest {
149
150
  * every page it serves from its cache. Fixed for the build.
150
151
  */
151
152
  headers?: Record<string, string>;
153
+ /**
154
+ * rscKit({ contentSecurityPolicy }), checked: the author's directives, to
155
+ * which the host adds each document's hashes, and a nonce when it streams.
156
+ */
157
+ contentSecurityPolicy?: ContentSecurityPolicy;
152
158
  /**
153
159
  * rscKit({ backendPaths }), normalised: a proxy in front sends a path equal
154
160
  * to one, or under it, to the backend and everything else here. `[]` when
package/dist/manifest.js CHANGED
@@ -1,13 +1,2 @@
1
- // The shape of routes.json — what the build discovered, for a host to read.
2
- //
3
- // The build already walks app/ to generate its entries, and every host needs
4
- // the same facts: which url a component answers, what layouts wrap it, which
5
- // slots and sections belong to it. Laravel used to scan the tree a second time
6
- // to work that out; a JS host would have had to write a third walk. This is the
7
- // one answer, and these are its types.
8
- //
9
- // Urls are segments rather than a pattern string, because the pattern is the
10
- // host's dialect: Laravel writes {slug}, Hono writes :slug, and neither is the
11
- // build's business.
12
1
  export {};
13
2
  //# sourceMappingURL=manifest.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,+EAA+E;AAC/E,gFAAgF;AAChF,uCAAuC;AACvC,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,oBAAoB","sourcesContent":["// The shape of routes.json — what the build discovered, for a host to read.\n//\n// The build already walks app/ to generate its entries, and every host needs\n// the same facts: which url a component answers, what layouts wrap it, which\n// slots and sections belong to it. Laravel used to scan the tree a second time\n// to work that out; a JS host would have had to write a third walk. This is the\n// one answer, and these are its types.\n//\n// Urls are segments rather than a pattern string, because the pattern is the\n// host's dialect: Laravel writes {slug}, Hono writes :slug, and neither is the\n// build's business.\n\nexport interface RouteSegment {\n /**\n * `host`: a `[name]` directory at the top of app/. Bound from the request's\n * host, never from a path segment - so `example.com/nope` is a 404 rather\n * than a tenant called \"nope\". See hostRouting.\n */\n type: \"static\" | \"param\" | \"catchAll\" | \"host\";\n value: string;\n}\n\nexport interface ManifestRoute {\n component: string;\n segments: RouteSegment[];\n layouts: string[];\n loadings: string[];\n /**\n * `error.tsx` files above this route, outermost first.\n *\n * The nearest one to a failure catches it, the same way the nearest\n * `loading.tsx` is the fallback. Optional: a manifest from a build before\n * error boundaries existed has none.\n */\n errors?: string[];\n /**\n * `not-found.tsx` files above this route, outermost first.\n *\n * A `notFound()` from this route's page or guard is answered by the nearest\n * one, rendered inside the layouts above it; the way `error.tsx` is the\n * nearest above a failure. A url no route owns has no route to ask, and is\n * answered by the one at the root. Optional: a manifest from a build before\n * this has none, and the root one answers everything.\n */\n notFounds?: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * Run before anything at or below them renders, on every path. A check is\n * not UI, and making it a layout meant the client could decline it: layouts\n * are skipped on a partial navigation, and what gets skipped is named in a\n * header nothing can verify.\n */\n middleware: string[];\n slots: Record<string, string>;\n sections: string[];\n /**\n * The host's route-config file beside this page, if it named one, and the\n * ancestor ones that also apply — outermost first, this page's excluded.\n *\n * Relative to the project root: an absolute path is true only on the machine\n * that produced it, and building in a container is ordinary.\n */\n config: string | null;\n ancestorConfigs: string[];\n /**\n * Host middleware names for this route, outermost first.\n *\n * Declared in a route.ts beside or above the page. The engine does not know\n * what they mean — they are the host's own vocabulary — it only runs them\n * past the host before anything at or below this route renders.\n *\n * Empty on a route that named none, and on every route in an app that never\n * wrote a route.ts, which is why this needs no flag.\n *\n * Optional because registration boots from the PREVIOUS build's manifest: a\n * shape change takes two builds to settle, and a required field would make\n * the first of those a hard failure rather than a route with no guards.\n */\n hostMiddleware?: string[];\n /**\n * Whether the page exports generateStaticParams.\n *\n * Recorded here so a host can plan a build — which routes to ask for urls,\n * which to leave on demand — without loading the server bundle first. The\n * function itself is reached through the bundle's getStaticParams(), because\n * only the bundle can run it.\n */\n staticParams: boolean;\n /**\n * Seconds a shared cache may keep this page: the smallest\n * `export const revalidate` across its layouts and the page itself, as Next\n * takes it. Absent when none says, or one says 0 - rendered per request, as\n * before. A page with it is not frozen at build; see pageCache.ts.\n */\n revalidate?: number;\n}\n\nexport interface ManifestIntercept {\n component: string;\n slot: string;\n segments: RouteSegment[];\n /** (.) same level, (..) one up, (...) from the root. */\n marker: string;\n}\n\n/**\n * A `route.ts` — an api endpoint rather than a page.\n *\n * Separate from `routes` because it is matched before them and answered\n * without rendering anything: no layouts, no payload, no client. A url cannot\n * be both, and the build refuses one that is.\n */\nexport interface ManifestApiRoute {\n /** The module name, as the engine's registry keys it. */\n name: string;\n /**\n * The file that answers, relative to the source directory - `app/api/x/route.ts`,\n * or `app/sitemap.ts` for a route the build synthesised from a metadata file\n * - so a line about the route can say where to look.\n */\n source?: string;\n segments: RouteSegment[];\n /** Which methods the file exports, so a 405 can name the rest. */\n methods: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * The same chain a page in that directory runs. A route.ts sits among the\n * pages it belongs with, so a guard on the directory covers it too —\n * anything else would mean adding an endpoint under a guarded path silently\n * opened a hole in it.\n */\n middleware: string[];\n /** Host middleware above this route (`export const middleware = [...]`), outermost first. */\n hostMiddleware?: string[];\n}\n\nexport interface RouteManifest {\n version: number;\n build: {\n output: string;\n exportPath: string;\n payloadName: string;\n /**\n * The site's own hosts, bare and lower-case. A request from any other\n * host is matched with that host's segment in front of its path - see\n * hostRouting. Absent or empty: every request is the site's own.\n */\n hosts?: string[];\n /**\n * Whether every response says what built it: `X-Powered-By: rsc-kit` and\n * a generator meta tag in the document. The name only, never the version.\n * `X-RSC-Kit` (how a response was served) is sent regardless.\n */\n identify?: boolean;\n /**\n * Whether any page or section declares `refreshOn`, so the server signs\n * names - and must refuse to serve, in production, without a key every\n * instance shares.\n */\n refreshOn?: boolean;\n /**\n * rscKit({ headers }): set on every response, and handed to an edge with\n * every page it serves from its cache. Fixed for the build.\n */\n headers?: Record<string, string>;\n /**\n * rscKit({ backendPaths }), normalised: a proxy in front sends a path equal\n * to one, or under it, to the backend and everything else here. `[]` when\n * none; absent from a build before 0.30.53.\n */\n backendPaths?: string[];\n };\n routes: ManifestRoute[];\n intercepts: ManifestIntercept[];\n /** Optional: a manifest from a build before api routes existed has none. */\n apis?: ManifestApiRoute[];\n}\n"]}
1
+ {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContentSecurityPolicy } from \"./csp.js\";\n// The shape of routes.json — what the build discovered, for a host to read.\n//\n// The build already walks app/ to generate its entries, and every host needs\n// the same facts: which url a component answers, what layouts wrap it, which\n// slots and sections belong to it. Laravel used to scan the tree a second time\n// to work that out; a JS host would have had to write a third walk. This is the\n// one answer, and these are its types.\n//\n// Urls are segments rather than a pattern string, because the pattern is the\n// host's dialect: Laravel writes {slug}, Hono writes :slug, and neither is the\n// build's business.\n\nexport interface RouteSegment {\n /**\n * `host`: a `[name]` directory at the top of app/. Bound from the request's\n * host, never from a path segment - so `example.com/nope` is a 404 rather\n * than a tenant called \"nope\". See hostRouting.\n */\n type: \"static\" | \"param\" | \"catchAll\" | \"host\";\n value: string;\n}\n\nexport interface ManifestRoute {\n component: string;\n segments: RouteSegment[];\n layouts: string[];\n loadings: string[];\n /**\n * `error.tsx` files above this route, outermost first.\n *\n * The nearest one to a failure catches it, the same way the nearest\n * `loading.tsx` is the fallback. Optional: a manifest from a build before\n * error boundaries existed has none.\n */\n errors?: string[];\n /**\n * `not-found.tsx` files above this route, outermost first.\n *\n * A `notFound()` from this route's page or guard is answered by the nearest\n * one, rendered inside the layouts above it; the way `error.tsx` is the\n * nearest above a failure. A url no route owns has no route to ask, and is\n * answered by the one at the root. Optional: a manifest from a build before\n * this has none, and the root one answers everything.\n */\n notFounds?: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * Run before anything at or below them renders, on every path. A check is\n * not UI, and making it a layout meant the client could decline it: layouts\n * are skipped on a partial navigation, and what gets skipped is named in a\n * header nothing can verify.\n */\n middleware: string[];\n slots: Record<string, string>;\n sections: string[];\n /**\n * The host's route-config file beside this page, if it named one, and the\n * ancestor ones that also apply — outermost first, this page's excluded.\n *\n * Relative to the project root: an absolute path is true only on the machine\n * that produced it, and building in a container is ordinary.\n */\n config: string | null;\n ancestorConfigs: string[];\n /**\n * Host middleware names for this route, outermost first.\n *\n * Declared in a route.ts beside or above the page. The engine does not know\n * what they mean — they are the host's own vocabulary — it only runs them\n * past the host before anything at or below this route renders.\n *\n * Empty on a route that named none, and on every route in an app that never\n * wrote a route.ts, which is why this needs no flag.\n *\n * Optional because registration boots from the PREVIOUS build's manifest: a\n * shape change takes two builds to settle, and a required field would make\n * the first of those a hard failure rather than a route with no guards.\n */\n hostMiddleware?: string[];\n /**\n * Whether the page exports generateStaticParams.\n *\n * Recorded here so a host can plan a build — which routes to ask for urls,\n * which to leave on demand — without loading the server bundle first. The\n * function itself is reached through the bundle's getStaticParams(), because\n * only the bundle can run it.\n */\n staticParams: boolean;\n /**\n * Seconds a shared cache may keep this page: the smallest\n * `export const revalidate` across its layouts and the page itself, as Next\n * takes it. Absent when none says, or one says 0 - rendered per request, as\n * before. A page with it is not frozen at build; see pageCache.ts.\n */\n revalidate?: number;\n}\n\nexport interface ManifestIntercept {\n component: string;\n slot: string;\n segments: RouteSegment[];\n /** (.) same level, (..) one up, (...) from the root. */\n marker: string;\n}\n\n/**\n * A `route.ts` — an api endpoint rather than a page.\n *\n * Separate from `routes` because it is matched before them and answered\n * without rendering anything: no layouts, no payload, no client. A url cannot\n * be both, and the build refuses one that is.\n */\nexport interface ManifestApiRoute {\n /** The module name, as the engine's registry keys it. */\n name: string;\n /**\n * The file that answers, relative to the source directory - `app/api/x/route.ts`,\n * or `app/sitemap.ts` for a route the build synthesised from a metadata file\n * - so a line about the route can say where to look.\n */\n source?: string;\n segments: RouteSegment[];\n /** Which methods the file exports, so a 405 can name the rest. */\n methods: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * The same chain a page in that directory runs. A route.ts sits among the\n * pages it belongs with, so a guard on the directory covers it too —\n * anything else would mean adding an endpoint under a guarded path silently\n * opened a hole in it.\n */\n middleware: string[];\n /** Host middleware above this route (`export const middleware = [...]`), outermost first. */\n hostMiddleware?: string[];\n}\n\nexport interface RouteManifest {\n version: number;\n build: {\n output: string;\n exportPath: string;\n payloadName: string;\n /**\n * The site's own hosts, bare and lower-case. A request from any other\n * host is matched with that host's segment in front of its path - see\n * hostRouting. Absent or empty: every request is the site's own.\n */\n hosts?: string[];\n /**\n * Whether every response says what built it: `X-Powered-By: rsc-kit` and\n * a generator meta tag in the document. The name only, never the version.\n * `X-RSC-Kit` (how a response was served) is sent regardless.\n */\n identify?: boolean;\n /**\n * Whether any page or section declares `refreshOn`, so the server signs\n * names - and must refuse to serve, in production, without a key every\n * instance shares.\n */\n refreshOn?: boolean;\n /**\n * rscKit({ headers }): set on every response, and handed to an edge with\n * every page it serves from its cache. Fixed for the build.\n */\n headers?: Record<string, string>;\n /**\n * rscKit({ contentSecurityPolicy }), checked: the author's directives, to\n * which the host adds each document's hashes, and a nonce when it streams.\n */\n contentSecurityPolicy?: ContentSecurityPolicy;\n /**\n * rscKit({ backendPaths }), normalised: a proxy in front sends a path equal\n * to one, or under it, to the backend and everything else here. `[]` when\n * none; absent from a build before 0.30.53.\n */\n backendPaths?: string[];\n };\n routes: ManifestRoute[];\n intercepts: ManifestIntercept[];\n /** Optional: a manifest from a build before api routes existed has none. */\n apis?: ManifestApiRoute[];\n}\n"]}
@@ -64,6 +64,11 @@ export declare function finishCacheable(request: Request, response: Response, en
64
64
  * it - but a not-found one is kept no longer than a 404.
65
65
  */
66
66
  saidNotFound?: () => boolean): Promise<Response>;
67
+ /**
68
+ * The body finishCacheable read to its end, for a caller that needs the whole
69
+ * document after it - a 304 carries none of its own.
70
+ */
71
+ export declare function keptBodyOf(answer: Response): ArrayBuffer | undefined;
67
72
  /**
68
73
  * Pages kept in this process, by the size of what they hold: a page is tens
69
74
  * or hundreds of KB, so a count says nothing about memory. Least recently
package/dist/pageCache.js CHANGED
@@ -231,6 +231,13 @@ saidNotFound = () => false) {
231
231
  return answer;
232
232
  }
233
233
  const keepable = new WeakMap();
234
+ /**
235
+ * The body finishCacheable read to its end, for a caller that needs the whole
236
+ * document after it - a 304 carries none of its own.
237
+ */
238
+ export function keptBodyOf(answer) {
239
+ return keepable.get(answer)?.body;
240
+ }
234
241
  /** Headers that belong to one answer, never to the kept page. */
235
242
  const NOT_KEPT = new Set(["date", "set-cookie", "content-length", "x-rsc-kit", "x-powered-by", "age"]);
236
243
  const utf8 = new TextDecoder("utf-8", { fatal: true });
@@ -1 +1 @@
1
- {"version":3,"file":"pageCache.js","sourceRoot":"","sources":["../src/pageCache.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,4EAA4E;AAC5E,2BAA2B;AAC3B,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,gGAAgG;AAChG,8EAA8E;AAC9E,4EAA4E;AAC5E,+DAA+D;AAC/D,uEAAuE;AACvE,qEAAqE;AACrE,mDAAmD;AACnD,2EAA2E;AAC3E,0CAA0C;AAC1C,2EAA2E;AAC3E,8EAA8E;AAC9E,2EAA2E;AAC3E,EAAE;AACF,4EAA4E;AAC5E,qEAAqE;AACrE,EAAE;AACF,6EAA6E;AAC7E,iEAAiE;AAEjE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,UAAU,EA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,CAAC;gBACH,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,EAAE,CAAC;YAC1C,CAAC;oBAAS,CAAC;gBACT,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACvB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// A page a shared cache may keep: `export const revalidate = N`.\n//\n// The page is rendered whole, judged, then sent. Public only when every check\n// passed for that render; otherwise `private, no-store`, exactly as before,\n// with `Cache-Status: rsc-kit; fwd=bypass; detail=<check>` saying which one\n// failed and a line in the log saying where. Cache-Control is the contract a\n// host caches by; Cache-Status is for counting and for the developer asking\n// why a page was not kept.\n//\n// The checks, in the order they can be made:\n//\n// 1. payload-url - a GET or HEAD, and a payload asked for at its own `?_rsc=<key>` url, and a\n// document never at one: a cache that ignores Vary keys on\n// the url alone, so either the other way round hands one\n// kind of answer to a request for the other\n// 2. the render read nothing that belongs to one visitor: cookies(),\n// headers(), request(), connection() - in the page, a layout, a\n// Suspense'd child, metadata or middleware.ts\n// 3. host-middleware - Laravel route middleware runs against the session\n// 4. set-cookie - nothing set a cookie\n// 5. nonce - no CSP nonce, which a shared copy would give everyone\n// 6. status - 200 or 404; a redirect, a 5xx or a render React reported\n// as failed inside the payload (failed-render) never is\n//\n// A public answer carries `Cache-Tag`: the tags of every cache() answer the\n// render used, so a CDN can purge the copy when one of them changes.\n//\n// Backends render as nobody - see renderAsNobody() - so a session cookie set\n// by the backend on every call does not make every page private.\n\nimport { HEADER, PER_CLIENT } from \"./headers.js\";\nimport { PAYLOAD_PARAM, payloadKey, withoutPayloadKey } from \"./js/payloadKey.js\";\nimport { cacheTagsRead, cacheTagVersionsRead, renderFailed, visitorReads } from \"./request.js\";\nimport type { CacheStore } from \"./cache.js\";\nimport { versionSource } from \"./changed.js\";\n\n/** What a request for a `revalidate` page carries from the moment it arrives. */\nexport interface PageCaching {\n /** Seconds a shared cache may keep the page. */\n revalidate: number;\n /** The url path, for the log line. */\n path: string;\n /** A check that failed before anything rendered, or after the page said notFound(). */\n refused: string | null;\n}\n\n/** A 404 is kept no longer than this, however long its page may be. */\nconst NOT_FOUND_LIMIT = 60;\n\n/** How long a cache may serve a stale page while one request refreshes it, or while the origin is failing. */\nconst STALE_WINDOW = 86_400;\n\nconst caching = new WeakMap<Request, PageCaching>();\n\n/**\n * Decide, for a request as it arrived, whether its answer may be judged at all.\n *\n * Null for anything but a GET or HEAD of a page that exports revalidate - the\n * answer is then what it always was. Keyed by the request the app sees, so the\n * entry in front, which renders a 404, finds it again.\n */\nexport function cachingFor(arrived: Request, revalidate: number | undefined): PageCaching | null {\n // A post is never kept, and its answer already says so.\n if (!revalidate || revalidate <= 0 || (arrived.method !== \"GET\" && arrived.method !== \"HEAD\")) return null;\n\n const url = new URL(arrived.url);\n const entry: PageCaching = { revalidate, path: url.pathname, refused: urlRefusal(arrived, url) };\n\n caching.set(withoutPayloadKey(arrived), entry);\n\n return entry;\n}\n\n/** What cachingFor() decided for this request, if anything. */\nexport function cachingOf(request: Request): PageCaching | null {\n return caching.get(withoutPayloadKey(request)) ?? null;\n}\n\n/**\n * Check 1. A payload answers at `?_rsc=<key>`, with the key its headers give;\n * a document never answers there. Either way round, a cache keying on the url\n * alone would hand a request one kind of answer for the other.\n */\nfunction urlRefusal(arrived: Request, url: URL): string | null {\n const key = url.searchParams.get(PAYLOAD_PARAM);\n const payload = arrived.headers.get(HEADER.rsc) !== null;\n\n if (payload ? key !== payloadKey(arrived.headers) : key !== null) return \"payload-url\";\n\n return null;\n}\n\n/**\n * Note what the render has read so far, for an answer that will be finished\n * somewhere else: the page said notFound(), and the entry in front renders\n * not-found.tsx in a scope of its own, where these reads are gone.\n */\nexport function noteReadsSoFar(entry: PageCaching): void {\n entry.refused ??= readRefusal();\n}\n\nfunction readRefusal(): string | null {\n if (renderFailed()) return \"failed-render\";\n\n const read = visitorReads()[0];\n\n return read ?? null;\n}\n\n/** The detail token a read is reported under: `cookies() in Header` is `cookies`. */\nfunction detailOf(refused: string): string {\n return refused.replace(/\\(.*$/, \"\").replace(/[^a-z-]/gi, \"-\");\n}\n\nconst logged = new Set<string>();\n\nconst REASONS: Record<string, string> = {\n \"payload-url\":\n \"a payload was asked for without its ?_rsc= key, or a document with one. The router always adds it; this was another client.\",\n \"host-middleware\": \"the route has host middleware, which runs against the visitor's session.\",\n \"set-cookie\": \"the answer set a cookie.\",\n nonce: \"the answer carries a CSP nonce, which a shared copy would give every visitor.\",\n status: \"only a 200 or a 404 is kept.\",\n \"failed-render\": \"React reported a failure inside the payload.\",\n};\n\n/** Once per page and reason: a page refused on every request says so once. */\nfunction logRefusal(entry: PageCaching, refused: string): void {\n const key = `${entry.path}\\n${refused}`;\n\n if (logged.has(key) || logged.size > 500) return;\n\n logged.add(key);\n\n // A read names what read, and where: `cookies() in Header`.\n const why = REASONS[refused] ?? `${refused} reads this visitor.`;\n\n console.warn(`[rsc-kit] ${entry.path} exports revalidate, and was sent private: ${why}`);\n}\n\nfunction bypass(response: Response, body: BodyInit | null, entry: PageCaching, refused: string): Response {\n const headers = new Headers(response.headers);\n\n headers.set(\"Cache-Control\", PER_CLIENT);\n headers.set(\"Cache-Status\", `rsc-kit; fwd=bypass; detail=${detailOf(refused)}`);\n headers.delete(\"ETag\");\n // A CDN that reads it reads it over Cache-Control, so a private answer never has it.\n headers.delete(\"CDN-Cache-Control\");\n logRefusal(entry, refused);\n\n return new Response(body, { status: response.status, statusText: response.statusText, headers });\n}\n\n/** How long a shared cache keeps a public answer, which both of its headers state. */\nfunction sharedLifetime(revalidate: number, status: number): { fresh: number; windows: string } {\n const notFound = status === 404;\n const stale = notFound ? NOT_FOUND_LIMIT : STALE_WINDOW;\n\n return {\n fresh: notFound ? Math.min(revalidate, NOT_FOUND_LIMIT) : revalidate,\n windows: `stale-while-revalidate=${stale}, stale-if-error=${stale}`,\n };\n}\n\n/**\n * What a public answer says: kept by shared caches for N seconds, refreshed\n * in the background for a day after that, never by the browser. A 404 for at\n * most a minute, so a scanner walking random urls cannot hold pages out.\n *\n * stale-if-error says the same window outright for an origin that is down,\n * erroring or mid-deploy: a cache left to choose may serve the error instead,\n * or a copy older than the page would ever have been kept for.\n */\nexport function publicCacheControl(revalidate: number, status: number): string {\n const { fresh, windows } = sharedLifetime(revalidate, status);\n\n return `public, max-age=0, s-maxage=${fresh}, ${windows}`;\n}\n\n/**\n * The same lifetime for a CDN that reads CDN-Cache-Control (RFC 9213), which\n * is meant for it alone: there max-age is the CDN's own, not a browser's. Some\n * edges keep a page only on this header, and Cache-Control stays beside it for\n * every cache that does not read it.\n */\nexport function cdnCacheControl(revalidate: number, status: number): string {\n const { fresh, windows } = sharedLifetime(revalidate, status);\n\n return `max-age=${fresh}, ${windows}`;\n}\n\n/** A tag a Cache-Tag list can carry: visible ASCII, no comma, which separates them. */\nconst TAG = /^[\\x21-\\x2b\\x2d-\\x7e]+$/;\n\nlet warnedTag = false;\n\n/**\n * The tags of every cache() answer a kept page used, as a CDN reads them:\n * `Cache-Tag: pages,post:1`. A purge by any of them drops the copy. A tag the\n * header cannot carry is left out, and said once: the copy then goes stale on\n * its own time, not on that change.\n */\nexport function cacheTagHeader(tags: readonly string[]): string | null {\n const kept = tags.filter((tag) => TAG.test(tag));\n\n if (kept.length < tags.length && !warnedTag) {\n warnedTag = true;\n const bad = tags.find((tag) => !TAG.test(tag));\n console.warn(\n `[rsc-kit] cache() tag ${JSON.stringify(bad)} cannot go in a Cache-Tag header (a comma, a space or a non-ASCII letter), so a CDN cannot purge by it.`,\n );\n }\n\n return kept.length ? kept.join(\",\") : null;\n}\n\nasync function etagOf(body: ArrayBuffer): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", body));\n let hex = \"\";\n\n for (let i = 0; i < 12; i++) hex += digest[i].toString(16).padStart(2, \"0\");\n\n return `\"${hex}\"`;\n}\n\nfunction matches(ifNoneMatch: string | null, etag: string): boolean {\n if (!ifNoneMatch) return false;\n\n return ifNoneMatch\n .split(\",\")\n .map((tag) => tag.trim().replace(/^W\\//, \"\"))\n .some((tag) => tag === etag || tag === \"*\");\n}\n\n/**\n * Finish the answer to a `revalidate` page: rendered whole, then judged.\n *\n * Called inside the request's scope, after every header the request will get\n * is on the answer - cookies included - so what it judges is what is sent.\n * Reading the body to its end is what waits for the render: a Suspense'd\n * child that reads cookies() is still running when the headers exist.\n */\nexport async function finishCacheable(\n request: Request,\n response: Response,\n entry: PageCaching,\n /**\n * Whether the answer turned out to be not-found.tsx, asked once the body is\n * read: a page can say notFound() in the middle of its stream, after a 200\n * went out. A payload is a 200 either way - the router reads the page from\n * it - but a not-found one is kept no longer than a 404.\n */\n saidNotFound: () => boolean = () => false,\n): Promise<Response> {\n if (entry.refused) return bypass(response, response.body, entry, entry.refused);\n\n if (response.status !== 200 && response.status !== 404) return bypass(response, response.body, entry, \"status\");\n\n const type = response.headers.get(\"Content-Type\") ?? \"\";\n\n if (!type.startsWith(\"text/html\") && !type.startsWith(\"text/x-component\")) {\n return bypass(response, response.body, entry, \"status\");\n }\n\n const body = await response.arrayBuffer();\n const refused =\n readRefusal() ??\n (response.headers.getSetCookie().length > 0 ? \"set-cookie\" : null) ??\n (/'nonce-/.test(response.headers.get(\"Content-Security-Policy\") ?? \"\") ? \"nonce\" : null);\n\n if (refused) return bypass(response, body, entry, refused);\n\n const headers = new Headers(response.headers);\n const etag = await etagOf(body);\n\n const status = saidNotFound() ? 404 : response.status;\n\n headers.set(\"Cache-Control\", publicCacheControl(entry.revalidate, status));\n headers.set(\"CDN-Cache-Control\", cdnCacheControl(entry.revalidate, status));\n headers.set(\"ETag\", etag);\n\n const tags = cacheTagHeader(cacheTagsRead());\n\n if (tags) headers.set(\"Cache-Tag\", tags);\n\n const kept: Keepable = { status: response.status, body, versions: cacheTagVersionsRead(), revalidate: entry.revalidate, notFound: saidNotFound() };\n\n if (response.status === 200 && matches(request.headers.get(\"If-None-Match\"), etag)) {\n headers.delete(\"Content-Length\");\n\n const answer = new Response(null, { status: 304, headers });\n\n keepable.set(answer, kept);\n\n return answer;\n }\n\n const answer = new Response(request.method === \"HEAD\" ? null : body, { status: response.status, statusText: response.statusText, headers });\n\n keepable.set(answer, kept);\n\n return answer;\n}\n\n// The engine's own copy of a public page: ISR on every host.\n//\n// A kept page is versioned, not purged. Its entry carries the version of\n// every tag its cache() answers were read under, and a lookup asks the\n// version source whether any moved since. changed(tag) bumps a version every\n// instance reads, so every pod misses at its next request with nothing sent\n// to it - and a render that was running when the change landed is stored\n// under the older version, so it is never served. Correctness needs only a\n// version source every instance shares; the store decides how often a page\n// is rendered, never whether a stale one is served.\n\n/** What finishCacheable() sent public, kept beside the answer for the page cache to store. */\ninterface Keepable {\n status: number;\n body: ArrayBuffer;\n versions: Record<string, number>;\n revalidate: number;\n /** A not-found page, kept no longer than a 404. */\n notFound: boolean;\n}\n\nconst keepable = new WeakMap<Response, Keepable>();\n\n/** A kept page, as the store holds it. */\ninterface KeptPage {\n /** Status. */\n s: number;\n /** Headers, as name and value pairs. */\n h: [string, string][];\n /** Body, as text: HTML and Flight both are. */\n b: string;\n /** Tag versions it was rendered under. */\n v: Record<string, number>;\n /** When it was rendered, in ms. */\n at: number;\n /** Seconds it is fresh for. */\n r: number;\n /** Seconds past that it may still be served while one render replaces it. */\n w: number;\n}\n\n/** Headers that belong to one answer, never to the kept page. */\nconst NOT_KEPT = new Set([\"date\", \"set-cookie\", \"content-length\", \"x-rsc-kit\", \"x-powered-by\", \"age\"]);\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\n\n/**\n * Pages kept in this process, by the size of what they hold: a page is tens\n * or hundreds of KB, so a count says nothing about memory. Least recently\n * used goes first.\n */\nexport function pageMemoryStore(maxBytes = 64 * 1024 * 1024): CacheStore {\n const entries = new Map<string, { value: string; until: number }>();\n let bytes = 0;\n\n const drop = (key: string) => {\n const entry = entries.get(key);\n\n if (!entry) return;\n\n entries.delete(key);\n bytes -= entry.value.length;\n };\n\n return {\n get(key) {\n const entry = entries.get(key);\n\n if (!entry) return undefined;\n\n if (entry.until <= Date.now()) {\n drop(key);\n\n return undefined;\n }\n\n // Re-inserted, so the Map's order is least recently used first.\n entries.delete(key);\n entries.set(key, entry);\n\n return entry.value;\n },\n set(key, value, ttl) {\n drop(key);\n\n if (value.length > maxBytes) return;\n\n entries.set(key, { value, until: Date.now() + ttl * 1000 });\n bytes += value.length;\n\n while (bytes > maxBytes) drop(entries.keys().next().value!);\n },\n };\n}\n\n/** A kept answer, and whether it is past its time: served, while one render replaces it. */\nexport interface KeptAnswer {\n response: Response;\n stale: boolean;\n}\n\nexport interface PageCache {\n /** The kept answer for this request, or null to render it now. */\n lookup(key: string, request: Request): Promise<KeptAnswer | null>;\n /** Whether a render for this key is running in this process. */\n busy(key: string): boolean;\n /** Keep the answer, when finishCacheable() sent it public. */\n keep(key: string, answer: Response): Promise<void>;\n /** Run one render per key at a time: a burst for a page nobody has kept waits for the first. */\n once<T>(key: string, render: () => Promise<T>): Promise<{ led: boolean; value?: T }>;\n}\n\nlet warnedPageStore = false;\n\n/** A store that fails is a render, not a broken page: said once. */\nfunction pageStoreFailed(error: unknown): void {\n if (warnedPageStore) return;\n warnedPageStore = true;\n console.warn(\"[rsc-kit] the page cache's store failed, so pages are being rendered each time instead:\", error);\n}\n\n/** The engine's page cache, over a store: the app's, or one of its own in memory. */\nexport function createPageCache(store: CacheStore): PageCache {\n const inFlight = new Map<string, Promise<unknown>>();\n\n return {\n async lookup(key, request) {\n let raw: string | null | undefined;\n\n try {\n raw = await store.get(`rsc-page|${key}`);\n } catch (error) {\n pageStoreFailed(error);\n\n return null;\n }\n\n if (!raw) return null;\n\n let kept: KeptPage;\n\n try {\n kept = JSON.parse(raw);\n } catch {\n return null;\n }\n\n const now = Date.now();\n const age = now - kept.at;\n\n // The store may keep it longer than asked; the age is checked here.\n // Past its time it is still served, for a while, as the stale copy a\n // render in the background replaces: no visitor waits on an expiry.\n if (age >= (kept.r + (kept.w ?? 0)) * 1000) return null;\n\n // A tag that moved is never served stale: whoever changed it is\n // looking for the change, so this request renders.\n if (Object.keys(kept.v).length > 0) {\n try {\n const moved = await versionSource().changed(kept.v, 0);\n\n if (Object.keys(moved).some((tag) => moved[tag] !== kept.v[tag])) return null;\n } catch {\n // Not knowing whether it changed is not knowing it did not.\n return null;\n }\n }\n\n const headers = new Headers(kept.h);\n\n headers.set(\"Age\", String(Math.floor((now - kept.at) / 1000)));\n\n const etag = headers.get(\"ETag\");\n\n const stale = age >= kept.r * 1000;\n\n if (kept.s === 200 && etag && matches(request.headers.get(\"If-None-Match\"), etag)) {\n return { response: new Response(null, { status: 304, headers }), stale };\n }\n\n return { response: new Response(request.method === \"HEAD\" ? null : kept.b, { status: kept.s, headers }), stale };\n },\n\n busy(key) {\n return inFlight.has(key);\n },\n\n async keep(key, answer) {\n const kept = keepable.get(answer);\n\n if (!kept) return;\n\n let body: string;\n\n try {\n body = utf8.decode(kept.body);\n } catch {\n // Not text: sent, never kept.\n return;\n }\n\n const headers: [string, string][] = [];\n\n answer.headers.forEach((value, name) => {\n if (!NOT_KEPT.has(name.toLowerCase())) headers.push([name, value]);\n });\n\n const notFound = kept.status === 404 || kept.notFound;\n const revalidate = notFound ? Math.min(kept.revalidate, NOT_FOUND_LIMIT) : kept.revalidate;\n // The same windows the answer's Cache-Control gives a CDN.\n const window = notFound ? NOT_FOUND_LIMIT : STALE_WINDOW;\n const page: KeptPage = { s: kept.status, h: headers, b: body, v: kept.versions, at: Date.now(), r: revalidate, w: window };\n\n try {\n await store.set(`rsc-page|${key}`, JSON.stringify(page), Math.ceil(revalidate + window));\n } catch (error) {\n pageStoreFailed(error);\n }\n },\n\n async once(key, render) {\n const pending = inFlight.get(key);\n\n if (pending) {\n await pending.catch(() => {});\n\n return { led: false };\n }\n\n const work = render();\n\n inFlight.set(key, work);\n\n try {\n return { led: true, value: await work };\n } finally {\n inFlight.delete(key);\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"pageCache.js","sourceRoot":"","sources":["../src/pageCache.ts"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CAAC;gBACH,MAAM,KAAK,CAAC,GAAG,CAAC,YAAY,GAAG,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,CAAC,CAAC;YAC3F,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,eAAe,CAAC,KAAK,CAAC,CAAC;YACzB,CAAC;QACH,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM;YACpB,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAElC,IAAI,OAAO,EAAE,CAAC;gBACZ,MAAM,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;gBAE9B,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;YACxB,CAAC;YAED,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC;YAEtB,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YAExB,IAAI,CAAC;gBACH,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,IAAI,EAAE,CAAC;YAC1C,CAAC;oBAAS,CAAC;gBACT,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACvB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// A page a shared cache may keep: `export const revalidate = N`.\n//\n// The page is rendered whole, judged, then sent. Public only when every check\n// passed for that render; otherwise `private, no-store`, exactly as before,\n// with `Cache-Status: rsc-kit; fwd=bypass; detail=<check>` saying which one\n// failed and a line in the log saying where. Cache-Control is the contract a\n// host caches by; Cache-Status is for counting and for the developer asking\n// why a page was not kept.\n//\n// The checks, in the order they can be made:\n//\n// 1. payload-url - a GET or HEAD, and a payload asked for at its own `?_rsc=<key>` url, and a\n// document never at one: a cache that ignores Vary keys on\n// the url alone, so either the other way round hands one\n// kind of answer to a request for the other\n// 2. the render read nothing that belongs to one visitor: cookies(),\n// headers(), request(), connection() - in the page, a layout, a\n// Suspense'd child, metadata or middleware.ts\n// 3. host-middleware - Laravel route middleware runs against the session\n// 4. set-cookie - nothing set a cookie\n// 5. nonce - no CSP nonce, which a shared copy would give everyone\n// 6. status - 200 or 404; a redirect, a 5xx or a render React reported\n// as failed inside the payload (failed-render) never is\n//\n// A public answer carries `Cache-Tag`: the tags of every cache() answer the\n// render used, so a CDN can purge the copy when one of them changes.\n//\n// Backends render as nobody - see renderAsNobody() - so a session cookie set\n// by the backend on every call does not make every page private.\n\nimport { HEADER, PER_CLIENT } from \"./headers.js\";\nimport { PAYLOAD_PARAM, payloadKey, withoutPayloadKey } from \"./js/payloadKey.js\";\nimport { cacheTagsRead, cacheTagVersionsRead, renderFailed, visitorReads } from \"./request.js\";\nimport type { CacheStore } from \"./cache.js\";\nimport { versionSource } from \"./changed.js\";\n\n/** What a request for a `revalidate` page carries from the moment it arrives. */\nexport interface PageCaching {\n /** Seconds a shared cache may keep the page. */\n revalidate: number;\n /** The url path, for the log line. */\n path: string;\n /** A check that failed before anything rendered, or after the page said notFound(). */\n refused: string | null;\n}\n\n/** A 404 is kept no longer than this, however long its page may be. */\nconst NOT_FOUND_LIMIT = 60;\n\n/** How long a cache may serve a stale page while one request refreshes it, or while the origin is failing. */\nconst STALE_WINDOW = 86_400;\n\nconst caching = new WeakMap<Request, PageCaching>();\n\n/**\n * Decide, for a request as it arrived, whether its answer may be judged at all.\n *\n * Null for anything but a GET or HEAD of a page that exports revalidate - the\n * answer is then what it always was. Keyed by the request the app sees, so the\n * entry in front, which renders a 404, finds it again.\n */\nexport function cachingFor(arrived: Request, revalidate: number | undefined): PageCaching | null {\n // A post is never kept, and its answer already says so.\n if (!revalidate || revalidate <= 0 || (arrived.method !== \"GET\" && arrived.method !== \"HEAD\")) return null;\n\n const url = new URL(arrived.url);\n const entry: PageCaching = { revalidate, path: url.pathname, refused: urlRefusal(arrived, url) };\n\n caching.set(withoutPayloadKey(arrived), entry);\n\n return entry;\n}\n\n/** What cachingFor() decided for this request, if anything. */\nexport function cachingOf(request: Request): PageCaching | null {\n return caching.get(withoutPayloadKey(request)) ?? null;\n}\n\n/**\n * Check 1. A payload answers at `?_rsc=<key>`, with the key its headers give;\n * a document never answers there. Either way round, a cache keying on the url\n * alone would hand a request one kind of answer for the other.\n */\nfunction urlRefusal(arrived: Request, url: URL): string | null {\n const key = url.searchParams.get(PAYLOAD_PARAM);\n const payload = arrived.headers.get(HEADER.rsc) !== null;\n\n if (payload ? key !== payloadKey(arrived.headers) : key !== null) return \"payload-url\";\n\n return null;\n}\n\n/**\n * Note what the render has read so far, for an answer that will be finished\n * somewhere else: the page said notFound(), and the entry in front renders\n * not-found.tsx in a scope of its own, where these reads are gone.\n */\nexport function noteReadsSoFar(entry: PageCaching): void {\n entry.refused ??= readRefusal();\n}\n\nfunction readRefusal(): string | null {\n if (renderFailed()) return \"failed-render\";\n\n const read = visitorReads()[0];\n\n return read ?? null;\n}\n\n/** The detail token a read is reported under: `cookies() in Header` is `cookies`. */\nfunction detailOf(refused: string): string {\n return refused.replace(/\\(.*$/, \"\").replace(/[^a-z-]/gi, \"-\");\n}\n\nconst logged = new Set<string>();\n\nconst REASONS: Record<string, string> = {\n \"payload-url\":\n \"a payload was asked for without its ?_rsc= key, or a document with one. The router always adds it; this was another client.\",\n \"host-middleware\": \"the route has host middleware, which runs against the visitor's session.\",\n \"set-cookie\": \"the answer set a cookie.\",\n nonce: \"the answer carries a CSP nonce, which a shared copy would give every visitor.\",\n status: \"only a 200 or a 404 is kept.\",\n \"failed-render\": \"React reported a failure inside the payload.\",\n};\n\n/** Once per page and reason: a page refused on every request says so once. */\nfunction logRefusal(entry: PageCaching, refused: string): void {\n const key = `${entry.path}\\n${refused}`;\n\n if (logged.has(key) || logged.size > 500) return;\n\n logged.add(key);\n\n // A read names what read, and where: `cookies() in Header`.\n const why = REASONS[refused] ?? `${refused} reads this visitor.`;\n\n console.warn(`[rsc-kit] ${entry.path} exports revalidate, and was sent private: ${why}`);\n}\n\nfunction bypass(response: Response, body: BodyInit | null, entry: PageCaching, refused: string): Response {\n const headers = new Headers(response.headers);\n\n headers.set(\"Cache-Control\", PER_CLIENT);\n headers.set(\"Cache-Status\", `rsc-kit; fwd=bypass; detail=${detailOf(refused)}`);\n headers.delete(\"ETag\");\n // A CDN that reads it reads it over Cache-Control, so a private answer never has it.\n headers.delete(\"CDN-Cache-Control\");\n logRefusal(entry, refused);\n\n return new Response(body, { status: response.status, statusText: response.statusText, headers });\n}\n\n/** How long a shared cache keeps a public answer, which both of its headers state. */\nfunction sharedLifetime(revalidate: number, status: number): { fresh: number; windows: string } {\n const notFound = status === 404;\n const stale = notFound ? NOT_FOUND_LIMIT : STALE_WINDOW;\n\n return {\n fresh: notFound ? Math.min(revalidate, NOT_FOUND_LIMIT) : revalidate,\n windows: `stale-while-revalidate=${stale}, stale-if-error=${stale}`,\n };\n}\n\n/**\n * What a public answer says: kept by shared caches for N seconds, refreshed\n * in the background for a day after that, never by the browser. A 404 for at\n * most a minute, so a scanner walking random urls cannot hold pages out.\n *\n * stale-if-error says the same window outright for an origin that is down,\n * erroring or mid-deploy: a cache left to choose may serve the error instead,\n * or a copy older than the page would ever have been kept for.\n */\nexport function publicCacheControl(revalidate: number, status: number): string {\n const { fresh, windows } = sharedLifetime(revalidate, status);\n\n return `public, max-age=0, s-maxage=${fresh}, ${windows}`;\n}\n\n/**\n * The same lifetime for a CDN that reads CDN-Cache-Control (RFC 9213), which\n * is meant for it alone: there max-age is the CDN's own, not a browser's. Some\n * edges keep a page only on this header, and Cache-Control stays beside it for\n * every cache that does not read it.\n */\nexport function cdnCacheControl(revalidate: number, status: number): string {\n const { fresh, windows } = sharedLifetime(revalidate, status);\n\n return `max-age=${fresh}, ${windows}`;\n}\n\n/** A tag a Cache-Tag list can carry: visible ASCII, no comma, which separates them. */\nconst TAG = /^[\\x21-\\x2b\\x2d-\\x7e]+$/;\n\nlet warnedTag = false;\n\n/**\n * The tags of every cache() answer a kept page used, as a CDN reads them:\n * `Cache-Tag: pages,post:1`. A purge by any of them drops the copy. A tag the\n * header cannot carry is left out, and said once: the copy then goes stale on\n * its own time, not on that change.\n */\nexport function cacheTagHeader(tags: readonly string[]): string | null {\n const kept = tags.filter((tag) => TAG.test(tag));\n\n if (kept.length < tags.length && !warnedTag) {\n warnedTag = true;\n const bad = tags.find((tag) => !TAG.test(tag));\n console.warn(\n `[rsc-kit] cache() tag ${JSON.stringify(bad)} cannot go in a Cache-Tag header (a comma, a space or a non-ASCII letter), so a CDN cannot purge by it.`,\n );\n }\n\n return kept.length ? kept.join(\",\") : null;\n}\n\nasync function etagOf(body: ArrayBuffer): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", body));\n let hex = \"\";\n\n for (let i = 0; i < 12; i++) hex += digest[i].toString(16).padStart(2, \"0\");\n\n return `\"${hex}\"`;\n}\n\nfunction matches(ifNoneMatch: string | null, etag: string): boolean {\n if (!ifNoneMatch) return false;\n\n return ifNoneMatch\n .split(\",\")\n .map((tag) => tag.trim().replace(/^W\\//, \"\"))\n .some((tag) => tag === etag || tag === \"*\");\n}\n\n/**\n * Finish the answer to a `revalidate` page: rendered whole, then judged.\n *\n * Called inside the request's scope, after every header the request will get\n * is on the answer - cookies included - so what it judges is what is sent.\n * Reading the body to its end is what waits for the render: a Suspense'd\n * child that reads cookies() is still running when the headers exist.\n */\nexport async function finishCacheable(\n request: Request,\n response: Response,\n entry: PageCaching,\n /**\n * Whether the answer turned out to be not-found.tsx, asked once the body is\n * read: a page can say notFound() in the middle of its stream, after a 200\n * went out. A payload is a 200 either way - the router reads the page from\n * it - but a not-found one is kept no longer than a 404.\n */\n saidNotFound: () => boolean = () => false,\n): Promise<Response> {\n if (entry.refused) return bypass(response, response.body, entry, entry.refused);\n\n if (response.status !== 200 && response.status !== 404) return bypass(response, response.body, entry, \"status\");\n\n const type = response.headers.get(\"Content-Type\") ?? \"\";\n\n if (!type.startsWith(\"text/html\") && !type.startsWith(\"text/x-component\")) {\n return bypass(response, response.body, entry, \"status\");\n }\n\n const body = await response.arrayBuffer();\n const refused =\n readRefusal() ??\n (response.headers.getSetCookie().length > 0 ? \"set-cookie\" : null) ??\n (/'nonce-/.test(response.headers.get(\"Content-Security-Policy\") ?? \"\") ? \"nonce\" : null);\n\n if (refused) return bypass(response, body, entry, refused);\n\n const headers = new Headers(response.headers);\n const etag = await etagOf(body);\n\n const status = saidNotFound() ? 404 : response.status;\n\n headers.set(\"Cache-Control\", publicCacheControl(entry.revalidate, status));\n headers.set(\"CDN-Cache-Control\", cdnCacheControl(entry.revalidate, status));\n headers.set(\"ETag\", etag);\n\n const tags = cacheTagHeader(cacheTagsRead());\n\n if (tags) headers.set(\"Cache-Tag\", tags);\n\n const kept: Keepable = { status: response.status, body, versions: cacheTagVersionsRead(), revalidate: entry.revalidate, notFound: saidNotFound() };\n\n if (response.status === 200 && matches(request.headers.get(\"If-None-Match\"), etag)) {\n headers.delete(\"Content-Length\");\n\n const answer = new Response(null, { status: 304, headers });\n\n keepable.set(answer, kept);\n\n return answer;\n }\n\n const answer = new Response(request.method === \"HEAD\" ? null : body, { status: response.status, statusText: response.statusText, headers });\n\n keepable.set(answer, kept);\n\n return answer;\n}\n\n// The engine's own copy of a public page: ISR on every host.\n//\n// A kept page is versioned, not purged. Its entry carries the version of\n// every tag its cache() answers were read under, and a lookup asks the\n// version source whether any moved since. changed(tag) bumps a version every\n// instance reads, so every pod misses at its next request with nothing sent\n// to it - and a render that was running when the change landed is stored\n// under the older version, so it is never served. Correctness needs only a\n// version source every instance shares; the store decides how often a page\n// is rendered, never whether a stale one is served.\n\n/** What finishCacheable() sent public, kept beside the answer for the page cache to store. */\ninterface Keepable {\n status: number;\n body: ArrayBuffer;\n versions: Record<string, number>;\n revalidate: number;\n /** A not-found page, kept no longer than a 404. */\n notFound: boolean;\n}\n\nconst keepable = new WeakMap<Response, Keepable>();\n\n/**\n * The body finishCacheable read to its end, for a caller that needs the whole\n * document after it - a 304 carries none of its own.\n */\nexport function keptBodyOf(answer: Response): ArrayBuffer | undefined {\n return keepable.get(answer)?.body;\n}\n\n/** A kept page, as the store holds it. */\ninterface KeptPage {\n /** Status. */\n s: number;\n /** Headers, as name and value pairs. */\n h: [string, string][];\n /** Body, as text: HTML and Flight both are. */\n b: string;\n /** Tag versions it was rendered under. */\n v: Record<string, number>;\n /** When it was rendered, in ms. */\n at: number;\n /** Seconds it is fresh for. */\n r: number;\n /** Seconds past that it may still be served while one render replaces it. */\n w: number;\n}\n\n/** Headers that belong to one answer, never to the kept page. */\nconst NOT_KEPT = new Set([\"date\", \"set-cookie\", \"content-length\", \"x-rsc-kit\", \"x-powered-by\", \"age\"]);\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\n\n/**\n * Pages kept in this process, by the size of what they hold: a page is tens\n * or hundreds of KB, so a count says nothing about memory. Least recently\n * used goes first.\n */\nexport function pageMemoryStore(maxBytes = 64 * 1024 * 1024): CacheStore {\n const entries = new Map<string, { value: string; until: number }>();\n let bytes = 0;\n\n const drop = (key: string) => {\n const entry = entries.get(key);\n\n if (!entry) return;\n\n entries.delete(key);\n bytes -= entry.value.length;\n };\n\n return {\n get(key) {\n const entry = entries.get(key);\n\n if (!entry) return undefined;\n\n if (entry.until <= Date.now()) {\n drop(key);\n\n return undefined;\n }\n\n // Re-inserted, so the Map's order is least recently used first.\n entries.delete(key);\n entries.set(key, entry);\n\n return entry.value;\n },\n set(key, value, ttl) {\n drop(key);\n\n if (value.length > maxBytes) return;\n\n entries.set(key, { value, until: Date.now() + ttl * 1000 });\n bytes += value.length;\n\n while (bytes > maxBytes) drop(entries.keys().next().value!);\n },\n };\n}\n\n/** A kept answer, and whether it is past its time: served, while one render replaces it. */\nexport interface KeptAnswer {\n response: Response;\n stale: boolean;\n}\n\nexport interface PageCache {\n /** The kept answer for this request, or null to render it now. */\n lookup(key: string, request: Request): Promise<KeptAnswer | null>;\n /** Whether a render for this key is running in this process. */\n busy(key: string): boolean;\n /** Keep the answer, when finishCacheable() sent it public. */\n keep(key: string, answer: Response): Promise<void>;\n /** Run one render per key at a time: a burst for a page nobody has kept waits for the first. */\n once<T>(key: string, render: () => Promise<T>): Promise<{ led: boolean; value?: T }>;\n}\n\nlet warnedPageStore = false;\n\n/** A store that fails is a render, not a broken page: said once. */\nfunction pageStoreFailed(error: unknown): void {\n if (warnedPageStore) return;\n warnedPageStore = true;\n console.warn(\"[rsc-kit] the page cache's store failed, so pages are being rendered each time instead:\", error);\n}\n\n/** The engine's page cache, over a store: the app's, or one of its own in memory. */\nexport function createPageCache(store: CacheStore): PageCache {\n const inFlight = new Map<string, Promise<unknown>>();\n\n return {\n async lookup(key, request) {\n let raw: string | null | undefined;\n\n try {\n raw = await store.get(`rsc-page|${key}`);\n } catch (error) {\n pageStoreFailed(error);\n\n return null;\n }\n\n if (!raw) return null;\n\n let kept: KeptPage;\n\n try {\n kept = JSON.parse(raw);\n } catch {\n return null;\n }\n\n const now = Date.now();\n const age = now - kept.at;\n\n // The store may keep it longer than asked; the age is checked here.\n // Past its time it is still served, for a while, as the stale copy a\n // render in the background replaces: no visitor waits on an expiry.\n if (age >= (kept.r + (kept.w ?? 0)) * 1000) return null;\n\n // A tag that moved is never served stale: whoever changed it is\n // looking for the change, so this request renders.\n if (Object.keys(kept.v).length > 0) {\n try {\n const moved = await versionSource().changed(kept.v, 0);\n\n if (Object.keys(moved).some((tag) => moved[tag] !== kept.v[tag])) return null;\n } catch {\n // Not knowing whether it changed is not knowing it did not.\n return null;\n }\n }\n\n const headers = new Headers(kept.h);\n\n headers.set(\"Age\", String(Math.floor((now - kept.at) / 1000)));\n\n const etag = headers.get(\"ETag\");\n\n const stale = age >= kept.r * 1000;\n\n if (kept.s === 200 && etag && matches(request.headers.get(\"If-None-Match\"), etag)) {\n return { response: new Response(null, { status: 304, headers }), stale };\n }\n\n return { response: new Response(request.method === \"HEAD\" ? null : kept.b, { status: kept.s, headers }), stale };\n },\n\n busy(key) {\n return inFlight.has(key);\n },\n\n async keep(key, answer) {\n const kept = keepable.get(answer);\n\n if (!kept) return;\n\n let body: string;\n\n try {\n body = utf8.decode(kept.body);\n } catch {\n // Not text: sent, never kept.\n return;\n }\n\n const headers: [string, string][] = [];\n\n answer.headers.forEach((value, name) => {\n if (!NOT_KEPT.has(name.toLowerCase())) headers.push([name, value]);\n });\n\n const notFound = kept.status === 404 || kept.notFound;\n const revalidate = notFound ? Math.min(kept.revalidate, NOT_FOUND_LIMIT) : kept.revalidate;\n // The same windows the answer's Cache-Control gives a CDN.\n const window = notFound ? NOT_FOUND_LIMIT : STALE_WINDOW;\n const page: KeptPage = { s: kept.status, h: headers, b: body, v: kept.versions, at: Date.now(), r: revalidate, w: window };\n\n try {\n await store.set(`rsc-page|${key}`, JSON.stringify(page), Math.ceil(revalidate + window));\n } catch (error) {\n pageStoreFailed(error);\n }\n },\n\n async once(key, render) {\n const pending = inFlight.get(key);\n\n if (pending) {\n await pending.catch(() => {});\n\n return { led: false };\n }\n\n const work = render();\n\n inFlight.set(key, work);\n\n try {\n return { led: true, value: await work };\n } finally {\n inFlight.delete(key);\n }\n },\n };\n}\n"]}
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { PrerenderResult } from "./prerender.js";
2
+ import { type ContentSecurityPolicyOptions } from "./csp.js";
2
3
  import type { WebManifestOptions } from "./webManifest.js";
3
4
  import type { Plugin, PluginOption } from "vite";
4
5
  export interface RscKitOptions {
@@ -30,6 +31,22 @@ export interface RscKitOptions {
30
31
  * That is also why only the headers the edge contract allows are accepted.
31
32
  */
32
33
  headers?: Record<string, string>;
34
+ /**
35
+ * A Content-Security-Policy on every page, with what the page's own inline
36
+ * code needs added by the engine: the hash of each inline script and style
37
+ * in a page whose body is whole before it is sent (a stored page, a kept
38
+ * one, a shell), and a nonce, new per response, on one that streams.
39
+ *
40
+ * rscKit({ contentSecurityPolicy: { directives: { 'img-src': ["'self'", 'data:'] } } })
41
+ *
42
+ * `{}` is a strict default: `default-src 'self'; base-uri 'self';
43
+ * object-src 'none'; style-src-attr 'unsafe-inline'`. `reportOnly` sends
44
+ * Content-Security-Policy-Report-Only instead. A static export carries it
45
+ * as a `<meta>`. `vite dev` sends it too, with `'unsafe-eval'` for React's
46
+ * development build. Not together with a Content-Security-Policy in
47
+ * `headers`, which would be the same header twice.
48
+ */
49
+ contentSecurityPolicy?: ContentSecurityPolicyOptions;
33
50
  /**
34
51
  * An OpenAPI document from the route tree, at `/openapi.json`.
35
52
  *