@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,23 @@
1
+ /**
2
+ * Whether this runtime streams with native Node streams — the one probe every
3
+ * stream-kind decision reads: the Flight renderer (`rsc-runtime/rsc.ts`), the
4
+ * Flight source helpers (`flight-source.ts`), SSR's Flight decoder
5
+ * (`rsc-runtime/ssr.ts`), and SSR's HTML pipeline (`ssr-render.ts`,
6
+ * `ssr-entry.ts`). The RSC and SSR environments evaluate this module
7
+ * separately, and agree because it is a pure function of the runtime: a Node
8
+ * Flight source must only ever meet SSR's Node pipeline (TIM-1585).
9
+ *
10
+ * On Node, Bun, and Deno, `node:stream` is native. Cloudflare Workers with
11
+ * `nodejs_compat` also report `process.release.name === 'node'` (workerd's
12
+ * native `node:process`, compatibility dates from 2025 on), but implement
13
+ * `node:stream` in JS on top of Web Streams, which are the native path there;
14
+ * workerd identifies itself through `navigator.userAgent`.
15
+ *
16
+ * No other runtime check may decide a stream kind. Loading the Node entries
17
+ * on a runtime this accepts is not optional: an import failure is a build or
18
+ * install bug, and fails loudly where the import happens.
19
+ */
20
+ export const nodeStreamsPlatform: boolean =
21
+ typeof process !== 'undefined' &&
22
+ process.release?.name === 'node' &&
23
+ !(typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers');
@@ -31,6 +31,7 @@ import type { PhaseName } from './pipeline-outcome.ts';
31
31
  import { canonicalRequestPath } from './canonicalize.ts';
32
32
  import { isRscRequest } from '../shared/rsc-media-type.ts';
33
33
  import { appVisibleSearch } from '../shared/rsc-cache-key.ts';
34
+ import { withResponseInit } from './node-response.ts';
34
35
 
35
36
  // ─── Prototype-Pollution-Safe Sanitizer ────────────────────────────────────
36
37
 
@@ -238,7 +239,8 @@ export function mergeMissingHeaders(target: Headers, source: Headers): void {
238
239
  * rewrap at the framework boundary instead.
239
240
  */
240
241
  export function cloneWithMutableHeaders(response: Response): Response {
241
- return new Response(response.body, {
242
+ // A Node body (SSR, Flight payloads on Node) moves across as is.
243
+ return withResponseInit(response, {
242
244
  status: response.status,
243
245
  statusText: response.statusText,
244
246
  headers: new Headers(response.headers),
@@ -43,6 +43,7 @@ import { RSC_KEY_HEADERS } from '../shared/rsc-cache-key.ts';
43
43
  import { isDebug } from './debug.ts';
44
44
  import type { ReactFormState } from 'react-dom/client';
45
45
  import type { ActionErrorForRender } from './als-registry.ts';
46
+ import { nodeBodyOps } from './node-response.ts';
46
47
 
47
48
  // ─── Route Match Result ────────────────────────────────────────────────────
48
49
 
@@ -533,12 +534,19 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
533
534
  // detailed mode is on. Logs firstChunk/lastChunk/maxGap/close
534
535
  // on stream close — measures the post-flush stream tail that
535
536
  // the Server-Timing header can't capture (TIM-1106).
536
- if (serverTiming === 'detailed' && result.body) {
537
- result = new Response(wrapResponseWithStreamTiming(result.body, startTime), {
538
- status: result.status,
539
- statusText: result.statusText,
540
- headers: result.headers,
541
- });
537
+ if (serverTiming === 'detailed') {
538
+ // A Node body is timed as a Node stream; reading `.body`
539
+ // would convert it to a Web one.
540
+ const nodeBody = nodeBodyOps(result);
541
+ if (nodeBody) {
542
+ result = nodeBody.timed(startTime);
543
+ } else if (result.body) {
544
+ result = new Response(wrapResponseWithStreamTiming(result.body, startTime), {
545
+ status: result.status,
546
+ statusText: result.statusText,
547
+ headers: result.headers,
548
+ });
549
+ }
542
550
  }
543
551
 
544
552
  return result;
@@ -8,9 +8,9 @@ import { createElement } from 'react';
8
8
 
9
9
  import { SlotOutlet } from '../../client/slot-outlet.tsx';
10
10
  import type { CoercedParams } from '../../shared/param-value.ts';
11
- import { renderToReadableStream } from '../../rsc-runtime/rsc.ts';
11
+ import { renderFlight } from '../../rsc-runtime/rsc.ts';
12
12
  import { requestContextAls } from '../als-registry.ts';
13
- import { readAllBytesWithDeadline } from '../stream-utils.ts';
13
+ import { collectFlightBytes } from '../flight-source.ts';
14
14
  import type { PrebuiltRegistration } from '../prebuilt-runtime.ts';
15
15
  import { createCaptureScope, type NestedWrapperRender } from './capture-state.ts';
16
16
  import { resolveTags } from './lifetime.ts';
@@ -80,7 +80,7 @@ export async function renderEntry(
80
80
  // inside it reports to this entry (cycle + nesting clamp).
81
81
  bytes = await capture.run(() =>
82
82
  requestContextAls.run(store, async () => {
83
- const stream = renderToReadableStream(
83
+ const source = renderFlight(
84
84
  createElement(registration.component as RenderableComponent, renderProps),
85
85
  {
86
86
  onError(error: unknown) {
@@ -93,14 +93,14 @@ export async function renderEntry(
93
93
  );
94
94
  // On timeout the reader is cancelled, never abandoned mid-read
95
95
  // (design/13 A2/A3), and the entry fails.
96
- const drained = await readAllBytesWithDeadline(stream, timeoutMs, 'render');
96
+ const drained = await collectFlightBytes(source, timeoutMs, 'render');
97
97
  const tags = resolveTags(registration.options, props);
98
98
  resolvedTags = tags.length > 0 ? tags : undefined;
99
99
  return drained;
100
100
  })
101
101
  );
102
102
  } catch (error) {
103
- // Sync component throw (renderToReadableStream creation), drain
103
+ // Sync component throw (render creation), drain
104
104
  // timeout, or stream error.
105
105
  failure ??= error;
106
106
  }
@@ -67,7 +67,7 @@ import { lookupOverlay, storeOverlayEntry, overlayKey } from './prebuilt/overlay
67
67
  import { getWaitUntil } from './waituntil-bridge.ts';
68
68
  import { runBackgroundFlight } from './pipeline-helpers.ts';
69
69
  import { runOutsideReactCacheScope } from './react-cache-scope.ts';
70
- import { readAllBytesWithDeadline } from './stream-utils.ts';
70
+ import { collectFlightBytes, type RenderFlight } from './flight-source.ts';
71
71
  import { DEFAULT_RENDER_TIMEOUT_MS } from './render-timeout.ts';
72
72
  import { createSingleflight } from '../cache/singleflight.ts';
73
73
  import {
@@ -265,10 +265,7 @@ async function tryReviveSlotShell(
265
265
 
266
266
  interface RscFunctions {
267
267
  createFromReadableStream: (stream: ReadableStream<Uint8Array>) => Promise<unknown>;
268
- renderToReadableStream: (
269
- element: unknown,
270
- options?: { onError?: (error: unknown) => string }
271
- ) => ReadableStream<Uint8Array>;
268
+ renderFlight: RenderFlight;
272
269
  }
273
270
 
274
271
  let rscFns: RscFunctions | null = null;
@@ -331,7 +328,7 @@ async function captureComponentPayload(
331
328
  props: Record<string, unknown>,
332
329
  options: PrebuiltComponentOptions
333
330
  ): Promise<CapturedPayload> {
334
- const { renderToReadableStream } = requireRscFunctions();
331
+ const { renderFlight } = requireRscFunctions();
335
332
  const element = createElement(component as RenderableComponent, props);
336
333
  // Render inside a capture scope so nested cache.component wrappers render
337
334
  // live (bake flat into this entry) per design/45 §Nesting Semantics. The
@@ -355,16 +352,16 @@ async function captureComponentPayload(
355
352
  // requests), so it must not bake in values memoized for the request
356
353
  // that happened to trigger it. Flight gives the capture its own
357
354
  // per-render cache instead (TIM-1529).
358
- const stream: ReadableStream<Uint8Array> = runOutsideReactCacheScope(() =>
359
- renderToReadableStream(element, {
355
+ const source = runOutsideReactCacheScope(() =>
356
+ renderFlight(element, {
360
357
  onError(error: unknown) {
361
358
  renderError ??= { error };
362
359
  return '';
363
360
  },
364
361
  })
365
362
  );
366
- const bytes = await readAllBytesWithDeadline(
367
- stream,
363
+ const bytes = await collectFlightBytes(
364
+ source,
368
365
  getCaptureTimeoutMs(),
369
366
  '[timber] component re-render capture'
370
367
  );
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import { createElement } from 'react';
13
- import { renderToReadableStream } from '../../rsc-runtime/rsc.ts';
13
+ import { renderFlight } from '../../rsc-runtime/rsc.ts';
14
14
 
15
15
  import type { RouteMatch } from '../pipeline.ts';
16
16
  import { logRenderError } from '../logger.ts';
@@ -27,7 +27,7 @@ import { isRscRequest } from '../../shared/rsc-media-type.ts';
27
27
  import { withPublishedParams } from '../publish-params.ts';
28
28
  import { getCookiesForSsr } from '../cookie-context.ts';
29
29
  import { callSsr } from './ssr-bridge.ts';
30
- import { teeWithErrorPropagation } from '../stream-utils.ts';
30
+ import { cancelFlightSource, teeFlightSource, type FlightSource } from '../flight-source.ts';
31
31
  import { isDevMode } from '../debug.ts';
32
32
  import { clientErrorMessage } from '../client-error-message.ts';
33
33
  import { ErrorReconstituter } from '../../client/error-reconstituter.tsx';
@@ -289,15 +289,17 @@ async function renderErrorPageViaRsc(
289
289
  // wrap, which every payload the server sends needs. An error page on a
290
290
  // dynamic route reads params like any other page, and SSR would get them
291
291
  // from the request ALS while the hydrated client got an empty record.
292
+ let inlineStream: FlightSource | undefined;
292
293
  try {
293
- const rscStream = renderToReadableStream(withPublishedParams(element), {
294
+ const rscStream = renderFlight(withPublishedParams(element), {
294
295
  signal: req.signal,
295
296
  onError(err: unknown) {
296
297
  reportRenderError(err, req, { segments: match.segments });
297
298
  },
298
299
  });
299
300
 
300
- const [ssrStream, inlineStream] = teeWithErrorPropagation(rscStream);
301
+ let ssrStream: FlightSource;
302
+ [ssrStream, inlineStream] = teeFlightSource(rscStream);
301
303
 
302
304
  const nonce = getCspNonce();
303
305
  const navContext: NavContext = {
@@ -322,6 +324,8 @@ async function renderErrorPageViaRsc(
322
324
  // errors in user error page code. Terminates in the framework default
323
325
  // page, not a blank body: a crashing error page is precisely when the
324
326
  // reader has nothing else to go on (TIM-1258).
327
+ // Nothing will read the inline branch now; release the render.
328
+ if (inlineStream) cancelFlightSource(inlineStream);
325
329
  logRenderError({ method: req.method, path: url.pathname, error: renderError });
326
330
  return defaultStatusPageResponse(status, responseHeaders);
327
331
  }
@@ -63,6 +63,7 @@ import { isDebug, isDevMode, setDebugFromConfig } from '../debug.ts';
63
63
  import { capturePrebuiltPayloads } from '../prebuilt-builder.ts';
64
64
  import { setPrebuiltPayloadSource } from '../prebuilt/payload-source.ts';
65
65
  import { setRscFunctions, setComponentRefreshTimeout } from '../prebuilt-runtime.ts';
66
+ import { cancelFlightSource, setFlightRenderTimeout } from '../flight-source.ts';
66
67
  import { installReactCacheBridge } from '../react-cache-bridge.ts';
67
68
  import { setKeyDisciplineStrict } from '../prebuilt/key-discipline.ts';
68
69
  import { createAutoSitemapHandler } from '../sitemap-handler.ts';
@@ -176,14 +177,14 @@ async function createRequestHandler(manifest: typeof routeManifest, runtimeConfi
176
177
  const rscMod = await import('../../rsc-runtime/rsc.ts');
177
178
  setRscFunctions({
178
179
  createFromReadableStream: rscMod.createFromReadableStream,
179
- renderToReadableStream: rscMod.renderToReadableStream,
180
+ renderFlight: rscMod.renderFlight,
180
181
  });
181
182
 
182
183
  // One React.cache scope per request, shared by proxy.ts, middleware.ts,
183
184
  // route handlers, and the render (TIM-1529). Flight installs its
184
185
  // dispatcher lazily, so the warm-up constructs one throwaway render.
185
186
  const bridge = installReactCacheBridge(() => {
186
- rscMod.renderToReadableStream(null, { onError() {} }).cancel();
187
+ cancelFlightSource(rscMod.renderFlight(null, { onError() {} }));
187
188
  });
188
189
  if (!bridge.installed) {
189
190
  console.warn(
@@ -495,6 +496,7 @@ const renderTimeoutMs = (config as Record<string, unknown>).renderTimeoutMs as n
495
496
  const { setDefaultSingleflightTimeout } = await import('../../cache/timber-cache.ts');
496
497
  setDefaultSingleflightTimeout(renderTimeoutMs);
497
498
  setComponentRefreshTimeout(renderTimeoutMs);
499
+ setFlightRenderTimeout(renderTimeoutMs);
498
500
 
499
501
  const cacheConfig = (config as Record<string, unknown>).cache as
500
502
  | { strictKeyDiscipline?: boolean }
@@ -53,7 +53,10 @@ export interface RenderRouteDeps {
53
53
  clientSegmentCache: boolean;
54
54
  renderDenyFallback: DenyFallbackRenderer;
55
55
  buildManifest: BuildManifest;
56
- /** The resolved `renderTimeoutMs`: bounds encoding a no-JS form state. */
56
+ /**
57
+ * The resolved `renderTimeoutMs`: bounds the page's Flight render (on Node)
58
+ * and encoding a no-JS form state.
59
+ */
57
60
  renderTimeoutMs: number;
58
61
  globalError?: { load: () => Promise<unknown>; filePath: string };
59
62
  }
@@ -191,7 +194,7 @@ export async function renderRoute(
191
194
 
192
195
  // Render to RSC Flight stream with signal tracking.
193
196
  const _rscStart = performance.now();
194
- const { rscStream, signals } = renderRscStream(payload, req, leafDenyChain);
197
+ const { rscStream, signals } = renderRscStream(payload, req, deps.renderTimeoutMs, leafDenyChain);
195
198
 
196
199
  recordTiming({
197
200
  name: 'rsc-init',
@@ -25,10 +25,17 @@ import type { SlotSkipEntry } from '../slot-resolver.ts';
25
25
 
26
26
  import { buildSegmentInfo } from './helpers.ts';
27
27
  import { RSC_CONTENT_TYPE } from '../../shared/rsc-media-type.ts';
28
+ import { getFirstDeniedSegmentIndex } from '../deny-boundary.ts';
28
29
 
29
30
  import { rscErrorEnvelope } from '../rsc-error-envelope.ts';
30
31
 
31
32
  import type { RenderSignals } from './render-signals.ts';
33
+ import {
34
+ cancelFlightSource,
35
+ flightResponse,
36
+ peekFlight,
37
+ type FlightSource,
38
+ } from '../flight-source.ts';
32
39
 
33
40
  /**
34
41
  * Ceiling on waiting for a first chunk that is already in flight, used only
@@ -42,11 +49,13 @@ const FIRST_CHUNK_CEILING_MS = 50;
42
49
  /**
43
50
  * Build an RSC payload Response for a client-side navigation request.
44
51
  *
45
- * Reads the first chunk from the RSC stream before committing headers.
46
- * Async components throw during stream consumption, not during
47
- * renderToReadableStream. Reading one chunk triggers rendering of the
48
- * initial component tree, allowing onError to capture DenySignal/
49
- * RedirectSignal before we commit the response. See TIM-344.
52
+ * Waits for the first chunk of the Flight source before committing headers.
53
+ * Async components throw during stream consumption, not when the render
54
+ * starts. Waiting for one chunk lets the initial component tree render,
55
+ * allowing onError to capture DenySignal/RedirectSignal before we commit the
56
+ * response. See TIM-344. The chunk is not consumed (`peekFlight`): on Node
57
+ * it stays in the source, which becomes the response through `flightResponse`
58
+ * — a Node body, piped to the socket as is.
50
59
  *
51
60
  * The commit point is the close of Flight's opening window: the first chunk
52
61
  * plus one macrotask turn. Nothing is held for it. A signal that lands
@@ -63,7 +72,7 @@ const FIRST_CHUNK_CEILING_MS = 50;
63
72
  * nested components, and was removed in TIM-1495.
64
73
  */
65
74
  export async function buildRscPayloadResponse(
66
- rscStream: ReadableStream<Uint8Array>,
75
+ rscStream: FlightSource,
67
76
  signals: RenderSignals,
68
77
  segments: ManifestSegmentNode[],
69
78
  layoutComponents: LayoutComponentEntry[],
@@ -71,8 +80,8 @@ export async function buildRscPayloadResponse(
71
80
  skippedSegments?: string[],
72
81
  slotSkipInfo?: SlotSkipEntry[]
73
82
  ): Promise<Response> {
74
- // Read the first chunk from the RSC stream before committing headers.
75
- // Race the first read against signal detection — if an async component
83
+ // Wait for the first chunk of the Flight source before committing headers.
84
+ // Race it against signal detection — if an async component
76
85
  // throws a RedirectSignal or DenySignal, the onError callback resolves
77
86
  // signals.captured and we can react immediately without waiting for
78
87
  // the full macrotask queue.
@@ -87,32 +96,28 @@ export async function buildRscPayloadResponse(
87
96
  // per-request setTimeout(0) macrotask delay for the common case
88
97
  // (no signal). A 50ms ceiling timeout guards against edge cases
89
98
  // where onError never fires.
90
- const reader = rscStream.getReader();
91
-
92
- type RaceResult =
93
- | { type: 'data'; chunk: ReadableStreamReadResult<Uint8Array> }
94
- | { type: 'signal' };
95
-
96
- // Retained rather than inlined into the race below. When a signal wins, the
97
- // usual answer is to cancel — but an ADDRESSED deny is one whose error row
98
- // the client's boundary is going to render, so that payload has to survive
99
- // (TIM-1356). Taking delivery of the read already in flight is not the
100
- // "bare read() after a signal won" the async rules forbid; issuing a second
101
- // one would be. It still gets a ceiling below.
102
- const pendingRead = reader.read();
99
+ //
100
+ // The wait is retained rather than inlined into the race below. When a
101
+ // signal wins, the usual answer is to cancel — but an ADDRESSED deny is one
102
+ // whose error row the client's boundary is going to render, so that payload
103
+ // has to survive (TIM-1356). Taking delivery of the first chunk already
104
+ // being waited for is not the "bare read() after a signal won" the async
105
+ // rules forbid; issuing a second read would be. It still gets a ceiling below.
106
+ const peek = peekFlight(rscStream);
107
+ const source = peek.source;
103
108
 
104
- let first: RaceResult;
109
+ let first: 'data' | 'signal';
105
110
  try {
106
111
  first = await Promise.race([
107
- pendingRead.then((chunk) => ({ type: 'data' as const, chunk })),
108
- signals.captured.then(() => ({ type: 'signal' as const })),
112
+ peek.ready.then(() => 'data' as const),
113
+ signals.captured.then(() => 'signal' as const),
109
114
  ]);
110
115
  } catch (_readError) {
111
116
  // The RSC stream itself errored on first read. (A component's error is
112
117
  // not this: it arrives as an error row in a stream that reads fine.)
113
118
  // Return an error response so the client can hard-navigate for the
114
119
  // SSR-rendered error page. See design/10-error-handling.md.
115
- reader.cancel().catch(() => {});
120
+ cancelFlightSource(source);
116
121
  return rscErrorEnvelope(500, responseHeaders);
117
122
  }
118
123
 
@@ -129,7 +134,7 @@ export async function buildRscPayloadResponse(
129
134
  // tracked and nothing is waited for: the cost is one timer turn, and the
130
135
  // status is 200 either way — this decides which mechanism answers, not
131
136
  // what the response claims.
132
- if (first.type === 'data' && !signals.redirectSignal && !signals.denySignal) {
137
+ if (first === 'data' && !signals.redirectSignal && !signals.denySignal) {
133
138
  await new Promise<void>((r) => setTimeout(r, 0));
134
139
  }
135
140
 
@@ -139,7 +144,7 @@ export async function buildRscPayloadResponse(
139
144
  // A redirect or an unplaced deny replaces the payload, so the stream is
140
145
  // released before the signal is rethrown to the pipeline.
141
146
  if (signals.redirectSignal) {
142
- reader.cancel().catch(() => {});
147
+ cancelFlightSource(source);
143
148
  throw signals.redirectSignal;
144
149
  }
145
150
  // An addressed deny needs no fallback: the payload already carries its error
@@ -155,18 +160,17 @@ export async function buildRscPayloadResponse(
155
160
  // first. See TIM-1356. The fallback also owns the hard-navigate answer
156
161
  // for a deny AccessGate marked `_hardNavigate` (TIM-1363).
157
162
  if (signals.unplacedDeny) {
158
- reader.cancel().catch(() => {});
163
+ cancelFlightSource(source);
159
164
  throw signals.unplacedDeny;
160
165
  }
161
166
 
162
- // Extract the first chunk from the race result. If a signal won the race,
163
- // the redirect and the unplaced deny were rethrown above, so only an
164
- // addressed deny reaches the second branch. The last branch is a fail-safe
165
- // for a signal that is neither: it cancels the reader rather than issuing
166
- // a bare read() that could hang forever on a stalled stream (TIM-519).
167
- let firstRead: ReadableStreamReadResult<Uint8Array>;
168
- if (first.type === 'data') {
169
- firstRead = first.chunk;
167
+ // If a signal won the race, the redirect and the unplaced deny were
168
+ // rethrown above, so only an addressed deny reaches the first branch. The
169
+ // last branch is a fail-safe for a signal that is neither: it cancels the
170
+ // stream rather than waiting on one that could hang forever (TIM-519).
171
+ let body: FlightSource | null;
172
+ if (first === 'data') {
173
+ body = source;
170
174
  } else if (signals.denySignal?.owners) {
171
175
  // An addressed deny won the race before its own error row surfaced.
172
176
  // Cancelling here would hand the client a 4xx payload with nothing in it
@@ -174,12 +178,13 @@ export async function buildRscPayloadResponse(
174
178
  // nothing at all. Take delivery of the read already in flight instead,
175
179
  // under a ceiling so a stalled stream still cannot hang the response.
176
180
  const TIMED_OUT = Symbol('first-chunk-timeout');
181
+ let ceiling: ReturnType<typeof setTimeout> | undefined;
177
182
  const raced = await Promise.race([
178
- pendingRead,
179
- new Promise<typeof TIMED_OUT>((resolve) =>
180
- setTimeout(() => resolve(TIMED_OUT), FIRST_CHUNK_CEILING_MS)
181
- ),
182
- ]);
183
+ peek.ready,
184
+ new Promise<typeof TIMED_OUT>((resolve) => {
185
+ ceiling = setTimeout(() => resolve(TIMED_OUT), FIRST_CHUNK_CEILING_MS);
186
+ }),
187
+ ]).finally(() => clearTimeout(ceiling));
183
188
 
184
189
  // Missing the ceiling must not be reported as a finished stream. Under
185
190
  // event-loop contention or slow serialization the row is late rather than
@@ -198,38 +203,15 @@ export async function buildRscPayloadResponse(
198
203
  // is a real cost, on a path that needs a status page and a stalled stream
199
204
  // to reach at all.
200
205
  if (raced === TIMED_OUT) {
201
- reader.cancel().catch(() => {});
206
+ cancelFlightSource(source);
202
207
  return rscErrorEnvelope(signals.denySignal.status, responseHeaders);
203
208
  }
204
- firstRead = raced;
209
+ body = source;
205
210
  } else {
206
- await reader.cancel();
207
- firstRead = { done: true, value: undefined };
211
+ cancelFlightSource(source);
212
+ body = null;
208
213
  }
209
214
 
210
- // Reconstruct the stream: prepend the buffered first chunk,
211
- // then continue piping from the original reader.
212
- const patchedStream = new ReadableStream<Uint8Array>({
213
- start(controller) {
214
- if (firstRead.value) controller.enqueue(firstRead.value);
215
- if (firstRead.done) {
216
- controller.close();
217
- return;
218
- }
219
- },
220
- async pull(controller) {
221
- const { value, done } = await reader.read();
222
- if (done) {
223
- controller.close();
224
- return;
225
- }
226
- controller.enqueue(value);
227
- },
228
- cancel() {
229
- reader.cancel();
230
- },
231
- });
232
-
233
215
  responseHeaders.set('content-type', `${RSC_CONTENT_TYPE}; charset=utf-8`);
234
216
 
235
217
  // Metadata (<title>/<meta>/<link>) now rides the RSC Flight payload as
@@ -244,7 +226,6 @@ export async function buildRscPayloadResponse(
244
226
  // it. Recorded in ALS during render by AccessGate's catch path; a gate that
245
227
  // denies after this point leaves it unset, and the header then describes
246
228
  // the full chain, which is the merge-point answer either way.
247
- const { getFirstDeniedSegmentIndex } = await import('../deny-boundary.ts');
248
229
  const resolvedDenyIndex = getFirstDeniedSegmentIndex();
249
230
 
250
231
  // Emitted in full even when a deny rendered, because this header answers two
@@ -281,8 +262,6 @@ export async function buildRscPayloadResponse(
281
262
  // for every nested component that denies after I/O, and a status that is
282
263
  // sometimes right is a contract nothing may rely on. So it makes no claim.
283
264
  // See design/04-authorization.md §"Status codes on the RSC payload path".
284
- return new Response(patchedStream, {
285
- status: 200,
286
- headers: responseHeaders,
287
- });
265
+ const init = { status: 200, headers: responseHeaders };
266
+ return body ? flightResponse(body, init) : new Response(null, init);
288
267
  }