export async function validatePreviewToken(token, signKey) {
    try {
        const parts = token.split('.');
        if (parts.length !== 3)
            return null;
        const signingInput = `${parts[0]}.${parts[1]}`;
        const signature = base64URLToBytes(parts[2]);
        const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(signKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
        const expected = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(signingInput)));
        if (!constantTimeEqual(signature, expected))
            return null;
        const payload = new TextDecoder().decode(base64URLToBytes(parts[1]));
        return JSON.parse(payload);
    }
    catch {
        return null;
    }
}
function base64URLToBytes(value) {
    const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
    const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=');
    const binary = atob(padded);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
        bytes[i] = binary.charCodeAt(i);
    }
    return bytes;
}
function constantTimeEqual(left, right) {
    if (left.length !== right.length)
        return false;
    let diff = 0;
    for (let i = 0; i < left.length; i++) {
        diff |= left[i] ^ right[i];
    }
    return diff === 0;
}
