"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.RequestAsyncStorageWrapper = void 0;
var _appRouterHeaders = require("../../client/components/app-router-headers");
var _readonlyHeaders = require("../app-render/readonly-headers");
var _readonlyRequestCookies = require("../app-render/readonly-request-cookies");
function headersWithoutFlight(headers) {
    const newHeaders = {
        ...headers
    };
    for (const param of _appRouterHeaders.FLIGHT_PARAMETERS){
        delete newHeaders[param.toString().toLowerCase()];
    }
    return newHeaders;
}
/**
 * Tries to get the preview data on the request for the given route. This
 * isn't enabled in the edge runtime yet.
 */ const tryGetPreviewData = process.env.NEXT_RUNTIME !== "edge" ? require("../api-utils/node").tryGetPreviewData : null;
const RequestAsyncStorageWrapper = {
    /**
   * Wrap the callback with the given store so it can access the underlying
   * store using hooks.
   *
   * @param storage underlying storage object returned by the module
   * @param context context to seed the store
   * @param callback function to call within the scope of the context
   * @returns the result returned by the callback
   */ wrap (storage, { req , res , renderOpts  }, callback) {
        // Reads of this are cached on the `req` object, so this should resolve
        // instantly. There's no need to pass this data down from a previous
        // invoke.
        const previewData = renderOpts && tryGetPreviewData && res ? tryGetPreviewData(req, res, renderOpts.previewProps) : false;
        let cachedHeadersInstance;
        let cachedCookiesInstance;
        const store = {
            get headers () {
                if (!cachedHeadersInstance) {
                    cachedHeadersInstance = new _readonlyHeaders.ReadonlyHeaders(headersWithoutFlight(req.headers));
                }
                return cachedHeadersInstance;
            },
            get cookies () {
                if (!cachedCookiesInstance) {
                    cachedCookiesInstance = new _readonlyRequestCookies.ReadonlyRequestCookies({
                        headers: {
                            get: (key)=>{
                                if (key !== "cookie") {
                                    throw new Error("Only cookie header is supported");
                                }
                                return req.headers.cookie;
                            }
                        }
                    });
                }
                return cachedCookiesInstance;
            },
            previewData
        };
        return storage.run(store, callback, store);
    }
};
exports.RequestAsyncStorageWrapper = RequestAsyncStorageWrapper;

//# sourceMappingURL=request-async-storage-wrapper.js.map