export type TransportBody = | { kind: 'json'; value: unknown; rawText: string } | { kind: 'text'; rawText: string } | { kind: 'empty'; rawText: '' }; export interface TransportResponse { method: string; path: string; status: number; statusText?: string; headers: Readonly>; contentType?: string; requestId?: string; body: TransportBody; } export interface TransportResponseContext { method: string; path: string; } export function isHttpSuccess(response: Pick): boolean { return response.status >= 200 && response.status < 300; } export function normalizeResponseHeaders(headers: Headers): Record { const out: Record = {}; headers.forEach((value, name) => { out[name.toLowerCase()] = value; }); return out; } function requestIdFromHeaders(headers: Readonly>): string | undefined { return headers['x-request-id'] ?? headers['request-id'] ?? headers['x-correlation-id']; } /** * Consume a Fetch Response without assigning business meaning to it. HTTP and * JSON classification belongs to an endpoint ResponseContract. */ export async function readTransportResponse( response: Response, context: TransportResponseContext, ): Promise { const headers = normalizeResponseHeaders(response.headers); const rawText = await response.text(); const contentType = headers['content-type']; let body: TransportBody; if (rawText.length === 0) { body = { kind: 'empty', rawText: '' }; } else { try { body = { kind: 'json', value: JSON.parse(rawText), rawText }; } catch { body = { kind: 'text', rawText }; } } return { method: context.method, path: context.path, status: response.status, statusText: response.statusText || undefined, headers, contentType, requestId: requestIdFromHeaders(headers), body, }; } export function jsonTransportResponse( value: unknown, init: Partial> = {}, ): TransportResponse { const rawText = JSON.stringify(value); return { method: init.method ?? 'GET', path: init.path ?? '/', status: init.status ?? 200, statusText: init.statusText, headers: init.headers ?? { 'content-type': 'application/json' }, contentType: init.contentType ?? 'application/json', requestId: init.requestId, body: { kind: 'json', value, rawText }, }; }