Unverified Commit de7ce396 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Node.js streams: Fork points (#92252)

### What?

Implements native Node.js stream support for the RSC / HTML rendering.
This first step does not include cacheComponents / static generation.

Instead of converting between Node.js Readable streams and Web
ReadableStreams at every boundary, the rendering pipeline now uses
native Node.js `Transform`/`PassThrough`/`Readable` streams end-to-end
when the useNodeStreams experimental flag is enabled.

### Why?

The current rendering pipeline has a bottleneck on Web Streams. Each
step adds overhead: buffering, scheduling mismatches, and unnecessary
memory copies. Node.js streams are the native I/O primitive on the
server. Using them directly eliminates these conversion and
scheduling/promise costs.

This is the foundational plumbing needed to run the full app render
pipeline on native Node.js streams, which improves server-side rendering
throughput.

### How?

**Stream transform reimplementation** (`stream-ops.node.ts`):

All web `TransformStream`-based transforms have been reimplemented as
Node.js `Transform` streams:

- `createBufferedTransformStream` — coalesces chunks written in the same
microtask into a single `Uint8Array`
- `createFlightDataInjectionTransform` — interleaves RSC flight data
chunks with the HTML stream
- `createHeadInsertionTransform` — inserts server-generated HTML
(polyfills, scripts) before `</head>`
- `createMetadataTransform` — finds and replaces the `«nxt-icon»` meta
mark
- `createDeferredSuffixTransform` — appends the document suffix after
the first HTML chunk
- `createMoveSuffixTransform` — moves `</body></html>` to the end of the
stream
- `createHtmlDataDplIdTransform` — inserts a `data-dpl-id` attribute on
the opening `<html>` tag
- `createRootLayoutValidatorTransform` — validates `<html>` and `<body>`
tags are present (dev only)

**`ReplayableNodeStream`** (`app-render-prerender-utils.ts`):

New class that buffers all chunks from a source `Readable` and allows
creating multiple independent replay streams via `createReplayStream()`.
This replaces the web stream `tee()` operation for `ReactServerResult`
when using Node.js streams. Uses pull-based delivery (`_read()`) to
avoid AsyncLocalStorage context issues — chunks are only delivered when
the consumer reads, keeping them inside the correct ALS scope during
Fizz's `performWork`. Includes 392 lines of unit tests covering
buffering, live replay, error propagation, multiple independent replays,
subscriber cleanup, and dispose behavior.

**Native rendering functions**:

- `renderToNodeFlightStream` — calls React's `renderToPipeableStream`
directly, pipes to a `PassThrough`
- `renderToNodeFizzStream` — calls `renderToPipeableStream` for HTML
rendering without the web stream wrapper
- `createNodeInlinedDataStream` — wraps RSC flight data in `<script>`
tags using `Buffer` operations and `isUtf8()` for encoding detection

**`continueFizzStream` rewritten for Node.js**:

Instead of converting to web streams and delegating to
`webContinueFizzStream`, the Node.js path pipes through a chain of
native `Transform` streams directly: buffer → dpl-id → metadata →
deferred suffix → flight data injection → root layout validator → move
suffix → head insertion.

**API renames for clarity**:

- `renderToFlightStream` → `renderToWebFlightStream` /
`renderToNodeFlightStream`
- `renderToFizzStream` → `renderToWebFizzStream` /
`renderToNodeFizzStream`
- `createInlinedDataStream` → `createWebInlinedDataStream` /
`createNodeInlinedDataStream`
- `createDebugChannel` → `createWebDebugChannel` /
`createNodeDebugChannel`

**`app-render.tsx` fork points**:

The main render function now branches on
`process.env.__NEXT_USE_NODE_STREAMS` at two key points:
1. RSC rendering — uses `renderToNodeFlightStream` +
`createNodeDebugChannel`
2. HTML rendering — uses `renderToNodeFizzStream` + native
`continueFizzStream` with `createNodeInlinedDataStream`

All pre-render, cache components, and dev staged-render paths continue
to use web streams.

**CI updates** (`.github/workflows/build_and_test.yml`):

The `use-node-streams` test jobs now run without
`__NEXT_CACHE_COMPONENTS` / `__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS` /
`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER` to isolate the Node.js
streams path.
parent e75d006d
......@@ -1180,13 +1180,12 @@ jobs:
with:
afterBuild: |
export __NEXT_USE_NODE_STREAMS=true
export __NEXT_CACHE_COMPONENTS=true
export __NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS=true
export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true
export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json,test/use-node-streams-tests-manifest.json"
export NEXT_TEST_MODE=dev
export IS_TURBOPACK_TEST=1
export TURBOPACK_DEV=1
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
export RUST_BACKTRACE=1
node run-tests.js \
--timings \
......@@ -1208,13 +1207,12 @@ jobs:
with:
afterBuild: |
export __NEXT_USE_NODE_STREAMS=true
export __NEXT_CACHE_COMPONENTS=true
export __NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS=true
export __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=true
export NEXT_EXTERNAL_TESTS_FILTERS="test/cache-components-tests-manifest.json,test/use-node-streams-tests-manifest.json"
export NEXT_TEST_MODE=start
export IS_TURBOPACK_TEST=1
export TURBOPACK_BUILD=1
export __NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true
export RUST_BACKTRACE=1
node run-tests.js \
--timings \
......
......@@ -1150,5 +1150,9 @@
"1149": "Node.js Readable cannot be teed in the edge runtime",
"1150": "Node.js Readable cannot be converted to a web stream in the edge runtime",
"1151": "%s is being parsed as a normalized route, but it has a route group segment.",
"1152": "%s is being parsed as a normalized route, but it has a parallel route segment."
"1152": "%s is being parsed as a normalized route, but it has a parallel route segment.",
"1153": "renderToPipeableStream is not implemented",
"1154": "not implemented",
"1155": "Not implemented",
"1156": "Cannot create a replay stream after the ReplayableNodeStream has been disposed."
}
import { PassThrough } from 'node:stream'
import { ReplayableNodeStream } from './app-render-prerender-utils'
function collectBytes(
stream: import('node:stream').Readable
): Promise<number[][]> {
return new Promise((resolve, reject) => {
const chunks: number[][] = []
stream.on('data', (chunk: Buffer) => chunks.push(Array.from(chunk)))
stream.on('end', () => resolve(chunks))
stream.on('error', reject)
})
}
function tick(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve))
}
describe('ReplayableNodeStream', () => {
describe('construction and buffering', () => {
it('buffers Uint8Array chunks from the source', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([1, 2, 3]))
source.write(new Uint8Array([4, 5, 6]))
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
const collected = await collectBytes(replayable.createReplayStream())
expect(collected).toEqual([
[1, 2, 3],
[4, 5, 6],
])
})
it('converts Buffer chunks to Uint8Array before buffering', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(Buffer.from([10, 20, 30]))
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
const collected = await collectBytes(replayable.createReplayStream())
expect(collected).toEqual([[10, 20, 30]])
})
it('handles an immediately-ending empty stream', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
const collected = await collectBytes(replayable.createReplayStream())
expect(collected).toEqual([])
})
})
describe('createReplayStream – replay after source completes', () => {
it('replays all buffered chunks and ends', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([1, 2]))
source.write(new Uint8Array([3, 4]))
source.write(new Uint8Array([5, 6]))
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
const collected = await collectBytes(replayable.createReplayStream())
expect(collected).toEqual([
[1, 2],
[3, 4],
[5, 6],
])
})
it('returns chunks in original order', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
for (let i = 0; i < 10; i++) {
source.write(new Uint8Array([i]))
}
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
const collected = await collectBytes(replayable.createReplayStream())
const expected = Array.from({ length: 10 }, (_, i) => [i])
expect(collected).toEqual(expected)
})
it('replay from empty finished source emits no data then ends', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
const collected = await collectBytes(replayable.createReplayStream())
expect(collected).toEqual([])
})
})
describe('createReplayStream – live source (still streaming)', () => {
it('replays buffered chunks first then forwards new chunks', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([1, 2]))
const replay = replayable.createReplayStream()
const collectPromise = collectBytes(replay)
// Let _read() fire and drain the buffer before pushing live data.
await tick()
source.write(new Uint8Array([3, 4]))
source.end()
const collected = await collectPromise
expect(collected).toEqual([
[1, 2],
[3, 4],
])
})
it('onEnd from source closes the replay stream', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const replay = replayable.createReplayStream()
const replayEnded = new Promise<void>((r) => replay.on('end', r))
replay.resume()
source.end()
await replayEnded
})
it('onError from source destroys the replay stream', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const replay = replayable.createReplayStream()
const errorPromise = new Promise<Error>((resolve) => {
replay.on('error', resolve)
})
const testError = new Error('source failed')
source.destroy(testError)
const received = await errorPromise
expect(received).toBe(testError)
})
})
describe('createReplayStream – error before replay', () => {
it('immediately destroys replay if source already errored', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const testError = new Error('already broken')
source.destroy(testError)
await tick()
const replay = replayable.createReplayStream()
const errorPromise = new Promise<Error>((resolve) => {
replay.on('error', resolve)
})
const received = await errorPromise
expect(received).toBe(testError)
})
})
describe('multiple independent replay streams', () => {
it('each replay stream receives all buffered and live chunks', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([1]))
source.write(new Uint8Array([2]))
const replay1 = replayable.createReplayStream()
const replay2 = replayable.createReplayStream()
const collect1 = collectBytes(replay1)
const collect2 = collectBytes(replay2)
// Let _read() drain buffers before pushing live data.
await tick()
source.write(new Uint8Array([3]))
source.end()
const [collected1, collected2] = await Promise.all([collect1, collect2])
expect(collected1).toEqual([[1], [2], [3]])
expect(collected2).toEqual([[1], [2], [3]])
})
it('closing one replay stream does not affect the other', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const replay1 = replayable.createReplayStream()
const replay2 = replayable.createReplayStream()
replay1.destroy()
source.write(new Uint8Array([42]))
source.end()
const collected2 = await collectBytes(replay2)
expect(collected2).toEqual([[42]])
})
})
describe('subscriber cleanup', () => {
it('removes subscriber when replay stream is closed', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const replay = replayable.createReplayStream()
const subscribers = (replayable as any)._subscribers as Set<unknown>
expect(subscribers.size).toBe(1)
const closed = new Promise<void>((r) => replay.on('close', r))
replay.destroy()
await closed
expect(subscribers.size).toBe(0)
})
it('does not register a subscriber when source already ended', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
replayable.createReplayStream()
const subscribers = (replayable as any)._subscribers as Set<unknown>
expect(subscribers.size).toBe(0)
})
it('does not register a subscriber when source already errored', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.destroy(new Error('boom'))
await tick()
const replay = replayable.createReplayStream()
replay.on('error', () => {})
const subscribers = (replayable as any)._subscribers as Set<unknown>
expect(subscribers.size).toBe(0)
})
})
describe('data after dispose', () => {
it('does not crash when source emits data after dispose', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([1]))
replayable.dispose()
// Source keeps emitting after dispose — should not throw.
source.write(new Uint8Array([2]))
source.end()
await tick()
})
})
describe('error after partial data', () => {
it('replay gets error even when chunks were buffered before error', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([1, 2, 3]))
const testError = new Error('mid-stream failure')
source.destroy(testError)
await tick()
const replay = replayable.createReplayStream()
const errorPromise = new Promise<Error>((resolve) => {
replay.on('error', resolve)
})
const received = await errorPromise
expect(received).toBe(testError)
})
})
describe('multiple replays from completed source', () => {
it('each independently replays the full buffer', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([10]))
source.write(new Uint8Array([20]))
const ended = new Promise<void>((r) => source.on('end', r))
source.end()
await ended
const collected1 = await collectBytes(replayable.createReplayStream())
const collected2 = await collectBytes(replayable.createReplayStream())
const collected3 = await collectBytes(replayable.createReplayStream())
expect(collected1).toEqual([[10], [20]])
expect(collected2).toEqual([[10], [20]])
expect(collected3).toEqual([[10], [20]])
})
})
describe('dispose', () => {
it('throws InvariantError when creating replay after dispose', () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
replayable.dispose()
expect(() => replayable.createReplayStream()).toThrow(
/Cannot create a replay stream after the ReplayableNodeStream has been disposed/
)
})
it('clears buffer but keeps subscribers so streams can still end', () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
const replay = replayable.createReplayStream()
expect((replayable as any)._chunks).not.toBeNull()
expect((replayable as any)._subscribers.size).toBe(1)
replayable.dispose()
expect((replayable as any)._chunks).toBeNull()
// Subscribers must NOT be cleared: the replay stream's onEnd subscriber
// needs to remain active so the stream receives push(null) when the
// source ends, otherwise the consumer never sees EOF.
expect((replayable as any)._subscribers.size).toBe(1)
replay.destroy()
})
it('replay stream still ends when source ends after dispose', async () => {
const source = new PassThrough()
const replayable = new ReplayableNodeStream(source)
source.write(new Uint8Array([1, 2]))
const replay = replayable.createReplayStream()
replayable.dispose()
const collectPromise = collectBytes(replay)
// Let _read() drain buffered chunks before pushing live data.
await tick()
// Source ends after dispose — the replay stream should still close
source.write(new Uint8Array([3, 4]))
source.end()
const collected = await collectPromise
expect(collected).toEqual([
[1, 2],
[3, 4],
])
})
})
})
......@@ -13,12 +13,23 @@ function isWebStream(stream: AnyStream): stream is ReadableStream<Uint8Array> {
// in one that doesn't close even when the underlying is complete.
export class ReactServerResult {
private _stream: null | AnyStream
private _replayable: ReplayableNodeStream | null
constructor(stream: AnyStream) {
this._stream = stream
if (process.env.__NEXT_USE_NODE_STREAMS && !isWebStream(stream)) {
this._stream = null
this._replayable = new ReplayableNodeStream(stream as Readable)
} else {
this._stream = stream
this._replayable = null
}
}
tee(): AnyStream {
if (this._replayable) {
return this._replayable.createReplayStream()
}
if (this._stream === null) {
throw new Error(
'Cannot tee a ReactServerResult that has already been consumed'
......@@ -56,6 +67,13 @@ export class ReactServerResult {
}
consume(): AnyStream {
if (this._replayable) {
const stream = this._replayable.createReplayStream()
this._replayable.dispose()
this._replayable = null
return stream
}
if (this._stream === null) {
throw new Error(
'Cannot consume a ReactServerResult that has already been consumed'
......@@ -67,6 +85,147 @@ export class ReactServerResult {
}
}
type ReplayableStreamSubscriber = {
onChunk: (chunk: Uint8Array) => void
onEnd: () => void
onError: (err: Error) => void
}
/**
* Buffers all chunks from a Node.js Readable stream and allows creating new
* Readable streams that replay the buffered chunks plus any subsequent chunks
* from the source. Multiple replay streams can be created independently.
*/
export class ReplayableNodeStream {
private _chunks: Array<Uint8Array> | null
private _done: boolean
private _error: Error | null
private _subscribers: Set<ReplayableStreamSubscriber>
constructor(stream: Readable) {
this._chunks = []
this._done = false
this._error = null
this._subscribers = new Set()
stream.on('data', (chunk: Buffer | Uint8Array) => {
const buf = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk)
if (this._chunks !== null) {
this._chunks.push(buf)
}
for (const sub of this._subscribers) {
sub.onChunk(buf)
}
})
stream.on('end', () => {
this._done = true
for (const sub of this._subscribers) {
sub.onEnd()
}
this._subscribers.clear()
})
stream.on('error', (err: Error) => {
this._error = err
for (const sub of this._subscribers) {
sub.onError(err)
}
this._subscribers.clear()
})
}
/**
* Creates a new Node.js Readable stream that first emits all buffered chunks,
* then forwards any new chunks from the source as they arrive.
*
* Buffered chunks are delivered via _read() (pull-based) rather than pushed
* eagerly. This is critical because createReplayStream() is called outside
* of AsyncLocalStorage context, and eagerly pushing chunks triggers internal
* Node.js stream scheduling (process.nextTick for maybeReadMore) that
* captures the empty ALS context. By deferring to _read(), chunks are only
* delivered when the consumer reads, which happens inside the correct ALS
* scope (e.g. during Fizz's performWork).
*/
createReplayStream(): Readable {
if (this._chunks === null) {
throw new InvariantError(
'Cannot create a replay stream after the ReplayableNodeStream has been disposed.'
)
}
let ReadableCtor: typeof import('node:stream').Readable
if (process.env.TURBOPACK) {
ReadableCtor = (require('node:stream') as typeof import('node:stream'))
.Readable
} else if (process.env.__NEXT_BUNDLER === 'Webpack') {
ReadableCtor = (
__non_webpack_require__('node:stream') as typeof import('node:stream')
).Readable
} else {
ReadableCtor = (require('node:stream') as typeof import('node:stream'))
.Readable
}
const bufferedChunks = this._chunks.slice()
let bufferIndex = 0
let bufferDrained = false
const isDone = this._done
const sourceError = this._error
const stream = new ReadableCtor({
read() {
if (!bufferDrained) {
bufferDrained = true
for (let i = bufferIndex; i < bufferedChunks.length; i++) {
this.push(bufferedChunks[i])
}
bufferIndex = bufferedChunks.length
if (isDone) {
this.push(null)
}
}
},
})
if (sourceError) {
stream.destroy(sourceError)
return stream
}
if (isDone) {
return stream
}
const subscriber: ReplayableStreamSubscriber = {
onChunk: (chunk) => {
stream.push(chunk)
},
onEnd: () => {
stream.push(null)
},
onError: (err) => {
stream.destroy(err)
},
}
this._subscribers.add(subscriber)
stream.on('close', () => {
this._subscribers.delete(subscriber)
})
return stream
}
/**
* Clears the buffered chunks and all subscriber references. After calling
* this, no new replay streams can be created.
*/
dispose(): void {
this._chunks = null
}
}
export type ReactServerPrerenderResolveToType = {
prelude: ReadableStream<Uint8Array>
}
......
......@@ -46,18 +46,21 @@ import {
continueStaticFallbackPrerender,
streamToBuffer,
streamToString,
createInlinedDataStream,
createWebInlinedDataStream,
createPendingStream,
createOnHeadersCallback,
resumeAndAbort,
renderToFlightStream,
renderToFizzStream,
renderToWebFlightStream,
resumeToFizzStream,
getServerPrerender,
getClientPrerender,
processPrelude as processPreludeOp,
createDocumentClosingStream,
teeStream,
renderToWebFizzStream,
renderToNodeFlightStream,
renderToNodeFizzStream,
createNodeInlinedDataStream,
} from './stream-ops'
import type { AnyStream } from './stream-ops'
import { stripInternalQueries } from '../internal-utils'
......@@ -258,7 +261,8 @@ import {
} from './instant-validation/instant-config'
import { warnOnce } from '../../shared/lib/utils/warn-once'
import {
createDebugChannel,
createWebDebugChannel,
createNodeDebugChannel,
type DebugChannelPair,
} from './debug-channel-server'
import { createNodeStreamWithLateRelease } from './instant-validation/stream-utils'
......@@ -840,7 +844,7 @@ async function generateDynamicFlightRenderResult(
onFlightDataRenderError
)
const debugChannel = setReactDebugChannel && createDebugChannel()
const debugChannel = setReactDebugChannel && createWebDebugChannel()
if (debugChannel) {
setReactDebugChannel(debugChannel.clientSide, htmlRequestId, requestId)
......@@ -859,7 +863,7 @@ async function generateDynamicFlightRenderResult(
const flightStream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
renderToWebFlightStream,
ctx.componentMod,
rscPayload,
clientModules,
......@@ -1140,7 +1144,7 @@ async function stagedRenderToReadableStreamWithoutCachesInDev(
stageController.advanceStage(RenderStage.Static)
return workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
renderToWebFlightStream,
ctx.componentMod,
rscPayload,
clientModules,
......@@ -1306,7 +1310,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
setCacheStatus('bypass', htmlRequestId)
}
debugChannel = setReactDebugChannel && createDebugChannel()
debugChannel = setReactDebugChannel && createWebDebugChannel()
stream = await stagedRenderToReadableStreamWithoutCachesInDev(
ctx,
......@@ -2920,6 +2924,7 @@ async function renderToStream(
fallbackParams: OpaqueFallbackRouteParams | null
): Promise<AnyStream> {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
// MARK: renderToStream setup
const {
assetPrefix,
htmlRequestId,
......@@ -3027,6 +3032,7 @@ async function renderToStream(
// Run the rest of the function within the span's context so child spans
// (like "build component tree", "generateMetadata") are properly parented.
return getTracer().withSpan(renderSpan, async () => {
// MARK: renderToStream errorHandlers
const { reactServerErrorsByDigest } = workStore
function onHTMLRenderRSCError(err: DigestedError, silenceLog: boolean) {
return onInstrumentationRequestError?.(
......@@ -3081,6 +3087,7 @@ async function renderToStream(
// We only have a Prerender environment for projects opted into cacheComponents
cacheComponents
) {
// MARK: webstreams dev CacheComponents RSC
let debugChannel: DebugChannelPair | undefined
// eslint-disable-next-line @typescript-eslint/no-shadow
......@@ -3167,7 +3174,7 @@ async function renderToStream(
// We're either bypassing caches or we can't restart the render.
// Do a dynamic render, but with (basic) environment labels.
debugChannel = setReactDebugChannel && createDebugChannel()
debugChannel = setReactDebugChannel && createWebDebugChannel()
const serverStream =
await stagedRenderToReadableStreamWithoutCachesInDev(
......@@ -3197,6 +3204,7 @@ async function renderToStream(
)
}
} else if (cacheComponents && cachedNavigations) {
// MARK: webstreams cacheComponents RSC
// Production Cache Components + Cached Navigations: use staged
// rendering so the RSC payload includes the static stage byte length
// (`l` field), enabling the client to cache the static subset during
......@@ -3320,46 +3328,91 @@ async function renderToStream(
reactServerResult = new ReactServerResult(flightStream)
} else {
// This is a dynamic render. We don't do dynamic tracking because we're not prerendering
const RSCPayload: RSCPayload & RSCPayloadDevProperties =
await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
{ is404: res.statusCode === 404 }
)
// MARK: nodeStreams RSC
if (process.env.__NEXT_USE_NODE_STREAMS) {
// This is a dynamic render. We don't do dynamic tracking because we're not prerendering
const RSCPayload: RSCPayload & RSCPayloadDevProperties =
await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
{ is404: res.statusCode === 404 }
)
const debugChannel = setReactDebugChannel && createDebugChannel()
const debugChannel = setReactDebugChannel && createNodeDebugChannel()
if (debugChannel) {
const [readableSsr, readableBrowser] = teeStream(
debugChannel.clientSide.readable
)
if (debugChannel) {
const [readableSsr, readableBrowser] = teeStream(
debugChannel.clientSide.readable
)
reactDebugStream = readableSsr
reactDebugStream = readableSsr
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
)
}
reactServerResult = new ReactServerResult(
workUnitAsyncStorage.run(
requestStore,
renderToNodeFlightStream,
ctx.componentMod,
RSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
debugChannel: debugChannel?.serverSide,
}
)
)
}
} else {
// MARK: webStreams RSC
// This is a dynamic render. We don't do dynamic tracking because we're not prerendering
const RSCPayload: RSCPayload & RSCPayloadDevProperties =
await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
{ is404: res.statusCode === 404 }
)
reactServerResult = new ReactServerResult(
workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
ctx.componentMod,
RSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
debugChannel: debugChannel?.serverSide,
}
const debugChannel = setReactDebugChannel && createWebDebugChannel()
if (debugChannel) {
const [readableSsr, readableBrowser] = teeStream(
debugChannel.clientSide.readable
)
reactDebugStream = readableSsr
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
)
}
reactServerResult = new ReactServerResult(
workUnitAsyncStorage.run(
requestStore,
renderToWebFlightStream,
ctx.componentMod,
RSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
debugChannel: debugChannel?.serverSide,
}
)
)
)
}
}
// React doesn't start rendering synchronously but we want the RSC render to have a chance to start
......@@ -3367,139 +3420,285 @@ async function renderToStream(
// one task before continuing
await waitAtLeastOneReactRenderTask()
// If provided, the postpone state should be parsed as JSON so it can be
// provided to React.
if (typeof renderOpts.postponed === 'string') {
if (postponedState?.type === DynamicState.DATA) {
// We have a complete HTML Document in the prerender but we need to
// still include the new server component render because it was not included
// in the static prelude.
const inlinedDataStream = createInlinedDataStream(
reactServerResult.tee(),
nonce,
formState
)
// MARK: nodeStreams HTML
if (process.env.__NEXT_USE_NODE_STREAMS) {
// If provided, the postpone state should be parsed as JSON so it can be
// provided to React.
if (typeof renderOpts.postponed === 'string') {
if (postponedState?.type === DynamicState.DATA) {
// We have a complete HTML Document in the prerender but we need to
// still include the new server component render because it was not included
// in the static prelude.
const inlinedDataStream = createWebInlinedDataStream(
reactServerResult.tee(),
nonce,
formState
)
// End the span since there's no async rendering in this path
if (renderSpan.isRecording()) renderSpan.end()
return chainStreams(inlinedDataStream, createDocumentClosingStream())
} else if (postponedState) {
// We assume we have dynamic HTML requiring a resume render to complete
const { postponed, preludeState } =
getPostponedFromState(postponedState)
// End the span since there's no async rendering in this path
if (renderSpan.isRecording()) renderSpan.end()
return chainStreams(
inlinedDataStream,
createDocumentClosingStream()
)
} else if (postponedState) {
// We assume we have dynamic HTML requiring a resume render to complete
const { postponed, preludeState } =
getPostponedFromState(postponedState)
const resumeAppElement = (
<App
reactServerStream={reactServerResult.tee()}
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>
)
const resumeAppElement = (
<App
reactServerStream={reactServerResult.tee()}
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>
)
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
const { stream: htmlStream, allReady } =
await workUnitAsyncStorage.run(
requestStore,
resumeToFizzStream,
resumeAppElement,
postponed,
{ onError: htmlRendererErrorHandler, nonce }
)
const { stream: htmlStream, allReady } =
await workUnitAsyncStorage.run(
requestStore,
resumeToFizzStream,
resumeAppElement,
postponed,
{ onError: htmlRendererErrorHandler, nonce }
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
return await continueDynamicHTMLResume(htmlStream, {
delayDataUntilFirstHtmlChunk:
preludeState === DynamicHTMLPreludeState.Empty,
inlinedDataStream: createWebInlinedDataStream(
reactServerResult.consume(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.sharedContext.deploymentId,
})
}
}
// This is a regular dynamic render
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
const generateStaticHTML =
supportsDynamicResponse !== true || !!shouldWaitOnAllReady
const appElement = (
<App
reactServerStream={reactServerResult.tee()}
// TODO: Pass Node.js debugStream
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>
)
return await continueDynamicHTMLResume(htmlStream, {
delayDataUntilFirstHtmlChunk:
preludeState === DynamicHTMLPreludeState.Empty,
inlinedDataStream: createInlinedDataStream(
reactServerResult.consume(),
const fizzOptions = {
onError: htmlRendererErrorHandler,
nonce,
onHeaders: (headers: { [header: string]: string }) => {
for (const key in headers) {
appendHeader(key, headers[key])
}
},
maxHeadersLength: reactMaxHeadersLength,
bootstrapScriptContent,
bootstrapScripts: [bootstrapScript],
formState,
}
const { stream: htmlStream, allReady } = await workUnitAsyncStorage.run(
requestStore,
renderToNodeFizzStream,
appElement,
fizzOptions
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
return await continueFizzStream(htmlStream, {
inlinedDataStream: createNodeInlinedDataStream(
reactServerResult.consume(),
nonce,
formState
),
isStaticGeneration: generateStaticHTML,
allReady,
deploymentId: ctx.sharedContext.deploymentId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout: !!process.env.__NEXT_DEV_SERVER,
})
} else {
// MARK: webStreams HTML
// If provided, the postpone state should be parsed as JSON so it can be
// provided to React.
if (typeof renderOpts.postponed === 'string') {
if (postponedState?.type === DynamicState.DATA) {
// We have a complete HTML Document in the prerender but we need to
// still include the new server component render because it was not included
// in the static prelude.
const inlinedDataStream = createWebInlinedDataStream(
reactServerResult.tee(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.sharedContext.deploymentId,
})
}
}
)
// This is a regular dynamic render
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
// End the span since there's no async rendering in this path
if (renderSpan.isRecording()) renderSpan.end()
return chainStreams(
inlinedDataStream,
createDocumentClosingStream()
)
} else if (postponedState) {
// We assume we have dynamic HTML requiring a resume render to complete
const { postponed, preludeState } =
getPostponedFromState(postponedState)
const generateStaticHTML =
supportsDynamicResponse !== true || !!shouldWaitOnAllReady
const resumeAppElement = (
<App
reactServerStream={reactServerResult.tee()}
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>
)
const appElement = (
<App
reactServerStream={reactServerResult.tee()}
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>
)
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
const fizzOptions = {
onError: htmlRendererErrorHandler,
nonce,
onHeaders: (headers: Headers) => {
for (const [key, value] of headers) {
appendHeader(key, value)
const { stream: htmlStream, allReady } =
await workUnitAsyncStorage.run(
requestStore,
resumeToFizzStream,
resumeAppElement,
postponed,
{ onError: htmlRendererErrorHandler, nonce }
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
return await continueDynamicHTMLResume(htmlStream, {
delayDataUntilFirstHtmlChunk:
preludeState === DynamicHTMLPreludeState.Empty,
inlinedDataStream: createWebInlinedDataStream(
reactServerResult.consume(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
deploymentId: ctx.sharedContext.deploymentId,
})
}
},
maxHeadersLength: reactMaxHeadersLength,
bootstrapScriptContent,
bootstrapScripts: [bootstrapScript],
formState,
}
}
const { stream: htmlStream, allReady } = await workUnitAsyncStorage.run(
requestStore,
renderToFizzStream,
appElement,
fizzOptions
)
// This is a regular dynamic render
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
const generateStaticHTML =
supportsDynamicResponse !== true || !!shouldWaitOnAllReady
return await continueFizzStream(htmlStream, {
inlinedDataStream: createInlinedDataStream(
reactServerResult.consume(),
const appElement = (
<App
reactServerStream={reactServerResult.tee()}
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>
)
const fizzOptions = {
onError: htmlRendererErrorHandler,
nonce,
formState
),
isStaticGeneration: generateStaticHTML,
allReady,
deploymentId: ctx.sharedContext.deploymentId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout: !!process.env.__NEXT_DEV_SERVER,
})
onHeaders: (headers: Headers) => {
headers.forEach((value, key) => {
appendHeader(key, value)
})
},
maxHeadersLength: reactMaxHeadersLength,
bootstrapScriptContent,
bootstrapScripts: [bootstrapScript],
formState,
}
const { stream: htmlStream, allReady } = await workUnitAsyncStorage.run(
requestStore,
renderToWebFizzStream,
appElement,
fizzOptions
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
return await continueFizzStream(htmlStream, {
inlinedDataStream: createWebInlinedDataStream(
reactServerResult.consume(),
nonce,
formState
),
isStaticGeneration: generateStaticHTML,
allReady,
deploymentId: ctx.sharedContext.deploymentId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout: !!process.env.__NEXT_DEV_SERVER,
})
}
// MARK: renderToStream errorRecovery
} catch (err) {
if (
isStaticGenBailoutError(err) ||
......@@ -3583,7 +3782,7 @@ async function renderToStream(
errorServerStream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
renderToWebFlightStream,
ctx.componentMod,
errorRSCPayload,
clientModules,
......@@ -3611,7 +3810,7 @@ async function renderToStream(
const { stream: errorHtmlStream, allReady: errorAllReady } =
await workUnitAsyncStorage.run(
requestStore,
renderToFizzStream,
renderToWebFizzStream,
<ErrorApp
reactServerStream={errorServerStream}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
......@@ -3633,7 +3832,7 @@ async function renderToStream(
})
return await continueFizzStream(errorHtmlStream, {
inlinedDataStream: createInlinedDataStream(
inlinedDataStream: createWebInlinedDataStream(
// This is intentionally using the readable datastream from the
// main render rather than the flight data from the error page
// render
......@@ -3746,7 +3945,7 @@ async function renderWithRestartOnCacheMissInDev(
)
requestStore.cacheSignal = cacheSignal
let debugChannel = setReactDebugChannel && createDebugChannel()
let debugChannel = setReactDebugChannel && createWebDebugChannel()
const { clientModules } = getClientReferenceManifest()
// Note: The stage controller starts out in the `Before` stage,
......@@ -3761,7 +3960,7 @@ async function renderWithRestartOnCacheMissInDev(
const streamPair = teeStream(
workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
renderToWebFlightStream,
ComponentMod,
initialRscPayload,
clientModules,
......@@ -3914,7 +4113,7 @@ async function renderWithRestartOnCacheMissInDev(
// The initial render already wrote to its debug channel.
// We're not using it, so we need to create a new one.
debugChannel = setReactDebugChannel && createDebugChannel()
debugChannel = setReactDebugChannel && createWebDebugChannel()
// Note: The stage controller starts out in the `Before` stage,
// where sync IO does not cause aborts, so it's okay if it happens before render.
......@@ -3928,7 +4127,7 @@ async function renderWithRestartOnCacheMissInDev(
const streamPair = teeStream(
workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
renderToWebFlightStream,
ComponentMod,
finalRscPayload,
clientModules,
......@@ -4251,7 +4450,7 @@ async function logMessagesAndSendErrorsToBrowser(
const { clientModules } = getClientReferenceManifest()
const errorsFlightStream = renderToFlightStream(
const errorsFlightStream = renderToWebFlightStream(
ctx.componentMod,
{ errors, errorCodes },
clientModules,
......@@ -4835,7 +5034,7 @@ async function validateInstantConfigs(
stageEndTimes,
} = await collectStagedSegmentData(
ctx.componentMod,
renderToFlightStream,
renderToWebFlightStream,
{
[RenderStage.Static]: accumulatedChunks.staticChunks,
[RenderStage.Runtime]: accumulatedChunks.runtimeChunks,
......@@ -4912,7 +5111,7 @@ async function validateInstantConfigs(
const { stream: serverStream, debugStream } =
await createCombinedPayloadStream(
ctx.componentMod,
renderToFlightStream,
renderToWebFlightStream,
payloadResult.payload,
extraChunksController,
reactController.signal,
......@@ -5226,7 +5425,7 @@ async function renderWithRestartOnCacheMissInValidation(
const stream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
renderToWebFlightStream,
ComponentMod,
initialRscPayload,
clientModules,
......@@ -5327,7 +5526,7 @@ async function renderWithRestartOnCacheMissInValidation(
const stream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
renderToWebFlightStream,
ComponentMod,
finalRscPayload,
clientModules,
......@@ -6700,13 +6899,13 @@ async function prerenderToStream(
// segments, since those are the only ones whose data is not complete.
const emptyReactServerResult =
await createReactServerPrerenderResultFromRender(
renderToFlightStream(ComponentMod, [], clientModules, {
renderToWebFlightStream(ComponentMod, [], clientModules, {
filterStackFrame,
onError: serverComponentsErrorHandler,
})
)
finalStream = await continueStaticFallbackPrerender(htmlStream, {
inlinedDataStream: createInlinedDataStream(
inlinedDataStream: createWebInlinedDataStream(
emptyReactServerResult.consumeAsStream(),
nonce,
formState
......@@ -6718,7 +6917,7 @@ async function prerenderToStream(
} else {
// Normal static prerender case, no fallback param handling needed
finalStream = await continueStaticPrerender(htmlStream, {
inlinedDataStream: createInlinedDataStream(
inlinedDataStream: createWebInlinedDataStream(
reactServerResult.consumeAsStream(),
nonce,
formState
......@@ -6777,7 +6976,7 @@ async function prerenderToStream(
await createReactServerPrerenderResultFromRender(
workUnitAsyncStorage.run(
reactServerPrerenderStore,
renderToFlightStream,
renderToWebFlightStream,
ComponentMod,
RSCPayload,
clientModules,
......@@ -6972,7 +7171,7 @@ async function prerenderToStream(
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueStaticPrerender(htmlStream, {
inlinedDataStream: createInlinedDataStream(
inlinedDataStream: createWebInlinedDataStream(
reactServerResult.consumeAsStream(),
nonce,
formState
......@@ -7015,7 +7214,7 @@ async function prerenderToStream(
await createReactServerPrerenderResultFromRender(
workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToFlightStream,
renderToWebFlightStream,
ComponentMod,
RSCPayload,
clientModules,
......@@ -7028,7 +7227,7 @@ async function prerenderToStream(
const { stream: htmlStream } = await workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToFizzStream,
renderToWebFizzStream,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={reactServerResult.asUnclosingStream()}
......@@ -7070,7 +7269,7 @@ async function prerenderToStream(
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueFizzStream(htmlStream, {
inlinedDataStream: createInlinedDataStream(
inlinedDataStream: createWebInlinedDataStream(
reactServerResult.consumeAsStream(),
nonce,
formState
......@@ -7215,7 +7414,7 @@ async function prerenderToStream(
const errorServerStreamRaw = workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToFlightStream,
renderToWebFlightStream,
ComponentMod,
errorRSCPayload,
clientModules,
......@@ -7241,7 +7440,7 @@ async function prerenderToStream(
try {
const { stream: errorHtmlStream } = await workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToFizzStream,
renderToWebFizzStream,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<ErrorApp
reactServerStream={errorServerStream}
......@@ -7283,7 +7482,7 @@ async function prerenderToStream(
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueFizzStream(errorHtmlStream, {
inlinedDataStream: createInlinedDataStream(
inlinedDataStream: createWebInlinedDataStream(
flightStream,
nonce,
formState
......
......@@ -6,14 +6,14 @@
import { PassThrough, Writable } from 'node:stream'
import type { DebugChannelPair } from './debug-channel-server.web'
export function createDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
return undefined
}
return createNodeDebugChannel()
}
export { createWebDebugChannel } from './debug-channel-server.web'
function createNodeDebugChannel(): DebugChannelPair {
/**
* Creates a debug channel using Node.js streams.
* Use with renderToNodeFlightStream (React's renderToPipeableStream),
* which expects debugChannel to be a Node.js stream with a .write() method.
*/
export function createNodeDebugChannel(): DebugChannelPair {
const readable = new PassThrough()
// Use a plain Writable instead of exposing the PassThrough directly.
......
......@@ -8,9 +8,11 @@ export type {
DebugChannelPair,
DebugChannelServer,
} from './debug-channel-server.web'
import type { DebugChannelPair } from './debug-channel-server.web'
type DebugChannelMod = {
createDebugChannel: typeof import('./debug-channel-server.web').createDebugChannel
createWebDebugChannel: typeof import('./debug-channel-server.web').createWebDebugChannel
createNodeDebugChannel: typeof import('./debug-channel-server.web').createNodeDebugChannel
}
let _m: DebugChannelMod
......@@ -22,4 +24,18 @@ if (process.env.__NEXT_USE_NODE_STREAMS) {
require('./debug-channel-server.web') as typeof import('./debug-channel-server.web')
}
export const createDebugChannel = _m.createDebugChannel
export function createWebDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
return undefined
}
return _m.createWebDebugChannel()
}
export function createNodeDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
return undefined
}
return _m.createNodeDebugChannel()
}
......@@ -10,22 +10,17 @@ export type DebugChannelPair = {
clientSide: DebugChannelClient
}
// Opaque: PassThrough on node, { writable: WritableStream } on web.
// Each React render API handles its own variant.
export type DebugChannelServer = any
type DebugChannelClient = {
readable: AnyStream
}
export function createDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
return undefined
}
return createWebDebugChannel()
}
/**
* Creates a debug channel using web WritableStream/ReadableStream.
* Use with renderToWebFlightStream (React's renderToReadableStream),
* which expects debugChannel = { writable: WritableStream }.
*/
export function createWebDebugChannel(): DebugChannelPair {
let readableController: ReadableStreamDefaultController | undefined
......@@ -52,3 +47,12 @@ export function createWebDebugChannel(): DebugChannelPair {
clientSide: { readable: clientSideReadable },
}
}
/**
* Creates a debug channel using Node.js streams.
* Use with renderToNodeFlightStream (React's renderToPipeableStream),
* which expects debugChannel to be a Node.js stream with a .write() method.
*/
export function createNodeDebugChannel(): DebugChannelPair {
throw new Error('not implemented')
}
......@@ -41,7 +41,7 @@ import {
createNodeStreamWithLateRelease,
createNodeStreamFromChunks,
} from './stream-utils'
import { createDebugChannel } from '../debug-channel-server'
import { createWebDebugChannel } from '../debug-channel-server'
import type { FlightComponentMod } from '../stream-ops'
// eslint-disable-next-line import/no-extraneous-dependencies
......@@ -297,7 +297,7 @@ export async function collectStagedSegmentData(
cacheEntry: SegmentCacheItem
): Promise<void> => {
const segmentDebugChannel = cacheEntry.debugChunks
? createDebugChannel()
? createWebDebugChannel()
: undefined
const itemStream = renderFlightStream(
......@@ -536,7 +536,7 @@ export async function createCombinedPayloadStream(
const allChunks: Uint8Array[] = []
const debugChunks: Uint8Array[] | null = isDebugChannelEnabled ? [] : null
const debugChannel = isDebugChannelEnabled ? createDebugChannel() : null
const debugChannel = isDebugChannelEnabled ? createWebDebugChannel() : null
let streamFinished: Promise<any>
......
......@@ -84,6 +84,7 @@ export function makeGetServerInsertedHTML({
return ''
}
// TODO: This should use Node streams when __NEXT_USE_NODE_STREAMS is true
const stream = await renderToReadableStream(
<>
{polyfillTags}
......
......@@ -14,11 +14,10 @@ import {
resumeToPipeableStream,
} from 'react-dom/server'
import { prerender } from 'react-dom/static'
import { PassThrough, Readable } from 'node:stream'
import { PassThrough, Readable, Transform } from 'node:stream'
import { isUtf8 } from 'node:buffer'
import type { ReactDOMServerReadableStream } from 'react-dom/server'
import {
continueFizzStream as webContinueFizzStream,
continueStaticPrerender as webContinueStaticPrerender,
continueDynamicPrerender as webContinueDynamicPrerender,
continueStaticFallbackPrerender as webContinueStaticFallbackPrerender,
......@@ -27,12 +26,21 @@ import {
streamToString as webStreamToString,
createDocumentClosingStream as webCreateDocumentClosingStream,
createRuntimePrefetchTransformStream,
CLOSE_TAG,
} from '../stream-utils/node-web-streams-helper'
import { indexOfUint8Array } from '../stream-utils/uint8array-helpers'
import { ENCODED_TAGS } from '../stream-utils/encoded-tags'
import { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants'
import { htmlEscapeJsonString } from '../htmlescape'
import { createInlinedDataReadableStream } from './use-flight-response'
import type { AnyStream as AnyStreamType } from './app-render-prerender-utils'
import { DetachedPromise } from '../../lib/detached-promise'
import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants'
import {
atLeastOneTask,
waitAtLeastOneReactRenderTask,
} from '../../lib/scheduler'
// ---------------------------------------------------------------------------
// Re-export shared types from the web module
......@@ -105,76 +113,515 @@ function webToReadable(
return Readable.fromWeb(stream as WebReadableStream)
}
// ---------------------------------------------------------------------------
// Buffered transform – Node.js Transform that coalesces chunks written in the
// same microtask into a single Uint8Array before pushing downstream.
// ---------------------------------------------------------------------------
function createBufferedTransformStream(): Transform {
let bufferedChunks: Array<Uint8Array> = []
let bufferByteLength = 0
let flushScheduled = false
function flushBuffered(stream: Transform): void {
if (bufferedChunks.length === 0) return
const merged = new Uint8Array(bufferByteLength)
let copiedBytes = 0
for (let i = 0; i < bufferedChunks.length; i++) {
const bufferedChunk = bufferedChunks[i]
merged.set(bufferedChunk, copiedBytes)
copiedBytes += bufferedChunk.byteLength
}
bufferedChunks.length = 0
bufferByteLength = 0
stream.push(merged)
}
return new Transform({
transform(chunk, _encoding, callback) {
bufferedChunks.push(chunk)
bufferByteLength += chunk.byteLength
if (!flushScheduled) {
flushScheduled = true
queueMicrotask(() => {
flushScheduled = false
flushBuffered(this)
})
}
callback()
},
flush(callback) {
flushBuffered(this)
callback()
},
})
}
// ---------------------------------------------------------------------------
// Flight data injection – Node.js Transform that passes HTML chunks through
// while pulling from a separate data stream and interleaving its chunks.
// ---------------------------------------------------------------------------
function createFlightDataInjectionTransform(
dataStream: Readable,
delayDataUntilFirstHtmlChunk: boolean
): Transform {
let htmlStreamFinished = false
let pull: Promise<void> | null = null
let donePulling = false
function startOrContinuePulling(target: Transform) {
if (!pull) {
pull = startPulling(target)
}
return pull
}
async function startPulling(target: Transform) {
if (delayDataUntilFirstHtmlChunk) {
// Buffer the inlined data stream until we've left the current Task so
// it's inserted after flushing the shell.
await atLeastOneTask()
}
try {
const iterator = dataStream[Symbol.asyncIterator]()
while (true) {
const { done, value } = await iterator.next()
if (done) {
donePulling = true
return
}
// Prioritize HTML over RSC data: the SSR render produces HTML from
// the same RSC stream, so yield a task to let HTML flush first.
if (!delayDataUntilFirstHtmlChunk && !htmlStreamFinished) {
await atLeastOneTask()
}
target.push(value)
}
} catch (err) {
target.destroy(err as Error)
}
}
const nodeTransform = new Transform({
transform(chunk, _encoding, callback) {
this.push(chunk)
if (delayDataUntilFirstHtmlChunk) {
startOrContinuePulling(this)
}
callback()
},
flush(callback) {
htmlStreamFinished = true
if (donePulling) {
callback()
return
}
startOrContinuePulling(this).then(
() => callback(),
(err) => callback(err as Error)
)
},
})
if (!delayDataUntilFirstHtmlChunk) {
startOrContinuePulling(nodeTransform)
}
return nodeTransform
}
// ---------------------------------------------------------------------------
// Head insertion – Node.js Transform that inserts server-generated HTML
// (e.g. <script>, <style>) right before </head>, or prepends it if no
// </head> tag is found (PPR resume case).
// ---------------------------------------------------------------------------
function createHeadInsertionTransform(
insert: () => Promise<string>
): Transform {
let inserted = false
let hasBytes = false
return new Transform({
async transform(chunk, _encoding, callback) {
hasBytes = true
try {
const insertion = await insert()
if (inserted) {
if (insertion) {
this.push(Buffer.from(insertion))
}
this.push(chunk)
} else {
const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
if (index !== -1) {
if (insertion) {
const encodedInsertion = Buffer.from(insertion)
const merged = Buffer.allocUnsafe(
chunk.length + encodedInsertion.length
)
merged.set(chunk.slice(0, index))
merged.set(encodedInsertion, index)
merged.set(chunk.slice(index), index + encodedInsertion.length)
this.push(merged)
} else {
this.push(chunk)
}
inserted = true
} else {
if (insertion) {
this.push(Buffer.from(insertion))
}
this.push(chunk)
inserted = true
}
}
callback()
} catch (err) {
callback(err as Error)
}
},
async flush(callback) {
try {
if (hasBytes) {
const insertion = await insert()
if (insertion) {
this.push(Buffer.from(insertion))
}
}
callback()
} catch (err) {
callback(err as Error)
}
},
})
}
// ---------------------------------------------------------------------------
// Metadata transform – Node.js Transform that finds the «nxt-icon» meta mark
// and replaces it with a script tag (or removes it if inside <head>).
// ---------------------------------------------------------------------------
function createMetadataTransform(
insert: () => Promise<string> | string
): Transform {
let chunkIndex = -1
let isMarkRemoved = false
return new Transform({
async transform(chunk, _encoding, callback) {
let iconMarkIndex = -1
let closedHeadIndex = -1
chunkIndex++
if (isMarkRemoved) {
this.push(chunk)
callback()
return
}
try {
let iconMarkLength = 0
iconMarkIndex = indexOfUint8Array(chunk, ENCODED_TAGS.META.ICON_MARK)
if (iconMarkIndex === -1) {
this.push(chunk)
callback()
return
}
iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length
if (chunk[iconMarkIndex + iconMarkLength] === 47) {
iconMarkLength += 2
} else {
iconMarkLength++
}
if (chunkIndex === 0) {
closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
if (iconMarkIndex < closedHeadIndex) {
const replaced = Buffer.allocUnsafe(chunk.length - iconMarkLength)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex
)
chunk = replaced
} else {
const insertion = await insert()
const encodedInsertion = Buffer.from(insertion)
const insertionLength = encodedInsertion.length
const replaced = Buffer.allocUnsafe(
chunk.length - iconMarkLength + insertionLength
)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(encodedInsertion, iconMarkIndex)
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
}
isMarkRemoved = true
} else {
const insertion = await insert()
const encodedInsertion = Buffer.from(insertion)
const insertionLength = encodedInsertion.length
const replaced = Buffer.allocUnsafe(
chunk.length - iconMarkLength + insertionLength
)
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(encodedInsertion, iconMarkIndex)
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
isMarkRemoved = true
}
this.push(chunk)
callback()
} catch (err) {
callback(err as Error)
}
},
})
}
// ---------------------------------------------------------------------------
// Deferred suffix – Node.js Transform that appends a suffix string after the
// first HTML chunk, deferring via queueMicrotask so the chunk flushes first.
// ---------------------------------------------------------------------------
function createDeferredSuffixTransform(suffix: string): Transform {
let flushed = false
const encodedSuffix = Buffer.from(suffix)
return new Transform({
transform(chunk, _encoding, callback) {
this.push(chunk)
if (!flushed) {
flushed = true
queueMicrotask(() => {
this.push(encodedSuffix)
})
}
callback()
},
flush(callback) {
if (!flushed) {
this.push(encodedSuffix)
}
callback()
},
})
}
// ---------------------------------------------------------------------------
// Move suffix – Node.js Transform that strips </body></html> from its
// original position and re-appends it at the very end of the stream, so any
// content injected after the suffix still appears before the closing tags.
// ---------------------------------------------------------------------------
function createMoveSuffixTransform(): Transform {
let foundSuffix = false
return new Transform({
transform(chunk, _encoding, callback) {
if (foundSuffix) {
this.push(chunk)
callback()
return
}
const index = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.BODY_AND_HTML)
if (index > -1) {
foundSuffix = true
if (chunk.length === ENCODED_TAGS.CLOSED.BODY_AND_HTML.length) {
callback()
return
}
const before = chunk.slice(0, index)
this.push(before)
if (chunk.length > ENCODED_TAGS.CLOSED.BODY_AND_HTML.length + index) {
const after = chunk.slice(
index + ENCODED_TAGS.CLOSED.BODY_AND_HTML.length
)
this.push(after)
}
} else {
this.push(chunk)
}
callback()
},
flush(callback) {
this.push(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
callback()
},
})
}
// ---------------------------------------------------------------------------
// data-dpl-id insertion – Node.js Transform that inserts a `data-dpl-id`
// attribute on the opening <html tag for deployment identification.
// ---------------------------------------------------------------------------
function createHtmlDataDplIdTransform(dplId: string): Transform {
let didTransform = false
return new Transform({
transform(chunk, _encoding, callback) {
if (didTransform) {
this.push(chunk)
callback()
return
}
const htmlTagIndex = indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML)
if (htmlTagIndex === -1) {
this.push(chunk)
callback()
return
}
const insertionPoint = htmlTagIndex + ENCODED_TAGS.OPENING.HTML.length
const encodedAttribute = Buffer.from(` data-dpl-id="${dplId}"`)
const modified = Buffer.allocUnsafe(
chunk.length + encodedAttribute.length
)
modified.set(chunk.subarray(0, insertionPoint))
modified.set(encodedAttribute, insertionPoint)
modified.set(
chunk.subarray(insertionPoint),
insertionPoint + encodedAttribute.length
)
this.push(modified)
didTransform = true
callback()
},
})
}
// ---------------------------------------------------------------------------
// Root layout validator – Node.js Transform that checks whether <html> and
// <body> tags are present in the streamed output. Dev-only; appends an
// error template when tags are missing so the error overlay can display it.
// ---------------------------------------------------------------------------
function createRootLayoutValidatorTransform(): Transform {
let foundHtml = false
let foundBody = false
return new Transform({
transform(chunk, _encoding, callback) {
if (
!foundHtml &&
indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.HTML) > -1
) {
foundHtml = true
}
if (
!foundBody &&
indexOfUint8Array(chunk, ENCODED_TAGS.OPENING.BODY) > -1
) {
foundBody = true
}
this.push(chunk)
callback()
},
flush(callback) {
const missingTags: ('html' | 'body')[] = []
if (!foundHtml) missingTags.push('html')
if (!foundBody) missingTags.push('body')
if (missingTags.length) {
this.push(
Buffer.from(
`<html id="__next_error__">
<template
data-next-error-message="Missing ${missingTags
.map((c) => `<${c}>`)
.join(
missingTags.length > 1 ? ' and ' : ''
)} tags in the root layout.\nRead more at https://nextjs.org/docs/messages/missing-root-layout-tags"
data-next-error-digest="${MISSING_ROOT_TAGS_ERROR}"
data-next-error-stack=""
></template>
`
)
)
}
callback()
},
})
}
// ---------------------------------------------------------------------------
// Rendering functions (output Node Readable natively via PassThrough)
// ---------------------------------------------------------------------------
export function renderToFlightStream(
export { renderToWebFlightStream } from './stream-ops.web'
export function renderToNodeFlightStream(
ComponentMod: FlightComponentMod,
payload: any,
clientModules: any,
opts: any,
runInContext?: <T>(fn: () => T) => T
opts: any
): AnyStream {
const run: <T>(fn: () => T) => T = runInContext ?? ((fn) => fn())
if (ComponentMod.renderToPipeableStream) {
const pt = new PassThrough()
const pipeable = run(() =>
ComponentMod.renderToPipeableStream!(payload, clientModules, opts)
)
pipeable.pipe(pt)
return pt
if (!ComponentMod.renderToPipeableStream) {
throw new Error('renderToPipeableStream is not implemented')
}
// Fallback: use web API and convert
const webStream = run(() =>
ComponentMod.renderToReadableStream(payload, clientModules, opts)
const pt = new PassThrough()
const pipeable = ComponentMod.renderToPipeableStream!(
payload,
clientModules,
opts
)
return webToReadable(webStream)
pipeable.pipe(pt)
return pt
}
export async function renderToFizzStream(
export { renderToWebFizzStream } from './stream-ops.web'
export async function renderToNodeFizzStream(
element: React.ReactElement,
streamOptions: any,
runInContext?: <T>(fn: () => T) => T
streamOptions: any
): Promise<FizzStreamResult> {
const run: <T>(fn: () => T) => T = runInContext ?? ((fn) => fn())
const pt = new PassThrough()
const shellReady = new DetachedPromise<void>()
const allReady = new DetachedPromise<void>()
// Node.js renderToPipeableStream passes a plain object to onHeaders,
// but callers expect a web Headers instance.
const originalOnHeaders = streamOptions?.onHeaders
const wrappedOnHeaders = originalOnHeaders
? (headers: Record<string, string>) => {
originalOnHeaders(new Headers(headers))
}
: undefined
const pipeable = run(() =>
getTracer().trace(AppRenderSpan.renderToReadableStream, () =>
renderToPipeableStream(element, {
...streamOptions,
onHeaders: wrappedOnHeaders,
onShellReady() {
streamOptions?.onShellReady?.()
pipeable.pipe(pt)
shellReady.resolve()
},
onShellError(error: unknown) {
streamOptions?.onShellError?.(error)
shellReady.reject(error)
},
onAllReady() {
streamOptions?.onAllReady?.()
allReady.resolve()
},
onError: streamOptions?.onError,
})
)
const pipeable = getTracer().trace(AppRenderSpan.renderToReadableStream, () =>
renderToPipeableStream(element, {
...streamOptions,
onHeaders: streamOptions?.onHeaders,
onShellReady() {
streamOptions?.onShellReady?.()
pipeable.pipe(pt)
shellReady.resolve()
},
onShellError(error: unknown) {
streamOptions?.onShellError?.(error)
shellReady.reject(error)
},
onAllReady() {
streamOptions?.onAllReady?.()
allReady.resolve()
},
onError: streamOptions?.onError,
})
)
await shellReady.promise
......@@ -238,23 +685,84 @@ export async function resumeAndAbort(
export async function continueFizzStream(
renderStream: AnyStream,
opts: import('./stream-ops.web').ContinueFizzStreamOptions
): Promise<AnyStream> {
const webOpts = {
...opts,
inlinedDataStream: opts.inlinedDataStream
? nodeReadableToWebReadableStream(opts.inlinedDataStream)
: undefined,
{
suffix,
inlinedDataStream,
isStaticGeneration,
allReady,
deploymentId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout,
}: import('./stream-ops.web').ContinueFizzStreamOptions
): Promise<Readable> {
// Suffix itself might contain close tags at the end, so we need to split it.
const suffixUnclosed = suffix ? suffix.split(CLOSE_TAG, 1)[0] : null
if (isStaticGeneration) {
if (allReady) {
await allReady
}
} else {
// Otherwise, we want to make sure Fizz is done with all microtasky work
// before we start pulling the stream and cause a flush.
await waitAtLeastOneReactRenderTask()
}
// The web continueFizzStream reads renderStream.allReady from the stream
// object itself (ReactDOMServerReadableStream). A plain ReadableStream from
// readableToWeb() won't have that property, so we attach it from opts.
const webStream = nodeReadableToWebReadableStream(renderStream)
const fizzLike = Object.assign(webStream, {
allReady: opts.allReady ?? Promise.resolve(),
}) as ReactDOMServerReadableStream
const webResult = await webContinueFizzStream(fizzLike, webOpts)
return webToReadable(webResult)
// Pipe the render stream through Node.js Transforms:
// 1. Buffer – coalesces chunks written in the same microtask into one Uint8Array
// 2. Flight data injection – interleaves RSC data chunks with the HTML stream
// 3. Head insertion – inserts server-generated HTML before </head>
const buffered = createBufferedTransformStream()
webToReadable(renderStream).pipe(buffered)
let source: Readable = buffered
if (deploymentId) {
const dplId = createHtmlDataDplIdTransform(deploymentId)
source.pipe(dplId)
source = dplId
}
// Metadata (icon mark replacement)
const metadata = createMetadataTransform(getServerInsertedMetadata)
source.pipe(metadata)
source = metadata
// Insert suffix content
if (suffixUnclosed != null && suffixUnclosed.length > 0) {
const deferredSuffix = createDeferredSuffixTransform(suffixUnclosed)
source.pipe(deferredSuffix)
source = deferredSuffix
}
// Flight data injection – interleaves RSC data chunks with the HTML stream
if (inlinedDataStream) {
const flightInjection = createFlightDataInjectionTransform(
webToReadable(inlinedDataStream),
true
)
source.pipe(flightInjection)
source = flightInjection
}
if (validateRootLayout) {
const rootLayoutValidator = createRootLayoutValidatorTransform()
source.pipe(rootLayoutValidator)
source = rootLayoutValidator
}
// Close tags should always be deferred to the end
const moveSuffix = createMoveSuffixTransform()
source.pipe(moveSuffix)
source = moveSuffix
// Head insertion – inserts server-generated HTML before </head>
const headInsertion = createHeadInsertionTransform(getServerInsertedHTML)
source.pipe(headInsertion)
source = headInsertion
return source
}
export async function continueStaticPrerender(
......@@ -361,7 +869,7 @@ export async function streamToString(stream: AnyStream): Promise<string> {
return webStreamToString(nodeReadableToWebReadableStream(stream))
}
export function createInlinedDataStream(
export function createWebInlinedDataStream(
source: AnyStream,
nonce: string | undefined,
formState: unknown | null
......@@ -371,6 +879,109 @@ export function createInlinedDataStream(
return webToReadable(webResult)
}
export function createNodeInlinedDataStream(
source: AnyStream,
nonce: string | undefined,
formState: unknown | null
): AnyStream {
const startScriptTag = nonce
? `<script nonce=${JSON.stringify(nonce)}>`
: '<script>'
const dataStream = webToReadable(source)
const pt = new PassThrough()
// Write initial bootstrap instructions
let scriptContents = `(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(
JSON.stringify([INLINE_FLIGHT_PAYLOAD_BOOTSTRAP])
)})`
if (formState != null) {
scriptContents += `;self.__next_f.push(${htmlEscapeJsonString(
JSON.stringify([INLINE_FLIGHT_PAYLOAD_FORM_STATE, formState])
)})`
}
pt.push(Buffer.from(`${startScriptTag}${scriptContents}</script>`))
// Pull from the flight data stream and wrap each chunk in a <script> tag
pullFlightData(dataStream, pt, startScriptTag)
return pt
}
const INLINE_FLIGHT_PAYLOAD_BOOTSTRAP = 0
const INLINE_FLIGHT_PAYLOAD_DATA = 1
const INLINE_FLIGHT_PAYLOAD_FORM_STATE = 2
const INLINE_FLIGHT_PAYLOAD_BINARY = 3
async function pullFlightData(
dataStream: Readable,
output: PassThrough,
startScriptTag: string
): Promise<void> {
function waitForReadableOrEnd(): Promise<void> {
if (dataStream.readableLength > 0 || dataStream.readableEnded) {
return Promise.resolve()
}
return new Promise<void>((resolve, reject) => {
function cleanup() {
dataStream.removeListener('readable', onDone)
dataStream.removeListener('end', onDone)
dataStream.removeListener('error', onError)
}
function onDone() {
cleanup()
resolve()
}
function onError(err: Error) {
cleanup()
reject(err)
}
dataStream.on('readable', onDone)
dataStream.on('end', onDone)
dataStream.on('error', onError)
})
}
try {
while (true) {
const chunk: Buffer | null = dataStream.read()
if (chunk !== null) {
let htmlInlinedData: string
if (isUtf8(chunk)) {
const decodedString = chunk.toString('utf-8')
htmlInlinedData = htmlEscapeJsonString(
JSON.stringify([INLINE_FLIGHT_PAYLOAD_DATA, decodedString])
)
} else {
const base64 = Buffer.from(
chunk.buffer,
chunk.byteOffset,
chunk.byteLength
).toString('base64')
htmlInlinedData = htmlEscapeJsonString(
JSON.stringify([INLINE_FLIGHT_PAYLOAD_BINARY, base64])
)
}
output.push(
Buffer.from(
`${startScriptTag}self.__next_f.push(${htmlInlinedData})</script>`
)
)
continue
}
if (dataStream.readableEnded) {
output.end()
return
}
await waitForReadableOrEnd()
}
} catch (err) {
output.destroy(err as Error)
}
}
export function createPendingStream(): AnyStream {
return new PassThrough()
}
......
......@@ -40,13 +40,16 @@ export const streamToBuffer = _m.streamToBuffer
export const chainStreams = _m.chainStreams
export const createDocumentClosingStream = _m.createDocumentClosingStream
export const processPrelude = _m.processPrelude
export const createInlinedDataStream = _m.createInlinedDataStream
export const createWebInlinedDataStream = _m.createWebInlinedDataStream
export const createNodeInlinedDataStream = _m.createNodeInlinedDataStream
export const createPendingStream = _m.createPendingStream
export const createOnHeadersCallback = _m.createOnHeadersCallback
export const resumeAndAbort = _m.resumeAndAbort
export const renderToFlightStream = _m.renderToFlightStream
export const renderToWebFlightStream = _m.renderToWebFlightStream
export const renderToNodeFlightStream = _m.renderToNodeFlightStream
export const streamToString = _m.streamToString
export const renderToFizzStream = _m.renderToFizzStream
export const renderToWebFizzStream = _m.renderToWebFizzStream
export const renderToNodeFizzStream = _m.renderToNodeFizzStream
export const resumeToFizzStream = _m.resumeToFizzStream
export const getServerPrerender = _m.getServerPrerender
export const getClientPrerender = _m.getClientPrerender
......
......@@ -176,7 +176,7 @@ export async function processPrelude(
// Composed helpers
// ---------------------------------------------------------------------------
export function createInlinedDataStream(
export function createWebInlinedDataStream(
source: AnyStream,
nonce: string | undefined,
formState: unknown | null
......@@ -188,6 +188,14 @@ export function createInlinedDataStream(
)
}
export function createNodeInlinedDataStream(
_source: AnyStream,
_nonce: string | undefined,
_formState: unknown | null
): AnyStream {
throw new Error('not implemented')
}
export function createPendingStream(): AnyStream {
return new ReadableStream<Uint8Array>()
}
......@@ -214,7 +222,16 @@ export async function resumeAndAbort(
)
}
export function renderToFlightStream(
export function renderToNodeFlightStream(
_ComponentMod: FlightComponentMod,
_payload: FlightPayload,
_clientModules: FlightClientModules,
_opts: FlightRenderOptions
): AnyStream {
throw new Error('not implemented')
}
export function renderToWebFlightStream(
ComponentMod: FlightComponentMod,
payload: FlightPayload,
clientModules: FlightClientModules,
......@@ -227,7 +244,7 @@ export async function streamToString(stream: AnyStream): Promise<string> {
return webStreamToString(stream as ReadableStream<Uint8Array>)
}
export async function renderToFizzStream(
export async function renderToWebFizzStream(
element: React.ReactElement,
streamOptions: any
): Promise<FizzStreamResult> {
......@@ -239,6 +256,13 @@ export async function renderToFizzStream(
return { stream, allReady: stream.allReady, abort: undefined }
}
export async function renderToNodeFizzStream(
_element: React.ReactElement,
_streamOptions: any
): Promise<FizzStreamResult> {
throw new Error('Not implemented')
}
export async function resumeToFizzStream(
element: React.ReactElement,
postponedState: PostponedState,
......
......@@ -343,7 +343,7 @@ export function renderToInitialFizzStream({
)
}
function createMetadataTransformStream(
export function createMetadataTransformStream(
insert: () => Promise<string> | string
): TransformStream<Uint8Array, Uint8Array> {
let chunkIndex = -1
......@@ -444,7 +444,7 @@ function createMetadataTransformStream(
})
}
function createHeadInsertionTransformStream(
export function createHeadInsertionTransformStream(
insert: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> {
let inserted = false
......@@ -668,7 +668,7 @@ export function createInstantTestScriptInsertionTransformStream(
// Suffix after main body content - scripts before </body>,
// but wait for the major chunks to be enqueued.
function createDeferredSuffixStream(
export function createDeferredSuffixStream(
suffix: string
): TransformStream<Uint8Array, Uint8Array> {
let flushed = false
......@@ -713,7 +713,7 @@ function createDeferredSuffixStream(
})
}
function createFlightDataInjectionTransformStream(
export function createFlightDataInjectionTransformStream(
stream: ReadableStream<Uint8Array>,
delayDataUntilFirstHtmlChunk: boolean
): TransformStream<Uint8Array, Uint8Array> {
......@@ -793,14 +793,17 @@ function createFlightDataInjectionTransformStream(
})
}
const CLOSE_TAG = '</body></html>'
export const CLOSE_TAG = '</body></html>'
/**
* This transform stream moves the suffix to the end of the stream, so results
* like `</body></html><script>...</script>` will be transformed to
* `<script>...</script></body></html>`.
*/
function createMoveSuffixStream(): TransformStream<Uint8Array, Uint8Array> {
export function createMoveSuffixStream(): TransformStream<
Uint8Array,
Uint8Array
> {
let foundSuffix = false
return new TransformStream({
......@@ -875,7 +878,7 @@ function createStripDocumentClosingTagsTransform(): TransformStream<
})
}
function createHtmlDataDplIdTransformStream(
export function createHtmlDataDplIdTransformStream(
dplId: string
): TransformStream<Uint8Array, Uint8Array> {
let didTransform = false
......@@ -973,7 +976,7 @@ export function createRootLayoutValidatorStream(): TransformStream<
})
}
function chainTransformers<T>(
export function chainTransformers<T>(
readable: ReadableStream<T>,
transformers: ReadonlyArray<TransformStream<T, T> | null>
): ReadableStream<T> {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment