"use strict";
// TODO grab data from URL or kv namespace
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSnippetUrl = exports.getData = void 0;
const PROD_CDN = 'cdn.optimizely.com';
const STAGING_CDN = 'optimizely-staging.s3.us-east-1.amazonaws.com';
const dataMap = new Map();
function getCeilTime(ttl) {
    var coeff = 1000 * ttl;
    return Math.ceil(performance.now() / coeff) * coeff;
}
async function getData(accountId, snippetId, isProd = true, ttl = 0, logger) {
    const bucket = isProd ? PROD_CDN : STAGING_CDN;
    let configUrl;
    if (accountId !== undefined && accountId > 0) {
        configUrl = `https://${bucket}/public/${accountId}/s/${snippetId}/web_sdk_v0.json`;
    }
    else {
        configUrl = `https://${bucket}/js/web_sdk_v0_${snippetId}.json`;
    }
    const mapkey = configUrl + getCeilTime(ttl);
    if (ttl > 0 && dataMap.has(mapkey)) {
        logger.info('Edge Rewriter - Using cached data object.');
        return structuredClone(dataMap.get(mapkey));
    }
    logger.info('Edge Rewriter - Getting data manifest from: ', configUrl);
    const configResponse = await fetch(configUrl, { cf: { cacheTtl: ttl } });
    logger.debug('Edge Rewriter - Loaded with cache status: ', configResponse.headers.get('cf-cache-status'));
    const configJson = await configResponse.json();
    if (ttl > 0) {
        dataMap.clear(); // clear all cache
        dataMap.set(mapkey, configJson);
        logger.debug('Edge Rewriter - Data object loaded and cached.');
    }
    return structuredClone(configJson);
}
exports.getData = getData;
function getSnippetUrl(accountId, snippetId, isProd = true) {
    const bucket = isProd ? PROD_CDN : STAGING_CDN;
    let configUrl;
    if (accountId !== undefined) {
        configUrl = `https://${bucket}/public/${accountId}/s/${snippetId}.js`;
        //eg. https://cdn.optimizely.com/public/6529002483/s/at_us_home.js
    }
    else {
        configUrl = `https://${bucket}/js/${snippetId}.js`;
        //eg. https://cdn.optimizely.com/js/21617700362.js
    }
    return configUrl;
}
exports.getSnippetUrl = getSnippetUrl;
