import { loadConfig } from "./config.js"; const config = loadConfig(); /** * Fetches from the AppView API and returns parsed JSON. * * Throws two distinct error shapes that callers must classify: * - `"AppView network error: ..."` — AppView is unreachable; callers should * return 503 so the user knows to retry. * - `"AppView API error: N ..."` — AppView returned a non-ok HTTP status; * callers should map to an appropriate response (404, 400, 500, etc.). */ export async function fetchApi( path: string, options?: { cookieHeader?: string } ): Promise { const url = `${config.appviewUrl}/api${path}`; const headers: Record = {}; if (options?.cookieHeader) { headers["Cookie"] = options.cookieHeader; } let res: Response; try { res = await fetch(url, { headers }); } catch (error) { throw new Error( `AppView network error: ${error instanceof Error ? error.message : String(error)}` ); } if (!res.ok) { throw new Error(`AppView API error: ${res.status} ${res.statusText}`); } let parsed: T; try { parsed = (await res.json()) as T; } catch (error) { throw new Error( `AppView response error: invalid JSON from ${path} (${error instanceof Error ? error.message : String(error)})` ); } return parsed; }