// Plausible bug: lastStatus remembers the most recent 5xx even when the final attempt was a network error, and `if (delay)` skips sleep(0).export type HttpResponse = { status: number; body: string };export class NetworkError extends Error { public readonly kind = "network" as const; constructor(message: string) { super(message); }}export type Fetcher = (url: string) => Promise<HttpResponse>;export type RetryOptions = { retries: number; baseDelayMs: number; sleep: (ms: number) => Promise<void>;};export class HttpError extends Error { public readonly kind = "http" as const; constructor(public readonly status: number) { super(`http ${status}`); }}export class ExhaustedError extends Error { public readonly kind = "exhausted" as const; constructor( public readonly attempts: number, public readonly lastStatus?: number, ) { super(`exhausted after ${attempts} attempts`); }}export async function retryFetch(fetcher: Fetcher, url: string, options: RetryOptions): Promise<string> { const { retries, baseDelayMs, sleep } = options; let lastStatus: number | undefined; for (let attempt = 0; attempt <= retries; attempt += 1) { if (attempt > 0) { const delay = baseDelayMs * 2 ** (attempt - 1); if (delay) await sleep(delay); } try { const res = await fetcher(url); if (res.status >= 200 && res.status < 300) return res.body; if (res.status < 500) throw new HttpError(res.status); lastStatus = res.status; } catch (e) { if (e instanceof HttpError) throw e; } } throw new ExhaustedError(retries + 1, lastStatus);}