export async function getUncachedEdgeConfigValue(edgeConfig, key) {
    const connection = parseEdgeConfigConnection(edgeConfig);
    if (!connection) {
        throw new Error('Invalid Edge Config connection string');
    }
    const headers = new Headers({
        authorization: `Bearer ${connection.token}`,
        'x-edge-config-min-updated-at': `${Number.MAX_SAFE_INTEGER}`,
    });
    if (process.env.VERCEL_ENV) {
        headers.set('x-edge-config-vercel-env', process.env.VERCEL_ENV);
    }
    const url = `${connection.baseUrl}/item/${encodeURIComponent(key)}?version=${encodeURIComponent(connection.version)}`;
    const response = await fetch(url, {
        headers,
        cache: 'no-store',
    });
    if (response.ok) {
        return response.json();
    }
    if (response.status === 404 && response.headers.has('x-edge-config-digest')) {
        return undefined;
    }
    const body = await response.text().catch(() => '');
    throw new Error(`Edge Config read ${key} returned ${response.status}: ${body.slice(0, 500)}`);
}
function parseEdgeConfigConnection(value) {
    const text = value.trim();
    if (!text)
        return null;
    return parseEdgeConfigQueryConnection(text)
        || parseVercelEdgeConfigURL(text)
        || parseExternalEdgeConfigURL(text);
}
function parseEdgeConfigQueryConnection(value) {
    if (!value.startsWith('edge-config:'))
        return null;
    const params = new URLSearchParams(value.slice('edge-config:'.length));
    const id = params.get('id') || '';
    const token = params.get('token') || '';
    if (!id || !token)
        return null;
    return {
        baseUrl: `https://edge-config.vercel.com/${id}`,
        token,
        version: params.get('version') || '1',
    };
}
function parseVercelEdgeConfigURL(value) {
    let url;
    try {
        url = new URL(value);
    }
    catch {
        return null;
    }
    if (url.protocol !== 'https:' || url.host !== 'edge-config.vercel.com')
        return null;
    const id = url.pathname.split('/').filter(Boolean)[0] || '';
    const token = url.searchParams.get('token') || '';
    if (!id || !id.startsWith('ecfg') || !token)
        return null;
    return {
        baseUrl: `https://edge-config.vercel.com/${id}`,
        token,
        version: url.searchParams.get('version') || '1',
    };
}
function parseExternalEdgeConfigURL(value) {
    let url;
    try {
        url = new URL(value);
    }
    catch {
        return null;
    }
    let id = url.searchParams.get('id') || '';
    const token = url.searchParams.get('token') || '';
    const version = url.searchParams.get('version') || '1';
    if (!id || url.pathname.startsWith('/ecfg_')) {
        id = url.pathname.split('/').filter(Boolean)[0] || '';
    }
    if (!id || !token)
        return null;
    url.search = '';
    const base = url.toString().replace(/\/+$/, '');
    return {
        baseUrl: base,
        token,
        version,
    };
}
