// Planu — Web Fetcher: HTTP client with retry + cache
import { getCached, setCache, DEFAULT_CONFIG } from './cache.js';
export async function fetchUrl(url, config = DEFAULT_CONFIG) {
    const cached = getCached(url);
    if (cached) {
        return { content: cached, source: 'cache', stale: false };
    }
    for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
        try {
            const response = await globalThis.fetch(url, {
                headers: { 'User-Agent': config.userAgent },
                signal: AbortSignal.timeout(config.timeoutMs),
            });
            if (response.ok) {
                const content = await response.text();
                setCache(url, content, config.defaultTtlSeconds * 1000);
                return { content, source: 'web', stale: false };
            }
            // Only retry on rate limiting (429)
            if (response.status === 429 && attempt < config.maxRetries) {
                await delay(config.retryBackoffMs * 2 ** attempt);
                continue;
            }
            return null;
        }
        catch {
            // Network errors: fail fast, no retry
            return null;
        }
    }
    return null;
}
function delay(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}
//# sourceMappingURL=http-client.js.map