import { retryDelayMs, unexplainedMessage } from './game/errors'; import type { ApiErrorBody, Envelope } from './types'; type CallResult = | { ok: true; envelope: Envelope; dryRun: boolean } | { ok: false; error: ApiErrorBody }; interface CallOptions { dryRun?: boolean; /** Sent as `Idempotency-Key` so a retried money move is applied once (federation deposit/withdraw). */ idempotencyKey?: string; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** * Client-side call through the same-origin proxy. `href` is an API path like `/v1/ships/ORION-1/dock`. * Transient errors are retried once (see `retryDelayMs`). */ export async function callApi( method: string, href: string, body?: Record, { dryRun = false, idempotencyKey }: CallOptions = {} ): Promise> { const sep = href.includes('?') ? '&' : '?'; const url = `/api${href}${dryRun ? `${sep}dry_run=1` : ''}`; const headers: Record = {}; if (body) headers['content-type'] = 'application/json'; if (idempotencyKey) headers['idempotency-key'] = idempotencyKey; for (let attempt = 0; ; attempt++) { let res: Response; try { res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined }); } catch { return { ok: false, error: { status: 0, code: 'network', message: 'Could not reach the server.' } }; } const json = await res.json().catch(() => null); if (res.ok) return { ok: true, envelope: json as Envelope, dryRun }; const error: ApiErrorBody = json?.error ?? { status: res.status, code: 'unexplained', message: unexplainedMessage(res.status, res.statusText) }; const wait = attempt === 0 ? retryDelayMs(res.status, error.code, res.headers.get('retry-after')) : null; if (wait === null) return { ok: false, error }; await sleep(wait); } }