@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,430 @@
1
+ /**
2
+ * Node halves of the Flight source helpers in `flight-source.ts`.
3
+ *
4
+ * Only loaded on Node (`flight-source.ts` imports it behind
5
+ * `nodeStreamsPlatform`), so Workers never evaluate it.
6
+ *
7
+ * A Node Flight source is an object-mode `Readable` whose chunks are exactly
8
+ * what React's `renderToPipeableStream` wrote: `Uint8Array` views for short
9
+ * rows, and JS strings for long rows (≥ ~1365 chars) and text row bodies.
10
+ * The Node Flight client (`createFromNodeStream`) requires every string chunk
11
+ * in its original shape — it throws "String chunks need to be passed in their
12
+ * original shape" if one is split or merged — so nothing here splits or
13
+ * concatenates a chunk on its way to a consumer.
14
+ *
15
+ * Design doc: 02-rendering-pipeline.md §"RSC → SSR → Client Hydration",
16
+ * §"Stream Tee"
17
+ */
18
+
19
+ import { Readable, Transform } from 'node:stream';
20
+ import { NodeBodyResponse } from './node-body-response.ts';
21
+ import { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';
22
+ import { RenderTimeoutError } from './render-timeout.ts';
23
+
24
+ // `String.prototype.toWellFormed` ships in every Node timber supports
25
+ // (engines: >=22.18) but is ES2024, past the project's ES2022 lib; this file
26
+ // only runs on Node.
27
+ declare global {
28
+ interface String {
29
+ toWellFormed(): string;
30
+ }
31
+ }
32
+
33
+ /** A chunk of a Node Flight source. */
34
+ export type NodeFlightChunk = string | Uint8Array;
35
+
36
+ /** The part of React's `PipeableStream` a Flight render hands us. */
37
+ export interface PipeableFlight {
38
+ pipe<T extends NodeJS.WritableStream>(destination: T): T;
39
+ abort(reason?: unknown): void;
40
+ }
41
+
42
+ /**
43
+ * Every stream here carries one no-op `'error'` listener. `destroy(err)` emits
44
+ * `'error'`, and a stream whose consumer already detached (an iterator that
45
+ * returned, a pipeline that finished) or has not attached yet would otherwise
46
+ * turn a cancel into an uncaught exception. Real consumers attach their own
47
+ * listeners, which still see every error.
48
+ */
49
+ function ignoreError(): void {}
50
+
51
+ /**
52
+ * Release a Node Flight source: destroy it with `reason`, which aborts the
53
+ * render behind it. Cancellation reasons in the pipeline are `unknown` (a Web
54
+ * `cancel(reason)` takes anything); `destroy` takes an `Error`. Never throws
55
+ * and never leaves an unhandled `'error'` event, whoever is listening.
56
+ */
57
+ export function destroyNodeFlight(stream: Readable, reason: unknown): void {
58
+ if (!stream.listeners('error').includes(ignoreError)) stream.on('error', ignoreError);
59
+ const error =
60
+ reason === undefined || reason === null
61
+ ? undefined
62
+ : reason instanceof Error
63
+ ? reason
64
+ : new Error(String(reason));
65
+ stream.destroy(error);
66
+ }
67
+
68
+ /** When a Node Flight render is aborted, besides its consumer cancelling. */
69
+ export interface NodeFlightAbort {
70
+ /** The request's signal (client disconnect). */
71
+ signal?: AbortSignal;
72
+ /** Abort with a `RenderTimeoutError` after this long, if still rendering. */
73
+ timeoutMs?: number;
74
+ }
75
+
76
+ /**
77
+ * Pipe a Flight render into an object-mode Node source.
78
+ *
79
+ * - Strings pass through `toWellFormed()`, as Next does
80
+ * (`renderToNodeFlightStream`): SSR decodes the raw string while the inline
81
+ * copy round-trips through JSON + `TextEncoder`, which turns a lone
82
+ * surrogate into U+FFFD, so without it SSR and hydration see different
83
+ * text. Length in UTF-16 units is unchanged, so a text row's length header
84
+ * still holds.
85
+ * - `renderToPipeableStream` takes no `signal`. `abort()` is called when the
86
+ * request signal fires, when `timeoutMs` passes (design/02 §"Always Wire
87
+ * abort() to Both Request Signal AND Timeout"), and when the source is
88
+ * destroyed (a consumer cancelling), with the destroy reason — the reason a
89
+ * Web `cancel(reason)` hands Flight. The listener and the timer are
90
+ * released when the source closes.
91
+ */
92
+ export function pipeFlightToNode(
93
+ flight: PipeableFlight,
94
+ { signal, timeoutMs }: NodeFlightAbort
95
+ ): Readable {
96
+ const onAbort = (): void => flight.abort(signal?.reason);
97
+ const timer =
98
+ timeoutMs === undefined
99
+ ? undefined
100
+ : setTimeout(
101
+ () => flight.abort(new RenderTimeoutError(timeoutMs, 'Flight render')),
102
+ timeoutMs
103
+ );
104
+ const stream = new Transform({
105
+ objectMode: true,
106
+ transform(chunk: NodeFlightChunk, _encoding, callback) {
107
+ callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);
108
+ },
109
+ destroy(error, callback) {
110
+ signal?.removeEventListener('abort', onAbort);
111
+ clearTimeout(timer);
112
+ // A no-op once Flight has finished (it ignores abort after close).
113
+ flight.abort(error ?? undefined);
114
+ callback(error);
115
+ },
116
+ });
117
+ stream.on('error', ignoreError);
118
+ if (signal?.aborted) flight.abort(signal.reason);
119
+ else signal?.addEventListener('abort', onAbort, { once: true });
120
+ flight.pipe(stream);
121
+ return stream;
122
+ }
123
+
124
+ /** Bytes a chunk occupies, for the tee's divergence guard. */
125
+ function chunkByteLength(chunk: NodeFlightChunk): number {
126
+ return typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;
127
+ }
128
+
129
+ /**
130
+ * Tee a Node Flight source into two object-mode branches, with the contract
131
+ * of `teeWithErrorPropagation` (`stream-utils.ts`):
132
+ *
133
+ * - Each branch has its own queue, so the lagging branch buffers without
134
+ * bound until the divergence guard (`maxBufferBytes`, default 5MB, counted
135
+ * in UTF-8 bytes) cancels both. Nothing couples the branches' backpressure:
136
+ * the inline branch is not read until Fizz emits its first HTML chunk, and
137
+ * Fizz needs SSR to consume Flight first, so a `pipe()` into two
138
+ * PassThroughs would deadlock once the inline one filled.
139
+ * - The source is read at the pace of the faster branch (paused only while
140
+ * neither branch wants data), like a Web `tee()`.
141
+ * - An error on the source, or a branch destroyed before it ended, destroys
142
+ * the other branch with an error and destroys the source — which aborts the
143
+ * render — so neither consumer hangs and both are released.
144
+ */
145
+ export function teeNodeFlight(
146
+ source: Readable,
147
+ maxBufferBytes: number = DEFAULT_MAX_BUFFER_BYTES
148
+ ): [Readable, Readable] {
149
+ interface Branch {
150
+ readable: Readable;
151
+ queue: Array<NodeFlightChunk | null>;
152
+ /**
153
+ * Bytes this branch holds that its consumer has not read: the queue, plus
154
+ * chunks pushed into the readable and still in its buffer.
155
+ */
156
+ heldBytes: number;
157
+ /**
158
+ * Sizes of the chunks pushed into the readable, oldest first, until the
159
+ * consumer reads them. In object mode `readableLength` counts buffered
160
+ * chunks, so any beyond it at the front have been consumed.
161
+ */
162
+ pushedSizes: number[];
163
+ /** `_read` was called and nothing has been pushed since. */
164
+ wanting: boolean;
165
+ }
166
+
167
+ let tornDown = false;
168
+ const branches: [Branch, Branch] = [createBranch(), createBranch()];
169
+
170
+ function createBranch(): Branch {
171
+ const branch: Branch = {
172
+ readable: new Readable({
173
+ objectMode: true,
174
+ read() {
175
+ settle(branch);
176
+ branch.wanting = true;
177
+ drain(branch);
178
+ },
179
+ destroy(error, callback) {
180
+ // A branch that ended normally releases nothing; one destroyed
181
+ // early (its consumer cancelled, or teardown) takes the rest down.
182
+ if (!branch.readable.readableEnded) {
183
+ teardown(error ?? new Error('RSC stream tee branch cancelled'), error);
184
+ }
185
+ callback(error);
186
+ },
187
+ }),
188
+ queue: [],
189
+ heldBytes: 0,
190
+ pushedSizes: [],
191
+ wanting: false,
192
+ };
193
+ branch.readable.on('error', ignoreError);
194
+ return branch;
195
+ }
196
+
197
+ /** Stop counting the pushed chunks the consumer has read. */
198
+ function settle(branch: Branch): void {
199
+ while (branch.pushedSizes.length > branch.readable.readableLength) {
200
+ branch.heldBytes -= branch.pushedSizes.shift() ?? 0;
201
+ }
202
+ }
203
+
204
+ function drain(branch: Branch): void {
205
+ while (branch.wanting) {
206
+ const chunk = branch.queue.shift();
207
+ if (chunk === undefined) break;
208
+ if (chunk === null) {
209
+ branch.wanting = false;
210
+ branch.readable.push(null);
211
+ return;
212
+ }
213
+ branch.pushedSizes.push(chunkByteLength(chunk));
214
+ branch.wanting = branch.readable.push(chunk);
215
+ }
216
+ if (branch.wanting && source.isPaused()) source.resume();
217
+ }
218
+
219
+ /**
220
+ * Destroy both branches and the source. `branchError` is what the branches'
221
+ * consumers see; `sourceReason` is what Flight is aborted with — the
222
+ * consumer's own cancel reason, which may be `undefined`, as with a Web tee.
223
+ */
224
+ function teardown(branchError: Error, sourceReason: Error | null | undefined): void {
225
+ if (tornDown) return;
226
+ tornDown = true;
227
+ source.off('data', onData);
228
+ for (const branch of branches) {
229
+ branch.queue.length = 0;
230
+ branch.heldBytes = 0;
231
+ branch.pushedSizes.length = 0;
232
+ if (!branch.readable.destroyed) branch.readable.destroy(branchError);
233
+ }
234
+ source.destroy(sourceReason ?? undefined);
235
+ }
236
+
237
+ function onData(chunk: NodeFlightChunk): void {
238
+ const bytes = chunkByteLength(chunk);
239
+ for (const branch of branches) {
240
+ branch.queue.push(chunk);
241
+ branch.heldBytes += bytes;
242
+ drain(branch);
243
+ }
244
+ // What the lagging branch holds is the divergence between the two.
245
+ for (const branch of branches) settle(branch);
246
+ const divergence = Math.max(branches[0].heldBytes, branches[1].heldBytes);
247
+ if (divergence > maxBufferBytes) {
248
+ const error = teeBufferExceeded(maxBufferBytes, divergence);
249
+ teardown(error, error);
250
+ return;
251
+ }
252
+ if (!branches[0].wanting && !branches[1].wanting) source.pause();
253
+ }
254
+
255
+ const finished = finishedState(source);
256
+ if (finished) {
257
+ if ('error' in finished) teardown(finished.error, finished.error);
258
+ else for (const branch of branches) branch.readable.push(null);
259
+ return [branches[0].readable, branches[1].readable];
260
+ }
261
+
262
+ source.on('data', onData);
263
+ source.on('end', () => {
264
+ for (const branch of branches) {
265
+ branch.queue.push(null);
266
+ drain(branch);
267
+ }
268
+ });
269
+ source.on('error', (error: Error) => teardown(error, error));
270
+ source.on('close', () => {
271
+ if (!source.readableEnded) {
272
+ teardown(new Error('RSC stream closed before it ended'), undefined);
273
+ }
274
+ });
275
+
276
+ return [branches[0].readable, branches[1].readable];
277
+ }
278
+
279
+ /**
280
+ * A Node Flight source as a `Response` (`NodeBodyResponse`): its body stays a
281
+ * Node stream all the way to the adapter, which pipes it to the socket
282
+ * (LOCAL-1475). Nothing in the Flight path converts it to a Web stream.
283
+ *
284
+ * Every chunk that arrives in one tick goes out as one buffer, with string
285
+ * chunks encoded straight into it. React writes a flush synchronously, and
286
+ * its Node build passes each long row as its own string: a heavy payload
287
+ * arrives as ~4x the chunks of the Web build's 4KB views, and the socket pays
288
+ * per write. The body pauses the source while the client is slow (a payload
289
+ * never piles up in memory), destroying it early destroys the source (which
290
+ * aborts the render), and an error or early close on the source ends it.
291
+ * Wired by hand rather than with `pipeline()`, which allocates an
292
+ * AbortController and an error on every finish.
293
+ */
294
+ export function nodeFlightResponse(source: Readable, init: ResponseInit): Response {
295
+ return new NodeBodyResponse(batchFlightBytes(source), init);
296
+ }
297
+
298
+ /** Largest batch the payload body coalesces before pushing (and checking backpressure). */
299
+ const MAX_BATCH_BYTES = 64 * 1024;
300
+
301
+ function batchFlightBytes(source: Readable): Readable {
302
+ let batch: NodeFlightChunk[] = [];
303
+ let batchBytes = 0;
304
+ let scheduled = false;
305
+ // Assigned once the source listeners exist; a body destroyed before then
306
+ // (an already-finished source) has none to remove.
307
+ let detach = (): void => {};
308
+
309
+ // One allocation per batch: strings are encoded straight into it, at their
310
+ // offset, rather than each into its own array and then copied.
311
+ const emit = (): void => {
312
+ scheduled = false;
313
+ if (batch.length === 0 || bytes.destroyed) return;
314
+ const merged = Buffer.allocUnsafe(batchBytes);
315
+ let offset = 0;
316
+ for (const chunk of batch) {
317
+ if (typeof chunk === 'string') {
318
+ offset += merged.write(chunk, offset);
319
+ } else {
320
+ merged.set(chunk, offset);
321
+ offset += chunk.byteLength;
322
+ }
323
+ }
324
+ batch = [];
325
+ batchBytes = 0;
326
+ // Backpressure: a slow client stops the render's output here instead of
327
+ // the whole payload piling up in memory. read() resumes it.
328
+ if (!bytes.push(merged)) source.pause();
329
+ };
330
+
331
+ const bytes = new Readable({
332
+ read() {
333
+ if (source.isPaused()) source.resume();
334
+ },
335
+ destroy(error, callback) {
336
+ // A batch still queued is dropped, so its microtask pushes nothing.
337
+ batch = [];
338
+ batchBytes = 0;
339
+ detach();
340
+ // The client left early: release the render.
341
+ if (!source.readableEnded) destroyNodeFlight(source, error ?? undefined);
342
+ callback(error);
343
+ },
344
+ });
345
+ bytes.on('error', ignoreError);
346
+
347
+ const finished = finishedState(source);
348
+ if (finished) {
349
+ // A finished source emits no more events for the wiring below to see.
350
+ if ('error' in finished) bytes.destroy(finished.error);
351
+ else bytes.push(null);
352
+ return bytes;
353
+ }
354
+
355
+ const onData = (chunk: NodeFlightChunk): void => {
356
+ batch.push(chunk);
357
+ batchBytes += chunkByteLength(chunk);
358
+ // A flush that writes a lot in one tick goes out in capped batches, so
359
+ // backpressure can pause the source mid-flush instead of after it.
360
+ if (batchBytes >= MAX_BATCH_BYTES) {
361
+ emit();
362
+ } else if (!scheduled) {
363
+ scheduled = true;
364
+ queueMicrotask(emit);
365
+ }
366
+ };
367
+ const onEnd = (): void => {
368
+ emit();
369
+ bytes.push(null);
370
+ };
371
+ const onError = (error: Error): void => {
372
+ bytes.destroy(error);
373
+ };
374
+ const onClose = (): void => {
375
+ if (!source.readableEnded) {
376
+ bytes.destroy(source.errored ?? new Error('RSC stream closed before it ended'));
377
+ }
378
+ };
379
+ detach = (): void => {
380
+ source.off('data', onData);
381
+ source.off('end', onEnd);
382
+ source.off('error', onError);
383
+ source.off('close', onClose);
384
+ };
385
+ source.on('data', onData);
386
+ source.on('end', onEnd);
387
+ source.on('error', onError);
388
+ source.on('close', onClose);
389
+ return bytes;
390
+ }
391
+
392
+ /**
393
+ * Why `source` will never emit again, if it was destroyed or ended before a
394
+ * consumer attached: `'end'`, `'error'` and `'close'` have already fired,
395
+ * so a consumer that only listens would wait forever. `null` while live.
396
+ */
397
+ function finishedState(source: Readable): { ended: true } | { error: Error } | null {
398
+ if (source.readableEnded) return { ended: true };
399
+ if (!source.destroyed) return null;
400
+ return { error: source.errored ?? new Error('RSC stream closed before it ended') };
401
+ }
402
+
403
+ /**
404
+ * Settles once a chunk (or the end) can be read from `source`, without
405
+ * consuming it: the chunk stays in the source for whatever reads it next.
406
+ * Rejects if the source errors first.
407
+ *
408
+ * The `'readable'` listener is removed on settle; Node restores the stream's
409
+ * flowing state on the next tick, so a consumer attached afterwards (a pipe,
410
+ * a `'data'` listener) still starts it.
411
+ */
412
+ export function whenNodeFlightReadable(source: Readable): Promise<void> {
413
+ if (source.readableLength > 0) return Promise.resolve();
414
+ const finished = finishedState(source);
415
+ if (finished) return 'error' in finished ? Promise.reject(finished.error) : Promise.resolve();
416
+ return new Promise<void>((resolve, reject) => {
417
+ const settle = (error?: Error): void => {
418
+ source.off('readable', onReadable);
419
+ source.off('error', settle);
420
+ source.off('close', onClose);
421
+ if (error) reject(error);
422
+ else resolve();
423
+ };
424
+ const onReadable = (): void => settle();
425
+ const onClose = (): void => settle(source.errored ?? undefined);
426
+ source.on('readable', onReadable);
427
+ source.on('error', settle);
428
+ source.on('close', onClose);
429
+ });
430
+ }