/** * src/clients/http.ts * ==================== * Shared HTTP core for 0pt's four platform clients (cl0ud/st0re/n0d/aud0). * One place for the behaviours Master-DoD §6/§10 require of every * cross-product call: * * - request timeout (no hung platform call can wedge a capability), * - typed `SiaxError` mapping from upstream status codes (retryable vs * permanent explicit, correlation id carried, no raw upstream body leaked * into the error message), * - canonical SIAX context propagation headers (src/platform/siax-context.ts) * plus optional service `Authorization` bearer (never the end-user token), * - JSON body handling. * * Each client keeps its own wire mapping (the four dependencies genuinely * differ: ST0RE is camelCase + X-Tenant-Id/X-Actor-Id, AUD0 is snake_case, * CL0UD wraps in a `{ data, meta }` envelope, N0D is snake_case + 202) — this * module owns only the transport discipline they share. */ import { SiaxError, siaxErrorCodeForUpstreamStatus } from "../platform/errors"; import { toPropagationHeaders, type SiaxRequestContext } from "../platform/siax-context"; export interface SiaxHttpOptions { /** Dependency name for error attribution, e.g. "st0re". */ dependency: string; baseUrl: string; /** Service bearer token (machine identity). Optional — some deployments gate by network + headers. */ token?: string; /** Per-request timeout in ms. Default 15_000. */ timeoutMs?: number; } export interface SiaxRequestOptions { method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; path: string; /** Query string parameters (skipped when undefined). */ query?: Record; body?: unknown; /** Canonical SIAX context — serialized to propagation headers when present. */ context?: SiaxRequestContext; /** Extra headers (e.g. ST0RE's X-Idempotency-Key). Applied last. */ headers?: Record; /** Statuses the caller handles itself (returned, not thrown). */ acceptStatuses?: number[]; } export interface SiaxHttpResponse { status: number; /** Parsed JSON body, or undefined when the body was empty/non-JSON. */ json: unknown; } export class SiaxHttp { private readonly dependency: string; private readonly baseUrl: string; private readonly token?: string; private readonly timeoutMs: number; constructor(opts: SiaxHttpOptions) { this.dependency = opts.dependency; this.baseUrl = opts.baseUrl.replace(/\/+$/, ""); this.token = opts.token; this.timeoutMs = opts.timeoutMs ?? 15_000; } async request(opts: SiaxRequestOptions): Promise { const url = new URL(`${this.baseUrl}${opts.path}`); for (const [k, v] of Object.entries(opts.query ?? {})) { if (v !== undefined) url.searchParams.set(k, v); } const headers: Record = { "Content-Type": "application/json" }; if (this.token) headers["Authorization"] = `Bearer ${this.token}`; if (opts.context) Object.assign(headers, toPropagationHeaders(opts.context)); Object.assign(headers, opts.headers ?? {}); const correlationId = opts.context?.correlationId; let res: Response; try { // NOTE: fetch is called with a STRING (not a URL object) so test fetch // stubs that inspect `url.includes(...)` keep working. res = await fetch(url.toString(), { method: opts.method, headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body), signal: AbortSignal.timeout(this.timeoutMs), }); } catch (cause) { // Network failure / timeout: the dependency is unavailable — retryable. throw new SiaxError( "DEPENDENCY_UNAVAILABLE", this.dependency, `${opts.method} ${opts.path} failed to reach ${this.dependency} (${cause instanceof Error ? cause.name : "fetch error"})`, { correlationId, cause } ); } if (!res.ok && !(opts.acceptStatuses ?? []).includes(res.status)) { // Read the upstream machine-readable code when present, but never embed // the raw body in the error (§6: no sensitive internals). const upstream = (await res.json().catch(() => undefined)) as | { error?: { code?: string; message?: string } } | undefined; const upstreamCode = upstream?.error?.code; throw new SiaxError( siaxErrorCodeForUpstreamStatus(res.status), this.dependency, `${opts.method} ${opts.path} → HTTP ${res.status}${upstreamCode ? ` (${upstreamCode})` : ""}`, { correlationId } ); } const json = (await res.json().catch(() => undefined)) as unknown; return { status: res.status, json }; } }