@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
@@ -20,19 +20,14 @@ import config from 'virtual:timber-config';
20
20
  import schemaCodecs from 'virtual:timber-schema';
21
21
  import { setLinkCodecs } from '../params/codec-registry.ts';
22
22
  setLinkCodecs(schemaCodecs);
23
- import {
24
- createFromReadableStream,
25
- createFromNodeStream,
26
- hasNodeStreamDecode,
27
- } from '../rsc-runtime/ssr.ts';
23
+ import { createFromReadableStream, createFromNodeStream } from '../rsc-runtime/ssr.ts';
28
24
  import { AsyncLocalStorage } from 'node:async_hooks';
29
25
 
30
26
  import {
31
27
  renderSsrStream,
32
28
  renderSsrNodeStream,
33
- nodeReadableToWeb,
34
29
  useNodeStreams,
35
- buildSsrResponse,
30
+ ssrResponseInit,
36
31
  type SsrStreamOptions,
37
32
  } from './ssr-render.ts';
38
33
  import { SsrStreamError } from './signal-identity.ts';
@@ -44,6 +39,7 @@ import { splitPayloadRoot } from '../shared/payload-root.ts';
44
39
  import { formStateForSsr } from './ssr-form-state.ts';
45
40
  import { resolveRenderTimeoutMs } from './render-timeout.ts';
46
41
  import type { NavContext, SsrRenderResult } from './ssr-bridge-types.ts';
42
+ import type { FlightSource } from './flight-source.ts';
47
43
 
48
44
  // Pre-import Node.js stream modules at module load time — not per-request.
49
45
  // Dynamic imports of node-stream-transforms and node:stream/promises were
@@ -54,29 +50,24 @@ let _nodeStreamImports: {
54
50
  createNodeMoveSuffixTransform: typeof import('./node-stream-transforms.ts').createNodeMoveSuffixTransform;
55
51
  createNodeFlightInjector: typeof import('./node-stream-transforms.ts').createNodeFlightInjector;
56
52
  runNodePipelineWithErrorHandling: typeof import('./node-stream-transforms.ts').runNodePipelineWithErrorHandling;
57
- ReadableFromWeb: (
58
- webStream: import('stream/web').ReadableStream
59
- ) => import('node:stream').Readable;
53
+ NodeBodyResponse: typeof import('./node-body-response.ts').NodeBodyResponse;
60
54
  } | null = null;
61
55
 
56
+ // No fallback: on Node the RSC side renders Node Flight sources, which only
57
+ // this pipeline accepts (server/node-streams-platform.ts).
62
58
  if (useNodeStreams) {
63
- try {
64
- const [transforms, stream] = await Promise.all([
65
- import('./node-stream-transforms.ts'),
66
- import('node:stream'),
67
- ]);
68
- _nodeStreamImports = {
69
- createNodeBufferedTransform: transforms.createNodeBufferedTransform,
70
- createNodeHeadInjector: transforms.createNodeHeadInjector,
71
- createNodeMoveSuffixTransform: transforms.createNodeMoveSuffixTransform,
72
- createNodeFlightInjector: transforms.createNodeFlightInjector,
73
- runNodePipelineWithErrorHandling: transforms.runNodePipelineWithErrorHandling,
74
- ReadableFromWeb: (webStream: import('stream/web').ReadableStream) =>
75
- stream.Readable.fromWeb(webStream) as import('node:stream').Readable,
76
- };
77
- } catch {
78
- // Fall back to Web Streams path
79
- }
59
+ const [transforms, { NodeBodyResponse }] = await Promise.all([
60
+ import('./node-stream-transforms.ts'),
61
+ import('./node-body-response.ts'),
62
+ ]);
63
+ _nodeStreamImports = {
64
+ NodeBodyResponse,
65
+ createNodeBufferedTransform: transforms.createNodeBufferedTransform,
66
+ createNodeHeadInjector: transforms.createNodeHeadInjector,
67
+ createNodeMoveSuffixTransform: transforms.createNodeMoveSuffixTransform,
68
+ createNodeFlightInjector: transforms.createNodeFlightInjector,
69
+ runNodePipelineWithErrorHandling: transforms.runNodePipelineWithErrorHandling,
70
+ };
80
71
  }
81
72
 
82
73
  // ─── SSR Data ALS ─────────────────────────────────────────────────────────
@@ -93,11 +84,12 @@ const ssrDataAls = new AsyncLocalStorage<SsrData>();
93
84
  registerSsrDataProvider(() => ssrDataAls.getStore());
94
85
 
95
86
  /**
96
- * Handle SSR: decode an RSC stream and render it to hydration-ready HTML.
87
+ * Handle SSR: decode a Flight source and render it to hydration-ready HTML.
97
88
  *
98
89
  * Steps:
99
- * 1. Decode the RSC stream into a React element tree via createFromReadableStream
100
- * (resolves "use client" references to actual component modules for SSR)
90
+ * 1. Decode the Flight source into a React element tree via createFromNodeStream
91
+ * (Node) or createFromReadableStream (Workers), resolving "use client"
92
+ * references to actual component modules for SSR
101
93
  * 2. Render the decoded tree to HTML via renderToReadableStream (streaming)
102
94
  * 3. Wait for onShellReady before flushing (handled by renderSsrStream)
103
95
  * 4. Inject metadata into <head> and client scripts before </body>
@@ -112,12 +104,13 @@ registerSsrDataProvider(() => ssrDataAls.getStore());
112
104
  * the deny page. For deny() inside Suspense, the shell
113
105
  * succeeds and the error streams as a React error boundary after flush.
114
106
  *
115
- * @param rscStream - The ReadableStream from the RSC environment
107
+ * @param rscSource - The Flight source from the RSC environment: a Node stream
108
+ * on Node, a Web stream elsewhere, matching the HTML pipeline SSR runs
116
109
  * @param navContext - Per-request state passed across RSC→SSR boundary
117
110
  * @returns The HTML Response with hydration markers, plus SSR diagnostics
118
111
  */
119
112
  export async function handleSsr(
120
- rscStream: ReadableStream<Uint8Array>,
113
+ rscSource: FlightSource,
121
114
  navContext: NavContext
122
115
  ): Promise<SsrRenderResult> {
123
116
  return withSpan('timber.ssr', { 'timber.environment': 'ssr' }, async () => {
@@ -144,23 +137,29 @@ export async function handleSsr(
144
137
  // map, importing the actual components for server-side rendering.
145
138
  const _ssrStart = performance.now();
146
139
 
147
- // Decode the RSC stream into a React element tree.
148
- // On Node.js: convert Web ReadableStream → Node Readable → createFromNodeStream
149
- // (eliminates Promise-per-chunk overhead from Web Streams reader)
150
- // On Workers: createFromReadableStream (Web Streams are V8-native C++ there)
140
+ // Decode the Flight source into a React element tree. Each platform
141
+ // renders Flight in its own stream kind (server/flight-source.ts), so
142
+ // the source matches the HTML pipeline chosen below; nothing adapts one
143
+ // kind into the other.
144
+ // - Node.js: createFromNodeStream reads the object-mode Node stream,
145
+ // string chunks included (no Web Streams hop).
146
+ // - Workers: createFromReadableStream (Web Streams are V8-native there).
151
147
  //
152
148
  // The request CSP nonce goes to the Flight decoder too: Flight emits
153
149
  // `<script>` preinits for client-reference modules, and those need
154
150
  // the nonce as much as timber's own inline tags do (TIM-1414).
155
151
  const nonce = navContext.nonce;
156
152
  let root: unknown;
157
- if (hasNodeStreamDecode && _nodeStreamImports) {
158
- const nodeRscStream = _nodeStreamImports.ReadableFromWeb(
159
- rscStream as import('stream/web').ReadableStream
160
- );
161
- root = createFromNodeStream(nodeRscStream, { nonce });
153
+ if (_nodeStreamImports) {
154
+ if (rscSource.kind !== 'node' || !createFromNodeStream) {
155
+ throw new Error('[timber] SSR on Node received a Web Flight source');
156
+ }
157
+ root = createFromNodeStream(rscSource.stream, { nonce });
162
158
  } else {
163
- root = createFromReadableStream(rscStream, { nonce });
159
+ if (rscSource.kind !== 'web') {
160
+ throw new Error('[timber] SSR on Web Streams received a Node Flight source');
161
+ }
162
+ root = createFromReadableStream(rscSource.stream, { nonce });
164
163
  }
165
164
  // The payload root is `{ tree, params, slotParams }` — params ride
166
165
  // beside the tree rather than in a provider around it (TIM-1297).
@@ -187,8 +186,8 @@ export async function handleSsr(
187
186
  // Render to HTML stream (waits for onShellReady).
188
187
  //
189
188
  // Two paths based on platform:
190
- // - Node.js: renderToPipeableStream → Node Transform pipeline → Readable.toWeb() → Response
191
- // Entire pipeline stays in C++ native streams until the Response boundary.
189
+ // - Node.js: renderToPipeableStream → Node Transform pipeline → NodeBodyResponse
190
+ // The document stays a Node stream all the way to the socket.
192
191
  // - Workers: renderToReadableStream → Web TransformStream pipeline → Response
193
192
  // Web Streams are V8-native C++ built-ins on Workers.
194
193
  //
@@ -229,7 +228,8 @@ export async function handleSsr(
229
228
  );
230
229
  };
231
230
 
232
- let outputStream: ReadableStream<Uint8Array>;
231
+ const responseInit = ssrResponseInit(navContext.statusCode, navContext.responseHeaders);
232
+ let response: Response;
233
233
  let _renderEnd: number;
234
234
  if (_nodeStreamImports) {
235
235
  // Node.js fast path: full pipeline in native streams
@@ -239,6 +239,7 @@ export async function handleSsr(
239
239
  createNodeMoveSuffixTransform,
240
240
  createNodeFlightInjector,
241
241
  runNodePipelineWithErrorHandling,
242
+ NodeBodyResponse,
242
243
  } = _nodeStreamImports;
243
244
 
244
245
  const nodeHtmlStream = await renderSsrNodeStream(wrappedElement, renderOptions).catch(
@@ -256,10 +257,10 @@ export async function handleSsr(
256
257
  // 3. flightInjector: interleaves RSC scripts between HTML chunks (TIM-529)
257
258
  // 4. moveSuffix: strips </body></html>, re-emits at end (TIM-530)
258
259
  //
259
- // Post-shell error handling lives in the pump, not in a pipeline
260
- // stage: pipeline() destroys every stage on failure, so only an
261
- // output kept outside the pipeline can append the noindex script
262
- // and close cleanly (TIM-1019).
260
+ // Post-shell error handling lives in the pump, not in a stage: a
261
+ // failing stage takes the whole chain down, so only an output kept
262
+ // outside the chain can append the noindex script and close cleanly
263
+ // (TIM-1019).
263
264
  // Resolve the lazy segment script now that the shell is ready
264
265
  // (AccessGates have settled, ALS deny index is authoritative).
265
266
  const resolvedHeadHtml =
@@ -279,7 +280,9 @@ export async function handleSsr(
279
280
  navContext.signal,
280
281
  nonce
281
282
  );
282
- outputStream = nodeReadableToWeb(output);
283
+ // The document stays a Node stream to the socket: the adapter pipes
284
+ // it (`_toNodeResponse`), with no Web Streams round trip.
285
+ response = new NodeBodyResponse(output, responseInit);
283
286
  } else {
284
287
  // Web Streams path (CF Workers / fallback)
285
288
  const htmlStream = await renderSsrStream(wrappedElement, renderOptions).catch(renderFailed);
@@ -295,18 +298,19 @@ export async function handleSsr(
295
298
  // (AccessGates have settled, ALS deny index is authoritative).
296
299
  const resolvedHeadHtml =
297
300
  navContext.headHtml + formStateHead + (navContext.getHeadSegmentScript?.() ?? '');
298
- outputStream = htmlStream.pipeThrough(createBufferedTransformStream());
301
+ let outputStream = htmlStream.pipeThrough(createBufferedTransformStream());
299
302
  outputStream = injectHead(outputStream, resolvedHeadHtml);
300
303
  outputStream = injectRscPayload(outputStream, navContext.rscStream, {
301
304
  renderTimeoutMs,
302
305
  errorSignal: navContext._errorSignal,
303
306
  nonce,
304
307
  });
308
+ response = new Response(outputStream, responseInit);
305
309
  }
306
310
  const _pipelineEnd = performance.now();
307
311
 
308
312
  return {
309
- response: buildSsrResponse(outputStream, navContext.statusCode, navContext.responseHeaders),
313
+ response,
310
314
  timings: {
311
315
  decodeMs: Math.round(_decodeEnd - _ssrStart),
312
316
  shellMs: Math.round(_renderEnd - _decodeEnd),
@@ -26,6 +26,7 @@ import type { ReactFormState } from 'react-dom/client';
26
26
 
27
27
  import { createRenderTimeout, RenderTimeoutError } from './render-timeout.ts';
28
28
  import { logRenderError, logStreamingError } from './logger.ts';
29
+ import { nodeStreamsPlatform } from './node-streams-platform.ts';
29
30
  import { isAbortError, noindexScript } from './render-utils.ts';
30
31
 
31
32
  /**
@@ -71,52 +72,26 @@ function isFlightRelayedError(error: unknown): boolean {
71
72
 
72
73
  // ─── Platform Detection ──────────────────────────────────────────────────────
73
74
  //
74
- // Detect whether we're running on a platform with native Node.js streams.
75
- // On Node.js/Bun, `node:stream` is backed by C++ (libuv). On Cloudflare
76
- // Workers, `node:stream` via nodejs_compat is a JS polyfill — Web Streams
77
- // are the faster path there (V8-native C++ built-ins).
75
+ // Native Node streams or Web Streams, decided once by the platform probe every
76
+ // stream-kind decision shares (node-streams-platform.ts) — so SSR's pipeline
77
+ // always matches the kind of Flight source the RSC side renders. On Node the
78
+ // Node entries must load: a failure is a build bug and throws here, at module
79
+ // load, instead of silently falling back to a pipeline that rejects every
80
+ // Node Flight source.
78
81
  //
79
- // We detect once at module load to avoid per-request overhead.
80
- // The check: process.versions.node exists AND we can import node:stream.
81
- // Cloudflare Workers with nodejs_compat may polyfill process.versions but
82
- // the streams won't be native. The Readable.toWeb check confirms native support.
82
+ // The SSR bundle resolves react-dom/server to the edge/browser export (which
83
+ // lacks renderToPipeableStream), so the Node entry is imported explicitly.
83
84
 
84
- let _useNodeStreams = false;
85
85
  let _PassThrough: typeof import('node:stream').PassThrough | null = null;
86
- let _ReadableToWeb: ((readable: import('node:stream').Readable) => ReadableStream) | null = null;
87
86
  let _renderToPipeableStream: typeof import('react-dom/server').renderToPipeableStream | null = null;
88
87
 
89
- try {
90
- // Dynamic imports to avoid bundling node:stream and the Node.js-specific
91
- // react-dom/server entry for CF Workers builds.
92
- // On Node.js/Bun this resolves to native C++ streams.
93
- // On CF Workers this either fails or returns a JS polyfill.
94
- const nodeStream = await import('node:stream');
95
- if (
96
- typeof nodeStream.PassThrough === 'function' &&
97
- typeof nodeStream.Readable.toWeb === 'function' &&
98
- // Real Node.js — not a polyfill. Polyfills typically don't set
99
- // process.release.name to 'node'.
100
- typeof process !== 'undefined' &&
101
- process.release?.name === 'node'
102
- ) {
103
- // Dynamically import renderToPipeableStream from the Node.js-specific
104
- // entry point. The SSR bundle resolves react-dom/server to the edge/browser
105
- // export (which lacks renderToPipeableStream), so we import the .node file
106
- // directly. This is safe because we're inside a process.release.name === 'node'
107
- // guard — this code only runs on real Node.js.
108
- const reactDomServer = await import('react-dom/server.node');
109
- if (typeof reactDomServer.renderToPipeableStream === 'function') {
110
- _useNodeStreams = true;
111
- _PassThrough = nodeStream.PassThrough;
112
- _ReadableToWeb = nodeStream.Readable.toWeb as (
113
- readable: import('node:stream').Readable
114
- ) => ReadableStream;
115
- _renderToPipeableStream = reactDomServer.renderToPipeableStream;
116
- }
117
- }
118
- } catch {
119
- // node:stream or renderToPipeableStream not available — use Web Streams path
88
+ if (nodeStreamsPlatform) {
89
+ const [nodeStream, reactDomServer] = await Promise.all([
90
+ import('node:stream'),
91
+ import('react-dom/server.node'),
92
+ ]);
93
+ _PassThrough = nodeStream.PassThrough;
94
+ _renderToPipeableStream = reactDomServer.renderToPipeableStream;
120
95
  }
121
96
 
122
97
  /** Options shared by both SSR render paths (Node streams and Web Streams). */
@@ -145,7 +120,7 @@ export interface SsrStreamOptions {
145
120
  * Render a React element tree to a ReadableStream of HTML.
146
121
  *
147
122
  * Automatically selects the optimal rendering path for the platform:
148
- * - Node.js/Bun: `renderToPipeableStream` → Node.js native streams → `Readable.toWeb()`
123
+ * - Node.js/Bun: `renderToPipeableStream` → Node.js native streams (a `NodeBodyResponse`)
149
124
  * - CF Workers/Edge: `renderToReadableStream` → native Web Streams
150
125
  *
151
126
  * The returned stream begins yielding after onShellReady — everything
@@ -163,22 +138,21 @@ export async function renderSsrStream(
163
138
  }
164
139
 
165
140
  /** Whether the current platform uses native Node.js streams for SSR. */
166
- export const useNodeStreams = _useNodeStreams;
141
+ export const useNodeStreams = nodeStreamsPlatform;
167
142
 
168
143
  // ─── Node.js Path: renderToPipeableStream ────────────────────────────────────
169
144
  //
170
145
  // Uses React's Node.js-native API. HTML chunks flow through C++ stream
171
146
  // buffers with zero Promise allocations per chunk. Returns a Node.js
172
147
  // Readable — the caller (ssr-entry.ts) pipes through Node.js Transform
173
- // streams for injectHead/injectRscPayload before converting to Web
174
- // ReadableStream at the Response boundary.
148
+ // streams for injectHead/injectRscPayload and sends the result as a
149
+ // NodeBodyResponse, which the adapter pipes to the socket.
175
150
 
176
151
  /**
177
152
  * Render via renderToPipeableStream, returning a Node.js Readable.
178
153
  *
179
154
  * The entire HTML rendering + post-processing pipeline stays in native
180
- * Node.js streams (C++ backed). Only converted to Web ReadableStream
181
- * at the very end for the Response body.
155
+ * Node.js streams, to the socket (node-body-response.ts).
182
156
  */
183
157
  export async function renderSsrNodeStream(
184
158
  element: ReactNode,
@@ -215,11 +189,20 @@ export async function renderSsrNodeStream(
215
189
  resolve(passthrough);
216
190
  });
217
191
  } else {
218
- // No hold — allReady has almost certainly not fired yet.
219
- // Report false so the RSC entry runs the microtask retry loop.
220
- onFizzAllReadyResolved?.(allReadyFired);
221
- pipe(passthrough);
222
- resolve(passthrough);
192
+ // No hold — but give Fizz one task before the first pull. Its early
193
+ // work is scheduled as microtasks, and piping inside onShellReady
194
+ // flushes at once: anything that settles a few microtasks later (a
195
+ // Suspense boundary over cached data, streamed metadata) goes out
196
+ // as a fallback plus a reveal script instead of inline HTML — and
197
+ // the Web path, which flushes when the stream is pulled, inlines
198
+ // it. Next.js waits the same task (vercel/next.js#86311, #94347).
199
+ // When everything settles in that task, allReady has fired and the
200
+ // RSC entry skips its signal-promotion retry loop.
201
+ setImmediate(() => {
202
+ onFizzAllReadyResolved?.(allReadyFired);
203
+ pipe(passthrough);
204
+ resolve(passthrough);
205
+ });
223
206
  }
224
207
  },
225
208
 
@@ -288,13 +271,6 @@ export async function renderSsrNodeStream(
288
271
  });
289
272
  }
290
273
 
291
- /** Convert a Node.js Readable to a Web ReadableStream (zero-copy bridge). */
292
- export function nodeReadableToWeb(
293
- readable: import('node:stream').Readable
294
- ): ReadableStream<Uint8Array> {
295
- return _ReadableToWeb!(readable) as ReadableStream<Uint8Array>;
296
- }
297
-
298
274
  // ─── Web Streams Path: renderToReadableStream ────────────────────────────────
299
275
  //
300
276
  // Uses React's Web Streams API. On Cloudflare Workers, ReadableStream is a
@@ -443,26 +419,15 @@ export function wrapStreamWithErrorHandling(
443
419
  }
444
420
 
445
421
  /**
446
- * Build a Response from the SSR HTML stream with the correct
447
- * status code and headers from the navigation context.
448
- *
449
- * React 19.3+ automatically emits `<!DOCTYPE html>` when the root
450
- * element is `<html>`, so no framework-level doctype prepending is needed.
451
- *
452
- * Sets content-type to text/html if not already set by middleware. The
453
- * default goes on a response-local copy: `responseHeaders` is the
454
- * pipeline's shared bag, handed over on `NavContext`, and SSR only reads
455
- * it (design/49 §"A2").
422
+ * Status and headers for an SSR document: the pipeline's headers, copied (SSR
423
+ * never writes through `NavContext.responseHeaders`), with an HTML content
424
+ * type unless the app set one. The Node pipeline sends its body as a
425
+ * `NodeBodyResponse`; the Web pipeline as a `Response`.
456
426
  */
457
- export function buildSsrResponse(
458
- htmlStream: ReadableStream<Uint8Array>,
459
- statusCode: number,
460
- responseHeaders: Headers
461
- ): Response {
427
+ export function ssrResponseInit(statusCode: number, responseHeaders: Headers): ResponseInit {
462
428
  const headers = new Headers(responseHeaders);
463
429
  if (!headers.has('content-type')) {
464
430
  headers.set('content-type', 'text/html; charset=utf-8');
465
431
  }
466
-
467
- return new Response(htmlStream, { status: statusCode, headers });
432
+ return { status: statusCode, headers };
468
433
  }