@timber-js/app 0.2.0-alpha.219 → 0.2.0-alpha.220

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.
Files changed (164) hide show
  1. package/dist/_chunks/chains-CDK1AWZQ.js +1 -0
  2. package/dist/_chunks/{chains-YKZ8WpIW.js → chains-e_Buf9vg.js} +2 -7
  3. package/dist/_chunks/{chains-YKZ8WpIW.js.map → chains-e_Buf9vg.js.map} +1 -1
  4. package/dist/_chunks/{cli-check-D2WtbNqo.js → cli-check-DDwCkeDY.js} +2 -2
  5. package/dist/_chunks/{cli-check-D2WtbNqo.js.map → cli-check-DDwCkeDY.js.map} +1 -1
  6. package/dist/_chunks/cli-context-BJQB6rtF.js +1 -0
  7. package/dist/_chunks/{cli-context-By7k2xVo.js → cli-context-_mPttGGY.js} +3 -3
  8. package/dist/_chunks/{cli-context-By7k2xVo.js.map → cli-context-_mPttGGY.js.map} +1 -1
  9. package/dist/_chunks/{cli-schema-sync-CySLKrO3.js → cli-schema-sync-BdIebmk3.js} +3 -12
  10. package/dist/_chunks/{cli-schema-sync-CySLKrO3.js.map → cli-schema-sync-BdIebmk3.js.map} +1 -1
  11. package/dist/_chunks/cli-schema-sync-CLNfXQDK.js +1 -0
  12. package/dist/_chunks/dev-server-DkytOEG2.js +1 -0
  13. package/dist/_chunks/{dev-server-B8zsT-ee.js → dev-server-DnODXuNM.js} +31 -14
  14. package/dist/_chunks/{dev-server-B8zsT-ee.js.map → dev-server-DnODXuNM.js.map} +1 -1
  15. package/dist/_chunks/flight-source-node-0dE-t3kq.js +519 -0
  16. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +1 -0
  17. package/dist/_chunks/{live-graph-BhtrZpRd.js → live-graph-tSWrv8eH.js} +2 -2
  18. package/dist/_chunks/{live-graph-BhtrZpRd.js.map → live-graph-tSWrv8eH.js.map} +1 -1
  19. package/dist/_chunks/node-response-Dibufw_b.js +187 -0
  20. package/dist/_chunks/node-response-Dibufw_b.js.map +1 -0
  21. package/dist/_chunks/{plugin-context-BPBPc3lL.js → plugin-context-DxMMvjUt.js} +2 -18
  22. package/dist/_chunks/{plugin-context-BPBPc3lL.js.map → plugin-context-DxMMvjUt.js.map} +1 -1
  23. package/dist/_chunks/plugin-context-uDHFqHHJ.js +1 -0
  24. package/dist/_chunks/{walkers-Ber9bamD.js → walkers-qu8TpiLh.js} +2 -2
  25. package/dist/_chunks/{walkers-Ber9bamD.js.map → walkers-qu8TpiLh.js.map} +1 -1
  26. package/dist/adapters/nitro-preview.d.ts.map +1 -1
  27. package/dist/adapters/nitro.js +40 -1
  28. package/dist/adapters/nitro.js.map +1 -1
  29. package/dist/analyze/crawl-entry.js +2 -2
  30. package/dist/analyze/graph-command.js +3 -3
  31. package/dist/analyze/graph-command.js.map +1 -1
  32. package/dist/cli.js +5 -5
  33. package/dist/cli.js.map +1 -1
  34. package/dist/client/browser-entry/form-state.d.ts.map +1 -1
  35. package/dist/client/browser-entry/index.d.ts +1 -1
  36. package/dist/client/browser-entry/rsc-stream.d.ts +4 -1
  37. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -1
  38. package/dist/client/react-root.d.ts +6 -0
  39. package/dist/client/react-root.d.ts.map +1 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +36 -5
  42. package/dist/index.js.map +1 -1
  43. package/dist/plugins/encryption-runtime.d.ts +13 -0
  44. package/dist/plugins/encryption-runtime.d.ts.map +1 -0
  45. package/dist/plugins/entries.d.ts +1 -0
  46. package/dist/plugins/entries.d.ts.map +1 -1
  47. package/dist/plugins/server-bundle.d.ts +1 -1
  48. package/dist/plugins/server-bundle.d.ts.map +1 -1
  49. package/dist/routing/index.js +1 -1
  50. package/dist/rsc-runtime/encryption-runtime.d.ts +25 -0
  51. package/dist/rsc-runtime/encryption-runtime.d.ts.map +1 -0
  52. package/dist/rsc-runtime/render-flight.d.ts +14 -0
  53. package/dist/rsc-runtime/render-flight.d.ts.map +1 -0
  54. package/dist/rsc-runtime/rsc.d.ts +6 -2
  55. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  56. package/dist/rsc-runtime/ssr.d.ts +6 -12
  57. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  58. package/dist/server/action-handler.d.ts.map +1 -1
  59. package/dist/server/compress.d.ts +2 -0
  60. package/dist/server/compress.d.ts.map +1 -1
  61. package/dist/server/deny-renderer.d.ts +2 -1
  62. package/dist/server/deny-renderer.d.ts.map +1 -1
  63. package/dist/server/flight-injector-core.d.ts +125 -0
  64. package/dist/server/flight-injector-core.d.ts.map +1 -0
  65. package/dist/server/flight-scripts.d.ts +9 -0
  66. package/dist/server/flight-scripts.d.ts.map +1 -1
  67. package/dist/server/flight-source-node.d.ts +105 -0
  68. package/dist/server/flight-source-node.d.ts.map +1 -0
  69. package/dist/server/flight-source.d.ts +136 -0
  70. package/dist/server/flight-source.d.ts.map +1 -0
  71. package/dist/server/head-response.d.ts.map +1 -1
  72. package/dist/server/html-injector-core.d.ts +3 -91
  73. package/dist/server/html-injector-core.d.ts.map +1 -1
  74. package/dist/server/html-injectors.d.ts +5 -17
  75. package/dist/server/html-injectors.d.ts.map +1 -1
  76. package/dist/server/internal.js +78 -138
  77. package/dist/server/internal.js.map +1 -1
  78. package/dist/server/node-body-response.d.ts +55 -0
  79. package/dist/server/node-body-response.d.ts.map +1 -0
  80. package/dist/server/node-response.d.ts +62 -0
  81. package/dist/server/node-response.d.ts.map +1 -0
  82. package/dist/server/node-stream-transforms.d.ts +24 -21
  83. package/dist/server/node-stream-transforms.d.ts.map +1 -1
  84. package/dist/server/node-streams-platform.d.ts +21 -0
  85. package/dist/server/node-streams-platform.d.ts.map +1 -0
  86. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  87. package/dist/server/pipeline.d.ts.map +1 -1
  88. package/dist/server/prebuilt-runtime.d.ts +2 -3
  89. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  90. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  91. package/dist/server/rsc-entry/render-route.d.ts +4 -1
  92. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  93. package/dist/server/rsc-entry/rsc-payload.d.ts +9 -6
  94. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  95. package/dist/server/rsc-entry/rsc-stream.d.ts +9 -4
  96. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  97. package/dist/server/rsc-entry/ssr-bridge.d.ts +2 -1
  98. package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
  99. package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -1
  100. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  101. package/dist/server/ssr-bridge-types.d.ts +9 -4
  102. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  103. package/dist/server/ssr-entry.d.ts +8 -5
  104. package/dist/server/ssr-entry.d.ts.map +1 -1
  105. package/dist/server/ssr-render.d.ts +7 -16
  106. package/dist/server/ssr-render.d.ts.map +1 -1
  107. package/dist/server/stream-utils.d.ts +44 -10
  108. package/dist/server/stream-utils.d.ts.map +1 -1
  109. package/dist/shared/flight-base64.d.ts +13 -0
  110. package/dist/shared/flight-base64.d.ts.map +1 -0
  111. package/dist/shared/flight-segment.d.ts +18 -0
  112. package/dist/shared/flight-segment.d.ts.map +1 -0
  113. package/dist/shared/form-state-flight.d.ts +0 -4
  114. package/dist/shared/form-state-flight.d.ts.map +1 -1
  115. package/docs/learn/12-error-handling.mdx +1 -1
  116. package/package.json +1 -1
  117. package/src/adapters/nitro-preview.ts +39 -0
  118. package/src/client/browser-entry/form-state.ts +3 -2
  119. package/src/client/browser-entry/index.ts +14 -8
  120. package/src/client/browser-entry/rsc-stream.ts +14 -14
  121. package/src/client/react-root.ts +25 -2
  122. package/src/index.ts +2 -0
  123. package/src/plugins/encryption-runtime.ts +31 -0
  124. package/src/plugins/entries.ts +1 -1
  125. package/src/plugins/server-bundle.ts +17 -2
  126. package/src/rsc-runtime/encryption-runtime.ts +78 -0
  127. package/src/rsc-runtime/render-flight.ts +26 -0
  128. package/src/rsc-runtime/rsc.ts +7 -4
  129. package/src/rsc-runtime/ssr.ts +10 -48
  130. package/src/rsc-runtime/vendor-types.d.ts +31 -2
  131. package/src/server/action-handler.ts +43 -44
  132. package/src/server/compress.ts +49 -12
  133. package/src/server/deny-renderer.ts +14 -7
  134. package/src/server/flight-injector-core.ts +328 -0
  135. package/src/server/flight-scripts.ts +14 -2
  136. package/src/server/flight-source-node.ts +430 -0
  137. package/src/server/flight-source.ts +288 -0
  138. package/src/server/form-state-flight.ts +4 -4
  139. package/src/server/head-response.ts +6 -10
  140. package/src/server/html-injector-core.ts +24 -216
  141. package/src/server/html-injectors.ts +12 -71
  142. package/src/server/node-body-response.ts +236 -0
  143. package/src/server/node-response.ts +93 -0
  144. package/src/server/node-stream-transforms.ts +70 -53
  145. package/src/server/node-streams-platform.ts +23 -0
  146. package/src/server/pipeline-helpers.ts +3 -1
  147. package/src/server/pipeline.ts +14 -6
  148. package/src/server/prebuilt/capture-render.ts +5 -5
  149. package/src/server/prebuilt-runtime.ts +7 -10
  150. package/src/server/rsc-entry/error-renderer.ts +8 -4
  151. package/src/server/rsc-entry/index.ts +4 -2
  152. package/src/server/rsc-entry/render-route.ts +5 -2
  153. package/src/server/rsc-entry/rsc-payload.ts +52 -73
  154. package/src/server/rsc-entry/rsc-stream.ts +102 -106
  155. package/src/server/rsc-entry/ssr-bridge.ts +32 -10
  156. package/src/server/rsc-entry/ssr-renderer.ts +15 -18
  157. package/src/server/ssr-bridge-types.ts +10 -4
  158. package/src/server/ssr-entry.ts +56 -52
  159. package/src/server/ssr-render.ts +41 -76
  160. package/src/server/stream-utils.ts +125 -70
  161. package/src/shared/flight-base64.ts +23 -0
  162. package/src/shared/flight-segment.ts +35 -0
  163. package/src/shared/form-state-flight.ts +0 -15
  164. package/dist/_chunks/rolldown-runtime-D7D4PA-g.js +0 -13
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Flight sources — the one shape a Flight render takes on each platform.
3
+ *
4
+ * Every Flight render in the RSC environment goes through `renderFlight()`
5
+ * (`rsc-runtime/rsc.ts`, built by {@link createRenderFlight} here). On Node
6
+ * (`nodeStreamsPlatform`) it renders with `renderToPipeableStream` into an
7
+ * object-mode Node `Readable`; on Workers (and any runtime without native
8
+ * Node streams) with `renderToReadableStream`.
9
+ * A consumer on a given platform therefore only ever sees that platform's
10
+ * kind. The union exists so shared code typechecks for both; nothing adapts
11
+ * one kind into the other; a Node source becomes a Node-body response
12
+ * ({@link flightResponse}) that the adapter pipes to the socket.
13
+ *
14
+ * Consumers never switch on kind themselves — they use the helpers below:
15
+ * a timeout-guardable reader, cancel, tee, whole-payload collection, the
16
+ * response body, and the first-chunk wait.
17
+ *
18
+ * The Node halves live in `flight-source-node.ts`, loaded only on Node so
19
+ * Workers never evaluate them.
20
+ *
21
+ * Design doc: 02-rendering-pipeline.md §"RSC → SSR → Client Hydration"
22
+ */
23
+
24
+ import type { Readable } from 'node:stream';
25
+ import { nodeStreamsPlatform } from './node-streams-platform.ts';
26
+ import {
27
+ concatBytes,
28
+ drainWithDeadline,
29
+ teeWithErrorPropagation,
30
+ type ChunkReader,
31
+ type TeeOptions,
32
+ } from './stream-utils.ts';
33
+
34
+ /** A Flight render's output, as its platform streams it. */
35
+ export type FlightSource =
36
+ | { kind: 'node'; stream: Readable }
37
+ | { kind: 'web'; stream: ReadableStream<Uint8Array> };
38
+
39
+ /**
40
+ * One chunk of a Flight source. A Web source yields bytes only; a Node
41
+ * source yields bytes for short rows and JS strings for long rows, which
42
+ * must reach the Node Flight client unsplit and unmerged.
43
+ */
44
+ export type FlightChunk = string | Uint8Array;
45
+
46
+ const nodeFlight = nodeStreamsPlatform ? await import('./flight-source-node.ts') : null;
47
+
48
+ /** The Node helpers, which a `kind: 'node'` source can only exist alongside. */
49
+ function requireNodeFlight(): NonNullable<typeof nodeFlight> {
50
+ if (!nodeFlight) {
51
+ throw new Error('[timber] a Node Flight source reached a runtime without node:stream');
52
+ }
53
+ return nodeFlight;
54
+ }
55
+
56
+ // ─── Rendering ──────────────────────────────────────────────────────────────
57
+
58
+ /** Options every Flight render takes. */
59
+ export interface FlightRenderOptions {
60
+ /**
61
+ * Flight's error callback. Its return value is the digest written into the
62
+ * error row.
63
+ */
64
+ onError?: (error: unknown) => string | void;
65
+ /** Aborts the render (client disconnect). */
66
+ signal?: AbortSignal;
67
+ /**
68
+ * Aborts the render with a `RenderTimeoutError` after this long, if it is
69
+ * still running. Defaults to the configured `renderTimeoutMs`
70
+ * ({@link setFlightRenderTimeout}), so no render can stream forever. Node only, where the source's close clears the timer:
71
+ * Workers keep the stock `renderToReadableStream` call, whose end is not
72
+ * observable without wrapping its stream, and bound a request's wall time
73
+ * themselves.
74
+ */
75
+ timeoutMs?: number;
76
+ }
77
+
78
+ /**
79
+ * The deadline every Flight render gets unless it passes its own: the
80
+ * resolved `renderTimeoutMs`, set once at boot by the RSC entry (as
81
+ * `setDefaultSingleflightTimeout` is). A render that streams to a client — an
82
+ * action result holding a promise that never settles, a deny or error page —
83
+ * would otherwise run for as long as the client stays connected (design/02
84
+ * §"Always Wire abort() to Both Request Signal AND Timeout").
85
+ */
86
+ let defaultRenderTimeoutMs: number | undefined;
87
+
88
+ export function setFlightRenderTimeout(timeoutMs: number | undefined): void {
89
+ defaultRenderTimeoutMs = timeoutMs;
90
+ }
91
+
92
+ /** Render a model to a Flight source. */
93
+ export type RenderFlight = (model: unknown, options?: FlightRenderOptions) => FlightSource;
94
+
95
+ /** plugin-rsc's `renderToReadableStream`, with the options timber passes. */
96
+ export type WebFlightRenderer = (
97
+ model: unknown,
98
+ options?: { onError?: (error: unknown) => string | void; signal?: AbortSignal }
99
+ ) => ReadableStream<Uint8Array>;
100
+
101
+ /** plugin-rsc's `renderToPipeableStream` (`rsc.node`), with the options timber passes. */
102
+ export type NodeFlightRenderer = (
103
+ model: unknown,
104
+ options?: { onError?: (error: unknown) => string | void }
105
+ ) => import('./flight-source-node.ts').PipeableFlight;
106
+
107
+ /**
108
+ * Build `renderFlight()` from the platform's renderers. The Node renderer is
109
+ * used whenever it was loaded (on Node it always is — see `rsc-runtime/rsc.ts`);
110
+ * otherwise every render is a Web stream.
111
+ *
112
+ * On Node only one Flight server build may ever render in a process: React
113
+ * throws "Currently React only supports one RSC renderer at a time" when a
114
+ * second build's render starts. That is the second reason every render goes
115
+ * through here.
116
+ */
117
+ export function createRenderFlight(
118
+ web: WebFlightRenderer,
119
+ node: NodeFlightRenderer | null
120
+ ): RenderFlight {
121
+ if (node) {
122
+ const { pipeFlightToNode } = requireNodeFlight();
123
+ return (model, options = {}) => ({
124
+ kind: 'node',
125
+ stream: pipeFlightToNode(node(model, { onError: options.onError }), {
126
+ signal: options.signal,
127
+ timeoutMs: options.timeoutMs ?? defaultRenderTimeoutMs,
128
+ }),
129
+ });
130
+ }
131
+ return (model, options = {}) => ({
132
+ kind: 'web',
133
+ stream: web(model, { onError: options.onError, signal: options.signal }),
134
+ });
135
+ }
136
+
137
+ // ─── Reading ────────────────────────────────────────────────────────────────
138
+
139
+ /** A pull reader over a Flight source, of either kind. */
140
+ export interface FlightReader extends ChunkReader<FlightChunk> {
141
+ /**
142
+ * Every chunk the source already holds, taken without waiting — for
143
+ * coalescing them into one inline script. Always empty for a Web source,
144
+ * which has no synchronous read.
145
+ */
146
+ takeBuffered(): FlightChunk[];
147
+ }
148
+
149
+ /**
150
+ * A pull reader over either kind. `read()` is unguarded: every caller races
151
+ * it against a timeout (design/02 §"Always Timeout-Guard Stream Reads").
152
+ * `cancel()` releases the source, which aborts the render.
153
+ */
154
+ export function openFlightReader(source: FlightSource): FlightReader {
155
+ if (source.kind === 'web') {
156
+ const reader = source.stream.getReader();
157
+ return {
158
+ read: () => reader.read(),
159
+ takeBuffered: () => [],
160
+ cancel: (reason) => void reader.cancel(reason).catch(() => {}),
161
+ };
162
+ }
163
+ const { destroyNodeFlight } = requireNodeFlight();
164
+ const stream = source.stream;
165
+ const iterator: AsyncIterator<FlightChunk> = stream[Symbol.asyncIterator]();
166
+ return {
167
+ read: async () => {
168
+ const result = await iterator.next();
169
+ return result.done ? { done: true, value: undefined } : { done: false, value: result.value };
170
+ },
171
+ // Between `next()` calls the iterator holds nothing back, so reading the
172
+ // stream directly takes exactly the chunks it would have yielded next.
173
+ takeBuffered: () => {
174
+ const chunks: FlightChunk[] = [];
175
+ while (stream.readableLength > 0 && !stream.destroyed) {
176
+ const chunk: FlightChunk | null = stream.read();
177
+ if (chunk === null) break;
178
+ chunks.push(chunk);
179
+ }
180
+ return chunks;
181
+ },
182
+ cancel: (reason) => destroyNodeFlight(stream, reason),
183
+ };
184
+ }
185
+
186
+ /** Release a source nothing will read, aborting the render behind it. */
187
+ export function cancelFlightSource(source: FlightSource, reason?: unknown): void {
188
+ if (source.kind === 'web') {
189
+ source.stream.cancel(reason).catch(() => {});
190
+ return;
191
+ }
192
+ requireNodeFlight().destroyNodeFlight(source.stream, reason);
193
+ }
194
+
195
+ /** A chunk as bytes. */
196
+ export function flightChunkBytes(chunk: FlightChunk): Uint8Array {
197
+ return typeof chunk === 'string' ? encoder.encode(chunk) : chunk;
198
+ }
199
+
200
+ const encoder = new TextEncoder();
201
+
202
+ /**
203
+ * Read a whole Flight source into bytes under one overall deadline, cancelling
204
+ * it on every exit (`drainWithDeadline`). For renders whose payload is stored
205
+ * rather than streamed: the no-JS form state and both prebuilt captures.
206
+ */
207
+ export async function collectFlightBytes(
208
+ source: FlightSource,
209
+ timeoutMs: number,
210
+ label: string
211
+ ): Promise<Uint8Array<ArrayBuffer>> {
212
+ const chunks = await drainWithDeadline(openFlightReader(source), timeoutMs, label);
213
+ return concatBytes(chunks.map(flightChunkBytes));
214
+ }
215
+
216
+ // ─── Splitting and Sending ──────────────────────────────────────────────────
217
+
218
+ /**
219
+ * Tee a source for SSR and the inline payload, each branch its source's kind.
220
+ * Both implementations share one contract: unbounded lag up to the
221
+ * divergence guard, and an error or cancel on either branch reaches the
222
+ * other and the render (design/02 §"Stream Tee").
223
+ */
224
+ export function teeFlightSource(
225
+ source: FlightSource,
226
+ options?: TeeOptions
227
+ ): [FlightSource, FlightSource] {
228
+ if (source.kind === 'web') {
229
+ const [a, b] = teeWithErrorPropagation(source.stream, options);
230
+ return [
231
+ { kind: 'web', stream: a },
232
+ { kind: 'web', stream: b },
233
+ ];
234
+ }
235
+ const [a, b] = requireNodeFlight().teeNodeFlight(source.stream, options?.maxBufferBytes);
236
+ return [
237
+ { kind: 'node', stream: a },
238
+ { kind: 'node', stream: b },
239
+ ];
240
+ }
241
+
242
+ /**
243
+ * A source as a `Response`. A Web source is the body as is; a Node source
244
+ * stays a Node stream to the socket (`NodeBodyResponse`, node-response.ts), so
245
+ * a payload is never converted Node → Web → Node.
246
+ */
247
+ export function flightResponse(source: FlightSource, init: ResponseInit): Response {
248
+ if (source.kind === 'web') return new Response(source.stream, init);
249
+ return requireNodeFlight().nodeFlightResponse(source.stream, init);
250
+ }
251
+
252
+ /** A source whose first chunk can be awaited without losing it. */
253
+ export interface FlightPeek {
254
+ /**
255
+ * Settles when the first chunk (or the end) is available. Rejects if the
256
+ * source errors first. Unguarded, like every read: callers race it.
257
+ */
258
+ ready: Promise<void>;
259
+ /** The source, first chunk included — what to send or cancel afterwards. */
260
+ source: FlightSource;
261
+ }
262
+
263
+ /**
264
+ * Wait for a source's first chunk without consuming it, so the payload path
265
+ * can decide on a response before committing to the stream. A Node source
266
+ * waits for `'readable'` and keeps its chunk; a Web source reads the chunk
267
+ * and replays it at the head of a wrapping stream.
268
+ */
269
+ export function peekFlight(source: FlightSource): FlightPeek {
270
+ if (source.kind === 'node') {
271
+ return { ready: requireNodeFlight().whenNodeFlightReadable(source.stream), source };
272
+ }
273
+ const reader = source.stream.getReader();
274
+ let pending: Promise<ReadableStreamReadResult<Uint8Array>> | null = reader.read();
275
+ const ready = pending.then(() => {});
276
+ const stream = new ReadableStream<Uint8Array>({
277
+ async pull(controller) {
278
+ const result = await (pending ?? reader.read());
279
+ pending = null;
280
+ if (result.done) controller.close();
281
+ else controller.enqueue(result.value);
282
+ },
283
+ cancel(reason) {
284
+ return reader.cancel(reason);
285
+ },
286
+ });
287
+ return { ready, source: { kind: 'web', stream } };
288
+ }
@@ -24,9 +24,9 @@
24
24
  */
25
25
 
26
26
  import type { ReactFormState } from 'react-dom/client';
27
- import { renderToReadableStream } from '../rsc-runtime/rsc.ts';
27
+ import { renderFlight } from '../rsc-runtime/rsc.ts';
28
28
  import { swallow } from './logger.ts';
29
- import { readAllBytesWithDeadline } from './stream-utils.ts';
29
+ import { collectFlightBytes } from './flight-source.ts';
30
30
 
31
31
  /**
32
32
  * Serialize the form state with Flight, or return `null` when it cannot be,
@@ -44,13 +44,13 @@ export async function encodeFormState(
44
44
  // including a rejected nested promise) here, and writes an error row in
45
45
  // its place; a result with an error row in it is not the action's result.
46
46
  const flightErrors: unknown[] = [];
47
- const stream = renderToReadableStream(formState, {
47
+ const source = renderFlight(formState, {
48
48
  signal,
49
49
  onError(error: unknown) {
50
50
  flightErrors.push(error);
51
51
  },
52
52
  });
53
- const bytes = await readAllBytesWithDeadline(stream, timeoutMs, 'no-JS form state encode');
53
+ const bytes = await collectFlightBytes(source, timeoutMs, 'no-JS form state encode');
54
54
  if (flightErrors.length === 0) return bytes;
55
55
  failure = flightErrors[0];
56
56
  } catch (error) {
@@ -22,6 +22,8 @@
22
22
  * applying it twice is a no-op.
23
23
  */
24
24
 
25
+ import { discardResponseBody, nodeBodyOps } from './node-response.ts';
26
+
25
27
  /**
26
28
  * Return a bodyless copy of `response` when `method` is HEAD.
27
29
  *
@@ -34,17 +36,11 @@
34
36
  */
35
37
  export function stripHeadBody(response: Response, method: string): Response {
36
38
  if (method.toUpperCase() !== 'HEAD') return response;
37
- const body = response.body;
38
- if (body === null) return response;
39
+ // A Node body is checked without converting it (`.body` would).
40
+ const nodeBody = nodeBodyOps(response);
41
+ if (nodeBody ? !nodeBody.hasBody : response.body === null) return response;
39
42
 
40
- // `cancel()` rejects if the stream is already errored and throws
41
- // synchronously if it is locked — neither is actionable here, the body is
42
- // being discarded either way.
43
- try {
44
- body.cancel().catch(() => {});
45
- } catch {
46
- /* stream already locked or disturbed */
47
- }
43
+ discardResponseBody(response);
48
44
 
49
45
  return new Response(null, {
50
46
  status: response.status,
@@ -2,8 +2,9 @@
2
2
  * HTML injector core — pure stateful helpers for streaming HTML post-processing.
3
3
  *
4
4
  * These helpers contain the actual byte/string logic for the held-flush
5
- * streaming pipeline (buffered transforms, suffix moving, head injection,
6
- * RSC flight interleaving). They are stream-shape agnostic: they know
5
+ * streaming pipeline (buffered transforms, suffix moving, head injection;
6
+ * RSC flight interleaving has its own core, `flight-injector-core.ts`).
7
+ * They are stream-shape agnostic: they know
7
8
  * nothing about Web `TransformStream` or Node.js `Transform` and contain
8
9
  * no `setImmediate` scheduling or controller plumbing.
9
10
  *
@@ -24,17 +25,6 @@
24
25
  * Design docs: 02-rendering-pipeline.md §"Streaming Constraints", 18-build-system.md §"Entry Files"
25
26
  */
26
27
 
27
- import { createMachine, type Machine } from '../utils/state-machine.ts';
28
- import { flightChunkScript } from './flight-scripts.ts';
29
- import {
30
- flightInjectionTransitions,
31
- isHtmlDone,
32
- isPullDone,
33
- type FlightInjectionState,
34
- type FlightInjectionEvent,
35
- } from './flight-injection-state.ts';
36
- import { withTimeout, RenderTimeoutError, resolveRenderTimeoutMs } from './render-timeout.ts';
37
-
38
28
  // ─── Encoders / Constants ────────────────────────────────────────────────────
39
29
 
40
30
  const encoder = new TextEncoder();
@@ -44,11 +34,6 @@ export const SUFFIX = '</body></html>';
44
34
  /** UTF-8 bytes of {@link SUFFIX}. Cached so wrappers don't re-encode per request. */
45
35
  export const SUFFIX_BYTES: Uint8Array = encoder.encode(SUFFIX);
46
36
 
47
- /** Encode a UTF-8 string. Convenience for wrappers that need a single source of truth. */
48
- export function encodeUtf8(text: string): Uint8Array {
49
- return encoder.encode(text);
50
- }
51
-
52
37
  // ─── Buffered Aggregator ─────────────────────────────────────────────────────
53
38
 
54
39
  /**
@@ -154,17 +139,26 @@ export function createSuffixState(): SuffixState {
154
139
  };
155
140
  }
156
141
 
157
- /** Find `needle` in `haystack` starting from byte offset `start`. Returns -1 if not found. */
142
+ /**
143
+ * Find `needle` in `haystack` starting from byte offset `start`. Returns -1
144
+ * if not found. Jumps between candidates with the native
145
+ * `TypedArray.indexOf` on the needle's first byte: the suffix mover scans
146
+ * every byte of every document, and a byte-by-byte JS loop was the top
147
+ * self-time entry in profiles of large pages (LOCAL-1476).
148
+ */
158
149
  function indexOfBytes(haystack: Uint8Array, needle: Uint8Array, start = 0): number {
159
- const hLen = haystack.byteLength;
160
150
  const nLen = needle.byteLength;
161
151
  if (nLen === 0) return start;
162
- const last = hLen - nLen;
163
- outer: for (let i = start; i <= last; i++) {
164
- for (let j = 0; j < nLen; j++) {
165
- if (haystack[i + j] !== needle[j]) continue outer;
166
- }
167
- return i;
152
+ const last = haystack.byteLength - nLen;
153
+ const first = needle[0];
154
+ for (
155
+ let i = haystack.indexOf(first, start);
156
+ i !== -1 && i <= last;
157
+ i = haystack.indexOf(first, i + 1)
158
+ ) {
159
+ let j = 1;
160
+ while (j < nLen && haystack[i + j] === needle[j]) j++;
161
+ if (j === nLen) return i;
168
162
  }
169
163
  return -1;
170
164
  }
@@ -198,10 +192,11 @@ export function processSuffixChunk(state: SuffixState, chunk: Uint8Array): Suffi
198
192
  state.tail = null;
199
193
  const beforeEnd = idx;
200
194
  const afterStart = idx + SUFFIX_BYTES.byteLength;
195
+ // Views, not copies: callers emit these bytes and never write to them.
201
196
  return {
202
197
  kind: 'suffixFound',
203
- before: beforeEnd > 0 ? combined.slice(0, beforeEnd) : null,
204
- after: afterStart < combined.byteLength ? combined.slice(afterStart) : null,
198
+ before: beforeEnd > 0 ? combined.subarray(0, beforeEnd) : null,
199
+ after: afterStart < combined.byteLength ? combined.subarray(afterStart) : null,
205
200
  };
206
201
  }
207
202
 
@@ -211,7 +206,7 @@ export function processSuffixChunk(state: SuffixState, chunk: Uint8Array): Suffi
211
206
  state.tail = combined.slice(safeEnd);
212
207
 
213
208
  if (safeEnd === 0) return { kind: 'noSuffix' };
214
- return { kind: 'noSuffix', emitSafe: combined.slice(0, safeEnd) };
209
+ return { kind: 'noSuffix', emitSafe: combined.subarray(0, safeEnd) };
215
210
  }
216
211
 
217
212
  /**
@@ -323,190 +318,3 @@ export function injectorFlush(state: InjectorState): Uint8Array | null {
323
318
  if (!state.injected && state.tail) return encoder.encode(state.tail);
324
319
  return null;
325
320
  }
326
-
327
- // ─── Flight Injection Core ───────────────────────────────────────────────────
328
-
329
- /**
330
- * Pure async core of the RSC flight-injection transform.
331
- *
332
- * Both wrappers (Web `TransformStream` and Node `Transform`) implement the
333
- * exact same protocol around an RSC reader:
334
- *
335
- * 1. On the first HTML chunk, send `FIRST_CHUNK` and start the pull loop.
336
- * 2. The pull loop reads from `rscReader` (timeout-guarded), wraps each
337
- * chunk in a `<script>` via `flightChunkScript`, and pushes it onto a
338
- * pending queue. Between reads, it yields with a single-shot
339
- * `setImmediate` so HTML chunks get event-loop priority — and after
340
- * yielding, it drains the queue (via the wrapper's `onYieldDrain`)
341
- * so flight data reaches the client at shell-flush time.
342
- * 3. After every emitted HTML chunk, the wrapper drains the queue.
343
- * 4. On `flush()` the wrapper sends `HTML_DONE` and awaits `pullPromise`.
344
- * No polling — just `.then()`.
345
- *
346
- * The wrappers only differ in:
347
- * - How they push bytes (controller.enqueue vs transform.push).
348
- * - How they signal a terminal error (controller.error vs transform.destroy).
349
- *
350
- * This class owns the state machine, the pending queue, and the pull
351
- * loop itself. The wrapper supplies the drain callback and consumes the
352
- * pending queue + machine state to decide what to push.
353
- *
354
- * **No polling.** See design/02-rendering-pipeline.md §"No Polling".
355
- * **Always timeout-guarded reads.** Per design/02 §"Streaming Constraints".
356
- */
357
- export interface FlightInjectorOptions {
358
- /**
359
- * Timeout in milliseconds for individual RSC stream reads. If a single
360
- * `rscReader.read()` call does not resolve within this duration, the
361
- * read is aborted and the stream errors with a `RenderTimeoutError`.
362
- * Default: 30000 (30s). `0` ("disabled") still enforces a 120s ceiling
363
- * so a stalled RSC stream can never hang the connection forever.
364
- */
365
- renderTimeoutMs?: number;
366
- /** Signal that fires when an unhandled RSC error is detected. */
367
- errorSignal?: AbortSignal;
368
- /** Request CSP nonce, stamped on every emitted `<script>` (TIM-1414). */
369
- nonce?: string;
370
- }
371
-
372
- export class FlightInjectorCore {
373
- readonly machine: Machine<FlightInjectionState, FlightInjectionEvent>;
374
- /** Script chunks waiting to be drained between HTML chunks. */
375
- readonly pending: Uint8Array[] = [];
376
-
377
- private readonly rscReader: ReadableStreamDefaultReader<Uint8Array>;
378
- private readonly timeoutMs: number;
379
- private readonly errorSignal?: AbortSignal;
380
- private readonly nonce?: string;
381
- private readonly decoder = new TextDecoder('utf-8', { fatal: true });
382
- private pullPromise: Promise<void> | null = null;
383
- private _aborted = false;
384
-
385
- constructor(rscStream: ReadableStream<Uint8Array>, options: FlightInjectorOptions = {}) {
386
- this.rscReader = rscStream.getReader();
387
- this.timeoutMs = resolveRenderTimeoutMs(options.renderTimeoutMs);
388
- this.errorSignal = options.errorSignal;
389
- this.nonce = options.nonce;
390
- this.machine = createMachine<FlightInjectionState, FlightInjectionEvent>({
391
- initial: { phase: 'init' },
392
- transitions: flightInjectionTransitions,
393
- });
394
- }
395
-
396
- /** Tell the machine the first HTML chunk has arrived. Idempotent-ish: caller checks. */
397
- notifyFirstChunk(): void {
398
- this.machine.send({ type: 'FIRST_CHUNK' });
399
- }
400
-
401
- /** Tell the machine HTML output is finished — pull loop will stop yielding. */
402
- notifyHtmlDone(): void {
403
- this.machine.send({ type: 'HTML_DONE' });
404
- }
405
-
406
- get isInit(): boolean {
407
- return this.machine.state.phase === 'init';
408
- }
409
-
410
- get isPullDone(): boolean {
411
- return isPullDone(this.machine.state);
412
- }
413
-
414
- get hasPullPromise(): boolean {
415
- return this.pullPromise !== null;
416
- }
417
-
418
- /**
419
- * Get (or start) the pull-loop promise. The wrapper calls this from
420
- * `flush()` and chains `.then()` onto it — never `await` without an
421
- * existing finish callback (we don't want to block transform()).
422
- *
423
- * `onYieldDrain` is invoked between RSC reads while HTML is still
424
- * streaming. It must drain the pending queue into the output stream.
425
- */
426
- ensurePullLoop(onYieldDrain: () => void): Promise<void> {
427
- if (!this.pullPromise) {
428
- this.pullPromise = this.runPullLoop(onYieldDrain);
429
- }
430
- return this.pullPromise;
431
- }
432
-
433
- /**
434
- * Get the current terminal error if the machine is in the error phase,
435
- * else `null`. Wrappers use this after a drain to decide whether to
436
- * `controller.error()` / `transform.destroy()`.
437
- */
438
- get terminalError(): unknown {
439
- return this.machine.state.phase === 'error' ? this.machine.state.error : null;
440
- }
441
-
442
- /**
443
- * Abort the pull loop and release the RSC reader. Called by stream
444
- * wrappers when the HTML pipeline is torn down (Node `destroy()`,
445
- * Web `cancel()`). Safe to call multiple times.
446
- */
447
- abort(reason?: unknown): void {
448
- if (this._aborted) return;
449
- this._aborted = true;
450
- this.rscReader.cancel(reason).catch(() => {});
451
- this.pending.length = 0;
452
- }
453
-
454
- get isAborted(): boolean {
455
- return this._aborted;
456
- }
457
-
458
- private async runPullLoop(onYieldDrain: () => void): Promise<void> {
459
- // Yield once so the first HTML shell chunk flows through the wrapper
460
- // before we start reading RSC data.
461
- await new Promise<void>((r) => setImmediate(r));
462
-
463
- try {
464
- for (;;) {
465
- if (this._aborted) return;
466
-
467
- // Guard each read with a timeout so a permanently hung RSC stream
468
- // eventually aborts. See design/02 §"Streaming Constraints".
469
- const readPromise = this.rscReader.read();
470
- const { done, value } = await withTimeout(
471
- readPromise,
472
- this.timeoutMs,
473
- 'RSC stream read timed out'
474
- );
475
-
476
- if (done) {
477
- this.machine.send({ type: 'PULL_DONE' });
478
- return;
479
- }
480
-
481
- // If an unhandled RSC error was detected, stop injecting Flight
482
- // data. Continue reading (to prevent tee buffer divergence) but
483
- // discard the chunks so corrupted data never reaches the client.
484
- // See TIM-938.
485
- if (this.errorSignal?.aborted) {
486
- continue;
487
- }
488
-
489
- const decoded = this.decoder.decode(value, { stream: true });
490
- this.pending.push(encoder.encode(flightChunkScript(decoded, this.nonce)));
491
-
492
- // Yield between reads so HTML chunks get priority — but only while
493
- // HTML is still streaming. Once flush() fires (HTML_DONE), drain
494
- // without yielding so remaining RSC data doesn't stall.
495
- if (!isHtmlDone(this.machine.state)) {
496
- await new Promise<void>((r) => setImmediate(r));
497
- // After yielding, drain. Without this, hydration blocks waiting
498
- // for flight data stuck in pending[]. Safe because we're between
499
- // event-loop ticks (no transform() call mid-execution → no
500
- // mid-tag risk; the buffered transform upstream coalesced HTML
501
- // chunks to coherent fragments).
502
- if (this.pending.length > 0) onYieldDrain();
503
- }
504
- }
505
- } catch (err) {
506
- if (err instanceof RenderTimeoutError) {
507
- this.rscReader.cancel(err).catch(() => {});
508
- }
509
- this.machine.send({ type: 'PULL_ERROR', error: err });
510
- }
511
- }
512
- }