import assert from 'assert';
import { getConfig } from '../shared/config.js';
export async function postRemote(input, controller) {
    const remote = getConfig('remote');
    assert(typeof remote === 'string');
    let body;
    let headers = {};
    if (typeof input.body === 'string') {
        body = input.body;
        headers['content-type'] = 'application/json';
    }
    else if (input.body instanceof FormData) {
        body = input.body;
        // headers['content-type'] = 'multipart/form-data'
    }
    else {
        body = JSON.stringify(body);
        headers['content-type'] = 'application/json';
    }
    return fetchWithTimeout(`${remote}${input.path}`, {
        method: 'POST',
        headers,
        body,
        controller,
    });
}
export async function getRemote(path, controller) {
    const remote = getConfig('remote');
    assert(typeof remote === 'string');
    return fetchWithTimeout(`${remote}${path}`, {
        method: 'GET',
        controller,
    });
}
export function buildRemoteRequest(method, path, body) {
    return {
        method,
        path,
        body,
    };
}
export function isRemoteRequest(input) {
    return Boolean(input.remote);
}
export async function fetchWithTimeout(resource, options = {}) {
    const { timeout = 20000 } = options;
    const controller = options.controller || new AbortController();
    const id = setTimeout(() => controller.abort('timeout'), timeout);
    const response = await fetch(resource, {
        ...options,
        signal: controller.signal,
    });
    clearTimeout(id);
    return response;
}
export async function requestMany(controller, list) {
    return Promise.all(list.map((req, i) => {
        req.catch(e => {
            controller.abort(e);
        });
        return req;
    }));
}
//# sourceMappingURL=request.js.map