@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,328 @@
1
+ /**
2
+ * Flight injector core — the pull loop that turns the inline Flight source
3
+ * into `<script>` tags interleaved with the HTML stream.
4
+ *
5
+ * Shape-agnostic like the rest of `html-injector-core.ts`: the Web wrapper
6
+ * (`html-injectors.ts`) and the Node wrapper (`node-stream-transforms.ts`)
7
+ * compose this class, and it reads either kind of Flight source through
8
+ * `openFlightReader` (`flight-source.ts`), so the inline branch is a Node
9
+ * stream end to end on Node and a Web stream on Workers.
10
+ *
11
+ * Design docs: 02-rendering-pipeline.md §"Stream Tee",
12
+ * §"Scripts at Chunk Boundaries Only", §"Streaming Constraints"
13
+ */
14
+
15
+ import { createMachine, type Machine } from '../utils/state-machine.ts';
16
+ import { flightBinaryChunkScript, flightChunkScript } from './flight-scripts.ts';
17
+ import {
18
+ flightInjectionTransitions,
19
+ isHtmlDone,
20
+ isPullDone,
21
+ type FlightInjectionState,
22
+ type FlightInjectionEvent,
23
+ } from './flight-injection-state.ts';
24
+ import {
25
+ openFlightReader,
26
+ type FlightChunk,
27
+ type FlightReader,
28
+ type FlightSource,
29
+ } from './flight-source.ts';
30
+ import { withTimeout, resolveRenderTimeoutMs } from './render-timeout.ts';
31
+
32
+ const encoder = new TextEncoder();
33
+
34
+ // ─── Chunk → Script Encoding ─────────────────────────────────────────────────
35
+
36
+ /**
37
+ * Bytes at the end of `bytes` that start a UTF-8 sequence the chunk does not
38
+ * finish: a multibyte character can span two adjacent byte chunks. Zero when
39
+ * the chunk ends on a character boundary, or when its tail is not a valid
40
+ * sequence start at all (then the run fails validation as a whole).
41
+ */
42
+ function incompleteUtf8Tail(bytes: Uint8Array): number {
43
+ const end = bytes.byteLength;
44
+ for (let i = end - 1; i >= Math.max(0, end - 3); i--) {
45
+ const byte = bytes[i];
46
+ if ((byte & 0xc0) === 0x80) continue; // continuation byte
47
+ const needed = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;
48
+ return end - i < needed ? end - i : 0;
49
+ }
50
+ return 0;
51
+ }
52
+
53
+ function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
54
+ const out = new Uint8Array(a.byteLength + b.byteLength);
55
+ out.set(a, 0);
56
+ out.set(b, a.byteLength);
57
+ return out;
58
+ }
59
+
60
+ /**
61
+ * Turns Flight chunks into inline script tags, in order.
62
+ *
63
+ * - Adjacent text in one batch of chunks becomes one `[1, text]` script, so
64
+ * the many small chunks Node's Flight writer produces (a header chunk and a
65
+ * string per long row) cost one script, not one each.
66
+ * - A string chunk (Node only) is already text: it is JSON-escaped straight
67
+ * into the tuple, with no decode.
68
+ * - A run of byte chunks is decoded as a whole, holding back an incomplete
69
+ * trailing character for the next chunk. A run that is not valid UTF-8 —
70
+ * the binary row of a typed array or ArrayBuffer — is sent as a
71
+ * `[3, base64]` tuple instead of failing the response. The browser
72
+ * (`client/browser-entry/rsc-stream.ts`) enqueues both tuples' bytes in
73
+ * order, so it rebuilds the exact byte stream either way.
74
+ */
75
+ export class FlightInlineEncoder {
76
+ // ignoreBOM: each run is decoded on its own, and a U+FEFF at the start of a
77
+ // run is content (a byte boundary can land just before one), not a mark.
78
+ private readonly decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
79
+ /** Bytes held back because they end in an incomplete UTF-8 sequence. */
80
+ private carry: Uint8Array | null = null;
81
+
82
+ constructor(private readonly nonce?: string) {}
83
+
84
+ /** The scripts for a batch of chunks, in order. */
85
+ push(chunks: readonly FlightChunk[]): string[] {
86
+ const scripts: string[] = [];
87
+ let text = '';
88
+ const add = (bytes: Uint8Array): void => {
89
+ const decoded = this.decode(bytes);
90
+ if (decoded !== null) {
91
+ text += decoded;
92
+ return;
93
+ }
94
+ if (text) scripts.push(flightChunkScript(text, this.nonce));
95
+ text = '';
96
+ scripts.push(flightBinaryChunkScript(bytes, this.nonce));
97
+ };
98
+ for (const chunk of chunks) {
99
+ if (typeof chunk === 'string') {
100
+ // Bytes held back before a string never completed a character.
101
+ if (this.carry) add(this.takeCarry());
102
+ text += chunk;
103
+ continue;
104
+ }
105
+ const run = this.carry ? concat(this.takeCarry(), chunk) : chunk;
106
+ const cut = run.byteLength - incompleteUtf8Tail(run);
107
+ if (cut < run.byteLength) this.carry = run.slice(cut);
108
+ if (cut > 0) add(run.subarray(0, cut));
109
+ }
110
+ if (text) scripts.push(flightChunkScript(text, this.nonce));
111
+ return scripts;
112
+ }
113
+
114
+ /** The scripts for bytes still held back at the end of the stream. */
115
+ end(): string[] {
116
+ if (!this.carry) return [];
117
+ const bytes = this.takeCarry();
118
+ const text = this.decode(bytes);
119
+ return [
120
+ text === null
121
+ ? flightBinaryChunkScript(bytes, this.nonce)
122
+ : flightChunkScript(text, this.nonce),
123
+ ];
124
+ }
125
+
126
+ private takeCarry(): Uint8Array {
127
+ const carry = this.carry ?? new Uint8Array(0);
128
+ this.carry = null;
129
+ return carry;
130
+ }
131
+
132
+ /** The bytes as text, or `null` if they are not valid UTF-8. */
133
+ private decode(bytes: Uint8Array): string | null {
134
+ try {
135
+ return this.decoder.decode(bytes);
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+ }
141
+
142
+ // ─── Flight Injection Core ───────────────────────────────────────────────────
143
+
144
+ /**
145
+ * Both wrappers (Web `TransformStream` and Node `Transform`) implement the
146
+ * exact same protocol around the inline Flight source:
147
+ *
148
+ * 1. On the first HTML chunk, send `FIRST_CHUNK` and start the pull loop.
149
+ * 2. The pull loop reads the source (timeout-guarded), turns each chunk
150
+ * into `<script>` tags via {@link FlightInlineEncoder}, and pushes them
151
+ * onto a pending queue. Between reads, it yields with a single-shot
152
+ * `setImmediate` so HTML chunks get event-loop priority — and after
153
+ * yielding, it drains the queue (via the wrapper's `onYieldDrain`)
154
+ * so flight data reaches the client at shell-flush time.
155
+ * 3. After every emitted HTML chunk, the wrapper drains the queue.
156
+ * 4. On `flush()` the wrapper sends `HTML_DONE` and awaits `pullPromise`.
157
+ * No polling — just `.then()`.
158
+ *
159
+ * The wrappers only differ in:
160
+ * - How they push bytes (controller.enqueue vs transform.push).
161
+ * - How they signal a terminal error (controller.error vs transform.destroy).
162
+ *
163
+ * **No polling.** See design/02-rendering-pipeline.md §"No Polling".
164
+ * **Always timeout-guarded reads.** Per design/02 §"Streaming Constraints".
165
+ */
166
+ export interface FlightInjectorOptions {
167
+ /**
168
+ * Timeout in milliseconds for individual Flight reads. If one read does
169
+ * not resolve within this duration, the read is aborted and the stream
170
+ * errors with a `RenderTimeoutError`. Default: 30000 (30s). `0`
171
+ * ("disabled") still enforces a 120s ceiling so a stalled RSC stream can
172
+ * never hang the connection forever.
173
+ */
174
+ renderTimeoutMs?: number;
175
+ /** Signal that fires when an unhandled RSC error is detected. */
176
+ errorSignal?: AbortSignal;
177
+ /** Request CSP nonce, stamped on every emitted `<script>` (TIM-1414). */
178
+ nonce?: string;
179
+ }
180
+
181
+ export class FlightInjectorCore {
182
+ readonly machine: Machine<FlightInjectionState, FlightInjectionEvent>;
183
+ /** Script chunks waiting to be drained between HTML chunks. */
184
+ readonly pending: Uint8Array[] = [];
185
+
186
+ private readonly reader: FlightReader;
187
+ private readonly timeoutMs: number;
188
+ private readonly errorSignal?: AbortSignal;
189
+ private readonly encoder: FlightInlineEncoder;
190
+ private pullPromise: Promise<void> | null = null;
191
+ private _aborted = false;
192
+
193
+ constructor(source: FlightSource, options: FlightInjectorOptions = {}) {
194
+ this.reader = openFlightReader(source);
195
+ this.timeoutMs = resolveRenderTimeoutMs(options.renderTimeoutMs);
196
+ this.errorSignal = options.errorSignal;
197
+ this.encoder = new FlightInlineEncoder(options.nonce);
198
+ this.machine = createMachine<FlightInjectionState, FlightInjectionEvent>({
199
+ initial: { phase: 'init' },
200
+ transitions: flightInjectionTransitions,
201
+ });
202
+ }
203
+
204
+ /** Tell the machine the first HTML chunk has arrived. Idempotent-ish: caller checks. */
205
+ notifyFirstChunk(): void {
206
+ this.machine.send({ type: 'FIRST_CHUNK' });
207
+ }
208
+
209
+ /** Tell the machine HTML output is finished — pull loop will stop yielding. */
210
+ notifyHtmlDone(): void {
211
+ this.machine.send({ type: 'HTML_DONE' });
212
+ }
213
+
214
+ get isInit(): boolean {
215
+ return this.machine.state.phase === 'init';
216
+ }
217
+
218
+ get isPullDone(): boolean {
219
+ return isPullDone(this.machine.state);
220
+ }
221
+
222
+ get hasPullPromise(): boolean {
223
+ return this.pullPromise !== null;
224
+ }
225
+
226
+ /**
227
+ * Get (or start) the pull-loop promise. The wrapper calls this from
228
+ * `flush()` and chains `.then()` onto it — never `await` without an
229
+ * existing finish callback (we don't want to block transform()).
230
+ *
231
+ * `onYieldDrain` is invoked between Flight reads while HTML is still
232
+ * streaming. It must drain the pending queue into the output stream.
233
+ */
234
+ ensurePullLoop(onYieldDrain: () => void): Promise<void> {
235
+ if (!this.pullPromise) {
236
+ this.pullPromise = this.runPullLoop(onYieldDrain);
237
+ }
238
+ return this.pullPromise;
239
+ }
240
+
241
+ /**
242
+ * Get the current terminal error if the machine is in the error phase,
243
+ * else `null`. Wrappers use this after a drain to decide whether to
244
+ * `controller.error()` / `transform.destroy()`.
245
+ */
246
+ get terminalError(): unknown {
247
+ return this.machine.state.phase === 'error' ? this.machine.state.error : null;
248
+ }
249
+
250
+ /**
251
+ * Abort the pull loop and release the Flight source. Called by stream
252
+ * wrappers when the HTML pipeline is torn down (Node `destroy()`,
253
+ * Web `cancel()`). Safe to call multiple times.
254
+ */
255
+ abort(reason?: unknown): void {
256
+ if (this._aborted) return;
257
+ this._aborted = true;
258
+ // A finished pull loop already read the source to its end, or released
259
+ // it when it failed; cancelling again would only build an error for
260
+ // nothing on every completed response.
261
+ if (!this.isPullDone) this.reader.cancel(reason);
262
+ this.pending.length = 0;
263
+ }
264
+
265
+ get isAborted(): boolean {
266
+ return this._aborted;
267
+ }
268
+
269
+ private enqueue(scripts: string[]): void {
270
+ for (const script of scripts) this.pending.push(encoder.encode(script));
271
+ }
272
+
273
+ private async runPullLoop(onYieldDrain: () => void): Promise<void> {
274
+ // Yield once so the first HTML shell chunk flows through the wrapper
275
+ // before we start reading Flight data.
276
+ await new Promise<void>((r) => setImmediate(r));
277
+
278
+ try {
279
+ for (;;) {
280
+ if (this._aborted) return;
281
+
282
+ // Guard each read with a timeout so a permanently hung RSC stream
283
+ // eventually aborts. See design/02 §"Streaming Constraints".
284
+ const result = await withTimeout(
285
+ this.reader.read(),
286
+ this.timeoutMs,
287
+ 'RSC stream read timed out'
288
+ );
289
+
290
+ if (result.done) {
291
+ if (!this.errorSignal?.aborted) this.enqueue(this.encoder.end());
292
+ this.machine.send({ type: 'PULL_DONE' });
293
+ return;
294
+ }
295
+
296
+ // If an unhandled RSC error was detected, stop injecting Flight
297
+ // data. Continue reading (to prevent tee buffer divergence) but
298
+ // discard the chunks so corrupted data never reaches the client.
299
+ // See TIM-938.
300
+ if (this.errorSignal?.aborted) {
301
+ continue;
302
+ }
303
+
304
+ // Coalesce: everything the source already holds goes into the same
305
+ // scripts (Node only — a Web source never has chunks to take).
306
+ this.enqueue(this.encoder.push([result.value, ...this.reader.takeBuffered()]));
307
+
308
+ // Yield between reads so HTML chunks get priority — but only while
309
+ // HTML is still streaming. Once flush() fires (HTML_DONE), drain
310
+ // without yielding so remaining RSC data doesn't stall.
311
+ if (!isHtmlDone(this.machine.state)) {
312
+ await new Promise<void>((r) => setImmediate(r));
313
+ // After yielding, drain. Without this, hydration blocks waiting
314
+ // for flight data stuck in pending[]. Safe because we're between
315
+ // event-loop ticks (no transform() call mid-execution → no
316
+ // mid-tag risk; the buffered transform upstream coalesced HTML
317
+ // chunks to coherent fragments).
318
+ if (this.pending.length > 0) onYieldDrain();
319
+ }
320
+ }
321
+ } catch (err) {
322
+ // Release the source on any failure (a timed-out read leaves it live);
323
+ // abort() skips the cancel once the loop is done.
324
+ this.reader.cancel(err);
325
+ this.machine.send({ type: 'PULL_ERROR', error: err });
326
+ }
327
+ }
328
+ }
@@ -16,7 +16,7 @@
16
16
  */
17
17
 
18
18
  import { nonceAttr } from './render-utils.ts';
19
- import { formStateToBase64 } from '../shared/form-state-flight.ts';
19
+ import { flightBytesToBase64 } from '../shared/flight-base64.ts';
20
20
 
21
21
  // ─── JSON Escaping ────────────────────────────────────────────────────────
22
22
 
@@ -67,6 +67,18 @@ export function flightChunkScript(data: string, nonce?: string): string {
67
67
  return `<script${nonceAttr(nonce)}>(${FLIGHT_VAR}=${FLIGHT_VAR}||[]).push(${escaped})</script>`;
68
68
  }
69
69
 
70
+ /**
71
+ * Generate a push script for Flight bytes that are not valid UTF-8 — the
72
+ * binary row of a typed array or ArrayBuffer, which a `[1, text]` tuple
73
+ * cannot carry. Sent as base64 in a `[3, base64]` tuple; the browser
74
+ * decodes it back to the same bytes (client/browser-entry/rsc-stream.ts).
75
+ * Base64 has no character that can end the script element or the string,
76
+ * the same argument {@link formStateScript} makes.
77
+ */
78
+ export function flightBinaryChunkScript(bytes: Uint8Array, nonce?: string): string {
79
+ return `<script${nonceAttr(nonce)}>(${FLIGHT_VAR}=${FLIGHT_VAR}||[]).push([3,"${flightBytesToBase64(bytes)}"])</script>`;
80
+ }
81
+
70
82
  /**
71
83
  * Generate the script that embeds a no-JS action's form state for
72
84
  * hydration: its Flight bytes (server/form-state-flight.ts), as base64. Only
@@ -76,5 +88,5 @@ export function flightChunkScript(data: string, nonce?: string): string {
76
88
  * §"No-JS Result Round-Trip".
77
89
  */
78
90
  export function formStateScript(bytes: Uint8Array, nonce?: string): string {
79
- return `<script${nonceAttr(nonce)}>self.__timber_form_state="${formStateToBase64(bytes)}"</script>`;
91
+ return `<script${nonceAttr(nonce)}>self.__timber_form_state="${flightBytesToBase64(bytes)}"</script>`;
80
92
  }