"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveCachedString = exports.getCachedString = exports.digestTextSha256 = void 0;
/**
 * Get the SHA-256 of a given string
 *
 * @param text Text to hash
 * @returns Promise<string>
 */
async function digestTextSha256(text) {
    const myDigest = await crypto.subtle.digest({ name: 'SHA-256' }, new TextEncoder().encode(text));
    const hexString = [...new Uint8Array(myDigest)]
        .map(b => b.toString(16).padStart(2, '0'))
        .join('');
    return hexString;
}
exports.digestTextSha256 = digestTextSha256;
/**
 * Return a make up string to a given hash key
 *
 * @param key a string to indentify the cache  (currently the SHA-256 of the content)
 * @returns
 */
function getCacheKeyUrl(key) {
    return `http://cache.optimizely.com/edge_delivery_cache/${key}`;
}
/**
 *
 * @param key
 * @returns The cache string of a given key or undefined if not found
 */
async function getCachedString(key) {
    let myCache = await caches.open('custom:cache');
    const cacheReponse = await myCache.match(getCacheKeyUrl(key));
    return await cacheReponse?.text();
}
exports.getCachedString = getCachedString;
/**
 * Save a string on cache with the given key and ttl
 *
 * @param key To identify the saved string
 * @param content Content string to save
 * @param ttl Number of seconds to keep on cache
 */
async function saveCachedString(key, content, ttl = 120) {
    let myCache = await caches.open('custom:cache');
    let url = getCacheKeyUrl(key);
    let response = new Response(content, {
        status: 200,
        headers: {
            'Cache-Control': `max-age=${ttl}`,
        },
    });
    await myCache.put(url, response);
}
exports.saveCachedString = saveCachedString;
