| import type { |
| CacheNodeSeedData, |
| FlightRouterState, |
| InitialRSCPayload, |
| Segment as FlightRouterStateSegment, |
| DynamicParamTypesShort, |
| } from './types' |
| import type { ManifestNode } from '../../build/webpack/plugins/flight-manifest-plugin' |
|
|
| |
| import { createFromReadableStream } from 'react-server-dom-webpack/client' |
| |
| import { unstable_prerender as prerender } from 'react-server-dom-webpack/static' |
|
|
| import { |
| streamFromBuffer, |
| streamToBuffer, |
| } from '../stream-utils/node-web-streams-helper' |
| import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler' |
| import type { |
| HeadData, |
| LoadingModuleData, |
| } from '../../shared/lib/app-router-context.shared-runtime' |
| import { |
| encodeChildSegmentKey, |
| encodeSegment, |
| ROOT_SEGMENT_KEY, |
| type EncodedSegment, |
| } from '../../shared/lib/segment-cache/segment-value-encoding' |
| import { getDigestForWellKnownError } from './create-error-handler' |
| import type { FallbackRouteParams } from '../request/fallback-params' |
|
|
| |
| |
| export type RootTreePrefetch = { |
| buildId: string |
| tree: TreePrefetch |
| head: HeadData |
| isHeadPartial: boolean |
| staleTime: number |
| } |
|
|
| export type TreePrefetch = { |
| |
| segment: FlightRouterStateSegment |
|
|
| |
| slots: null | { |
| [parallelRouteKey: string]: TreePrefetch |
| } |
|
|
| |
| |
| |
| |
| |
| isRootLayout: boolean |
| } |
|
|
| export type SegmentPrefetch = { |
| buildId: string |
| rsc: React.ReactNode | null |
| loading: LoadingModuleData | Promise<LoadingModuleData> |
| isPartial: boolean |
| } |
|
|
| const filterStackFrame = |
| process.env.NODE_ENV !== 'production' |
| ? (require('../lib/source-maps') as typeof import('../lib/source-maps')) |
| .filterStackFrameDEV |
| : undefined |
|
|
| function onSegmentPrerenderError(error: unknown) { |
| const digest = getDigestForWellKnownError(error) |
| if (digest) { |
| return digest |
| } |
| |
| |
| } |
|
|
| export async function collectSegmentData( |
| fullPageDataBuffer: Buffer, |
| staleTime: number, |
| clientModules: ManifestNode, |
| serverConsumerManifest: any, |
| fallbackRouteParams: FallbackRouteParams | null |
| ): Promise<Map<string, Buffer>> { |
| |
|
|
| |
| const resultMap = new Map<string, Buffer>() |
|
|
| |
| |
| |
| |
| |
| try { |
| await createFromReadableStream(streamFromBuffer(fullPageDataBuffer), { |
| serverConsumerManifest, |
| }) |
| await waitAtLeastOneReactRenderTask() |
| } catch {} |
|
|
| |
| const abortController = new AbortController() |
| const onCompletedProcessingRouteTree = async () => { |
| |
| |
| |
| await waitAtLeastOneReactRenderTask() |
| abortController.abort() |
| } |
|
|
| |
| |
| |
| |
| const segmentTasks: Array<Promise<[string, Buffer]>> = [] |
| const { prelude: treeStream } = await prerender( |
| |
| |
| |
| |
| <PrefetchTreeData |
| fullPageDataBuffer={fullPageDataBuffer} |
| fallbackRouteParams={fallbackRouteParams} |
| serverConsumerManifest={serverConsumerManifest} |
| clientModules={clientModules} |
| staleTime={staleTime} |
| segmentTasks={segmentTasks} |
| onCompletedProcessingRouteTree={onCompletedProcessingRouteTree} |
| />, |
| clientModules, |
| { |
| filterStackFrame, |
| signal: abortController.signal, |
| onError: onSegmentPrerenderError, |
| } |
| ) |
|
|
| |
| const treeBuffer = await streamToBuffer(treeStream) |
| resultMap.set('/_tree', treeBuffer) |
|
|
| |
| |
| |
| for (const [segmentPath, buffer] of await Promise.all(segmentTasks)) { |
| resultMap.set(segmentPath, buffer) |
| } |
|
|
| return resultMap |
| } |
|
|
| async function PrefetchTreeData({ |
| fullPageDataBuffer, |
| fallbackRouteParams, |
| serverConsumerManifest, |
| clientModules, |
| staleTime, |
| segmentTasks, |
| onCompletedProcessingRouteTree, |
| }: { |
| fullPageDataBuffer: Buffer |
| serverConsumerManifest: any |
| fallbackRouteParams: FallbackRouteParams | null |
| clientModules: ManifestNode |
| staleTime: number |
| segmentTasks: Array<Promise<[string, Buffer]>> |
| onCompletedProcessingRouteTree: () => void |
| }): Promise<RootTreePrefetch | null> { |
| |
| |
| |
| |
| |
| const initialRSCPayload: InitialRSCPayload = await createFromReadableStream( |
| createUnclosingPrefetchStream(streamFromBuffer(fullPageDataBuffer)), |
| { |
| serverConsumerManifest, |
| } |
| ) |
|
|
| const buildId = initialRSCPayload.b |
|
|
| |
| const flightDataPaths = initialRSCPayload.f |
| if (flightDataPaths.length !== 1 && flightDataPaths[0].length !== 3) { |
| console.error( |
| 'Internal Next.js error: InitialRSCPayload does not match the expected ' + |
| 'shape for a prerendered page during segment prefetch generation.' |
| ) |
| return null |
| } |
| const flightRouterState: FlightRouterState = flightDataPaths[0][0] |
| const seedData: CacheNodeSeedData = flightDataPaths[0][1] |
| const head: HeadData = flightDataPaths[0][2] |
|
|
| |
| |
| |
| const tree = collectSegmentDataImpl( |
| flightRouterState, |
| buildId, |
| seedData, |
| fallbackRouteParams, |
| clientModules, |
| ROOT_SEGMENT_KEY, |
| segmentTasks |
| ) |
|
|
| const isHeadPartial = await isPartialRSCData(head, clientModules) |
|
|
| |
| |
| |
| onCompletedProcessingRouteTree() |
|
|
| |
| const treePrefetch: RootTreePrefetch = { |
| buildId, |
| tree, |
| head, |
| isHeadPartial, |
| staleTime, |
| } |
| return treePrefetch |
| } |
|
|
| function collectSegmentDataImpl( |
| route: FlightRouterState, |
| buildId: string, |
| seedData: CacheNodeSeedData | null, |
| fallbackRouteParams: FallbackRouteParams | null, |
| clientModules: ManifestNode, |
| key: string, |
| segmentTasks: Array<Promise<[string, Buffer]>> |
| ): TreePrefetch { |
| |
| |
| let slotMetadata: { [parallelRouteKey: string]: TreePrefetch } | null = null |
|
|
| const children = route[1] |
| const seedDataChildren = seedData !== null ? seedData[2] : null |
| for (const parallelRouteKey in children) { |
| const childRoute = children[parallelRouteKey] |
| const childSegment = childRoute[0] |
| const childSeedData = |
| seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null |
|
|
| const childKey = encodeChildSegmentKey( |
| key, |
| parallelRouteKey, |
| Array.isArray(childSegment) && fallbackRouteParams !== null |
| ? encodeSegmentWithPossibleFallbackParam( |
| childSegment, |
| fallbackRouteParams |
| ) |
| : encodeSegment(childSegment) |
| ) |
| const childTree = collectSegmentDataImpl( |
| childRoute, |
| buildId, |
| childSeedData, |
| fallbackRouteParams, |
| clientModules, |
| childKey, |
| segmentTasks |
| ) |
| if (slotMetadata === null) { |
| slotMetadata = {} |
| } |
| slotMetadata[parallelRouteKey] = childTree |
| } |
|
|
| if (seedData !== null) { |
| |
| segmentTasks.push( |
| |
| |
| waitAtLeastOneReactRenderTask().then(() => |
| renderSegmentPrefetch(buildId, seedData, key, clientModules) |
| ) |
| ) |
| } else { |
| |
| |
| |
| |
| |
| } |
|
|
| |
| |
| return { |
| segment: route[0], |
| slots: slotMetadata, |
| isRootLayout: route[4] === true, |
| } |
| } |
|
|
| function encodeSegmentWithPossibleFallbackParam( |
| segment: [string, string, DynamicParamTypesShort], |
| fallbackRouteParams: FallbackRouteParams |
| ): EncodedSegment { |
| const name = segment[0] |
| if (!fallbackRouteParams.has(name)) { |
| |
| return encodeSegment(segment) |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const encodedSegment = encodeSegment(segment) |
| const lastIndex = encodedSegment.lastIndexOf('$') |
| const encodedFallbackSegment = |
| |
| |
| |
| encodedSegment.substring(0, lastIndex + 1) + `[${name}]` |
| return encodedFallbackSegment as EncodedSegment |
| } |
|
|
| async function renderSegmentPrefetch( |
| buildId: string, |
| seedData: CacheNodeSeedData, |
| key: string, |
| clientModules: ManifestNode |
| ): Promise<[string, Buffer]> { |
| |
| |
| |
| const rsc = seedData[1] |
| const loading = seedData[3] |
| const segmentPrefetch: SegmentPrefetch = { |
| buildId, |
| rsc, |
| loading, |
| isPartial: await isPartialRSCData(rsc, clientModules), |
| } |
| |
| |
| |
| const abortController = new AbortController() |
| waitAtLeastOneReactRenderTask().then(() => abortController.abort()) |
| const { prelude: segmentStream } = await prerender( |
| segmentPrefetch, |
| clientModules, |
| { |
| filterStackFrame, |
| signal: abortController.signal, |
| onError: onSegmentPrerenderError, |
| } |
| ) |
| const segmentBuffer = await streamToBuffer(segmentStream) |
| if (key === ROOT_SEGMENT_KEY) { |
| return ['/_index', segmentBuffer] |
| } else { |
| return [key, segmentBuffer] |
| } |
| } |
|
|
| async function isPartialRSCData( |
| rsc: React.ReactNode, |
| clientModules: ManifestNode |
| ): Promise<boolean> { |
| |
| |
| |
| |
| |
| let isPartial = false |
| const abortController = new AbortController() |
| waitAtLeastOneReactRenderTask().then(() => { |
| |
| |
| isPartial = true |
| abortController.abort() |
| }) |
| await prerender(rsc, clientModules, { |
| filterStackFrame, |
| signal: abortController.signal, |
| onError() {}, |
| onPostpone() { |
| |
| |
| isPartial = true |
| }, |
| }) |
| return isPartial |
| } |
|
|
| function createUnclosingPrefetchStream( |
| originalFlightStream: ReadableStream<Uint8Array> |
| ): ReadableStream<Uint8Array> { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const reader = originalFlightStream.getReader() |
| return new ReadableStream({ |
| async pull(controller) { |
| while (true) { |
| const { done, value } = await reader.read() |
| if (!done) { |
| |
| |
| controller.enqueue(value) |
| continue |
| } |
| |
| |
| return |
| } |
| }, |
| }) |
| } |
|
|