"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpRequest = httpRequest;
exports.fetchJson = fetchJson;
exports.fetchText = fetchText;
const DEFAULT_TIMEOUT = parseInt(process.env.LT_HTTP_FETCH_TIMEOUT_MS || '30000', 10);
async function httpRequest(args) {
    const start = Date.now();
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), args.timeout_ms || DEFAULT_TIMEOUT);
    try {
        const response = await fetch(args.url, {
            method: args.method || 'GET',
            headers: args.headers,
            body: args.body,
            signal: controller.signal,
        });
        const body = await response.text();
        const headers = {};
        response.headers.forEach((value, key) => { headers[key] = value; });
        return {
            status: response.status,
            headers,
            body,
            elapsed_ms: Date.now() - start,
        };
    }
    finally {
        clearTimeout(timeout);
    }
}
async function fetchJson(args) {
    const result = await httpRequest({
        url: args.url,
        method: 'GET',
        headers: { Accept: 'application/json', ...args.headers },
    });
    try {
        return { data: JSON.parse(result.body), status: result.status };
    }
    catch {
        return { data: result.body, status: result.status };
    }
}
async function fetchText(args) {
    const result = await httpRequest({
        url: args.url,
        method: 'GET',
        headers: args.headers,
    });
    return {
        text: result.body,
        status: result.status,
        content_type: result.headers['content-type'] || 'text/plain',
    };
}
