"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpError = void 0;
exports.isHttpError = isHttpError;
exports.fetchWithTimeout = fetchWithTimeout;
exports.postWithTimeout = postWithTimeout;
class HttpError extends Error {
    status;
    constructor(status, message) {
        super(message);
        this.status = status;
        this.name = "HttpError";
    }
}
exports.HttpError = HttpError;
function isHttpError(error) {
    return error instanceof HttpError;
}
const toStringRecord = (headers) => {
    const normalizedHeaders = {};
    for (const [key, value] of Object.entries(headers)) {
        if (value !== undefined && value !== null) {
            normalizedHeaders[key.toLowerCase()] = String(value);
        }
    }
    return normalizedHeaders;
};
const applyQueryParams = (url, params) => {
    if (Object.keys(params).length === 0)
        return url;
    const parsedUrl = new URL(url);
    for (const [key, value] of Object.entries(params)) {
        if (value !== undefined && value !== null) {
            parsedUrl.searchParams.append(key, String(value));
        }
    }
    return parsedUrl.toString();
};
async function baseFetch(url, method, body, params, headers, timeout, responseType = "json") {
    const fullUrl = applyQueryParams(url, params);
    const response = await fetch(fullUrl, {
        method,
        body,
        headers: toStringRecord(headers),
        ...(timeout && timeout > 0 && { signal: AbortSignal.timeout(timeout) }),
    });
    const text = await response.text();
    if (!response.ok) {
        let errorMessage;
        try {
            errorMessage = JSON.parse(text)?.error;
        }
        catch {
        }
        throw new HttpError(response.status, errorMessage ?? `HTTP ${response.status}: ${response.statusText}`);
    }
    if (responseType === "text") {
        return text;
    }
    try {
        return JSON.parse(text);
    }
    catch {
        const contentType = response.headers.get("content-type") ?? "unknown";
        throw new Error(`Expected JSON response from ${fullUrl} but received content-type: ${contentType} (body: ${text.slice(0, 256)})`);
    }
}
function fetchWithTimeout(url, params = {}, headers = {}, timeout, responseType = "json") {
    return baseFetch(url, "GET", undefined, params, headers, timeout, responseType);
}
function postWithTimeout(url, body, params = {}, headers = {}, timeout, responseType = "json") {
    return baseFetch(url, "POST", JSON.stringify(body), params, { "Content-Type": "application/json", ...headers }, timeout, responseType);
}
//# sourceMappingURL=FetchUtils.js.map