"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPreviewData = exports.setJerryAuth = exports.isValidPreviewRequest = void 0;
const cookie_1 = __importDefault(require("cookie"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const crypto_utils_1 = require("./crypto-utils");
const NEXT_PREVIEW_DATA_COOKIE = "__next_preview_data";
const NEXT_PRERENDER_BYPASS_COOKIE = "__prerender_bypass";
const JERRY_AUTH_COOKIE = "jerryauth";
const defaultPreviewCookies = {
    [NEXT_PRERENDER_BYPASS_COOKIE]: "",
    [NEXT_PREVIEW_DATA_COOKIE]: ""
};
const isValidPreviewRequest = (cookies, previewModeSigningKey) => {
    const previewCookies = getPreviewCookies(cookies);
    if (hasPreviewCookies(previewCookies)) {
        try {
            jsonwebtoken_1.default.verify(previewCookies[NEXT_PREVIEW_DATA_COOKIE], previewModeSigningKey);
            return true;
        }
        catch (e) {
            console.warn("Found preview headers without valid authentication token");
        }
    }
    return false;
};
exports.isValidPreviewRequest = isValidPreviewRequest;
const setJerryAuth = (cloudfrontRequest, renderRequest, signingKey, encryptionKey) => {
    var _a, _b, _c, _d, _e;
    const cloudFrontCookie = (_c = (_b = (_a = cloudfrontRequest.headers.cookie) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : "";
    const encryptedPreviewDataPayload = (_d = exports.getPreviewData(cloudFrontCookie, signingKey)) === null || _d === void 0 ? void 0 : _d.data;
    if (!encryptedPreviewDataPayload)
        return;
    const decryptedPreviewDataPayload = decryptPreviewData(encryptionKey, encryptedPreviewDataPayload);
    setJerryAuthToken(decryptedPreviewDataPayload, cloudFrontCookie);
    const previewJwt = signPreviewData(encryptionKey, signingKey, decryptedPreviewDataPayload);
    renderRequest.headers = Object.assign(Object.assign({}, renderRequest.headers), { cookie: `${NEXT_PREVIEW_DATA_COOKIE}=${previewJwt !== null && previewJwt !== void 0 ? previewJwt : defaultPreviewCookies[NEXT_PREVIEW_DATA_COOKIE]}; ${NEXT_PRERENDER_BYPASS_COOKIE}=${(_e = getPreRenderBypass(cloudFrontCookie)) !== null && _e !== void 0 ? _e : defaultPreviewCookies[NEXT_PRERENDER_BYPASS_COOKIE]}` });
};
exports.setJerryAuth = setJerryAuth;
const getPreviewCookies = (cookies) => {
    const targetCookie = cookies || [];
    return targetCookie.reduce((previewCookies, cookieObj) => {
        const parsedCookie = cookie_1.default.parse(cookieObj.value);
        if (hasPreviewCookies(parsedCookie)) {
            return parsedCookie;
        }
        return previewCookies;
    }, defaultPreviewCookies);
};
const hasPreviewCookies = (cookies) => !!(cookies[NEXT_PREVIEW_DATA_COOKIE] && cookies[NEXT_PRERENDER_BYPASS_COOKIE]);
const decryptPreviewData = (encryptionKey, data) => JSON.parse(crypto_utils_1.decryptWithSecret(Buffer.from(encryptionKey), data));
const setJerryAuthToken = (decryptedPreviewData, cookie) => {
    var _a;
    decryptedPreviewData.token = (_a = decryptedPreviewData.token) !== null && _a !== void 0 ? _a : getJerryAuth(cookie);
};
const signPreviewData = (encryptionKey, signingKey, payLoad) => {
    try {
        return jsonwebtoken_1.default.sign({
            data: crypto_utils_1.encryptWithSecret(Buffer.from(encryptionKey), JSON.stringify(payLoad))
        }, signingKey);
    }
    catch (e) {
        console.warn(e);
        return undefined;
    }
};
const getOneFromCookieString = (cookie, key) => {
    var _a;
    const value = `; ${cookie}`;
    const parts = value.split(`; ${key}=`);
    if (parts.length === 2)
        return (_a = parts.pop()) === null || _a === void 0 ? void 0 : _a.split(";").shift();
};
const getPreviewData = (cookie, signingKey) => {
    const previewDataCookieInJwtFormat = getOneFromCookieString(cookie, NEXT_PREVIEW_DATA_COOKIE);
    try {
        return previewDataCookieInJwtFormat
            ? jsonwebtoken_1.default.verify(previewDataCookieInJwtFormat, signingKey)
            : undefined;
    }
    catch (e) {
        console.warn(e);
        return undefined;
    }
};
exports.getPreviewData = getPreviewData;
const getJerryAuth = (cookie) => {
    return getOneFromCookieString(cookie, JERRY_AUTH_COOKIE);
};
const getPreRenderBypass = (cookie) => {
    return getOneFromCookieString(cookie, NEXT_PRERENDER_BYPASS_COOKIE);
};
