import { FLIGHT_HEADERS } from '../../client/components/app-router-headers';
import { HeadersAdapter } from '../web/spec-extension/adapters/headers';
import { MutableRequestCookiesAdapter, RequestCookiesAdapter } from '../web/spec-extension/adapters/request-cookies';
import { ResponseCookies, RequestCookies } from '../web/spec-extension/cookies';
import { DraftModeProvider } from './draft-mode-provider';
import { splitCookiesString } from '../web/utils';
import { AfterContext } from '../after/after-context';
function getHeaders(headers) {
    const cleaned = HeadersAdapter.from(headers);
    for (const header of FLIGHT_HEADERS){
        cleaned.delete(header.toLowerCase());
    }
    return HeadersAdapter.seal(cleaned);
}
function getMutableCookies(headers, onUpdateCookies) {
    const cookies = new RequestCookies(HeadersAdapter.from(headers));
    return MutableRequestCookiesAdapter.wrap(cookies, onUpdateCookies);
}
export const withRequestStore = (storage, { req, url, res, renderOpts, isHmrRefresh, serverComponentsHmrCache }, callback)=>{
    function defaultOnUpdateCookies(cookies) {
        if (res) {
            res.setHeader('Set-Cookie', cookies);
        }
    }
    const cache = {};
    const store = {
        // Rather than just using the whole `url` here, we pull the parts we want
        // to ensure we don't use parts of the URL that we shouldn't. This also
        // lets us avoid requiring an empty string for `search` in the type.
        url: {
            pathname: url.pathname,
            search: url.search ?? ''
        },
        get headers () {
            if (!cache.headers) {
                // Seal the headers object that'll freeze out any methods that could
                // mutate the underlying data.
                cache.headers = getHeaders(req.headers);
            }
            return cache.headers;
        },
        get cookies () {
            if (!cache.cookies) {
                // if middleware is setting cookie(s), then include those in
                // the initial cached cookies so they can be read in render
                const requestCookies = new RequestCookies(HeadersAdapter.from(req.headers));
                if ('x-middleware-set-cookie' in req.headers && typeof req.headers['x-middleware-set-cookie'] === 'string') {
                    const setCookieValue = req.headers['x-middleware-set-cookie'];
                    const responseHeaders = new Headers();
                    for (const cookie of splitCookiesString(setCookieValue)){
                        responseHeaders.append('set-cookie', cookie);
                    }
                    const responseCookies = new ResponseCookies(responseHeaders);
                    // Transfer cookies from ResponseCookies to RequestCookies
                    for (const cookie of responseCookies.getAll()){
                        requestCookies.set(cookie.name, cookie.value ?? '');
                    }
                }
                // Seal the cookies object that'll freeze out any methods that could
                // mutate the underlying data.
                cache.cookies = RequestCookiesAdapter.seal(requestCookies);
            }
            return cache.cookies;
        },
        get mutableCookies () {
            if (!cache.mutableCookies) {
                cache.mutableCookies = getMutableCookies(req.headers, (renderOpts == null ? void 0 : renderOpts.onUpdateCookies) || (res ? defaultOnUpdateCookies : undefined));
            }
            return cache.mutableCookies;
        },
        get draftMode () {
            if (!cache.draftMode) {
                cache.draftMode = new DraftModeProvider(renderOpts == null ? void 0 : renderOpts.previewProps, req, this.cookies, this.mutableCookies);
            }
            return cache.draftMode;
        },
        reactLoadableManifest: (renderOpts == null ? void 0 : renderOpts.reactLoadableManifest) || {},
        assetPrefix: (renderOpts == null ? void 0 : renderOpts.assetPrefix) || '',
        afterContext: createAfterContext(renderOpts),
        isHmrRefresh,
        serverComponentsHmrCache: serverComponentsHmrCache || globalThis.__serverComponentsHmrCache
    };
    if (store.afterContext) {
        return store.afterContext.run(store, ()=>storage.run(store, callback, store));
    }
    return storage.run(store, callback, store);
};
function createAfterContext(renderOpts) {
    if (!isAfterEnabled(renderOpts)) {
        return undefined;
    }
    const { waitUntil, onClose, ComponentMod } = renderOpts;
    const cacheScope = ComponentMod == null ? void 0 : ComponentMod.createCacheScope();
    return new AfterContext({
        waitUntil,
        onClose,
        cacheScope
    });
}
function isAfterEnabled(renderOpts) {
    var _renderOpts_experimental;
    return (renderOpts == null ? void 0 : (_renderOpts_experimental = renderOpts.experimental) == null ? void 0 : _renderOpts_experimental.after) ?? false;
}

//# sourceMappingURL=with-request-store.js.map