"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "renderToHTMLOrFlight", {
    enumerable: true,
    get: function() {
        return renderToHTMLOrFlight;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default(require("react"));
const _renderresult = /*#__PURE__*/ _interop_require_default(require("../render-result"));
const _nodewebstreamshelper = require("../stream-utils/node-web-streams-helper");
const _internalutils = require("../internal-utils");
const _approuterheaders = require("../../client/components/app-router-headers");
const _metadata = require("../../lib/metadata/metadata");
const _withrequeststore = require("../async-storage/with-request-store");
const _withstaticgenerationstore = require("../async-storage/with-static-generation-store");
const _notfound = require("../../client/components/not-found");
const _redirect = require("../../client/components/redirect");
const _patchfetch = require("../lib/patch-fetch");
const _constants = require("../lib/trace/constants");
const _tracer = require("../lib/trace/tracer");
const _flightrenderresult = require("./flight-render-result");
const _createerrorhandler = require("./create-error-handler");
const _getshortdynamicparamtype = require("./get-short-dynamic-param-type");
const _getsegmentparam = require("./get-segment-param");
const _getscriptnoncefromheader = require("./get-script-nonce-from-header");
const _parseandvalidateflightrouterstate = require("./parse-and-validate-flight-router-state");
const _createflightrouterstatefromloadertree = require("./create-flight-router-state-from-loader-tree");
const _actionhandler = require("./action-handler");
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");
const _log = require("../../build/output/log");
const _requestcookies = require("../web/spec-extension/adapters/request-cookies");
const _serverinsertedhtml = require("./server-inserted-html");
const _requiredscripts = require("./required-scripts");
const _addpathprefix = require("../../shared/lib/router/utils/add-path-prefix");
const _makegetserverinsertedhtml = require("./make-get-server-inserted-html");
const _walktreewithflightrouterstate = require("./walk-tree-with-flight-router-state");
const _createcomponenttree = require("./create-component-tree");
const _getassetquerystring = require("./get-asset-query-string");
const _encryptionutils = require("./encryption-utils");
const _postponedstate = require("./postponed-state");
const _hooksservercontext = require("../../client/components/hooks-server-context");
const _useflightresponse = require("./use-flight-response");
const _staticgenerationbailout = require("../../client/components/static-generation-bailout");
const _formatservererror = require("../../lib/format-server-error");
const _dynamicrendering = require("./dynamic-rendering");
const _clientcomponentrendererlogger = require("../client-component-renderer-logger");
const _actionutils = require("./action-utils");
const _helpers = require("../base-http/helpers");
const _routeregex = require("../../shared/lib/router/utils/route-regex");
const _parserelativeurl = require("../../shared/lib/router/utils/parse-relative-url");
const _approuter = /*#__PURE__*/ _interop_require_default(require("../../client/components/app-router"));
const _serveractionrequestmeta = require("../lib/server-action-request-meta");
const _createinitialrouterstate = require("../../client/components/router-reducer/create-initial-router-state");
const _actionqueue = require("../../shared/lib/router/action-queue");
const _prerenderasyncstorageexternal = require("./prerender-async-storage.external");
const _utils = require("../instrumentation/utils");
const _segment = require("../../shared/lib/segment");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const flightDataPathHeadKey = 'h';
function parseRequestHeaders(headers, options) {
    const isPrefetchRequest = headers[_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] !== undefined;
    const isHmrRefresh = headers[_approuterheaders.NEXT_HMR_REFRESH_HEADER.toLowerCase()] !== undefined;
    const isRSCRequest = headers[_approuterheaders.RSC_HEADER.toLowerCase()] !== undefined;
    const shouldProvideFlightRouterState = isRSCRequest && (!isPrefetchRequest || !options.isRoutePPREnabled);
    const flightRouterState = shouldProvideFlightRouterState ? (0, _parseandvalidateflightrouterstate.parseAndValidateFlightRouterState)(headers[_approuterheaders.NEXT_ROUTER_STATE_TREE_HEADER.toLowerCase()]) : undefined;
    const csp = headers['content-security-policy'] || headers['content-security-policy-report-only'];
    const nonce = typeof csp === 'string' ? (0, _getscriptnoncefromheader.getScriptNonceFromHeader)(csp) : undefined;
    return {
        flightRouterState,
        isPrefetchRequest,
        isHmrRefresh,
        isRSCRequest,
        nonce
    };
}
function createNotFoundLoaderTree(loaderTree) {
    // Align the segment with parallel-route-default in next-app-loader
    const components = loaderTree[2];
    return [
        '',
        {
            children: [
                _segment.PAGE_SEGMENT_KEY,
                {},
                {
                    page: components['not-found']
                }
            ]
        },
        components
    ];
}
/**
 * Returns a function that parses the dynamic segment and return the associated value.
 */ function makeGetDynamicParamFromSegment(params, pagePath, fallbackRouteParams) {
    return function getDynamicParamFromSegment(// [slug] / [[slug]] / [...slug]
    segment) {
        const segmentParam = (0, _getsegmentparam.getSegmentParam)(segment);
        if (!segmentParam) {
            return null;
        }
        const key = segmentParam.param;
        let value = params[key];
        if (fallbackRouteParams && fallbackRouteParams.has(segmentParam.param)) {
            value = fallbackRouteParams.get(segmentParam.param);
        } else if (Array.isArray(value)) {
            value = value.map((i)=>encodeURIComponent(i));
        } else if (typeof value === 'string') {
            value = encodeURIComponent(value);
        }
        if (!value) {
            const isCatchall = segmentParam.type === 'catchall';
            const isOptionalCatchall = segmentParam.type === 'optional-catchall';
            if (isCatchall || isOptionalCatchall) {
                const dynamicParamType = _getshortdynamicparamtype.dynamicParamTypes[segmentParam.type];
                // handle the case where an optional catchall does not have a value,
                // e.g. `/dashboard/[[...slug]]` when requesting `/dashboard`
                if (isOptionalCatchall) {
                    return {
                        param: key,
                        value: null,
                        type: dynamicParamType,
                        treeSegment: [
                            key,
                            '',
                            dynamicParamType
                        ]
                    };
                }
                // handle the case where a catchall or optional catchall does not have a value,
                // e.g. `/foo/bar/hello` and `@slot/[...catchall]` or `@slot/[[...catchall]]` is matched
                value = pagePath.split('/')// remove the first empty string
                .slice(1)// replace any dynamic params with the actual values
                .flatMap((pathSegment)=>{
                    const param = (0, _routeregex.parseParameter)(pathSegment);
                    // if the segment matches a param, return the param value
                    // otherwise, it's a static segment, so just return that
                    return params[param.key] ?? param.key;
                });
                return {
                    param: key,
                    value,
                    type: dynamicParamType,
                    // This value always has to be a string.
                    treeSegment: [
                        key,
                        value.join('/'),
                        dynamicParamType
                    ]
                };
            }
        }
        const type = (0, _getshortdynamicparamtype.getShortDynamicParamType)(segmentParam.type);
        return {
            param: key,
            // The value that is passed to user code.
            value: value,
            // The value that is rendered in the router tree.
            treeSegment: [
                key,
                Array.isArray(value) ? value.join('/') : value,
                type
            ],
            type: type
        };
    };
}
function NonIndex({ ctx }) {
    const is404Page = ctx.pagePath === '/404';
    const isInvalidStatusCode = typeof ctx.res.statusCode === 'number' && ctx.res.statusCode > 400;
    if (is404Page || isInvalidStatusCode) {
        return /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
            name: "robots",
            content: "noindex"
        });
    }
    return null;
}
/**
 * This is used by server actions & client-side navigations to generate RSC data from a client-side request.
 * This function is only called on "dynamic" requests (ie, there wasn't already a static response).
 * It uses request headers (namely `Next-Router-State-Tree`) to determine where to start rendering.
 */ async function generateDynamicRSCPayload(ctx, options) {
    // Flight data that is going to be passed to the browser.
    // Currently a single item array but in the future multiple patches might be combined in a single request.
    let flightData = null;
    const { componentMod: { tree: loaderTree, createDynamicallyTrackedSearchParams, createDynamicallyTrackedParams }, getDynamicParamFromSegment, appUsingSizeAdjustment, requestStore: { url }, query, requestId, flightRouterState, staticGenerationStore } = ctx;
    if (!(options == null ? void 0 : options.skipFlight)) {
        const preloadCallbacks = [];
        const [MetadataTree, getMetadataReady] = (0, _metadata.createMetadataComponents)({
            tree: loaderTree,
            query,
            metadataContext: (0, _metadata.createTrackedMetadataContext)(url.pathname, ctx.renderOpts, staticGenerationStore),
            getDynamicParamFromSegment,
            appUsingSizeAdjustment,
            createDynamicallyTrackedSearchParams,
            createDynamicallyTrackedParams
        });
        flightData = (await (0, _walktreewithflightrouterstate.walkTreeWithFlightRouterState)({
            ctx,
            createSegmentPath: (child)=>child,
            loaderTreeToFilter: loaderTree,
            parentParams: {},
            flightRouterState,
            isFirst: true,
            // For flight, render metadata inside leaf page
            rscPayloadHead: /*#__PURE__*/ (0, _jsxruntime.jsxs)(_react.default.Fragment, {
                children: [
                    /*#__PURE__*/ (0, _jsxruntime.jsx)(NonIndex, {
                        ctx: ctx
                    }),
                    /*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataTree, {}, requestId)
                ]
            }, flightDataPathHeadKey),
            injectedCSS: new Set(),
            injectedJS: new Set(),
            injectedFontPreloadTags: new Set(),
            rootLayoutIncluded: false,
            getMetadataReady,
            preloadCallbacks
        })).map((path)=>path.slice(1)) // remove the '' (root) segment
        ;
    }
    // If we have an action result, then this is a server action response.
    // We can rely on this because `ActionResult` will always be a promise, even if
    // the result is falsey.
    if (options == null ? void 0 : options.actionResult) {
        return {
            a: options.actionResult,
            f: flightData,
            b: ctx.renderOpts.buildId
        };
    }
    // Otherwise, it's a regular RSC response.
    return {
        b: ctx.renderOpts.buildId,
        // Anything besides an action response should have non-null flightData.
        // We don't ever expect this to be null because `skipFlight` is only
        // used when invoked by a server action, which is covered above.
        // The client router can handle an empty string (treating it as an MPA navigation),
        // so we'll use that as a fallback.
        f: flightData ?? ''
    };
}
function createErrorContext(ctx, renderSource) {
    return {
        routerKind: 'App Router',
        routePath: ctx.pagePath,
        routeType: ctx.isAction ? 'action' : 'render',
        renderSource,
        revalidateReason: (0, _utils.getRevalidateReason)(ctx.staticGenerationStore)
    };
}
/**
 * Produces a RenderResult containing the Flight data for the given request. See
 * `generateDynamicRSCPayload` for information on the contents of the render result.
 */ async function generateDynamicFlightRenderResult(req, ctx, options) {
    const renderOpts = ctx.renderOpts;
    function onFlightDataRenderError(err) {
        return renderOpts.onInstrumentationRequestError == null ? void 0 : renderOpts.onInstrumentationRequestError.call(renderOpts, err, req, createErrorContext(ctx, 'react-server-components-payload'));
    }
    const onError = (0, _createerrorhandler.createFlightReactServerErrorHandler)(!!renderOpts.dev, onFlightDataRenderError);
    const rscPayload = await generateDynamicRSCPayload(ctx, options);
    // For app dir, use the bundled version of Flight server renderer (renderToReadableStream)
    // which contains the subset React.
    const flightReadableStream = ctx.componentMod.renderToReadableStream(rscPayload, ctx.clientReferenceManifest.clientModules, {
        onError,
        nonce: ctx.nonce
    });
    return new _flightrenderresult.FlightRenderResult(flightReadableStream, {
        fetchMetrics: ctx.staticGenerationStore.fetchMetrics
    });
}
/**
 * Crawlers will inadvertently think the canonicalUrl in the RSC payload should be crawled
 * when our intention is to just seed the router state with the current URL.
 * This function splits up the pathname so that we can later join it on
 * when we're ready to consume the path.
 */ function prepareInitialCanonicalUrl(url) {
    return (url.pathname + url.search).split('/');
}
// This is the data necessary to render <AppRouter /> when no SSR errors are encountered
async function getRSCPayload(tree, ctx, is404) {
    const injectedCSS = new Set();
    const injectedJS = new Set();
    const injectedFontPreloadTags = new Set();
    let missingSlots;
    // We only track missing parallel slots in development
    if (process.env.NODE_ENV === 'development') {
        missingSlots = new Set();
    }
    const { getDynamicParamFromSegment, query, appUsingSizeAdjustment, componentMod: { GlobalError, createDynamicallyTrackedSearchParams, createDynamicallyTrackedParams }, requestStore: { url }, staticGenerationStore } = ctx;
    const initialTree = (0, _createflightrouterstatefromloadertree.createFlightRouterStateFromLoaderTree)(tree, getDynamicParamFromSegment, query);
    const [MetadataTree, getMetadataReady] = (0, _metadata.createMetadataComponents)({
        tree,
        errorType: is404 ? 'not-found' : undefined,
        query,
        metadataContext: (0, _metadata.createTrackedMetadataContext)(url.pathname, ctx.renderOpts, staticGenerationStore),
        getDynamicParamFromSegment,
        appUsingSizeAdjustment,
        createDynamicallyTrackedSearchParams,
        createDynamicallyTrackedParams
    });
    const preloadCallbacks = [];
    const seedData = await (0, _createcomponenttree.createComponentTree)({
        ctx,
        createSegmentPath: (child)=>child,
        loaderTree: tree,
        parentParams: {},
        firstItem: true,
        injectedCSS,
        injectedJS,
        injectedFontPreloadTags,
        rootLayoutIncluded: false,
        getMetadataReady,
        missingSlots,
        preloadCallbacks
    });
    // When the `vary` response header is present with `Next-URL`, that means there's a chance
    // it could respond differently if there's an interception route. We provide this information
    // to `AppRouter` so that it can properly seed the prefetch cache with a prefix, if needed.
    const varyHeader = ctx.res.getHeader('vary');
    const couldBeIntercepted = typeof varyHeader === 'string' && varyHeader.includes(_approuterheaders.NEXT_URL);
    const initialHead = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_react.default.Fragment, {
        children: [
            /*#__PURE__*/ (0, _jsxruntime.jsx)(NonIndex, {
                ctx: ctx
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataTree, {}, ctx.requestId)
        ]
    }, flightDataPathHeadKey);
    return {
        // See the comment above the `Preloads` component (below) for why this is part of the payload
        P: /*#__PURE__*/ (0, _jsxruntime.jsx)(Preloads, {
            preloadCallbacks: preloadCallbacks
        }),
        b: ctx.renderOpts.buildId,
        p: ctx.assetPrefix,
        c: prepareInitialCanonicalUrl(url),
        i: !!couldBeIntercepted,
        f: [
            [
                initialTree,
                seedData,
                initialHead
            ]
        ],
        m: missingSlots,
        G: GlobalError,
        s: typeof ctx.renderOpts.postponed === 'string'
    };
}
/**
 * Preload calls (such as `ReactDOM.preloadStyle` and `ReactDOM.preloadFont`) need to be called during rendering
 * in order to create the appropriate preload tags in the DOM, otherwise they're a no-op. Since we invoke
 * renderToReadableStream with a function that returns component props rather than a component itself, we use
 * this component to "render  " the preload calls.
 */ function Preloads({ preloadCallbacks }) {
    preloadCallbacks.forEach((preloadFn)=>preloadFn());
    return null;
}
// This is the data necessary to render <AppRouter /> when an error state is triggered
async function getErrorRSCPayload(tree, ctx, errorType) {
    const { getDynamicParamFromSegment, query, appUsingSizeAdjustment, componentMod: { GlobalError, createDynamicallyTrackedSearchParams, createDynamicallyTrackedParams }, requestStore: { url }, requestId } = ctx;
    const [MetadataTree] = (0, _metadata.createMetadataComponents)({
        tree,
        // We create an untracked metadata context here because we can't postpone
        // again during the error render.
        metadataContext: (0, _metadata.createMetadataContext)(url.pathname, ctx.renderOpts),
        errorType,
        query,
        getDynamicParamFromSegment,
        appUsingSizeAdjustment,
        createDynamicallyTrackedSearchParams,
        createDynamicallyTrackedParams
    });
    const initialHead = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_react.default.Fragment, {
        children: [
            /*#__PURE__*/ (0, _jsxruntime.jsx)(NonIndex, {
                ctx: ctx
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(MetadataTree, {}, requestId),
            process.env.NODE_ENV === 'development' && /*#__PURE__*/ (0, _jsxruntime.jsx)("meta", {
                name: "next-error",
                content: "not-found"
            })
        ]
    }, flightDataPathHeadKey);
    const initialTree = (0, _createflightrouterstatefromloadertree.createFlightRouterStateFromLoaderTree)(tree, getDynamicParamFromSegment, query);
    // For metadata notFound error there's no global not found boundary on top
    // so we create a not found page with AppRouter
    const initialSeedData = [
        initialTree[0],
        /*#__PURE__*/ (0, _jsxruntime.jsxs)("html", {
            id: "__next_error__",
            children: [
                /*#__PURE__*/ (0, _jsxruntime.jsx)("head", {}),
                /*#__PURE__*/ (0, _jsxruntime.jsx)("body", {})
            ]
        }),
        {},
        null
    ];
    return {
        b: ctx.renderOpts.buildId,
        p: ctx.assetPrefix,
        c: prepareInitialCanonicalUrl(url),
        m: undefined,
        i: false,
        f: [
            [
                initialTree,
                initialSeedData,
                initialHead
            ]
        ],
        G: GlobalError,
        s: typeof ctx.renderOpts.postponed === 'string'
    };
}
// This component must run in an SSR context. It will render the RSC root component
function App({ reactServerStream, preinitScripts, clientReferenceManifest, nonce, ServerInsertedHTMLProvider }) {
    preinitScripts();
    const response = _react.default.use((0, _useflightresponse.useFlightStream)(reactServerStream, clientReferenceManifest, nonce));
    const initialState = (0, _createinitialrouterstate.createInitialRouterState)({
        buildId: response.b,
        initialFlightData: response.f,
        initialCanonicalUrlParts: response.c,
        // location and initialParallelRoutes are not initialized in the SSR render
        // they are set to an empty map and window.location, respectively during hydration
        initialParallelRoutes: null,
        location: null,
        couldBeIntercepted: response.i,
        postponed: response.s
    });
    const actionQueue = (0, _actionqueue.createMutableActionQueue)(initialState);
    const { HeadManagerContext } = require('../../shared/lib/head-manager-context.shared-runtime');
    return /*#__PURE__*/ (0, _jsxruntime.jsx)(HeadManagerContext.Provider, {
        value: {
            appDir: true,
            nonce
        },
        children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ServerInsertedHTMLProvider, {
            children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_approuter.default, {
                actionQueue: actionQueue,
                globalErrorComponent: response.G,
                assetPrefix: response.p
            })
        })
    });
}
// @TODO our error stream should be probably just use the same root component. But it was previously
// different I don't want to figure out if that is meaningful at this time so just keeping the behavior
// consistent for now.
function AppWithoutContext({ reactServerStream, preinitScripts, clientReferenceManifest, nonce }) {
    preinitScripts();
    const response = _react.default.use((0, _useflightresponse.useFlightStream)(reactServerStream, clientReferenceManifest, nonce));
    const initialState = (0, _createinitialrouterstate.createInitialRouterState)({
        buildId: response.b,
        initialFlightData: response.f,
        initialCanonicalUrlParts: response.c,
        // location and initialParallelRoutes are not initialized in the SSR render
        // they are set to an empty map and window.location, respectively during hydration
        initialParallelRoutes: null,
        location: null,
        couldBeIntercepted: response.i,
        postponed: response.s
    });
    const actionQueue = (0, _actionqueue.createMutableActionQueue)(initialState);
    return /*#__PURE__*/ (0, _jsxruntime.jsx)(_approuter.default, {
        actionQueue: actionQueue,
        globalErrorComponent: response.G,
        assetPrefix: response.p
    });
}
async function renderToHTMLOrFlightImpl(req, res, pagePath, query, renderOpts, requestStore, staticGenerationStore, parsedRequestHeaders, requestEndedState, postponedState) {
    var _getTracer_getRootSpanAttributes;
    const isNotFoundPath = pagePath === '/404';
    if (isNotFoundPath) {
        res.statusCode = 404;
    }
    // A unique request timestamp used by development to ensure that it's
    // consistent and won't change during this request. This is important to
    // avoid that resources can be deduped by React Float if the same resource is
    // rendered or preloaded multiple times: `<link href="a.css?v={Date.now()}"/>`.
    const requestTimestamp = Date.now();
    const { serverActionsManifest, ComponentMod, nextFontManifest, serverActions, assetPrefix = '', enableTainting } = renderOpts;
    // We need to expose the bundled `require` API globally for
    // react-server-dom-webpack. This is a hack until we find a better way.
    if (ComponentMod.__next_app__) {
        const instrumented = (0, _clientcomponentrendererlogger.wrapClientComponentLoader)(ComponentMod);
        // @ts-ignore
        globalThis.__next_require__ = instrumented.require;
        // When we are prerendering if there is a cacheSignal for tracking
        // cache reads we wrap the loadChunk in this tracking. This allows us
        // to treat chunk loading with similar semantics as cache reads to avoid
        // async loading chunks from causing a prerender to abort too early.
        // @ts-ignore
        globalThis.__next_chunk_load__ = instrumented.loadChunk;
    }
    if (process.env.NODE_ENV === 'development') {
        // reset isr status at start of request
        const { pathname } = new URL(req.url || '/', 'http://n');
        renderOpts.setAppIsrStatus == null ? void 0 : renderOpts.setAppIsrStatus.call(renderOpts, pathname, null);
    }
    if (// The type check here ensures that `req` is correctly typed, and the
    // environment variable check provides dead code elimination.
    process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextRequest)(req)) {
        req.originalRequest.on('end', ()=>{
            var _prerenderStore_dynamicTracking_dynamicAccesses, _prerenderStore_dynamicTracking;
            const staticGenStore = ComponentMod.staticGenerationAsyncStorage.getStore();
            const prerenderStore = _prerenderasyncstorageexternal.prerenderAsyncStorage.getStore();
            const isPPR = !!(prerenderStore == null ? void 0 : (_prerenderStore_dynamicTracking = prerenderStore.dynamicTracking) == null ? void 0 : (_prerenderStore_dynamicTracking_dynamicAccesses = _prerenderStore_dynamicTracking.dynamicAccesses) == null ? void 0 : _prerenderStore_dynamicTracking_dynamicAccesses.length);
            if (process.env.NODE_ENV === 'development' && staticGenStore && renderOpts.setAppIsrStatus && !isPPR) {
                // only node can be ISR so we only need to update the status here
                const { pathname } = new URL(req.url || '/', 'http://n');
                let { revalidate } = staticGenStore;
                if (typeof revalidate === 'undefined') {
                    revalidate = false;
                }
                if (revalidate === false || revalidate > 0) {
                    renderOpts.setAppIsrStatus(pathname, revalidate);
                }
            }
            requestEndedState.ended = true;
            if ('performance' in globalThis) {
                const metrics = (0, _clientcomponentrendererlogger.getClientComponentLoaderMetrics)({
                    reset: true
                });
                if (metrics) {
                    (0, _tracer.getTracer)().startSpan(_constants.NextNodeServerSpan.clientComponentLoading, {
                        startTime: metrics.clientComponentLoadStart,
                        attributes: {
                            'next.clientComponentLoadCount': metrics.clientComponentLoadCount
                        }
                    }).end(metrics.clientComponentLoadStart + metrics.clientComponentLoadTimes);
                }
            }
        });
    }
    const metadata = {};
    const appUsingSizeAdjustment = !!(nextFontManifest == null ? void 0 : nextFontManifest.appUsingSizeAdjust);
    // TODO: fix this typescript
    const clientReferenceManifest = renderOpts.clientReferenceManifest;
    const serverModuleMap = (0, _actionutils.createServerModuleMap)({
        serverActionsManifest,
        pageName: renderOpts.page
    });
    (0, _encryptionutils.setReferenceManifestsSingleton)({
        clientReferenceManifest,
        serverActionsManifest,
        serverModuleMap
    });
    ComponentMod.patchFetch();
    // Pull out the hooks/references from the component.
    const { tree: loaderTree, taintObjectReference } = ComponentMod;
    if (enableTainting) {
        taintObjectReference('Do not pass process.env to client components since it will leak sensitive data', process.env);
    }
    staticGenerationStore.fetchMetrics = [];
    metadata.fetchMetrics = staticGenerationStore.fetchMetrics;
    // don't modify original query object
    query = {
        ...query
    };
    (0, _internalutils.stripInternalQueries)(query);
    const { flightRouterState, isPrefetchRequest, isRSCRequest, nonce } = parsedRequestHeaders;
    /**
   * The metadata items array created in next-app-loader with all relevant information
   * that we need to resolve the final metadata.
   */ let requestId;
    if (process.env.NEXT_RUNTIME === 'edge') {
        requestId = crypto.randomUUID();
    } else {
        requestId = require('next/dist/compiled/nanoid').nanoid();
    }
    /**
   * Dynamic parameters. E.g. when you visit `/dashboard/vercel` which is rendered by `/dashboard/[slug]` the value will be {"slug": "vercel"}.
   */ const params = renderOpts.params ?? {};
    const { isStaticGeneration, fallbackRouteParams } = staticGenerationStore;
    const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(params, pagePath, fallbackRouteParams);
    const isActionRequest = (0, _serveractionrequestmeta.getServerActionRequestMetadata)(req).isServerAction;
    const ctx = {
        componentMod: ComponentMod,
        renderOpts,
        requestStore,
        staticGenerationStore,
        parsedRequestHeaders,
        getDynamicParamFromSegment,
        query,
        isPrefetch: isPrefetchRequest,
        isAction: isActionRequest,
        requestTimestamp,
        appUsingSizeAdjustment,
        flightRouterState,
        requestId,
        defaultRevalidate: false,
        pagePath,
        clientReferenceManifest,
        assetPrefix,
        isNotFoundPath,
        nonce,
        res
    };
    (_getTracer_getRootSpanAttributes = (0, _tracer.getTracer)().getRootSpanAttributes()) == null ? void 0 : _getTracer_getRootSpanAttributes.set('next.route', pagePath);
    if (isStaticGeneration) {
        // We're either building or revalidating. In either case we need to
        // prerender our page rather than render it.
        const prerenderToStreamWithTracing = (0, _tracer.getTracer)().wrap(_constants.AppRenderSpan.getBodyResult, {
            spanName: `prerender route (app) ${pagePath}`,
            attributes: {
                'next.route': pagePath
            }
        }, prerenderToStream);
        let response = await prerenderToStreamWithTracing(req, res, ctx, metadata, staticGenerationStore, loaderTree);
        // If we're debugging partial prerendering, print all the dynamic API accesses
        // that occurred during the render.
        // @TODO move into renderToStream function
        if (response.dynamicTracking && (0, _dynamicrendering.usedDynamicAPIs)(response.dynamicTracking) && response.dynamicTracking.isDebugDynamicAccesses) {
            (0, _log.warn)('The following dynamic usage was detected:');
            for (const access of (0, _dynamicrendering.formatDynamicAPIAccesses)(response.dynamicTracking)){
                (0, _log.warn)(access);
            }
        }
        // If we encountered any unexpected errors during build we fail the
        // prerendering phase and the build.
        if (response.digestErrorsMap.size) {
            const buildFailingError = response.digestErrorsMap.values().next().value;
            if (buildFailingError) throw buildFailingError;
        }
        // Pick first userland SSR error, which is also not a RSC error.
        if (response.ssrErrors.length) {
            const buildFailingError = response.ssrErrors.find((err)=>(0, _createerrorhandler.isUserLandError)(err));
            if (buildFailingError) throw buildFailingError;
        }
        const options = {
            metadata
        };
        // If we have pending revalidates, wait until they are all resolved.
        if (staticGenerationStore.pendingRevalidates) {
            var _staticGenerationStore_incrementalCache;
            options.waitUntil = Promise.all([
                (_staticGenerationStore_incrementalCache = staticGenerationStore.incrementalCache) == null ? void 0 : _staticGenerationStore_incrementalCache.revalidateTag(staticGenerationStore.revalidatedTags || []),
                ...Object.values(staticGenerationStore.pendingRevalidates || {})
            ]);
        }
        (0, _patchfetch.addImplicitTags)(staticGenerationStore, requestStore);
        if (staticGenerationStore.tags) {
            metadata.fetchTags = staticGenerationStore.tags.join(',');
        }
        // If force static is specifically set to false, we should not revalidate
        // the page.
        if (staticGenerationStore.forceStatic === false) {
            staticGenerationStore.revalidate = 0;
        }
        // Copy the revalidation value onto the render result metadata.
        metadata.revalidate = staticGenerationStore.revalidate ?? ctx.defaultRevalidate;
        // provide bailout info for debugging
        if (metadata.revalidate === 0) {
            metadata.staticBailoutInfo = {
                description: staticGenerationStore.dynamicUsageDescription,
                stack: staticGenerationStore.dynamicUsageStack
            };
        }
        return new _renderresult.default(await (0, _nodewebstreamshelper.streamToString)(response.stream), options);
    } else {
        // We're rendering dynamically
        if (isRSCRequest) {
            return generateDynamicFlightRenderResult(req, ctx);
        }
        const renderToStreamWithTracing = (0, _tracer.getTracer)().wrap(_constants.AppRenderSpan.getBodyResult, {
            spanName: `render route (app) ${pagePath}`,
            attributes: {
                'next.route': pagePath
            }
        }, renderToStream);
        let formState = null;
        if (isActionRequest) {
            // For action requests, we handle them differently with a special render result.
            const actionRequestResult = await (0, _actionhandler.handleAction)({
                req,
                res,
                ComponentMod,
                serverModuleMap,
                generateFlight: generateDynamicFlightRenderResult,
                staticGenerationStore,
                requestStore,
                serverActions,
                ctx
            });
            if (actionRequestResult) {
                if (actionRequestResult.type === 'not-found') {
                    const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree);
                    res.statusCode = 404;
                    const stream = await renderToStreamWithTracing(req, res, ctx, notFoundLoaderTree, formState, postponedState);
                    return new _renderresult.default(stream, {
                        metadata
                    });
                } else if (actionRequestResult.type === 'done') {
                    if (actionRequestResult.result) {
                        actionRequestResult.result.assignMetadata(metadata);
                        return actionRequestResult.result;
                    } else if (actionRequestResult.formState) {
                        formState = actionRequestResult.formState;
                    }
                }
            }
        }
        const options = {
            metadata
        };
        const stream = await renderToStreamWithTracing(req, res, ctx, loaderTree, formState, postponedState);
        // If we have pending revalidates, wait until they are all resolved.
        if (staticGenerationStore.pendingRevalidates) {
            var _staticGenerationStore_incrementalCache1;
            options.waitUntil = Promise.all([
                (_staticGenerationStore_incrementalCache1 = staticGenerationStore.incrementalCache) == null ? void 0 : _staticGenerationStore_incrementalCache1.revalidateTag(staticGenerationStore.revalidatedTags || []),
                ...Object.values(staticGenerationStore.pendingRevalidates || {})
            ]);
        }
        (0, _patchfetch.addImplicitTags)(staticGenerationStore, requestStore);
        if (staticGenerationStore.tags) {
            metadata.fetchTags = staticGenerationStore.tags.join(',');
        }
        // Create the new render result for the response.
        return new _renderresult.default(stream, options);
    }
}
const renderToHTMLOrFlight = (req, res, pagePath, query, fallbackRouteParams, renderOpts, serverComponentsHmrCache)=>{
    if (!req.url) {
        throw new Error('Invalid URL');
    }
    const url = (0, _parserelativeurl.parseRelativeUrl)(req.url, undefined, false);
    // We read these values from the request object as, in certain cases,
    // base-server will strip them to opt into different rendering behavior.
    const parsedRequestHeaders = parseRequestHeaders(req.headers, {
        isRoutePPREnabled: renderOpts.experimental.isRoutePPREnabled === true
    });
    const { isHmrRefresh } = parsedRequestHeaders;
    const requestEndedState = {
        ended: false
    };
    let postponedState = null;
    // If provided, the postpone state should be parsed so it can be provided to
    // React.
    if (typeof renderOpts.postponed === 'string') {
        if (fallbackRouteParams && fallbackRouteParams.size > 0) {
            throw new Error('Invariant: postponed state should not be provided when fallback params are provided');
        }
        postponedState = (0, _postponedstate.parsePostponedState)(renderOpts.postponed, renderOpts.params);
    }
    return (0, _withrequeststore.withRequestStore)(renderOpts.ComponentMod.requestAsyncStorage, {
        req,
        url,
        res,
        renderOpts,
        isHmrRefresh,
        serverComponentsHmrCache
    }, (requestStore)=>(0, _withstaticgenerationstore.withStaticGenerationStore)(renderOpts.ComponentMod.staticGenerationAsyncStorage, {
            page: renderOpts.routeModule.definition.page,
            fallbackRouteParams,
            renderOpts,
            requestEndedState
        }, (staticGenerationStore)=>renderToHTMLOrFlightImpl(req, res, pagePath, query, renderOpts, requestStore, staticGenerationStore, parsedRequestHeaders, requestEndedState, postponedState)));
};
async function renderToStream(req, res, ctx, tree, formState, postponedState) {
    const renderOpts = ctx.renderOpts;
    const ComponentMod = renderOpts.ComponentMod;
    // TODO: fix this typescript
    const clientReferenceManifest = renderOpts.clientReferenceManifest;
    const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = (0, _serverinsertedhtml.createServerInsertedHTML)();
    const tracingMetadata = (0, _makegetserverinsertedhtml.getTracedMetadata)((0, _tracer.getTracer)().getTracePropagationData(), renderOpts.experimental.clientTraceMetadata);
    const polyfills = renderOpts.buildManifest.polyfillFiles.filter((polyfill)=>polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')).map((polyfill)=>{
        var _renderOpts_subresourceIntegrityManifest;
        return {
            src: `${ctx.assetPrefix}/_next/${polyfill}${(0, _getassetquerystring.getAssetQueryString)(ctx, false)}`,
            integrity: (_renderOpts_subresourceIntegrityManifest = renderOpts.subresourceIntegrityManifest) == null ? void 0 : _renderOpts_subresourceIntegrityManifest[polyfill],
            crossOrigin: renderOpts.crossOrigin,
            noModule: true,
            nonce: ctx.nonce
        };
    });
    const [preinitScripts, bootstrapScript] = (0, _requiredscripts.getRequiredScripts)(renderOpts.buildManifest, // Why is assetPrefix optional on renderOpts?
    // @TODO make it default empty string on renderOpts and get rid of it from ctx
    ctx.assetPrefix, renderOpts.crossOrigin, renderOpts.subresourceIntegrityManifest, (0, _getassetquerystring.getAssetQueryString)(ctx, true), ctx.nonce, renderOpts.page);
    const reactServerErrorsByDigest = new Map();
    const silenceLogger = false;
    function onHTMLRenderRSCError(err) {
        return renderOpts.onInstrumentationRequestError == null ? void 0 : renderOpts.onInstrumentationRequestError.call(renderOpts, err, req, createErrorContext(ctx, 'react-server-components'));
    }
    const serverComponentsErrorHandler = (0, _createerrorhandler.createHTMLReactServerErrorHandler)(!!renderOpts.dev, !!renderOpts.nextExport, reactServerErrorsByDigest, silenceLogger, onHTMLRenderRSCError);
    function onHTMLRenderSSRError(err) {
        return renderOpts.onInstrumentationRequestError == null ? void 0 : renderOpts.onInstrumentationRequestError.call(renderOpts, err, req, createErrorContext(ctx, 'server-rendering'));
    }
    const allCapturedErrors = [];
    const htmlRendererErrorHandler = (0, _createerrorhandler.createHTMLErrorHandler)(!!renderOpts.dev, !!renderOpts.nextExport, reactServerErrorsByDigest, allCapturedErrors, silenceLogger, onHTMLRenderSSRError);
    let primaryRenderReactServerStream = null;
    const setHeader = res.setHeader.bind(res);
    try {
        // This is a dynamic render. We don't do dynamic tracking because we're not prerendering
        const RSCPayload = await getRSCPayload(tree, ctx, res.statusCode === 404);
        const reactServerStream = ComponentMod.renderToReadableStream(RSCPayload, clientReferenceManifest.clientModules, {
            onError: serverComponentsErrorHandler,
            nonce: ctx.nonce
        });
        primaryRenderReactServerStream = reactServerStream;
        // If provided, the postpone state should be parsed as JSON so it can be
        // provided to React.
        if (typeof renderOpts.postponed === 'string') {
            if ((postponedState == null ? void 0 : postponedState.type) === _postponedstate.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 inlinedReactServerDataStream = (0, _useflightresponse.createInlinedDataReadableStream)(reactServerStream, ctx.nonce, formState);
                return (0, _nodewebstreamshelper.chainStreams)(inlinedReactServerDataStream, (0, _nodewebstreamshelper.createDocumentClosingStream)());
            } else if (postponedState) {
                // We assume we have dynamic HTML requiring a resume render to complete
                const postponed = (0, _postponedstate.getPostponedFromState)(postponedState);
                const [reactServerRenderStream, reactServerDataStream] = reactServerStream.tee();
                primaryRenderReactServerStream = reactServerDataStream;
                const resume = require('react-dom/server.edge').resume;
                const htmlStream = await resume(/*#__PURE__*/ (0, _jsxruntime.jsx)(App, {
                    reactServerStream: reactServerRenderStream,
                    preinitScripts: preinitScripts,
                    clientReferenceManifest: clientReferenceManifest,
                    ServerInsertedHTMLProvider: ServerInsertedHTMLProvider,
                    nonce: ctx.nonce
                }), postponed, {
                    onError: htmlRendererErrorHandler,
                    nonce: ctx.nonce
                });
                const getServerInsertedHTML = (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
                    polyfills,
                    renderServerInsertedHTML,
                    serverCapturedErrors: allCapturedErrors,
                    basePath: renderOpts.basePath,
                    tracingMetadata: tracingMetadata
                });
                return await (0, _nodewebstreamshelper.continueDynamicHTMLResume)(htmlStream, {
                    inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(reactServerDataStream, ctx.nonce, formState),
                    getServerInsertedHTML
                });
            }
        }
        // This is a regular dynamic render
        const [// stream for rendering SSR
        reactServerRenderStream, // stream for inlining data and persisting static RSC response
        reactServerDataStream] = reactServerStream.tee();
        // If we error we'll use this stream to render the error page
        primaryRenderReactServerStream = reactServerDataStream;
        const renderToReadableStream = require('react-dom/server.edge').renderToReadableStream;
        const htmlStream = await renderToReadableStream(/*#__PURE__*/ (0, _jsxruntime.jsx)(App, {
            reactServerStream: reactServerRenderStream,
            preinitScripts: preinitScripts,
            clientReferenceManifest: clientReferenceManifest,
            ServerInsertedHTMLProvider: ServerInsertedHTMLProvider,
            nonce: ctx.nonce
        }), {
            onError: htmlRendererErrorHandler,
            nonce: ctx.nonce,
            onHeaders: (headers)=>{
                headers.forEach((value, key)=>{
                    setHeader(key, value);
                });
            },
            maxHeadersLength: renderOpts.reactMaxHeadersLength,
            // When debugging the static shell, client-side rendering should be
            // disabled to prevent blanking out the page.
            bootstrapScripts: renderOpts.isDebugStaticShell ? [] : [
                bootstrapScript
            ],
            formState
        });
        const getServerInsertedHTML = (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
            polyfills,
            renderServerInsertedHTML,
            serverCapturedErrors: allCapturedErrors,
            basePath: renderOpts.basePath,
            tracingMetadata: tracingMetadata
        });
        /**
     * Rules of Static & Dynamic HTML:
     *
     *    1.) We must generate static HTML unless the caller explicitly opts
     *        in to dynamic HTML support.
     *
     *    2.) If dynamic HTML support is requested, we must honor that request
     *        or throw an error. It is the sole responsibility of the caller to
     *        ensure they aren't e.g. requesting dynamic HTML for an AMP page.
     *
     * These rules help ensure that other existing features like request caching,
     * coalescing, and ISR continue working as intended.
     */ const generateStaticHTML = renderOpts.supportsDynamicResponse !== true;
        const validateRootLayout = renderOpts.dev;
        return await (0, _nodewebstreamshelper.continueFizzStream)(htmlStream, {
            inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(reactServerDataStream, ctx.nonce, formState),
            isStaticGeneration: generateStaticHTML,
            getServerInsertedHTML,
            serverInsertedHTMLToHead: true,
            validateRootLayout
        });
    } catch (err) {
        if ((0, _staticgenerationbailout.isStaticGenBailoutError)(err) || typeof err === 'object' && err !== null && 'message' in err && typeof err.message === 'string' && err.message.includes('https://nextjs.org/docs/advanced-features/static-html-export')) {
            // Ensure that "next dev" prints the red error overlay
            throw err;
        }
        // If a bailout made it to this point, it means it wasn't wrapped inside
        // a suspense boundary.
        const shouldBailoutToCSR = (0, _bailouttocsr.isBailoutToCSRError)(err);
        if (shouldBailoutToCSR) {
            const stack = (0, _formatservererror.getStackWithoutErrorMessage)(err);
            (0, _log.error)(`${err.reason} should be wrapped in a suspense boundary at page "${ctx.pagePath}". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n${stack}`);
            throw err;
        }
        if ((0, _notfound.isNotFoundError)(err)) {
            res.statusCode = 404;
        }
        let hasRedirectError = false;
        if ((0, _redirect.isRedirectError)(err)) {
            hasRedirectError = true;
            res.statusCode = (0, _redirect.getRedirectStatusCodeFromError)(err);
            if (err.mutableCookies) {
                const headers = new Headers();
                // If there were mutable cookies set, we need to set them on the
                // response.
                if ((0, _requestcookies.appendMutableCookies)(headers, err.mutableCookies)) {
                    setHeader('set-cookie', Array.from(headers.values()));
                }
            }
            const redirectUrl = (0, _addpathprefix.addPathPrefix)((0, _redirect.getURLFromRedirectError)(err), renderOpts.basePath);
            setHeader('Location', redirectUrl);
        }
        const is404 = res.statusCode === 404;
        if (!is404 && !hasRedirectError && !shouldBailoutToCSR) {
            res.statusCode = 500;
        }
        const errorType = is404 ? 'not-found' : hasRedirectError ? 'redirect' : undefined;
        const [errorPreinitScripts, errorBootstrapScript] = (0, _requiredscripts.getRequiredScripts)(renderOpts.buildManifest, ctx.assetPrefix, renderOpts.crossOrigin, renderOpts.subresourceIntegrityManifest, (0, _getassetquerystring.getAssetQueryString)(ctx, false), ctx.nonce, '/_not-found/page');
        const errorRSCPayload = await getErrorRSCPayload(tree, ctx, errorType);
        const errorServerStream = ComponentMod.renderToReadableStream(errorRSCPayload, clientReferenceManifest.clientModules, {
            onError: serverComponentsErrorHandler,
            nonce: ctx.nonce
        });
        if (primaryRenderReactServerStream === null) {
            // We errored when we did not have an RSC stream to read from. This is not just a render
            // error, we need to throw early
            throw err;
        }
        try {
            const fizzStream = await (0, _nodewebstreamshelper.renderToInitialFizzStream)({
                ReactDOMServer: require('react-dom/server.edge'),
                element: /*#__PURE__*/ (0, _jsxruntime.jsx)(AppWithoutContext, {
                    reactServerStream: errorServerStream,
                    preinitScripts: errorPreinitScripts,
                    clientReferenceManifest: clientReferenceManifest,
                    nonce: ctx.nonce
                }),
                streamOptions: {
                    nonce: ctx.nonce,
                    // Include hydration scripts in the HTML
                    bootstrapScripts: [
                        errorBootstrapScript
                    ],
                    formState
                }
            });
            /**
       * Rules of Static & Dynamic HTML:
       *
       *    1.) We must generate static HTML unless the caller explicitly opts
       *        in to dynamic HTML support.
       *
       *    2.) If dynamic HTML support is requested, we must honor that request
       *        or throw an error. It is the sole responsibility of the caller to
       *        ensure they aren't e.g. requesting dynamic HTML for an AMP page.
       *
       * These rules help ensure that other existing features like request caching,
       * coalescing, and ISR continue working as intended.
       */ const generateStaticHTML = renderOpts.supportsDynamicResponse !== true;
            const validateRootLayout = renderOpts.dev;
            return await (0, _nodewebstreamshelper.continueFizzStream)(fizzStream, {
                inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(// This is intentionally using the readable datastream from the
                // main render rather than the flight data from the error page
                // render
                primaryRenderReactServerStream, ctx.nonce, formState),
                isStaticGeneration: generateStaticHTML,
                getServerInsertedHTML: (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
                    polyfills,
                    renderServerInsertedHTML,
                    serverCapturedErrors: [],
                    basePath: renderOpts.basePath,
                    tracingMetadata: tracingMetadata
                }),
                serverInsertedHTMLToHead: true,
                validateRootLayout
            });
        } catch (finalErr) {
            if (process.env.NODE_ENV === 'development' && (0, _notfound.isNotFoundError)(finalErr)) {
                const bailOnNotFound = require('../../client/components/dev-root-not-found-boundary').bailOnNotFound;
                bailOnNotFound();
            }
            throw finalErr;
        }
    }
}
/**
 * Determines whether we should generate static flight data.
 */ function shouldGenerateStaticFlightData(staticGenerationStore) {
    const { fallbackRouteParams, isStaticGeneration } = staticGenerationStore;
    if (!isStaticGeneration) return false;
    if (fallbackRouteParams && fallbackRouteParams.size > 0) {
        return false;
    }
    return true;
}
async function prerenderToStream(req, res, ctx, metadata, staticGenerationStore, tree) {
    // When prerendering formState is always null. We still include it
    // because some shared APIs expect a formState value and this is slightly
    // more explicit than making it an optional function argument
    const formState = null;
    const renderOpts = ctx.renderOpts;
    const ComponentMod = renderOpts.ComponentMod;
    // TODO: fix this typescript
    const clientReferenceManifest = renderOpts.clientReferenceManifest;
    const { fallbackRouteParams } = staticGenerationStore;
    const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = (0, _serverinsertedhtml.createServerInsertedHTML)();
    const tracingMetadata = (0, _makegetserverinsertedhtml.getTracedMetadata)((0, _tracer.getTracer)().getTracePropagationData(), renderOpts.experimental.clientTraceMetadata);
    const polyfills = renderOpts.buildManifest.polyfillFiles.filter((polyfill)=>polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')).map((polyfill)=>{
        var _renderOpts_subresourceIntegrityManifest;
        return {
            src: `${ctx.assetPrefix}/_next/${polyfill}${(0, _getassetquerystring.getAssetQueryString)(ctx, false)}`,
            integrity: (_renderOpts_subresourceIntegrityManifest = renderOpts.subresourceIntegrityManifest) == null ? void 0 : _renderOpts_subresourceIntegrityManifest[polyfill],
            crossOrigin: renderOpts.crossOrigin,
            noModule: true,
            nonce: ctx.nonce
        };
    });
    const [preinitScripts, bootstrapScript] = (0, _requiredscripts.getRequiredScripts)(renderOpts.buildManifest, // Why is assetPrefix optional on renderOpts?
    // @TODO make it default empty string on renderOpts and get rid of it from ctx
    ctx.assetPrefix, renderOpts.crossOrigin, renderOpts.subresourceIntegrityManifest, (0, _getassetquerystring.getAssetQueryString)(ctx, true), ctx.nonce, renderOpts.page);
    const reactServerErrorsByDigest = new Map();
    // We don't report errors during prerendering through our instrumentation hooks
    const silenceLogger = !!renderOpts.experimental.isRoutePPREnabled;
    function onHTMLRenderRSCError(err) {
        return renderOpts.onInstrumentationRequestError == null ? void 0 : renderOpts.onInstrumentationRequestError.call(renderOpts, err, req, createErrorContext(ctx, 'react-server-components'));
    }
    const serverComponentsErrorHandler = (0, _createerrorhandler.createHTMLReactServerErrorHandler)(!!renderOpts.dev, !!renderOpts.nextExport, reactServerErrorsByDigest, silenceLogger, onHTMLRenderRSCError);
    function onHTMLRenderSSRError(err) {
        return renderOpts.onInstrumentationRequestError == null ? void 0 : renderOpts.onInstrumentationRequestError.call(renderOpts, err, req, createErrorContext(ctx, 'server-rendering'));
    }
    const allCapturedErrors = [];
    const htmlRendererErrorHandler = (0, _createerrorhandler.createHTMLErrorHandler)(!!renderOpts.dev, !!renderOpts.nextExport, reactServerErrorsByDigest, allCapturedErrors, silenceLogger, onHTMLRenderSSRError);
    let dynamicTracking = null;
    let primaryRenderReactServerStream = null;
    const setHeader = (name, value)=>{
        res.setHeader(name, value);
        metadata.headers ??= {};
        metadata.headers[name] = res.getHeader(name);
        return res;
    };
    try {
        if (renderOpts.experimental.isRoutePPREnabled) {
            // We're statically generating with PPR and need to do dynamic tracking
            dynamicTracking = (0, _dynamicrendering.createDynamicTrackingState)(renderOpts.isDebugDynamicAccesses);
            const reactServerPrerenderStore = {
                dynamicTracking
            };
            const RSCPayload = await getRSCPayload(tree, ctx, res.statusCode === 404);
            const reactServerStream = _prerenderasyncstorageexternal.prerenderAsyncStorage.run(reactServerPrerenderStore, ComponentMod.renderToReadableStream, // ... the arguments for the function to run
            RSCPayload, clientReferenceManifest.clientModules, {
                onError: serverComponentsErrorHandler,
                nonce: ctx.nonce
            });
            const [// stream for rendering SSR
            reactServerRenderStream, // stream for inlining data and persisting static RSC response
            reactServerDataStream] = reactServerStream.tee();
            // If we error we'll use this stream to render the error page
            primaryRenderReactServerStream = reactServerDataStream;
            const ssrPrerenderStore = {
                dynamicTracking
            };
            const prerender = require('react-dom/static.edge').prerender;
            const { prelude, postponed } = await _prerenderasyncstorageexternal.prerenderAsyncStorage.run(ssrPrerenderStore, prerender, /*#__PURE__*/ (0, _jsxruntime.jsx)(App, {
                reactServerStream: reactServerRenderStream,
                preinitScripts: preinitScripts,
                clientReferenceManifest: clientReferenceManifest,
                ServerInsertedHTMLProvider: ServerInsertedHTMLProvider,
                nonce: ctx.nonce
            }), {
                onError: htmlRendererErrorHandler,
                onHeaders: (headers)=>{
                    headers.forEach((value, key)=>{
                        setHeader(key, value);
                    });
                },
                maxHeadersLength: renderOpts.reactMaxHeadersLength,
                // When debugging the static shell, client-side rendering should be
                // disabled to prevent blanking out the page.
                bootstrapScripts: renderOpts.isDebugStaticShell ? [] : [
                    bootstrapScript
                ]
            });
            const getServerInsertedHTML = (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
                polyfills,
                renderServerInsertedHTML,
                serverCapturedErrors: allCapturedErrors,
                basePath: renderOpts.basePath,
                tracingMetadata: tracingMetadata
            });
            const [persistedReactServerDataStream, inlinedReactServerDataStream] = reactServerDataStream.tee();
            // After awaiting here we've waited for the entire RSC render to complete. Crucially this means
            // that when we detect whether we've used dynamic APIs below we know we'll have picked up even
            // parts of the React Server render that might not be used in the SSR render.
            const flightData = await (0, _nodewebstreamshelper.streamToBuffer)(persistedReactServerDataStream);
            if (shouldGenerateStaticFlightData(staticGenerationStore)) {
                metadata.flightData = flightData;
            }
            /**
       * When prerendering there are three outcomes to consider
       *
       *   Dynamic HTML:      The prerender has dynamic holes (caused by using Next.js Dynamic Rendering APIs)
       *                      We will need to resume this result when requests are handled and we don't include
       *                      any server inserted HTML or inlined flight data in the static HTML
       *
       *   Dynamic Data:      The prerender has no dynamic holes but dynamic APIs were used. We will not
       *                      resume this render when requests are handled but we will generate new inlined
       *                      flight data since it is dynamic and differences may end up reconciling on the client
       *
       *   Static:            The prerender has no dynamic holes and no dynamic APIs were used. We statically encode
       *                      all server inserted HTML and flight data
       */ // First we check if we have any dynamic holes in our HTML prerender
            if ((0, _dynamicrendering.usedDynamicAPIs)(dynamicTracking)) {
                if (postponed != null) {
                    // Dynamic HTML case.
                    metadata.postponed = (0, _postponedstate.getDynamicHTMLPostponedState)(postponed, fallbackRouteParams);
                } else {
                    // Dynamic Data case.
                    metadata.postponed = (0, _postponedstate.getDynamicDataPostponedState)();
                }
                // Regardless of whether this is the Dynamic HTML or Dynamic Data case we need to ensure we include
                // server inserted html in the static response because the html that is part of the prerender may depend on it
                // It is possible in the set of stream transforms for Dynamic HTML vs Dynamic Data may differ but currently both states
                // require the same set so we unify the code path here
                return {
                    digestErrorsMap: reactServerErrorsByDigest,
                    ssrErrors: allCapturedErrors,
                    stream: await (0, _nodewebstreamshelper.continueDynamicPrerender)(prelude, {
                        getServerInsertedHTML
                    }),
                    dynamicTracking
                };
            } else if (fallbackRouteParams && fallbackRouteParams.size > 0) {
                // Rendering the fallback case.
                metadata.postponed = (0, _postponedstate.getDynamicDataPostponedState)();
                return {
                    digestErrorsMap: reactServerErrorsByDigest,
                    ssrErrors: allCapturedErrors,
                    stream: await (0, _nodewebstreamshelper.continueDynamicPrerender)(prelude, {
                        getServerInsertedHTML
                    }),
                    dynamicTracking
                };
            } else {
                // Static case
                // We still have not used any dynamic APIs. At this point we can produce an entirely static prerender response
                if (staticGenerationStore.forceDynamic) {
                    throw new _staticgenerationbailout.StaticGenBailoutError('Invariant: a Page with `dynamic = "force-dynamic"` did not trigger the dynamic pathway. This is a bug in Next.js');
                }
                let htmlStream = prelude;
                if (postponed != null) {
                    // We postponed but nothing dynamic was used. We resume the render now and immediately abort it
                    // so we can set all the postponed boundaries to client render mode before we store the HTML response
                    const resume = require('react-dom/server.edge').resume;
                    // We don't actually want to render anything so we just pass a stream
                    // that never resolves. The resume call is going to abort immediately anyway
                    const foreverStream = new ReadableStream();
                    const resumeStream = await resume(/*#__PURE__*/ (0, _jsxruntime.jsx)(App, {
                        reactServerStream: foreverStream,
                        preinitScripts: ()=>{},
                        clientReferenceManifest: clientReferenceManifest,
                        ServerInsertedHTMLProvider: ServerInsertedHTMLProvider,
                        nonce: ctx.nonce
                    }), JSON.parse(JSON.stringify(postponed)), {
                        signal: (0, _dynamicrendering.createPostponedAbortSignal)('static prerender resume'),
                        onError: htmlRendererErrorHandler,
                        nonce: ctx.nonce
                    });
                    // First we write everything from the prerender, then we write everything from the aborted resume render
                    htmlStream = (0, _nodewebstreamshelper.chainStreams)(prelude, resumeStream);
                }
                return {
                    digestErrorsMap: reactServerErrorsByDigest,
                    ssrErrors: allCapturedErrors,
                    stream: await (0, _nodewebstreamshelper.continueStaticPrerender)(htmlStream, {
                        inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(inlinedReactServerDataStream, ctx.nonce, formState),
                        getServerInsertedHTML
                    }),
                    dynamicTracking
                };
            }
        } else {
            // This is a regular static generation. We don't do dynamic tracking because we rely on
            // the old-school dynamic error handling to bail out of static generation
            const RSCPayload = await getRSCPayload(tree, ctx, res.statusCode === 404);
            const reactServerStream = ComponentMod.renderToReadableStream(RSCPayload, clientReferenceManifest.clientModules, {
                onError: serverComponentsErrorHandler,
                nonce: ctx.nonce
            });
            const [// stream for rendering SSR
            reactServerRenderStream, // stream for inlining data and persisting static RSC response
            reactServerDataStream] = reactServerStream.tee();
            // If we error we'll use this stream to render the error page
            primaryRenderReactServerStream = reactServerDataStream;
            const renderToReadableStream = require('react-dom/server.edge').renderToReadableStream;
            const htmlStream = await renderToReadableStream(/*#__PURE__*/ (0, _jsxruntime.jsx)(App, {
                reactServerStream: reactServerRenderStream,
                preinitScripts: preinitScripts,
                clientReferenceManifest: clientReferenceManifest,
                ServerInsertedHTMLProvider: ServerInsertedHTMLProvider,
                nonce: ctx.nonce
            }), {
                onError: htmlRendererErrorHandler,
                nonce: ctx.nonce,
                // When debugging the static shell, client-side rendering should be
                // disabled to prevent blanking out the page.
                bootstrapScripts: renderOpts.isDebugStaticShell ? [] : [
                    bootstrapScript
                ]
            });
            let continueInlineDataStream = reactServerDataStream;
            if (shouldGenerateStaticFlightData(staticGenerationStore)) {
                const [persistedReactServerDataStream, inlinedReactServerDataStream] = reactServerDataStream.tee();
                continueInlineDataStream = inlinedReactServerDataStream;
                metadata.flightData = await (0, _nodewebstreamshelper.streamToBuffer)(persistedReactServerDataStream);
            }
            const getServerInsertedHTML = (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
                polyfills,
                renderServerInsertedHTML,
                serverCapturedErrors: allCapturedErrors,
                basePath: renderOpts.basePath,
                tracingMetadata: tracingMetadata
            });
            return {
                digestErrorsMap: reactServerErrorsByDigest,
                ssrErrors: allCapturedErrors,
                stream: await (0, _nodewebstreamshelper.continueFizzStream)(htmlStream, {
                    inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(continueInlineDataStream, ctx.nonce, formState),
                    isStaticGeneration: true,
                    getServerInsertedHTML,
                    serverInsertedHTMLToHead: true
                })
            };
        }
    } catch (err) {
        if ((0, _staticgenerationbailout.isStaticGenBailoutError)(err) || typeof err === 'object' && err !== null && 'message' in err && typeof err.message === 'string' && err.message.includes('https://nextjs.org/docs/advanced-features/static-html-export')) {
            // Ensure that "next dev" prints the red error overlay
            throw err;
        }
        // If this is a static generation error, we need to throw it so that it
        // can be handled by the caller if we're in static generation mode.
        if ((0, _hooksservercontext.isDynamicServerError)(err)) {
            throw err;
        }
        // If a bailout made it to this point, it means it wasn't wrapped inside
        // a suspense boundary.
        const shouldBailoutToCSR = (0, _bailouttocsr.isBailoutToCSRError)(err);
        if (shouldBailoutToCSR) {
            const stack = (0, _formatservererror.getStackWithoutErrorMessage)(err);
            (0, _log.error)(`${err.reason} should be wrapped in a suspense boundary at page "${ctx.pagePath}". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n${stack}`);
            throw err;
        }
        if ((0, _notfound.isNotFoundError)(err)) {
            res.statusCode = 404;
        }
        let hasRedirectError = false;
        if ((0, _redirect.isRedirectError)(err)) {
            hasRedirectError = true;
            res.statusCode = (0, _redirect.getRedirectStatusCodeFromError)(err);
            if (err.mutableCookies) {
                const headers = new Headers();
                // If there were mutable cookies set, we need to set them on the
                // response.
                if ((0, _requestcookies.appendMutableCookies)(headers, err.mutableCookies)) {
                    setHeader('set-cookie', Array.from(headers.values()));
                }
            }
            const redirectUrl = (0, _addpathprefix.addPathPrefix)((0, _redirect.getURLFromRedirectError)(err), renderOpts.basePath);
            setHeader('Location', redirectUrl);
        }
        const is404 = res.statusCode === 404;
        if (!is404 && !hasRedirectError && !shouldBailoutToCSR) {
            res.statusCode = 500;
        }
        const errorType = is404 ? 'not-found' : hasRedirectError ? 'redirect' : undefined;
        const [errorPreinitScripts, errorBootstrapScript] = (0, _requiredscripts.getRequiredScripts)(renderOpts.buildManifest, ctx.assetPrefix, renderOpts.crossOrigin, renderOpts.subresourceIntegrityManifest, (0, _getassetquerystring.getAssetQueryString)(ctx, false), ctx.nonce, '/_not-found/page');
        const errorRSCPayload = await getErrorRSCPayload(tree, ctx, errorType);
        const errorServerStream = ComponentMod.renderToReadableStream(errorRSCPayload, clientReferenceManifest.clientModules, {
            onError: serverComponentsErrorHandler,
            nonce: ctx.nonce
        });
        if (primaryRenderReactServerStream === null) {
            // We errored when we did not have an RSC stream to read from. This is not just a render
            // error, we need to throw early
            throw err;
        }
        try {
            const fizzStream = await (0, _nodewebstreamshelper.renderToInitialFizzStream)({
                ReactDOMServer: require('react-dom/server.edge'),
                element: /*#__PURE__*/ (0, _jsxruntime.jsx)(AppWithoutContext, {
                    reactServerStream: errorServerStream,
                    preinitScripts: errorPreinitScripts,
                    clientReferenceManifest: clientReferenceManifest,
                    nonce: ctx.nonce
                }),
                streamOptions: {
                    nonce: ctx.nonce,
                    // Include hydration scripts in the HTML
                    bootstrapScripts: [
                        errorBootstrapScript
                    ],
                    formState
                }
            });
            if (shouldGenerateStaticFlightData(staticGenerationStore)) {
                const [persistedReactServerDataStream, inlinedReactServerDataStream] = primaryRenderReactServerStream.tee();
                primaryRenderReactServerStream = inlinedReactServerDataStream;
                const flightRenderResult = new _flightrenderresult.FlightRenderResult(persistedReactServerDataStream);
                metadata.flightData = await flightRenderResult.toUnchunkedBuffer(true);
            }
            const validateRootLayout = renderOpts.dev;
            return {
                // Returning the error that was thrown so it can be used to handle
                // the response in the caller.
                err,
                digestErrorsMap: reactServerErrorsByDigest,
                ssrErrors: allCapturedErrors,
                stream: await (0, _nodewebstreamshelper.continueFizzStream)(fizzStream, {
                    inlinedDataStream: (0, _useflightresponse.createInlinedDataReadableStream)(// This is intentionally using the readable datastream from the
                    // main render rather than the flight data from the error page
                    // render
                    primaryRenderReactServerStream, ctx.nonce, formState),
                    isStaticGeneration: true,
                    getServerInsertedHTML: (0, _makegetserverinsertedhtml.makeGetServerInsertedHTML)({
                        polyfills,
                        renderServerInsertedHTML,
                        serverCapturedErrors: [],
                        basePath: renderOpts.basePath,
                        tracingMetadata: tracingMetadata
                    }),
                    serverInsertedHTMLToHead: true,
                    validateRootLayout
                }),
                dynamicTracking
            };
        } catch (finalErr) {
            if (process.env.NODE_ENV === 'development' && (0, _notfound.isNotFoundError)(finalErr)) {
                const bailOnNotFound = require('../../client/components/dev-root-not-found-boundary').bailOnNotFound;
                bailOnNotFound();
            }
            throw finalErr;
        }
    }
}

//# sourceMappingURL=app-render.js.map