@rshono/core 1.0.0-rc.7 → 1.0.0-rc.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -13
- package/dist/builder/page-files.d.ts.map +1 -1
- package/dist/builder/page-files.js +7 -3
- package/dist/builder/page-files.js.map +1 -1
- package/dist/builder/public-env.d.ts +6 -0
- package/dist/builder/public-env.d.ts.map +1 -1
- package/dist/builder/public-env.js +6 -0
- package/dist/builder/public-env.js.map +1 -1
- package/dist/builder/rspack-config.d.ts.map +1 -1
- package/dist/builder/rspack-config.js +16 -19
- package/dist/builder/rspack-config.js.map +1 -1
- package/dist/cli/dev.d.ts.map +1 -1
- package/dist/cli/dev.js +63 -35
- package/dist/cli/dev.js.map +1 -1
- package/dist/cli/index.js +3 -4
- package/dist/cli/index.js.map +1 -1
- package/dist/config.d.ts +22 -65
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/deploy/contract.d.ts +5 -5
- package/dist/deploy/contract.js.map +1 -1
- package/dist/deploy/filesystem.d.ts.map +1 -1
- package/dist/deploy/filesystem.js +6 -7
- package/dist/deploy/filesystem.js.map +1 -1
- package/dist/deploy/node/runtime.d.ts +5 -5
- package/dist/deploy/node/runtime.d.ts.map +1 -1
- package/dist/deploy/node/runtime.js +7 -11
- package/dist/deploy/node/runtime.js.map +1 -1
- package/dist/deploy/presets.d.ts +2 -6
- package/dist/deploy/presets.d.ts.map +1 -1
- package/dist/deploy/presets.js +2 -6
- package/dist/deploy/presets.js.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/router.d.ts +15 -20
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +2 -3
- package/dist/router.js.map +1 -1
- package/dist/runtime/context.d.ts +53 -45
- package/dist/runtime/context.d.ts.map +1 -1
- package/dist/runtime/context.js +80 -82
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/control.d.ts.map +1 -1
- package/dist/runtime/control.js +7 -0
- package/dist/runtime/control.js.map +1 -1
- package/dist/runtime/dev-protocol.d.ts.map +1 -1
- package/dist/runtime/dev-protocol.js.map +1 -1
- package/dist/runtime/entry.client.js +29 -47
- package/dist/runtime/entry.client.js.map +1 -1
- package/dist/runtime/entry.rsc.d.ts.map +1 -1
- package/dist/runtime/entry.rsc.js +102 -138
- package/dist/runtime/entry.rsc.js.map +1 -1
- package/dist/runtime/flight-inject.d.ts +4 -4
- package/dist/runtime/flight-inject.js +2 -2
- package/dist/runtime/flight-inject.js.map +1 -1
- package/dist/runtime/navigation.js.map +1 -1
- package/dist/runtime/request.d.ts +3 -3
- package/dist/runtime/request.js +3 -3
- package/dist/runtime/request.js.map +1 -1
- package/dist/runtime/server.d.ts +3 -2
- package/dist/runtime/server.d.ts.map +1 -1
- package/dist/runtime/server.js +11 -8
- package/dist/runtime/server.js.map +1 -1
- package/dist/server/prerendered.d.ts +20 -35
- package/dist/server/prerendered.d.ts.map +1 -1
- package/dist/server/prerendered.js +8 -18
- package/dist/server/prerendered.js.map +1 -1
- package/dist/server/server-config.d.ts +10 -29
- package/dist/server/server-config.d.ts.map +1 -1
- package/dist/server/server-config.js +4 -70
- package/dist/server/server-config.js.map +1 -1
- package/dist/server/ssg.d.ts.map +1 -1
- package/dist/server/ssg.js +10 -11
- package/dist/server/ssg.js.map +1 -1
- package/package.json +1 -1
|
@@ -16,10 +16,10 @@
|
|
|
16
16
|
/**
|
|
17
17
|
* {@link Transformer} plus the `cancel` hook the Streams standard added for a cancelled readable side.
|
|
18
18
|
*
|
|
19
|
-
* Node calls it
|
|
20
|
-
* here rather than reached for with an `any`. It matters because `cancel` is the only notification
|
|
21
|
-
* a response ended *without* finishing, and both users of it release a listener that would
|
|
22
|
-
* outlive the request.
|
|
19
|
+
* Node calls it (verified on 22.x) but the bundled lib types have not caught up, so it is declared
|
|
20
|
+
* here rather than reached for with an `any`. It matters because `cancel` is the only notification
|
|
21
|
+
* that a response ended *without* finishing, and both users of it release a listener that would
|
|
22
|
+
* otherwise outlive the request.
|
|
23
23
|
*/
|
|
24
24
|
export type CancellableTransformer<I, O> = Transformer<I, O> & {
|
|
25
25
|
cancel?: (reason?: unknown) => void;
|
|
@@ -39,8 +39,8 @@ function escapeScript(script) {
|
|
|
39
39
|
* The bytes of `chunk` as a latin1 string, which is the form `btoa` takes.
|
|
40
40
|
*
|
|
41
41
|
* Sliced rather than `String.fromCharCode(...chunk)`, which passes one argument per byte and
|
|
42
|
-
* overflows the call stack on a chunk of any size.
|
|
43
|
-
*
|
|
42
|
+
* overflows the call stack on a chunk of any size. The slice width is a stack-safety choice, not a
|
|
43
|
+
* tuned one — this is only reached for a chunk that split a multi-byte character.
|
|
44
44
|
*/
|
|
45
45
|
function latin1(chunk) {
|
|
46
46
|
let out = '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flight-inject.js","sourceRoot":"","sources":["../../src/runtime/flight-inject.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAYH,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,gHAAgH;AAChH,MAAM,OAAO,GAAG,gBAAgB,CAAC;AACjC,MAAM,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AAS9C,MAAM,eAAe,GAAG,OAAO,YAAY,KAAK,UAAU,CAAC;AAC3D,MAAM,QAAQ,GAAmC,eAAe,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5G,MAAM,UAAU,GAAG,CAAC,MAAkB,EAAQ,EAAE;IAC9C,IAAI,eAAe;QAAE,cAAc,CAAC,MAAyC,CAAC,CAAC;;QAC1E,YAAY,CAAC,MAAuC,CAAC,CAAC;AAC7D,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,SAAS,YAAY,CAAC,MAAc;IAClC,OAAO,MAA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OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;YAC9D,CAAC;YAAC,MAAM,CAAC;gBACP,mFAAmF;gBACnF,SAAS,GAAG,IAAI,CAAC;gBACjB,YAAY,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACzC,CAAC;oBAAS,CAAC;gBACT,yFAAyF;gBACzF,+EAA+E;gBAC/E,MAAM,EAAE,EAAE,CAAC;YACb,CAAC;QACH,CAAC;QACD,MAAM,CAAC,MAAM;YACX,SAAS,GAAG,IAAI,CAAC;YACjB,IAAI,QAAQ,EAAE,CAAC;gBACb,UAAU,CAAC,QAAQ,CAAC,CAAC;gBACrB,QAAQ,GAAG,IAAI,CAAC;YAClB,CAAC;YACD,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;YACjB,+FAA+F;YAC/F,yEAAyE;YACzE,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAC7C,4EAA4E;YAC5E,UAAU,EAAE,CAAC;YACb,MAAM,EAAE,EAAE,CAAC;QACb,CAAC;KACF,CAAC;IACF,OAAO,IAAI,eAAe,CAAyB,WAAW,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * Carrying the flight payload inside the HTML document, so the browser hydrates from bytes it\n * already has rather than fetching the page a second time.\n *\n * The wire format is `rsc-html-stream`'s — a run of\n * `<script>(self.__FLIGHT_DATA||=[]).push(\"…\")</script>` tags — but the implementation is\n * first-party, because that package's `injectRSCPayload` tests each HTML chunk for the document\n * trailer with `endsWith`. React's byte writer packs its output into 2 kB views and splits any write\n * that straddles one, so `</body></html>` can arrive as two chunks; upstream then fails to hold it\n * back, and the document ends up with two trailers and the payload script after the first of them.\n * A page's byte layout is deterministic, so that is not an intermittent fault — an unlucky page is\n * malformed on every request. `test/unit.test.mjs` pins the split-trailer cases.\n *\n * The reader for this format is `readFlightPayload` in `entry.client.tsx`.\n */\n\n/**\n * {@link Transformer} plus the `cancel` hook the Streams standard added for a cancelled readable side.\n *\n * Node calls it — verified on 22.x — but the bundled lib types have not caught up, so it is declared\n * here rather than reached for with an `any`. It matters because `cancel` is the only notification that\n * a response ended *without* finishing, and both users of it release a listener that would otherwise\n * outlive the request.\n */\nexport type CancellableTransformer<I, O> = Transformer<I, O> & { cancel?: (reason?: unknown) => void };\n\nconst encoder = new TextEncoder();\n\n/** What React closes an `<html>` document with, and what this module re-emits after the last payload script. */\nconst TRAILER = '</body></html>';\nconst TRAILER_BYTES = encoder.encode(TRAILER);\n\n/**\n * A macrotask boundary. `setImmediate` where there is one (Node, Bun, Deno's node compat), which is\n * the current turn's check phase rather than a timer; `setTimeout` is the portable fallback that\n * every other runtime has. A Node timer has a 1ms floor and every HTML flush would pay it — worth\n * the two lines: uncontended time-to-last-byte on a 30 kB payload, 4.7ms → 3.0ms.\n */\ntype TaskHandle = ReturnType<typeof setTimeout> | ReturnType<typeof setImmediate>;\nconst hasSetImmediate = typeof setImmediate === 'function';\nconst schedule: (fn: () => void) => TaskHandle = hasSetImmediate ? setImmediate : (fn) => setTimeout(fn, 0);\nconst unschedule = (handle: TaskHandle): void => {\n if (hasSetImmediate) clearImmediate(handle as ReturnType<typeof setImmediate>);\n else clearTimeout(handle as ReturnType<typeof setTimeout>);\n};\n\n/**\n * Escapes the two sequences that would end a `<script>` element early.\n *\n * Guarded by an `includes('<')` because a flight payload usually has no `<` in it at all, and the\n * scan is far cheaper than two regex passes over 30 kB. `</script` becomes `</\\script` rather than\n * `<\\/script`, which would break the valid JS `0</script/` (a regexp literal).\n */\nfunction escapeScript(script: string): string {\n return script.includes('<') ? script.replace(/<!--/g, '<\\\\!--').replace(/<\\/(script)/gi, '</\\\\$1') : script;\n}\n\n/**\n * The bytes of `chunk` as a latin1 string, which is the form `btoa` takes.\n *\n * Sliced rather than `String.fromCharCode(...chunk)`, which passes one argument per byte and\n * overflows the call stack on a chunk of any size. Only reached for a chunk that split a multi-byte\n * character, so it is off the hot path and the slice size is a stack-safety choice, not a tuned one.\n */\nfunction latin1(chunk: Uint8Array): string {\n let out = '';\n for (let at = 0; at < chunk.length; at += 8192) out += String.fromCharCode(...chunk.subarray(at, at + 8192));\n return out;\n}\n\n/** Whether `buffer`'s first `length` bytes end with the document trailer. */\nfunction endsWithTrailer(buffer: Uint8Array, length: number): boolean {\n if (length < TRAILER_BYTES.length) return false;\n const from = length - TRAILER_BYTES.length;\n for (let i = 0; i < TRAILER_BYTES.length; i++) {\n if (buffer[from + i] !== TRAILER_BYTES[i]) return false;\n }\n return true;\n}\n\nexport function injectFlightPayload(\n rscStream: ReadableStream<Uint8Array>,\n options: { nonce?: string; onDone?: () => void } = {},\n): TransformStream<Uint8Array, Uint8Array> {\n const { nonce, onDone } = options;\n const scriptOpen = `<script${nonce ? ` nonce=\"${nonce}\"` : ''}>(self.__FLIGHT_DATA||=[]).push(`;\n const scriptClose = ')</script>';\n\n const { promise: flightWritten, resolve: flightDone } = Promise.withResolvers<void>();\n let startedFlight = false;\n\n const batch: Uint8Array[] = [];\n let boundary: TaskHandle | null = null;\n\n /**\n * Set once the consumer has gone away, so nothing downstream tries to enqueue into a readable that\n * can no longer take it.\n *\n * It cannot simply be the `cancel` hook that sets this. Per the Streams standard, cancelling the\n * readable *after* the close algorithm has started returns the pending finish promise without\n * running the transformer's `cancel` at all — and `flush` awaiting the whole flight payload is\n * precisely that window. So a failed enqueue is also treated as the signal, wherever one happens.\n */\n let cancelled = false;\n /** Held so {@link cancelled} can release the teed RSC branch rather than leaving it to be pumped. */\n let flightReader: ReadableStreamDefaultReader<Uint8Array> | null = null;\n\n /**\n * Emits the HTML buffered since the last boundary, holding back the document trailer for\n * {@link TransformStream.flush} to re-emit after the payload scripts.\n *\n * The batch is joined before the trailer is looked for, so a trailer React split across two views\n * is still found — that is the whole reason this module is not `rsc-html-stream/server`. React\n * writes its final flush in one synchronous run, so every chunk of the trailer lands in the same\n * batch; a trailer split *across* batches is not a shape React produces.\n */\n function emitBatch(controller: TransformStreamDefaultController<Uint8Array>): void {\n boundary = null;\n let total = 0;\n for (const chunk of batch) total += chunk.byteLength;\n if (total === 0) {\n batch.length = 0;\n return;\n }\n\n const joined = new Uint8Array(total);\n let at = 0;\n for (const chunk of batch) {\n joined.set(chunk, at);\n at += chunk.byteLength;\n }\n batch.length = 0;\n\n const end = endsWithTrailer(joined, total) ? total - TRAILER_BYTES.length : total;\n if (end > 0) controller.enqueue(joined.subarray(0, end));\n }\n\n async function writeFlight(controller: TransformStreamDefaultController<Uint8Array>): Promise<void> {\n const reader = (flightReader = rscStream.getReader());\n // `fatal`, so a chunk that split a multi-byte character throws rather than emitting U+FFFD and\n // corrupting the payload — the catch below falls back to a byte-exact encoding for it.\n const decoder = new TextDecoder('utf-8', { fatal: true });\n const push = (literal: string) => controller.enqueue(encoder.encode(scriptOpen + literal + scriptClose));\n for (;;) {\n if (cancelled) return;\n const { done, value } = await reader.read();\n if (done) break;\n // Only the *decode* is guarded. Wrapping the `push` in the same `try` conflated a split\n // multi-byte character with a controller nobody is reading any more, and answered the second by\n // re-encoding the chunk and enqueueing it again — which throws in turn, out of the catch.\n let literal: string;\n try {\n literal = escapeScript(JSON.stringify(decoder.decode(value, { stream: true })));\n } catch {\n literal = `Uint8Array.from(atob(${JSON.stringify(btoa(latin1(value)))}), m => m.codePointAt(0))`;\n }\n if (cancelled) return;\n // A failed enqueue means the consumer is gone. Stop pumping and release the RSC branch, so\n // `flush` unparks now rather than whenever the flight payload would have ended on its own.\n try {\n push(literal);\n } catch {\n cancelled = true;\n reader.cancel().catch(() => {});\n return;\n }\n }\n if (cancelled) return;\n const remaining = decoder.decode();\n if (remaining.length) push(escapeScript(JSON.stringify(remaining)));\n }\n\n const transformer: CancellableTransformer<Uint8Array, Uint8Array> = {\n transform(chunk, controller) {\n batch.push(chunk);\n if (boundary) return;\n // A macrotask, not a microtask: React writes a whole flush into its stream in one synchronous\n // run, but `pipeThrough` delivers those chunks to us one microtask at a time. Only a task\n // boundary guarantees the flush has arrived in full — a script injected between two of its\n // chunks would land inside a tag.\n boundary = schedule(() => {\n try {\n emitBatch(controller);\n } catch (error) {\n controller.error(error);\n flightDone();\n return;\n }\n if (!startedFlight) {\n startedFlight = true;\n writeFlight(controller)\n .catch((error) => controller.error(error))\n .then(flightDone);\n }\n });\n },\n async flush(controller) {\n await flightWritten;\n // That await spans the entire flight payload, and the consumer can go away inside it — a\n // browser's stop button, a navigation away, a proxy timeout. `cancel` below is *not* what tells\n // us so (see `cancelled`), which leaves the enqueue throwing `ERR_INVALID_STATE` as the only\n // signal. Unguarded it rejects `flush`, and nothing owns that rejection: it surfaces as an\n // unhandled one and, where the host does not swallow it, takes the process down.\n try {\n if (boundary) {\n unschedule(boundary);\n emitBatch(controller);\n }\n if (!cancelled) controller.enqueue(encoder.encode(TRAILER));\n } catch {\n // Nowhere left to put the trailer. A response the client abandoned is not a fault.\n cancelled = true;\n flightReader?.cancel().catch(() => {});\n } finally {\n // Unconditional, and the reason this is a `finally`: `onDone` is what releases the abort\n // forwarder in `renderComponent`, so it has to run however the response ended.\n onDone?.();\n }\n },\n cancel(reason) {\n cancelled = true;\n if (boundary) {\n unschedule(boundary);\n boundary = null;\n }\n batch.length = 0;\n // Without this the teed RSC branch keeps being pumped for a response nobody will read, and the\n // tee's other half buffers every chunk waiting for this one to catch up.\n flightReader?.cancel(reason).catch(() => {});\n // Unparks `flush` if it is waiting on a payload that will now never arrive.\n flightDone();\n onDone?.();\n },\n };\n return new TransformStream<Uint8Array, Uint8Array>(transformer);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flight-inject.js","sourceRoot":"","sources":["../../src/runtime/flight-inject.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAYH,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,gHAAgH;AAChH,MAAM,OAAO,GAAG,gBAAgB,CAAC;AACjC,MAAM,aAAa,GAAG,OAAO,CAAC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AAyB,WAAW,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * Carrying the flight payload inside the HTML document, so the browser hydrates from bytes it\n * already has rather than fetching the page a second time.\n *\n * The wire format is `rsc-html-stream`'s — a run of\n * `<script>(self.__FLIGHT_DATA||=[]).push(\"…\")</script>` tags — but the implementation is\n * first-party, because that package's `injectRSCPayload` tests each HTML chunk for the document\n * trailer with `endsWith`. React's byte writer packs its output into 2 kB views and splits any write\n * that straddles one, so `</body></html>` can arrive as two chunks; upstream then fails to hold it\n * back, and the document ends up with two trailers and the payload script after the first of them.\n * A page's byte layout is deterministic, so that is not an intermittent fault — an unlucky page is\n * malformed on every request. `test/unit.test.mjs` pins the split-trailer cases.\n *\n * The reader for this format is `readFlightPayload` in `entry.client.tsx`.\n */\n\n/**\n * {@link Transformer} plus the `cancel` hook the Streams standard added for a cancelled readable side.\n *\n * Node calls it (verified on 22.x) but the bundled lib types have not caught up, so it is declared\n * here rather than reached for with an `any`. It matters because `cancel` is the only notification\n * that a response ended *without* finishing, and both users of it release a listener that would\n * otherwise outlive the request.\n */\nexport type CancellableTransformer<I, O> = Transformer<I, O> & { cancel?: (reason?: unknown) => void };\n\nconst encoder = new TextEncoder();\n\n/** What React closes an `<html>` document with, and what this module re-emits after the last payload script. */\nconst TRAILER = '</body></html>';\nconst TRAILER_BYTES = encoder.encode(TRAILER);\n\n/**\n * A macrotask boundary. `setImmediate` where there is one (Node, Bun, Deno's node compat), which is\n * the current turn's check phase rather than a timer; `setTimeout` is the portable fallback that\n * every other runtime has. A Node timer has a 1ms floor and every HTML flush would pay it — worth\n * the two lines: uncontended time-to-last-byte on a 30 kB payload, 4.7ms → 3.0ms.\n */\ntype TaskHandle = ReturnType<typeof setTimeout> | ReturnType<typeof setImmediate>;\nconst hasSetImmediate = typeof setImmediate === 'function';\nconst schedule: (fn: () => void) => TaskHandle = hasSetImmediate ? setImmediate : (fn) => setTimeout(fn, 0);\nconst unschedule = (handle: TaskHandle): void => {\n if (hasSetImmediate) clearImmediate(handle as ReturnType<typeof setImmediate>);\n else clearTimeout(handle as ReturnType<typeof setTimeout>);\n};\n\n/**\n * Escapes the two sequences that would end a `<script>` element early.\n *\n * Guarded by an `includes('<')` because a flight payload usually has no `<` in it at all, and the\n * scan is far cheaper than two regex passes over 30 kB. `</script` becomes `</\\script` rather than\n * `<\\/script`, which would break the valid JS `0</script/` (a regexp literal).\n */\nfunction escapeScript(script: string): string {\n return script.includes('<') ? script.replace(/<!--/g, '<\\\\!--').replace(/<\\/(script)/gi, '</\\\\$1') : script;\n}\n\n/**\n * The bytes of `chunk` as a latin1 string, which is the form `btoa` takes.\n *\n * Sliced rather than `String.fromCharCode(...chunk)`, which passes one argument per byte and\n * overflows the call stack on a chunk of any size. The slice width is a stack-safety choice, not a\n * tuned one — this is only reached for a chunk that split a multi-byte character.\n */\nfunction latin1(chunk: Uint8Array): string {\n let out = '';\n for (let at = 0; at < chunk.length; at += 8192) out += String.fromCharCode(...chunk.subarray(at, at + 8192));\n return out;\n}\n\n/** Whether `buffer`'s first `length` bytes end with the document trailer. */\nfunction endsWithTrailer(buffer: Uint8Array, length: number): boolean {\n if (length < TRAILER_BYTES.length) return false;\n const from = length - TRAILER_BYTES.length;\n for (let i = 0; i < TRAILER_BYTES.length; i++) {\n if (buffer[from + i] !== TRAILER_BYTES[i]) return false;\n }\n return true;\n}\n\nexport function injectFlightPayload(\n rscStream: ReadableStream<Uint8Array>,\n options: { nonce?: string; onDone?: () => void } = {},\n): TransformStream<Uint8Array, Uint8Array> {\n const { nonce, onDone } = options;\n const scriptOpen = `<script${nonce ? ` nonce=\"${nonce}\"` : ''}>(self.__FLIGHT_DATA||=[]).push(`;\n const scriptClose = ')</script>';\n\n const { promise: flightWritten, resolve: flightDone } = Promise.withResolvers<void>();\n let startedFlight = false;\n\n const batch: Uint8Array[] = [];\n let boundary: TaskHandle | null = null;\n\n /**\n * Set once the consumer has gone away, so nothing downstream tries to enqueue into a readable that\n * can no longer take it.\n *\n * It cannot simply be the `cancel` hook that sets this. Per the Streams standard, cancelling the\n * readable *after* the close algorithm has started returns the pending finish promise without\n * running the transformer's `cancel` at all — and `flush` awaiting the whole flight payload is\n * precisely that window. So a failed enqueue is also treated as the signal, wherever one happens.\n */\n let cancelled = false;\n /** Held so {@link cancelled} can release the teed RSC branch rather than leaving it to be pumped. */\n let flightReader: ReadableStreamDefaultReader<Uint8Array> | null = null;\n\n /**\n * Emits the HTML buffered since the last boundary, holding back the document trailer for\n * {@link TransformStream.flush} to re-emit after the payload scripts.\n *\n * The batch is joined before the trailer is looked for, so a trailer React split across two views\n * is still found — that is the whole reason this module is not `rsc-html-stream/server`. React\n * writes its final flush in one synchronous run, so every chunk of the trailer lands in the same\n * batch; a trailer split *across* batches is not a shape React produces.\n */\n function emitBatch(controller: TransformStreamDefaultController<Uint8Array>): void {\n boundary = null;\n let total = 0;\n for (const chunk of batch) total += chunk.byteLength;\n if (total === 0) {\n batch.length = 0;\n return;\n }\n\n const joined = new Uint8Array(total);\n let at = 0;\n for (const chunk of batch) {\n joined.set(chunk, at);\n at += chunk.byteLength;\n }\n batch.length = 0;\n\n const end = endsWithTrailer(joined, total) ? total - TRAILER_BYTES.length : total;\n if (end > 0) controller.enqueue(joined.subarray(0, end));\n }\n\n async function writeFlight(controller: TransformStreamDefaultController<Uint8Array>): Promise<void> {\n const reader = (flightReader = rscStream.getReader());\n // `fatal`, so a chunk that split a multi-byte character throws rather than emitting U+FFFD and\n // corrupting the payload — the catch below falls back to a byte-exact encoding for it.\n const decoder = new TextDecoder('utf-8', { fatal: true });\n const push = (literal: string) => controller.enqueue(encoder.encode(scriptOpen + literal + scriptClose));\n for (;;) {\n if (cancelled) return;\n const { done, value } = await reader.read();\n if (done) break;\n // Only the *decode* is guarded. Wrapping the `push` in the same `try` conflated a split\n // multi-byte character with a controller nobody is reading any more, and answered the second by\n // re-encoding the chunk and enqueueing it again — which throws in turn, out of the catch.\n let literal: string;\n try {\n literal = escapeScript(JSON.stringify(decoder.decode(value, { stream: true })));\n } catch {\n literal = `Uint8Array.from(atob(${JSON.stringify(btoa(latin1(value)))}), m => m.codePointAt(0))`;\n }\n if (cancelled) return;\n // A failed enqueue means the consumer is gone. Stop pumping and release the RSC branch, so\n // `flush` unparks now rather than whenever the flight payload would have ended on its own.\n try {\n push(literal);\n } catch {\n cancelled = true;\n reader.cancel().catch(() => {});\n return;\n }\n }\n if (cancelled) return;\n const remaining = decoder.decode();\n if (remaining.length) push(escapeScript(JSON.stringify(remaining)));\n }\n\n const transformer: CancellableTransformer<Uint8Array, Uint8Array> = {\n transform(chunk, controller) {\n batch.push(chunk);\n if (boundary) return;\n // A macrotask, not a microtask: React writes a whole flush into its stream in one synchronous\n // run, but `pipeThrough` delivers those chunks to us one microtask at a time. Only a task\n // boundary guarantees the flush has arrived in full — a script injected between two of its\n // chunks would land inside a tag.\n boundary = schedule(() => {\n try {\n emitBatch(controller);\n } catch (error) {\n controller.error(error);\n flightDone();\n return;\n }\n if (!startedFlight) {\n startedFlight = true;\n writeFlight(controller)\n .catch((error) => controller.error(error))\n .then(flightDone);\n }\n });\n },\n async flush(controller) {\n await flightWritten;\n // That await spans the entire flight payload, and the consumer can go away inside it — a\n // browser's stop button, a navigation away, a proxy timeout. `cancel` below is *not* what tells\n // us so (see `cancelled`), which leaves the enqueue throwing `ERR_INVALID_STATE` as the only\n // signal. Unguarded it rejects `flush`, and nothing owns that rejection: it surfaces as an\n // unhandled one and, where the host does not swallow it, takes the process down.\n try {\n if (boundary) {\n unschedule(boundary);\n emitBatch(controller);\n }\n if (!cancelled) controller.enqueue(encoder.encode(TRAILER));\n } catch {\n // Nowhere left to put the trailer. A response the client abandoned is not a fault.\n cancelled = true;\n flightReader?.cancel().catch(() => {});\n } finally {\n // Unconditional, and the reason this is a `finally`: `onDone` is what releases the abort\n // forwarder in `renderComponent`, so it has to run however the response ended.\n onDone?.();\n }\n },\n cancel(reason) {\n cancelled = true;\n if (boundary) {\n unschedule(boundary);\n boundary = null;\n }\n batch.length = 0;\n // Without this the teed RSC branch keeps being pumped for a response nobody will read, and the\n // tee's other half buffers every chunk waiting for this one to catch up.\n flightReader?.cancel(reason).catch(() => {});\n // Unparks `flush` if it is waiting on a payload that will now never arrive.\n flightDone();\n onDone?.();\n },\n };\n return new TransformStream<Uint8Array, Uint8Array>(transformer);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"navigation.js","sourceRoot":"","sources":["../../src/runtime/navigation.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,OAAO,EAAkB,MAAM,OAAO,CAAC;AA6C3E,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC;AAEtB,MAAM,aAAa,GAAqB,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAErG;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAmB,aAAa,CAAC,CAAC;AAE5E,MAAM,iBAAiB,GAAG,aAAa,CAAyB,IAAI,CAAC,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAyE;IAC9H,MAAM,MAAM,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;IACzC,MAAM,KAAK,GAAG,OAAO,CAAkB,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI,GAAG,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAE/G,OAAO,KAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA8B,CAAC;AAC3F,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,UAAU,aAAa;IAC3B,MAAM,KAAK,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;IAC5C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,mKAAmK,CACpK,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["'use client';\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react';\n\n/**\n * Imperative navigation actions, reached as `useNavigation().router`.\n *\n * `push` / `replace` / `refresh` are **soft** navigations: the new page's flight\n * payload is fetched and applied in place, so client component state outside the\n * changed subtree survives. Off-site or non-HTTP hrefs fall back to a full load.\n *\n * @example\n * ```tsx\n * const { router } = useNavigation();\n * router.push('/dashboard'); // navigate, new history entry\n * router.replace('/login'); // navigate, no new entry\n * router.refresh(); // re-run this route's server components\n * ```\n */\nexport interface NavigationRouter {\n /** Navigates to `href` and pushes a new history entry. */\n push(href: string): void;\n /** Navigates to `href`, replacing the current history entry instead of adding one. */\n replace(href: string): void;\n /** Re-fetches the current route from the server, re-running its server components. */\n refresh(): void;\n /** `true` while a soft navigation is in flight — use it to disable controls or show a spinner. */\n pending: boolean;\n}\n\n// No `back()` / `forward()
|
|
1
|
+
{"version":3,"file":"navigation.js","sourceRoot":"","sources":["../../src/runtime/navigation.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,OAAO,EAAkB,MAAM,OAAO,CAAC;AA6C3E,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC;AAEtB,MAAM,aAAa,GAAqB,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAErG;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAmB,aAAa,CAAC,CAAC;AAE5E,MAAM,iBAAiB,GAAG,aAAa,CAAyB,IAAI,CAAC,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAyE;IAC9H,MAAM,MAAM,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;IACzC,MAAM,KAAK,GAAG,OAAO,CAAkB,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI,GAAG,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAE/G,OAAO,KAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA8B,CAAC;AAC3F,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,UAAU,aAAa;IAC3B,MAAM,KAAK,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;IAC5C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,mKAAmK,CACpK,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["'use client';\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react';\n\n/**\n * Imperative navigation actions, reached as `useNavigation().router`.\n *\n * `push` / `replace` / `refresh` are **soft** navigations: the new page's flight\n * payload is fetched and applied in place, so client component state outside the\n * changed subtree survives. Off-site or non-HTTP hrefs fall back to a full load.\n *\n * @example\n * ```tsx\n * const { router } = useNavigation();\n * router.push('/dashboard'); // navigate, new history entry\n * router.replace('/login'); // navigate, no new entry\n * router.refresh(); // re-run this route's server components\n * ```\n */\nexport interface NavigationRouter {\n /** Navigates to `href` and pushes a new history entry. */\n push(href: string): void;\n /** Navigates to `href`, replacing the current history entry instead of adding one. */\n replace(href: string): void;\n /** Re-fetches the current route from the server, re-running its server components. */\n refresh(): void;\n /** `true` while a soft navigation is in flight — use it to disable controls or show a spinner. */\n pending: boolean;\n}\n\n// No `back()` / `forward()` — `history.back()` and `history.forward()` need no framework, and the\n// traversal is picked up by the runtime's `popstate` listener either way.\n\n/** The current location plus the {@link NavigationRouter}, as returned by {@link useNavigation}. */\nexport interface NavigationState {\n /**\n * The full current {@link URL} — read `url.pathname`, `url.searchParams` and the\n * rest off it. A fresh instance per navigation, so mutating it affects nothing\n * else; it is not written back to the address bar either.\n */\n url: URL;\n /** Matched route params for the current page, e.g. `{ id: '42' }` for `/profile/:id`. */\n params: Record<string, string>;\n /** Imperative navigation actions and the `pending` flag. */\n router: NavigationRouter;\n}\n\nconst noop = () => {};\n\nconst defaultRouter: NavigationRouter = { push: noop, replace: noop, refresh: noop, pending: false };\n\n/**\n * Carries the live {@link NavigationRouter} implementation from the hydration runtime down\n * to {@link RouterProvider}. Framework internal — read the router through\n * {@link useNavigation} instead.\n *\n * @internal\n */\nexport const RouterContext = createContext<NavigationRouter>(defaultRouter);\n\nconst NavigationContext = createContext<NavigationState | null>(null);\n\n/**\n * Publishes the per-render location and params so {@link useNavigation} can read\n * them. Framework internal — the RSC entry wraps every page in one.\n *\n * @internal\n */\nexport function RouterProvider({ href, params, children }: { href: string; params: Record<string, string>; children: ReactNode }) {\n const router = useContext(RouterContext);\n const value = useMemo<NavigationState>(() => ({ url: new URL(href), params, router }), [href, params, router]);\n\n return <NavigationContext.Provider value={value}>{children}</NavigationContext.Provider>;\n}\n\n/**\n * Reactive access to the current URL and programmatic navigation, in one hook.\n *\n * Call it from a `'use client'` component. The location fields (`url` and\n * `params`) are computed on the server and travel in the flight payload, so they\n * are correct during SSR — no hydration flicker — and update automatically on\n * every navigation. The `router` sub-object holds the imperative actions plus a\n * `pending` flag that is `true` while a client navigation is in flight.\n *\n * Hooks can't run in a server component; read the same URL data there from\n * `getRequestContext()` (`@rshono/core/server`) instead.\n *\n * @example\n * ```tsx\n * 'use client';\n * import { useNavigation } from '@rshono/core/client';\n *\n * export function NextPage() {\n * const { url, router } = useNavigation();\n * const page = Number(url.searchParams.get('page') ?? '1');\n * return (\n * <button disabled={router.pending} onClick={() => router.push(`${url.pathname}?page=${page + 1}`)}>\n * Next {router.pending ? '…' : ''}\n * </button>\n * );\n * }\n * ```\n *\n * @returns The current {@link NavigationState}: `url` and `params`, plus `router`\n * ({@link NavigationRouter}) with `push` / `replace` / `refresh` / `pending`.\n * @throws If called outside a page's React tree, where there is no navigation\n * context to read.\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreclient | Docs — `@rshono/core/client`}\n * @see {@link https://www.rshono.com/docs/pages#client-components | Docs — client components}\n */\nexport function useNavigation(): NavigationState {\n const value = useContext(NavigationContext);\n if (!value) {\n throw new Error(\n \"[rshono] useNavigation() must be called inside a 'use client' component rendered by a page. In a server component, read the URL from getRequestContext() instead.\",\n );\n }\n return value;\n}\n"]}
|
|
@@ -29,9 +29,9 @@ export declare function acceptsRsc(request: Request): boolean;
|
|
|
29
29
|
/** True when the response should be a flight payload rather than an HTML document. */
|
|
30
30
|
export declare function wantsRsc(renderRequest: RenderRequest): boolean;
|
|
31
31
|
/**
|
|
32
|
-
* {@link wantsRsc} straight off the request, for the error and control-signal paths that have no
|
|
33
|
-
* {@link RenderRequest} to hand — they are reached from Hono's `onError` / `notFound
|
|
34
|
-
*
|
|
32
|
+
* {@link wantsRsc} straight off the request, for the error and control-signal paths that have no
|
|
33
|
+
* parsed {@link RenderRequest} to hand — they are reached from Hono's `onError` / `notFound` rather
|
|
34
|
+
* than from the render.
|
|
35
35
|
*/
|
|
36
36
|
export declare function requestWantsRsc(request: Request): boolean;
|
|
37
37
|
/** True when the request carries a server action to run before rendering. */
|
package/dist/runtime/request.js
CHANGED
|
@@ -33,9 +33,9 @@ export function wantsRsc(renderRequest) {
|
|
|
33
33
|
return renderRequest.kind === 'rsc' || renderRequest.kind === 'rsc-action';
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
|
-
* {@link wantsRsc} straight off the request, for the error and control-signal paths that have no
|
|
37
|
-
* {@link RenderRequest} to hand — they are reached from Hono's `onError` / `notFound
|
|
38
|
-
*
|
|
36
|
+
* {@link wantsRsc} straight off the request, for the error and control-signal paths that have no
|
|
37
|
+
* parsed {@link RenderRequest} to hand — they are reached from Hono's `onError` / `notFound` rather
|
|
38
|
+
* than from the render.
|
|
39
39
|
*/
|
|
40
40
|
export function requestWantsRsc(request) {
|
|
41
41
|
return wantsRsc(parseRenderRequest(request));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","sourceRoot":"","sources":["../../src/runtime/request.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAgB,GAAG,cAAc,CAAC;AACxC,MAAM,gBAAgB,GAAG,kBAAkB,CAAC;AAc5C,uHAAuH;AACvH,MAAM,UAAU,gBAAgB,CAAC,SAAiB,EAAE,MAAuC;IACzF,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAChD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,EAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC,CAAC;IAC1D,IAAI,MAAM;QAAE,OAAO,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IACrD,OAAO,IAAI,OAAO,CAAC,GAAG,EAAE;QACtB,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK;QAC/B,OAAO;QACP,IAAI,EAAE,MAAM,EAAE,IAAI;KACnB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,kBAAkB,GAAG,+DAA+D,CAAC;AAE3F,MAAM,UAAU,kBAAkB,CAAC,OAAgB;IACjD,IAAI,OAAO,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;QAC9B,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QACvD,IAAI,QAAQ;YAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC;QACtD,IAAI,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;YAAE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC;QACvG,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;IAC9B,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC;AAC5D,CAAC;AAED,gHAAgH;AAChH,MAAM,UAAU,UAAU,CAAC,OAAgB;IACzC,OAAO,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC,gBAAgB,CAAC,IAAI,KAAK,CAAC;AAC5E,CAAC;AAED,sFAAsF;AACtF,MAAM,UAAU,QAAQ,CAAC,aAA4B;IACnD,OAAO,aAAa,CAAC,IAAI,KAAK,KAAK,IAAI,aAAa,CAAC,IAAI,KAAK,YAAY,CAAC;AAC7E,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,OAAgB;IAC9C,OAAO,QAAQ,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,eAAe,CAAC,aAA4B;IAC1D,OAAO,aAAa,CAAC,IAAI,KAAK,aAAa,IAAI,aAAa,CAAC,IAAI,KAAK,YAAY,CAAC;AACrF,CAAC","sourcesContent":["const HEADER_ACTION_ID = 'x-rsc-action';\nconst RSC_CONTENT_TYPE = 'text/x-component';\n\n/**\n * The four distinct shapes an incoming render request can take, modeled as a\n * discriminated union so illegal combinations (e.g. an action id on a GET) are\n * unrepresentable and every consumer dispatches exhaustively on `kind`.\n *\n * - `document` — a normal navigation; respond with a full SSR HTML document.\n * - `rsc` — a soft-navigation flight fetch (`Accept: text/x-component`).\n * - `form-action` — a progressive-enhancement `<form>` POST (no JavaScript).\n * - `rsc-action` — a client-initiated server-action call carrying an action id.\n */\nexport type RenderRequest = { kind: 'document' } | { kind: 'rsc' } | { kind: 'form-action' } | { kind: 'rsc-action'; actionId: string };\n\n/** Builds the `Request` the client sends to ask a page for its flight payload, optionally carrying a server action. */\nexport function createRscRequest(urlString: string, action?: { id: string; body: BodyInit }): Request {\n const url = new URL(urlString, location.origin);\n const headers = new Headers({ Accept: RSC_CONTENT_TYPE });\n if (action) headers.set(HEADER_ACTION_ID, action.id);\n return new Request(url, {\n method: action ? 'POST' : 'GET',\n headers,\n body: action?.body,\n });\n}\n\nconst FORM_CONTENT_TYPES = /^(?:multipart\\/form-data|application\\/x-www-form-urlencoded)/i;\n\nexport function parseRenderRequest(request: Request): RenderRequest {\n if (request.method === 'POST') {\n const actionId = request.headers.get(HEADER_ACTION_ID);\n if (actionId) return { kind: 'rsc-action', actionId };\n if (FORM_CONTENT_TYPES.test(request.headers.get('content-type') ?? '')) return { kind: 'form-action' };\n return { kind: 'document' };\n }\n return { kind: acceptsRsc(request) ? 'rsc' : 'document' };\n}\n\n/** Whether the client asked for a flight payload. For GET paths that only need the boolean, without parsing. */\nexport function acceptsRsc(request: Request): boolean {\n return request.headers.get('accept')?.includes(RSC_CONTENT_TYPE) ?? false;\n}\n\n/** True when the response should be a flight payload rather than an HTML document. */\nexport function wantsRsc(renderRequest: RenderRequest): boolean {\n return renderRequest.kind === 'rsc' || renderRequest.kind === 'rsc-action';\n}\n\n/**\n * {@link wantsRsc} straight off the request, for the error and control-signal paths that have no
|
|
1
|
+
{"version":3,"file":"request.js","sourceRoot":"","sources":["../../src/runtime/request.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAgB,GAAG,cAAc,CAAC;AACxC,MAAM,gBAAgB,GAAG,kBAAkB,CAAC;AAc5C,uHAAuH;AACvH,MAAM,UAAU,gBAAgB,CAAC,SAAiB,E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,CAAC,gBAAgB,CAAC,IAAI,KAAK,CAAC;AAC5E,CAAC;AAED,sFAAsF;AACtF,MAAM,UAAU,QAAQ,CAAC,aAA4B;IACnD,OAAO,aAAa,CAAC,IAAI,KAAK,KAAK,IAAI,aAAa,CAAC,IAAI,KAAK,YAAY,CAAC;AAC7E,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,OAAgB;IAC9C,OAAO,QAAQ,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,eAAe,CAAC,aAA4B;IAC1D,OAAO,aAAa,CAAC,IAAI,KAAK,aAAa,IAAI,aAAa,CAAC,IAAI,KAAK,YAAY,CAAC;AACrF,CAAC","sourcesContent":["const HEADER_ACTION_ID = 'x-rsc-action';\nconst RSC_CONTENT_TYPE = 'text/x-component';\n\n/**\n * The four distinct shapes an incoming render request can take, modeled as a\n * discriminated union so illegal combinations (e.g. an action id on a GET) are\n * unrepresentable and every consumer dispatches exhaustively on `kind`.\n *\n * - `document` — a normal navigation; respond with a full SSR HTML document.\n * - `rsc` — a soft-navigation flight fetch (`Accept: text/x-component`).\n * - `form-action` — a progressive-enhancement `<form>` POST (no JavaScript).\n * - `rsc-action` — a client-initiated server-action call carrying an action id.\n */\nexport type RenderRequest = { kind: 'document' } | { kind: 'rsc' } | { kind: 'form-action' } | { kind: 'rsc-action'; actionId: string };\n\n/** Builds the `Request` the client sends to ask a page for its flight payload, optionally carrying a server action. */\nexport function createRscRequest(urlString: string, action?: { id: string; body: BodyInit }): Request {\n const url = new URL(urlString, location.origin);\n const headers = new Headers({ Accept: RSC_CONTENT_TYPE });\n if (action) headers.set(HEADER_ACTION_ID, action.id);\n return new Request(url, {\n method: action ? 'POST' : 'GET',\n headers,\n body: action?.body,\n });\n}\n\nconst FORM_CONTENT_TYPES = /^(?:multipart\\/form-data|application\\/x-www-form-urlencoded)/i;\n\nexport function parseRenderRequest(request: Request): RenderRequest {\n if (request.method === 'POST') {\n const actionId = request.headers.get(HEADER_ACTION_ID);\n if (actionId) return { kind: 'rsc-action', actionId };\n if (FORM_CONTENT_TYPES.test(request.headers.get('content-type') ?? '')) return { kind: 'form-action' };\n return { kind: 'document' };\n }\n return { kind: acceptsRsc(request) ? 'rsc' : 'document' };\n}\n\n/** Whether the client asked for a flight payload. For GET paths that only need the boolean, without parsing. */\nexport function acceptsRsc(request: Request): boolean {\n return request.headers.get('accept')?.includes(RSC_CONTENT_TYPE) ?? false;\n}\n\n/** True when the response should be a flight payload rather than an HTML document. */\nexport function wantsRsc(renderRequest: RenderRequest): boolean {\n return renderRequest.kind === 'rsc' || renderRequest.kind === 'rsc-action';\n}\n\n/**\n * {@link wantsRsc} straight off the request, for the error and control-signal paths that have no\n * parsed {@link RenderRequest} to hand — they are reached from Hono's `onError` / `notFound` rather\n * than from the render.\n */\nexport function requestWantsRsc(request: Request): boolean {\n return wantsRsc(parseRenderRequest(request));\n}\n\n/** True when the request carries a server action to run before rendering. */\nexport function isActionRequest(renderRequest: RenderRequest): renderRequest is Extract<RenderRequest, { kind: 'form-action' | 'rsc-action' }> {\n return renderRequest.kind === 'form-action' || renderRequest.kind === 'rsc-action';\n}\n"]}
|
package/dist/runtime/server.d.ts
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* and `'use server'` action modules: `getRequestContext()` for the URL, cookies,
|
|
4
4
|
* params, env and middleware variables, the `redirect()` and `notFound()`
|
|
5
5
|
* control-flow helpers, and `onServerError()` for reporting the errors the
|
|
6
|
-
* framework catches.
|
|
6
|
+
* framework catches. Plus `publicUrl(c)`, for middleware in `src/server.ts`, which
|
|
7
|
+
* is handed Hono's `c` rather than a request context.
|
|
7
8
|
*
|
|
8
9
|
* Server-only. Importing this from a `'use client'` module is a mistake — those
|
|
9
10
|
* run in the browser (and are SSR'd without a bound context). Read what you need
|
|
@@ -14,5 +15,5 @@
|
|
|
14
15
|
*
|
|
15
16
|
* @packageDocumentation
|
|
16
17
|
*/
|
|
17
|
-
export { getRequestContext, notFound, onServerError, redirect, type EnvVars, type RedirectStatus, type RequestContext, type ServerErrorContext, type ServerErrorHandler, type ServerErrorSource, } from './context.js';
|
|
18
|
+
export { getRequestContext, notFound, onServerError, publicUrl, redirect, type EnvVars, type RedirectStatus, type RequestContext, type ServerErrorContext, type ServerErrorHandler, type ServerErrorSource, } from './context.js';
|
|
18
19
|
//# sourceMappingURL=server.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/runtime/server.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/runtime/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAMH,OAAO,EACL,iBAAiB,EACjB,QAAQ,EACR,aAAa,EAIb,SAAS,EACT,QAAQ,EACR,KAAK,OAAO,EACZ,KAAK,cAAc,EAGnB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,GACvB,MAAM,cAAc,CAAC"}
|
package/dist/runtime/server.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* and `'use server'` action modules: `getRequestContext()` for the URL, cookies,
|
|
4
4
|
* params, env and middleware variables, the `redirect()` and `notFound()`
|
|
5
5
|
* control-flow helpers, and `onServerError()` for reporting the errors the
|
|
6
|
-
* framework catches.
|
|
6
|
+
* framework catches. Plus `publicUrl(c)`, for middleware in `src/server.ts`, which
|
|
7
|
+
* is handed Hono's `c` rather than a request context.
|
|
7
8
|
*
|
|
8
9
|
* Server-only. Importing this from a `'use client'` module is a mistake — those
|
|
9
10
|
* run in the browser (and are SSR'd without a bound context). Read what you need
|
|
@@ -14,11 +15,13 @@
|
|
|
14
15
|
*
|
|
15
16
|
* @packageDocumentation
|
|
16
17
|
*/
|
|
17
|
-
// A barrel rather than `./
|
|
18
|
-
// also exports the
|
|
19
|
-
// `
|
|
20
|
-
//
|
|
21
|
-
|
|
22
|
-
//
|
|
23
|
-
|
|
18
|
+
// A barrel rather than pointing the `./server` subpath straight at `./context.js`, where all of this
|
|
19
|
+
// is implemented: that module also exports the framework's own plumbing (`runWithContext`,
|
|
20
|
+
// `readParams`, `reportServerError`), and exposing it would put every one of those in a consumer's
|
|
21
|
+
// autocomplete and under semver. They stay reachable by relative import.
|
|
22
|
+
export { getRequestContext, notFound, onServerError,
|
|
23
|
+
// For middleware, which is handed Hono's `c` and so has no request context to read a URL from.
|
|
24
|
+
// Hono's own middleware all resolve the origin from `c.req.url`, which is the internal address
|
|
25
|
+
// behind a proxy — this is what `trustProxy` means to them.
|
|
26
|
+
publicUrl, redirect, } from './context.js';
|
|
24
27
|
//# sourceMappingURL=server.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/runtime/server.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/runtime/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,qGAAqG;AACrG,2FAA2F;AAC3F,mGAAmG;AACnG,yEAAyE;AACzE,OAAO,EACL,iBAAiB,EACjB,QAAQ,EACR,aAAa;AACb,+FAA+F;AAC/F,+FAA+F;AAC/F,4DAA4D;AAC5D,SAAS,EACT,QAAQ,GAST,MAAM,cAAc,CAAC","sourcesContent":["/**\n * `@rshono/core/server` — the request-scoped surface, for use inside server components\n * and `'use server'` action modules: `getRequestContext()` for the URL, cookies,\n * params, env and middleware variables, the `redirect()` and `notFound()`\n * control-flow helpers, and `onServerError()` for reporting the errors the\n * framework catches. Plus `publicUrl(c)`, for middleware in `src/server.ts`, which\n * is handed Hono's `c` rather than a request context.\n *\n * Server-only. Importing this from a `'use client'` module is a mistake — those\n * run in the browser (and are SSR'd without a bound context). Read what you need\n * on the server and pass it down as props, or use `useNavigation()` from\n * `@rshono/core/client` for URL data.\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n *\n * @packageDocumentation\n */\n\n// A barrel rather than pointing the `./server` subpath straight at `./context.js`, where all of this\n// is implemented: that module also exports the framework's own plumbing (`runWithContext`,\n// `readParams`, `reportServerError`), and exposing it would put every one of those in a consumer's\n// autocomplete and under semver. They stay reachable by relative import.\nexport {\n getRequestContext,\n notFound,\n onServerError,\n // For middleware, which is handed Hono's `c` and so has no request context to read a URL from.\n // Hono's own middleware all resolve the origin from `c.req.url`, which is the internal address\n // behind a proxy — this is what `trustProxy` means to them.\n publicUrl,\n redirect,\n type EnvVars,\n type RedirectStatus,\n // A type, not a value: `RequestContext` is handed to you by `getRequestContext()` or the `ctx` page\n // prop — one instance per request — and is never constructed by application code.\n type RequestContext,\n type ServerErrorContext,\n type ServerErrorHandler,\n type ServerErrorSource,\n} from './context.js';\n"]}
|
|
@@ -7,11 +7,9 @@
|
|
|
7
7
|
* it from the fs module would drag `node:fs` and `node:crypto` into a bundle that has neither.
|
|
8
8
|
*/
|
|
9
9
|
/**
|
|
10
|
-
* The two representations of a page, prerendered side by side
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* Writing only the HTML meant every in-app click re-rendered a page that was already built, so the
|
|
14
|
-
* prerender only ever paid off for cold loads and crawlers.
|
|
10
|
+
* The two representations of a page, prerendered side by side: a hard load wants the HTML document, a
|
|
11
|
+
* soft navigation asks the same URL for a flight payload. Without both, every in-app click would
|
|
12
|
+
* re-render a page that was already built.
|
|
15
13
|
*/
|
|
16
14
|
export type PrerenderVariant = 'html' | 'flight';
|
|
17
15
|
export declare const VARIANTS: {
|
|
@@ -45,37 +43,27 @@ export declare function prerenderedRelPath(requestPath: string, variant: Prerend
|
|
|
45
43
|
/**
|
|
46
44
|
* A bounded, insertion-ordered cache of prerendered pages.
|
|
47
45
|
*
|
|
48
|
-
* Bounded so a site with thousands of prerendered pages keeps a working set rather than the whole
|
|
49
|
-
* in memory. Only *hits* are ever stored: caching misses would let anyone mint entries by
|
|
50
|
-
* paths that don't exist. The files are written at build time and never change while the
|
|
51
|
-
* so an entry never needs invalidating.
|
|
52
|
-
*
|
|
53
|
-
* Shared because both targets need exactly this and had a hand-rolled copy of it, down to the same
|
|
54
|
-
* eviction line.
|
|
46
|
+
* Bounded so a site with thousands of prerendered pages keeps a working set rather than the whole
|
|
47
|
+
* build in memory. Only *hits* are ever stored: caching misses would let anyone mint entries by
|
|
48
|
+
* requesting paths that don't exist. The files are written at build time and never change while the
|
|
49
|
+
* server is up, so an entry never needs invalidating.
|
|
55
50
|
*/
|
|
56
51
|
export declare function createPageCache(max?: number): {
|
|
57
52
|
get(key: string): PrerenderedPage | undefined;
|
|
58
53
|
set(key: string, page: PrerenderedPage): void;
|
|
59
54
|
};
|
|
60
55
|
/**
|
|
61
|
-
* A weak `ETag` for a page body.
|
|
56
|
+
* A weak `ETag` for a page body — see {@link PrerenderedPage.etag} for why weak.
|
|
62
57
|
*
|
|
63
58
|
* Web Crypto rather than `node:crypto`, so the one implementation serves both a Node server and
|
|
64
|
-
* `workerd
|
|
65
|
-
* conversion, purely because the other one reached for a Node builtin.
|
|
66
|
-
*
|
|
67
|
-
* Deliberately **weak**: the bytes on the wire depend on whether the client took gzip, and a strong
|
|
68
|
-
* validator would have to differ between those two — so the 200 and the 304 that revalidates it would
|
|
69
|
-
* disagree, and a cache would treat them as different pages. A weak tag says "the same
|
|
70
|
-
* representation", which is exactly what is true across content codings.
|
|
59
|
+
* `workerd`.
|
|
71
60
|
*/
|
|
72
61
|
export declare function weakEtag(body: Uint8Array<ArrayBuffer>): Promise<string>;
|
|
73
62
|
/**
|
|
74
63
|
* Assembles a {@link PrerenderedPage} from a body just read out of the build.
|
|
75
64
|
*
|
|
76
|
-
* `storeEtag` is the validator the store supplied, where it has one — it already describes these
|
|
77
|
-
* bytes, so it is preferred over hashing them again, and only weakened.
|
|
78
|
-
* their own copy of this before, with two different digest implementations.
|
|
65
|
+
* `storeEtag` is the validator the store supplied, where it has one — it already describes these
|
|
66
|
+
* exact bytes, so it is preferred over hashing them again, and only weakened.
|
|
79
67
|
*/
|
|
80
68
|
export declare function toPrerenderedPage(body: Uint8Array<ArrayBuffer>, storeEtag?: string | null): Promise<PrerenderedPage>;
|
|
81
69
|
/** A prerendered page, ready to serve: its body and a validator derived from those exact bytes. */
|
|
@@ -84,26 +72,23 @@ export interface PrerenderedPage {
|
|
|
84
72
|
* The document or the flight payload, depending on which {@link PrerenderVariant} was read.
|
|
85
73
|
*
|
|
86
74
|
* Bytes rather than a string, because this is a *cache* entry served verbatim to every request that
|
|
87
|
-
* hits it
|
|
88
|
-
* way out
|
|
89
|
-
* re-encoding bytes it had already encoded once to measure them. Read once, encoded never.
|
|
75
|
+
* hits it — held as a string, each of those would pay a fresh UTF-8 encode of the whole page on the
|
|
76
|
+
* way out. Read once, encoded never.
|
|
90
77
|
*/
|
|
91
78
|
body: Uint8Array<ArrayBuffer>;
|
|
92
79
|
/**
|
|
93
|
-
* `Content-Length` for {@link body}, in bytes rather than characters.
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
* front is entitled to make decisions with it — whether gzipping this response is worth the framing,
|
|
97
|
-
* most obviously.
|
|
80
|
+
* `Content-Length` for {@link body}, in bytes rather than characters. Served explicitly because
|
|
81
|
+
* Hono sets no length for an in-memory body, and a proxy or CDN in front is entitled to make
|
|
82
|
+
* decisions with it — whether gzipping this response is worth the framing, most obviously.
|
|
98
83
|
*/
|
|
99
84
|
contentLength: string;
|
|
100
85
|
/**
|
|
101
86
|
* `ETag` for the page, so a revalidating client can be answered with a 304 instead of the body.
|
|
102
87
|
*
|
|
103
|
-
* Deliberately **weak**. The bytes on the wire depend on whether something in front re-encoded
|
|
104
|
-
* and a strong validator would have to differ per coding — so the 200 and the 304 that
|
|
105
|
-
* could disagree, and a cache would treat them as different pages. A weak tag says
|
|
106
|
-
* representation", which is
|
|
88
|
+
* Deliberately **weak**. The bytes on the wire depend on whether something in front re-encoded
|
|
89
|
+
* them, and a strong validator would have to differ per coding — so the 200 and the 304 that
|
|
90
|
+
* revalidates it could disagree, and a cache would treat them as different pages. A weak tag says
|
|
91
|
+
* "the same representation", which is what stays true across content codings.
|
|
107
92
|
*/
|
|
108
93
|
etag: string;
|
|
109
94
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerendered.d.ts","sourceRoot":"","sources":["../../src/server/prerendered.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH
|
|
1
|
+
{"version":3,"file":"prerendered.d.ts","sourceRoot":"","sources":["../../src/server/prerendered.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEjD,eAAO,MAAM,QAAQ;;iBACX,IAAI,EAAE,YAAY;iBAAE,MAAM,EAAE,WAAW;iBAAE,WAAW,EAAE,WAAW;;;iBAC/D,IAAI,EAAE,WAAW;iBAAE,MAAM,EAAE,kBAAkB;iBAAE,WAAW,EAAE,kBAAkB;;CACU,CAAC;AAErG;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAyB,GAAG,MAAM,GAAG,IAAI,CAKhG;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,MAAM,GAAG,IAAI,CAGhG;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,GAAG,SAAM,GAAG;IAAE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAAC;IAAC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe,GAAG,IAAI,CAAA;CAAE,CAU3I;AAED;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAO7E;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,eAAe,CAAC,CAM1H;AAED,mGAAmG;AACnG,MAAM,WAAW,eAAe;IAC9B;;;;;;OAMG;IACH,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IAC9B;;;;OAIG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;;;;;;OAOG;IACH,IAAI,EAAE,MAAM,CAAC;CACd"}
|
|
@@ -39,13 +39,10 @@ export function prerenderedRelPath(requestPath, variant) {
|
|
|
39
39
|
/**
|
|
40
40
|
* A bounded, insertion-ordered cache of prerendered pages.
|
|
41
41
|
*
|
|
42
|
-
* Bounded so a site with thousands of prerendered pages keeps a working set rather than the whole
|
|
43
|
-
* in memory. Only *hits* are ever stored: caching misses would let anyone mint entries by
|
|
44
|
-
* paths that don't exist. The files are written at build time and never change while the
|
|
45
|
-
* so an entry never needs invalidating.
|
|
46
|
-
*
|
|
47
|
-
* Shared because both targets need exactly this and had a hand-rolled copy of it, down to the same
|
|
48
|
-
* eviction line.
|
|
42
|
+
* Bounded so a site with thousands of prerendered pages keeps a working set rather than the whole
|
|
43
|
+
* build in memory. Only *hits* are ever stored: caching misses would let anyone mint entries by
|
|
44
|
+
* requesting paths that don't exist. The files are written at build time and never change while the
|
|
45
|
+
* server is up, so an entry never needs invalidating.
|
|
49
46
|
*/
|
|
50
47
|
export function createPageCache(max = 128) {
|
|
51
48
|
const pages = new Map();
|
|
@@ -60,16 +57,10 @@ export function createPageCache(max = 128) {
|
|
|
60
57
|
};
|
|
61
58
|
}
|
|
62
59
|
/**
|
|
63
|
-
* A weak `ETag` for a page body.
|
|
60
|
+
* A weak `ETag` for a page body — see {@link PrerenderedPage.etag} for why weak.
|
|
64
61
|
*
|
|
65
62
|
* Web Crypto rather than `node:crypto`, so the one implementation serves both a Node server and
|
|
66
|
-
* `workerd
|
|
67
|
-
* conversion, purely because the other one reached for a Node builtin.
|
|
68
|
-
*
|
|
69
|
-
* Deliberately **weak**: the bytes on the wire depend on whether the client took gzip, and a strong
|
|
70
|
-
* validator would have to differ between those two — so the 200 and the 304 that revalidates it would
|
|
71
|
-
* disagree, and a cache would treat them as different pages. A weak tag says "the same
|
|
72
|
-
* representation", which is exactly what is true across content codings.
|
|
63
|
+
* `workerd`.
|
|
73
64
|
*/
|
|
74
65
|
export async function weakEtag(body) {
|
|
75
66
|
const digest = await crypto.subtle.digest('SHA-256', body);
|
|
@@ -82,9 +73,8 @@ export async function weakEtag(body) {
|
|
|
82
73
|
/**
|
|
83
74
|
* Assembles a {@link PrerenderedPage} from a body just read out of the build.
|
|
84
75
|
*
|
|
85
|
-
* `storeEtag` is the validator the store supplied, where it has one — it already describes these
|
|
86
|
-
* bytes, so it is preferred over hashing them again, and only weakened.
|
|
87
|
-
* their own copy of this before, with two different digest implementations.
|
|
76
|
+
* `storeEtag` is the validator the store supplied, where it has one — it already describes these
|
|
77
|
+
* exact bytes, so it is preferred over hashing them again, and only weakened.
|
|
88
78
|
*/
|
|
89
79
|
export async function toPrerenderedPage(body, storeEtag) {
|
|
90
80
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerendered.js","sourceRoot":"","sources":["../../src/server/prerendered.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;
|
|
1
|
+
{"version":3,"file":"prerendered.js","sourceRoot":"","sources":["../../src/server/prerendered.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AASH,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,IAAI,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE;IAC3E,MAAM,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EA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,CAAC,IAA6B;IAC1D,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAC3D,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;SACnE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACtB,OAAO,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC;AACzC,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,IAA6B,EAAE,SAAyB;IAC9F,OAAO;QACL,IAAI;QACJ,aAAa,EAAE,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC;QACtC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,QAAQ,CAAC,IAAI,CAAC;KAC7E,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Everything about a prerendered page that doesn't need a filesystem: where the build puts it, and\n * what it looks like once read back.\n *\n * Split out of `ssg.ts` — which owns the writing and the reading, both through `node:fs` — because a\n * deploy target without a filesystem reads the very same layout out of an asset store, and importing\n * it from the fs module would drag `node:fs` and `node:crypto` into a bundle that has neither.\n */\n\n/**\n * The two representations of a page, prerendered side by side: a hard load wants the HTML document, a\n * soft navigation asks the same URL for a flight payload. Without both, every in-app click would\n * re-render a page that was already built.\n */\nexport type PrerenderVariant = 'html' | 'flight';\n\nexport const VARIANTS = {\n html: { file: 'index.html', accept: 'text/html', contentType: 'text/html' },\n flight: { file: 'index.rsc', accept: 'text/x-component', contentType: 'text/x-component' },\n} as const satisfies Record<PrerenderVariant, { file: string; accept: string; contentType: string }>;\n\n/**\n * Where a route's prerendered output lives, relative to the output root — or `null` for a path that\n * cannot be prerendered at all (one with a param or a wildcard left in it).\n *\n * Always `/`-separated, never the host's separator: the same string addresses a file on a filesystem\n * (`resolve()` and `join()` both accept forward slashes on Windows) and a key in an asset store,\n * where a backslash would simply be the wrong character.\n */\nexport function ssgFilePath(routePath: string, variant: PrerenderVariant = 'html'): string | null {\n if (/[:*]/.test(routePath)) return null;\n const trimmed = routePath.replace(/^\\/+|\\/+$/g, '');\n const file = VARIANTS[variant].file;\n return trimmed === '' ? file : `${trimmed}/${file}`;\n}\n\n/**\n * {@link ssgFilePath} for a path that came off a request, so traversal is a miss rather than a lookup.\n *\n * The first line of defence for every deploy target: a store addressed by key has no `resolve()` to\n * fall back on, so `..` has to be refused here or not at all.\n */\nexport function prerenderedRelPath(requestPath: string, variant: PrerenderVariant): string | null {\n if (/(^|\\/)\\.\\.?(\\/|$)/.test(requestPath)) return null;\n return ssgFilePath(requestPath, variant);\n}\n\n/**\n * A bounded, insertion-ordered cache of prerendered pages.\n *\n * Bounded so a site with thousands of prerendered pages keeps a working set rather than the whole\n * build in memory. Only *hits* are ever stored: caching misses would let anyone mint entries by\n * requesting paths that don't exist. The files are written at build time and never change while the\n * server is up, so an entry never needs invalidating.\n */\nexport function createPageCache(max = 128): { get(key: string): PrerenderedPage | undefined; set(key: string, page: PrerenderedPage): void } {\n const pages = new Map<string, PrerenderedPage>();\n return {\n get: (key) => pages.get(key),\n set(key, page) {\n pages.set(key, page);\n // Insertion-ordered, so the first key is the oldest. One entry in means at most one out.\n if (pages.size > max) pages.delete(pages.keys().next().value!);\n },\n };\n}\n\n/**\n * A weak `ETag` for a page body — see {@link PrerenderedPage.etag} for why weak.\n *\n * Web Crypto rather than `node:crypto`, so the one implementation serves both a Node server and\n * `workerd`.\n */\nexport async function weakEtag(body: Uint8Array<ArrayBuffer>): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', body);\n const base64url = btoa(String.fromCharCode(...new Uint8Array(digest)))\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n return `W/\"${base64url.slice(0, 22)}\"`;\n}\n\n/**\n * Assembles a {@link PrerenderedPage} from a body just read out of the build.\n *\n * `storeEtag` is the validator the store supplied, where it has one — it already describes these\n * exact bytes, so it is preferred over hashing them again, and only weakened.\n */\nexport async function toPrerenderedPage(body: Uint8Array<ArrayBuffer>, storeEtag?: string | null): Promise<PrerenderedPage> {\n return {\n body,\n contentLength: String(body.byteLength),\n etag: storeEtag ? storeEtag.replace(/^(?!W\\/)/, 'W/') : await weakEtag(body),\n };\n}\n\n/** A prerendered page, ready to serve: its body and a validator derived from those exact bytes. */\nexport interface PrerenderedPage {\n /**\n * The document or the flight payload, depending on which {@link PrerenderVariant} was read.\n *\n * Bytes rather than a string, because this is a *cache* entry served verbatim to every request that\n * hits it — held as a string, each of those would pay a fresh UTF-8 encode of the whole page on the\n * way out. Read once, encoded never.\n */\n body: Uint8Array<ArrayBuffer>;\n /**\n * `Content-Length` for {@link body}, in bytes rather than characters. Served explicitly because\n * Hono sets no length for an in-memory body, and a proxy or CDN in front is entitled to make\n * decisions with it — whether gzipping this response is worth the framing, most obviously.\n */\n contentLength: string;\n /**\n * `ETag` for the page, so a revalidating client can be answered with a 304 instead of the body.\n *\n * Deliberately **weak**. The bytes on the wire depend on whether something in front re-encoded\n * them, and a strong validator would have to differ per coding — so the 200 and the 304 that\n * revalidates it could disagree, and a cache would treat them as different pages. A weak tag says\n * \"the same representation\", which is what stays true across content codings.\n */\n etag: string;\n}\n"]}
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import type { RshonoConfig } from '../config.js';
|
|
2
2
|
/**
|
|
3
|
-
* The framework settings the server bundle needs at request time, fully resolved
|
|
4
|
-
* (defaults applied, `bodySizeLimit` parsed to bytes, origins normalized to hosts).
|
|
3
|
+
* The framework settings the server bundle needs at request time, fully resolved.
|
|
5
4
|
*
|
|
6
5
|
* The value is produced once by {@link resolveServerConfig} from `rshono.config.ts`
|
|
7
6
|
* and compiled into the server bundle as the `__RSHONO_CONFIG__` literal (see
|
|
8
7
|
* `builder/rspack-config.ts`) — there is no runtime env-var interface for these.
|
|
8
|
+
*
|
|
9
|
+
* Only two fields, because only two things here are decided by the *build*. The per-request
|
|
10
|
+
* security controls that used to live alongside them — the CSRF check, the CSP, the body cap — are
|
|
11
|
+
* Hono middleware an app registers in `src/server.ts`, where they can be configured per route and
|
|
12
|
+
* per environment instead of once per bundle.
|
|
9
13
|
*/
|
|
10
14
|
export interface ServerConfig {
|
|
11
15
|
/**
|
|
@@ -17,41 +21,18 @@ export interface ServerConfig {
|
|
|
17
21
|
isDev: boolean;
|
|
18
22
|
/** Honour `X-Forwarded-Host` / `-Proto` when resolving the browser-facing URL. Forced on in dev. */
|
|
19
23
|
trustProxy: boolean;
|
|
20
|
-
/** Send a strict per-request-nonce Content-Security-Policy with every HTML document. */
|
|
21
|
-
cspEnabled: boolean;
|
|
22
|
-
/** The resolved CSP directives (built-in defaults with the user's merged over them), minus the nonce. */
|
|
23
|
-
cspDirectives: Record<string, string>;
|
|
24
|
-
/** CSRF origin check on server-action POSTs. */
|
|
25
|
-
checkOrigin: boolean;
|
|
26
|
-
/** Extra origins allowed to post server actions, normalized to lowercase `URL.host` values. */
|
|
27
|
-
allowedOrigins: string[];
|
|
28
|
-
/** Max request body in bytes before a 413; `0` disables the cap. */
|
|
29
|
-
maxBodyBytes: number;
|
|
30
24
|
}
|
|
31
25
|
/**
|
|
32
|
-
* The
|
|
26
|
+
* The framework's built-in defaults.
|
|
33
27
|
*
|
|
34
|
-
* `
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* default both fall back to. A config field for them would have been a fourth precedence level for
|
|
38
|
-
* one number, overridden by the environment on every host that matters.
|
|
28
|
+
* `port` and `host` are not config fields at all — they come from `PORT` / `HOST` (or `--port`)
|
|
29
|
+
* wherever the address is resolved, `deploy/node/runtime.ts` for a server bundle and `cli/dev.ts`
|
|
30
|
+
* for the dev server, and this is what both fall back to.
|
|
39
31
|
*/
|
|
40
32
|
export declare const SERVER_DEFAULTS: {
|
|
41
|
-
readonly maxBodyBytes: number;
|
|
42
33
|
readonly port: 3000;
|
|
43
34
|
readonly host: '0.0.0.0';
|
|
44
35
|
};
|
|
45
|
-
/**
|
|
46
|
-
* The built-in {@link RshonoConfig.csp} policy, keyed by directive so
|
|
47
|
-
* {@link RshonoConfig.cspDirectives} can override entries individually.
|
|
48
|
-
*
|
|
49
|
-
* `script-src` carries the per-request nonce, appended at request time (see `entry.rsc.tsx`).
|
|
50
|
-
* `style-src` needs `'unsafe-inline'` because React writes inline styles.
|
|
51
|
-
*/
|
|
52
|
-
export declare const CSP_DEFAULTS: Record<string, string>;
|
|
53
|
-
/** Parse a {@link RshonoConfig.bodySizeLimit} value into a byte count (`false`/`0` → `0`, disabling the cap). */
|
|
54
|
-
export declare function parseByteSize(value: string | number | false | undefined): number | undefined;
|
|
55
36
|
/**
|
|
56
37
|
* Resolve the user's {@link RshonoConfig} into the {@link ServerConfig} baked into the bundle.
|
|
57
38
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-config.d.ts","sourceRoot":"","sources":["../../src/server/server-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD
|
|
1
|
+
{"version":3,"file":"server-config.d.ts","sourceRoot":"","sources":["../../src/server/server-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;OAKG;IACH,KAAK,EAAE,OAAO,CAAC;IACf,oGAAoG;IACpG,UAAU,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe;aAC1B,IAAI,EAAE,IAAI;aACV,IAAI,EAAE,SAAS;CACP,CAAC;AAEX;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,OAAO,CAAA;CAAE,GAAG,YAAY,CAKrG"}
|