import { apiFetch } from './api'; interface RequestErrors { create: (message: string, status: number | null) => Error; invalid: () => Error; lostMessage: string; failureLabel: string; } /** Transport only. Domain clients retain identity checks and receipt policy. * Never retry a write here: a lost response may already have been accepted. */ export async function requestJson( url: string, init: RequestInit, expectedStatus: number, parse: (body: unknown) => T, errors: RequestErrors ): Promise { let response: Response; try { response = await apiFetch(url, init); } catch (cause) { if (init.signal?.aborted) { throw cause; } throw errors.create(errors.lostMessage, null); } const body: unknown = response.status === 204 ? undefined : await response.json().catch(() => null); if (!response.ok) { const message = body && typeof body === 'object' && 'error' in body && typeof body.error === 'string' ? body.error : `${errors.failureLabel} (${response.status})`; throw errors.create(message, response.status); } try { if (response.status !== expectedStatus) { throw errors.invalid(); } return parse(body); } catch { throw errors.invalid(); } }