// fetch for the demo scripts. A connection that never opened did not reach the server, // so it is safe to try again; anything that may have been delivered is not retried. const NEVER_SENT = new Set(['UND_ERR_CONNECT_TIMEOUT', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN']); export async function fetchRetry(url, init = {}, { tries = 4, timeoutMs = 90000 } = {}) { for (let attempt = 1; ; attempt++) { try { return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }); } catch (e) { const code = e.cause?.code; const idempotent = !init.method || init.method === 'GET'; const safe = NEVER_SENT.has(code) || (idempotent && code === 'ECONNRESET'); if (!safe || attempt >= tries) throw e; console.log(` (network: ${code}, retrying)`); await new Promise((r) => setTimeout(r, 1500 * attempt)); } } }