import { combineWithSignal } from '../utils.ts'; // TODO: replace this by using AbortSignal.timeout() static method when it becomes widely available export function fetchWithTimeout( timeout: number, input: string | URL | Request, init?: RequestInit, ): Promise { function doFetch(signal: AbortSignal | null | undefined): Promise { return fetch(input, { ...init, signal }); } if (timeout <= 0) { return doFetch(init?.signal); } const ac = new AbortController(); if (init?.signal != null) { combineWithSignal(ac, init.signal); } let clear: () => void; const requestPromise = doFetch(ac.signal).finally(() => { clear?.(); }); const timeoutPromise = new Promise((_resolve, reject) => { const timeoutId = setTimeout(() => { ac.abort(); // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- 'TIMEOUT' is a sentinel matched by `error === 'TIMEOUT'` in doRequest reject('TIMEOUT'); }, timeout); clear = () => clearTimeout(timeoutId); }); return Promise.race([requestPromise, timeoutPromise]); }