import { GeocodingProviderError } from './errors' /** GET JSON, with a timeout joined to the caller's signal. A non-2xx answer throws. */ export async function getJson(driver: string, url: URL, init: { headers?: Record, signal?: AbortSignal, timeoutMs?: number, fetch?: typeof fetch, method?: string, body?: string } = {}): Promise { const timeout = AbortSignal.timeout(init.timeoutMs ?? 8000) const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout let response: Response try { response = await (init.fetch ?? fetch)(url, { method: init.method ?? 'GET', body: init.body, headers: { accept: 'application/json', ...init.headers }, signal }) } catch (error) { if (init.signal?.aborted) throw error throw new GeocodingProviderError(driver, `request failed: ${error instanceof Error ? error.message : String(error)}`) } if (!response.ok) { let code: string | undefined let message = `responded ${response.status}` try { const body = await response.json() as { code?: string, message?: string } code = body.code if (body.message) message = `${message}: ${body.message}` } catch {} throw new GeocodingProviderError(driver, message, response.status, code) } return await response.json() as T } /** One request at a time, `intervalMs` apart, across the process: for providers with a per-second policy. */ export function serialized(intervalMs: number, sleep: (ms: number) => Promise = ms => Bun.sleep(ms)): (work: () => Promise) => Promise { let last = 0 let queue: Promise = Promise.resolve() return (work: () => Promise): Promise => { const run = queue.then(async () => { const since = Date.now() - last if (since < intervalMs) await sleep(intervalMs - since) last = Date.now() return work() }) queue = run.then(() => undefined, () => undefined) return run } }