Commit 3eee562f authored by Jimmy Lai's avatar Jimmy Lai

app-render: switch stream/debug switchers to typed TS modules

parent dc293df0
......@@ -389,7 +389,7 @@ Server rendering code (`app-render.tsx`, route modules) is NOT bundled during th
- **Adding a new feature flag**: Either leave it as a runtime env var (both code paths in bundle), or create new bundle variants (separate DefinePlugin value per variant, new taskfile tasks, updated `module.compiled.js` selector)
- **Gotcha**: DefinePlugin entries in `next-runtime.webpack-config.js` must be scoped to the correct `bundleType` (e.g. `app` only, not `server`) to avoid replacing assignment targets in `next-server.ts`
- **react-server layer**: Only `entry-base.ts` is compiled in rspack's `(react-server)` layer. ALL imports from `react-server-dom-webpack/*` (Flight server/static APIs) must go through `entry-base.ts`. Other files like `stream-ops.node.ts` or `app-render.tsx` must access Flight APIs via the `ComponentMod` parameter (which is the `entry-base.ts` module exposed through the `app-page.ts` build template). Direct imports from `react-server-dom-webpack/server.node` or `react-server-dom-webpack/static` in files outside `entry-base.ts` will fail at runtime with "The react-server condition must be enabled". Dev mode may mask this error, but production workers fail immediately.
- **Compile-time switcher pattern**: Platform-specific code (node vs web) uses a `.js` switcher file that `require()`s either `.node.ts` or `.web.ts` based on a `process.env` flag. A `.d.ts` file declares the shared API surface. Types are defined canonically in `.node.ts` and imported via `import type` by `.web.ts`. Examples: `stream-ops.js` and `debug-channel-server.js` (gated on `__NEXT_USE_NODE_STREAMS`).
- **Compile-time switcher pattern**: Platform-specific code (node vs web) can use a single `.ts` switcher module that conditionally `require()`s either `.node.ts` or `.web.ts` into a typed variable, then re-exports the shared runtime API as named exports. Keep the branch as `if/else` so DefinePlugin can dead-code-eliminate the unused `require()`. Keep shared types canonical in `.node.ts`, with `.web.ts` importing them via `import type` and the switcher re-exporting types as needed. Examples: `stream-ops.ts` and `debug-channel-server.ts` (gated on `__NEXT_USE_NODE_STREAMS`/`NEXT_RUNTIME`).
- **Edge runtime is different**: Edge routes do NOT use pre-compiled runtime bundles. They are compiled by the user's webpack/Turbopack, so `define-env.ts` controls DCE. Feature flags that gate `node:*` imports must be forced to `false` for edge builds in `define-env.ts` (`isEdgeServer ? false : flagValue`), otherwise webpack will try to resolve `node:stream` etc. and fail.
- **Webpack DCE for `require()` calls**: Webpack only DCEs a `require()` when it sits inside the dead branch of an `if/else` whose condition DefinePlugin can evaluate at compile time. An early-return or `throw` before the `require()` does NOT work: webpack doesn't do control-flow analysis for throws/returns, so the `require()` is still traced. The correct pattern is `if (dead) { ... } else { require('node:stream') }`. Bare `if (live) { require(...) }` without else works for inline `node:*` specifiers but NOT for `require('./some-module')` that pulls a new file into the module graph. Always test edge changes with `pnpm test-start-webpack` on `test/e2e/app-dir/app/standalone.test.ts` (has edge routes), not with `NEXT_SKIP_ISOLATE=1` which skips the full webpack compilation.
- **`NEXT_RUNTIME` is not a feature flag for user server bundles**: In user-project webpack server compilers, `process.env.NEXT_RUNTIME` is inlined to `'nodejs'`. Guarding Node-only `require('node:*')` paths with `NEXT_RUNTIME === 'nodejs'` does not prune anything. For feature-gated codepaths (e.g. node streams), guard on the real feature define such as `process.env.__NEXT_USE_NODE_STREAMS`.
......
export {
createDebugChannel,
toNodeDebugChannel,
} from './debug-channel-server.web'
export type {
DebugChannelPair,
DebugChannelServer,
DebugChannelClient,
} from './debug-channel-server.node'
// Compile-time switcher for debug-channel-server.
// This file must stay as plain .js (not .ts) so that the CJS
// module.exports = require(...) pattern is preserved verbatim for
// webpack DCE to work. TypeScript would transform it during compilation.
if (process.env.NEXT_RUNTIME === 'edge') {
module.exports = require('./debug-channel-server.web')
} else if (process.env.__NEXT_USE_NODE_STREAMS) {
module.exports = require('./debug-channel-server.node')
} else {
module.exports = require('./debug-channel-server.web')
}
import type {
DebugChannelPair,
DebugChannelServer,
DebugChannelClient,
} from './debug-channel-server.node'
type DebugChannelRuntimeModule = {
createDebugChannel: () => DebugChannelPair | undefined
toNodeDebugChannel: (
webDebugChannel: DebugChannelServer
) => import('node:stream').Writable
}
let debugChannelRuntimeModule: DebugChannelRuntimeModule
if (process.env.NEXT_RUNTIME === 'edge') {
debugChannelRuntimeModule =
require('./debug-channel-server.web') as typeof import('./debug-channel-server.web')
} else if (process.env.__NEXT_USE_NODE_STREAMS) {
debugChannelRuntimeModule =
require('./debug-channel-server.node') as typeof import('./debug-channel-server.node')
} else {
debugChannelRuntimeModule =
require('./debug-channel-server.web') as typeof import('./debug-channel-server.web')
}
export const createDebugChannel = debugChannelRuntimeModule.createDebugChannel
export const toNodeDebugChannel = debugChannelRuntimeModule.toNodeDebugChannel
export type { DebugChannelPair, DebugChannelServer, DebugChannelClient }
import type { PrerenderOptions } from 'react-dom/static'
// Re-export shared types from the canonical definition in stream-ops.node.ts
export type {
AnyStream,
ContinueFizzStreamOptions,
ContinueStaticPrerenderOptions,
ContinueStreamSharedOptions,
ContinueDynamicHTMLResumeOptions,
FlightComponentMod,
ServerPrerenderComponentMod,
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.node'
import type {
AnyStream,
ContinueFizzStreamOptions,
ContinueStaticPrerenderOptions,
ContinueStreamSharedOptions,
ContinueDynamicHTMLResumeOptions,
FlightComponentMod,
ServerPrerenderComponentMod,
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.node'
import type { PostponedState } from 'react-dom/static'
// ---------------------------------------------------------------------------
// Continue functions
// ---------------------------------------------------------------------------
export declare const continueFizzStream: (
stream: AnyStream,
opts: ContinueFizzStreamOptions
) => Promise<AnyStream>
export declare const continueStaticPrerender: (
stream: AnyStream,
opts: ContinueStaticPrerenderOptions
) => Promise<AnyStream>
export declare const continueDynamicPrerender: (
stream: AnyStream,
opts: ContinueStreamSharedOptions
) => Promise<AnyStream>
export declare const continueStaticFallbackPrerender: (
stream: AnyStream,
opts: ContinueStaticPrerenderOptions
) => Promise<AnyStream>
export declare const continueDynamicHTMLResume: (
stream: AnyStream,
opts: ContinueDynamicHTMLResumeOptions
) => Promise<AnyStream>
// ---------------------------------------------------------------------------
// Utility functions
// ---------------------------------------------------------------------------
export declare const streamToBuffer: (stream: AnyStream) => Promise<Buffer>
export declare const chainStreams: (...streams: Array<AnyStream>) => AnyStream
export declare function processPrelude(unprocessedPrelude: AnyStream): Promise<{
prelude: AnyStream
preludeIsEmpty: boolean
}>
export declare function createDocumentClosingStream():
| ReadableStream<Uint8Array>
| import('node:stream').Readable
// ---------------------------------------------------------------------------
// Composed helpers
// ---------------------------------------------------------------------------
export declare function createInlinedDataStream(
source: AnyStream,
nonce: string | undefined,
formState: unknown | null
): AnyStream
export declare function createPendingStream(): AnyStream
export declare function createOnHeadersCallback(
appendHeader: (key: string, value: string) => void
): NonNullable<PrerenderOptions['onHeaders']>
export declare function resumeAndAbort(
element: React.ReactElement,
postponed: PostponedState | null,
opts: Record<string, any>
): Promise<AnyStream>
export declare function renderToFlightStream(
ComponentMod: FlightComponentMod,
payload: FlightPayload,
clientModules: FlightClientModules,
opts: FlightRenderOptions,
runInContext?: <T>(fn: () => T) => T
): AnyStream
export declare function streamToString(stream: AnyStream): Promise<string>
export type FizzStreamResult = {
stream: AnyStream
allReady: Promise<void>
abort?: (reason?: unknown) => void
}
export declare function renderToFizzStream(
element: React.ReactElement,
streamOptions: any,
runInContext?: <T>(fn: () => T) => T
): Promise<FizzStreamResult>
export declare function resumeToFizzStream(
element: React.ReactElement,
postponedState: PostponedState,
streamOptions: any,
runInContext?: <T>(fn: () => T) => T
): Promise<FizzStreamResult>
export declare function getServerPrerender(
ComponentMod: ServerPrerenderComponentMod
): (...args: any[]) => any
export declare const getClientPrerender: typeof import('react-dom/static').prerender
export declare function pipeRuntimePrefetchTransform(
stream: AnyStream,
sentinel: number,
isPartial: boolean,
staleTime: number
): AnyStream
// ---------------------------------------------------------------------------
// Node.js <-> Web conversion helpers
// ---------------------------------------------------------------------------
// nodeReadableToWeb is only available in node bundles; undefined in web bundles.
// Declared separately so the type includes `| undefined`.
export declare const nodeReadableToWeb:
| ((readable: import('node:stream').Readable) => ReadableStream<Uint8Array>)
| undefined
// Compile-time switcher for stream operations.
// This file must stay as plain .js (not .ts) so that the CJS
// module.exports = require(...) pattern is preserved verbatim for
// webpack DCE to work.
if (process.env.__NEXT_USE_NODE_STREAMS) {
module.exports = require('./stream-ops.node')
} else {
module.exports = require('./stream-ops.web')
}
import type { PrerenderOptions, PostponedState } from 'react-dom/static'
import type {
AnyStream,
ContinueFizzStreamOptions,
ContinueStaticPrerenderOptions,
ContinueStreamSharedOptions,
ContinueDynamicHTMLResumeOptions,
FlightComponentMod,
ServerPrerenderComponentMod,
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.node'
export type {
AnyStream,
ContinueFizzStreamOptions,
ContinueStaticPrerenderOptions,
ContinueStreamSharedOptions,
ContinueDynamicHTMLResumeOptions,
FlightComponentMod,
ServerPrerenderComponentMod,
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.node'
export type FizzStreamResult = {
stream: AnyStream
allReady: Promise<void>
abort?: (reason?: unknown) => void
}
type StreamOpsRuntimeModule = {
continueFizzStream: (
stream: AnyStream,
opts: ContinueFizzStreamOptions
) => Promise<AnyStream>
continueStaticPrerender: (
stream: AnyStream,
opts: ContinueStaticPrerenderOptions
) => Promise<AnyStream>
continueDynamicPrerender: (
stream: AnyStream,
opts: ContinueStreamSharedOptions
) => Promise<AnyStream>
continueStaticFallbackPrerender: (
stream: AnyStream,
opts: ContinueStaticPrerenderOptions
) => Promise<AnyStream>
continueDynamicHTMLResume: (
stream: AnyStream,
opts: ContinueDynamicHTMLResumeOptions
) => Promise<AnyStream>
streamToBuffer: (stream: AnyStream) => Promise<Buffer>
chainStreams: (...streams: Array<AnyStream>) => AnyStream
processPrelude: (unprocessedPrelude: AnyStream) => Promise<{
prelude: AnyStream
preludeIsEmpty: boolean
}>
createDocumentClosingStream: () =>
| ReadableStream<Uint8Array>
| import('node:stream').Readable
createInlinedDataStream: (
source: AnyStream,
nonce: string | undefined,
formState: unknown | null
) => AnyStream
createPendingStream: () => AnyStream
createOnHeadersCallback: (
appendHeader: (key: string, value: string) => void
) => NonNullable<PrerenderOptions['onHeaders']>
resumeAndAbort: (
element: React.ReactElement,
postponed: PostponedState | null,
opts: Record<string, any>
) => Promise<AnyStream>
renderToFlightStream: (
ComponentMod: FlightComponentMod,
payload: FlightPayload,
clientModules: FlightClientModules,
opts: FlightRenderOptions,
runInContext?: <T>(fn: () => T) => T
) => AnyStream
streamToString: (stream: AnyStream) => Promise<string>
renderToFizzStream: (
element: React.ReactElement,
streamOptions: any,
runInContext?: <T>(fn: () => T) => T
) => Promise<FizzStreamResult>
resumeToFizzStream: (
element: React.ReactElement,
postponedState: PostponedState,
streamOptions: any,
runInContext?: <T>(fn: () => T) => T
) => Promise<FizzStreamResult>
getServerPrerender: (
ComponentMod: ServerPrerenderComponentMod
) => (...args: any[]) => any
getClientPrerender: typeof import('react-dom/static').prerender
pipeRuntimePrefetchTransform: (
stream: AnyStream,
sentinel: number,
isPartial: boolean,
staleTime: number
) => AnyStream
nodeReadableToWeb:
| ((readable: import('node:stream').Readable) => ReadableStream<Uint8Array>)
| undefined
}
let streamOpsRuntimeModule: StreamOpsRuntimeModule
if (process.env.__NEXT_USE_NODE_STREAMS) {
streamOpsRuntimeModule =
require('./stream-ops.node') as typeof import('./stream-ops.node') as unknown as StreamOpsRuntimeModule
} else {
streamOpsRuntimeModule =
require('./stream-ops.web') as typeof import('./stream-ops.web') as unknown as StreamOpsRuntimeModule
}
export const continueFizzStream = streamOpsRuntimeModule.continueFizzStream
export const continueStaticPrerender =
streamOpsRuntimeModule.continueStaticPrerender
export const continueDynamicPrerender =
streamOpsRuntimeModule.continueDynamicPrerender
export const continueStaticFallbackPrerender =
streamOpsRuntimeModule.continueStaticFallbackPrerender
export const continueDynamicHTMLResume =
streamOpsRuntimeModule.continueDynamicHTMLResume
export const streamToBuffer = streamOpsRuntimeModule.streamToBuffer
export const chainStreams = streamOpsRuntimeModule.chainStreams
export const processPrelude = streamOpsRuntimeModule.processPrelude
export const createDocumentClosingStream =
streamOpsRuntimeModule.createDocumentClosingStream
export const createInlinedDataStream =
streamOpsRuntimeModule.createInlinedDataStream
export const createPendingStream = streamOpsRuntimeModule.createPendingStream
export const createOnHeadersCallback =
streamOpsRuntimeModule.createOnHeadersCallback
export const resumeAndAbort = streamOpsRuntimeModule.resumeAndAbort
export const renderToFlightStream = streamOpsRuntimeModule.renderToFlightStream
export const streamToString = streamOpsRuntimeModule.streamToString
export const renderToFizzStream = streamOpsRuntimeModule.renderToFizzStream
export const resumeToFizzStream = streamOpsRuntimeModule.resumeToFizzStream
export const getServerPrerender = streamOpsRuntimeModule.getServerPrerender
export const getClientPrerender = streamOpsRuntimeModule.getClientPrerender
export const pipeRuntimePrefetchTransform =
streamOpsRuntimeModule.pipeRuntimePrefetchTransform
export const nodeReadableToWeb = streamOpsRuntimeModule.nodeReadableToWeb
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