/*!
 * Custom elements for Nanopore-Digital Web applications
 */
export async function clientFetch(url, { body, ...customConfig } = {}) {
    const headers = {
        Accept: 'application/json, text/plain, */*',
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
        Cache: 'no-cache',
    };
    const config = {
        method: body ? 'POST' : 'GET',
        credentials: 'include',
        keepalive: true,
        mode: 'cors',
        ...customConfig,
        headers: {
            ...headers,
            ...customConfig.headers,
        },
    };
    if (body) {
        config.body = JSON.stringify(body);
    }
    let id = setTimeout(() => { }, 0);
    if (window.AbortController) {
        const controller = new AbortController();
        const { timeout = 500 } = customConfig;
        id = setTimeout(() => controller.abort(), timeout);
        config.signal = controller.signal;
    }
    const response = await fetch(url, config);
    clearTimeout(id);
    if (response.ok) {
        return await response.json();
    }
    else {
        const errorMessage = await response.text();
        return new Error(errorMessage);
    }
}
