export function timeout( pending: Promise | ((args: { signal: AbortSignal }) => Promise), ms: number, ): Promise { const error = new TimeoutError(); let timeout: ReturnType; let ac: AbortController | undefined; if (typeof pending === 'function') { ac = new AbortController(); pending = pending({ signal: ac.signal }); } return Promise.race([ pending, new Promise((_resolve, reject) => { timeout = setTimeout(() => { ac?.abort(error); reject(error); }, ms); }), ]).finally(() => { clearTimeout(timeout); }); } export class TimeoutError extends Error { constructor() { super('TimeoutError'); } }