import { PROBLEM_CONTENT_TYPE, type ProblemDetails } from '@superlist/shared' /** * Base URL of the API. Also used to open the SSE streams (`list-events`). * * Empty by default: the API is reached through the `/api` prefix on the same * origin (Vite proxies it in dev, nginx in production). Set `VITE_API_URL` to * point at another origin — the `/api` suffix is always appended to it. */ const origin = import.meta.env.VITE_API_URL || '' export const apiBaseUrl = `${origin}/api` /** Error thrown when the API answers with a RFC 9457 Problem Details payload. */ export class ApiError extends Error { readonly problem: ProblemDetails constructor(problem: ProblemDetails) { super(problem.title) this.name = 'ApiError' this.problem = problem } } /** Reads a Problem Details body, falling back to a generic problem. */ export async function readProblem(response: Response): Promise { const contentType = response.headers.get('content-type') ?? '' if (contentType.includes(PROBLEM_CONTENT_TYPE)) { try { return (await response.json()) as ProblemDetails } catch { // fall through to the generic problem below } } return { type: 'about:blank', title: response.statusText || 'Request failed', status: response.status, } } /** Thin `fetch` wrapper: JSON by default, sessions enabled, problems as errors. */ export async function apiFetch(path: string, init: RequestInit = {}): Promise { const response = await fetch(`${apiBaseUrl}${path}`, { credentials: 'include', ...init, headers: { 'content-type': 'application/json', ...init.headers, }, }) if (!response.ok) { throw new ApiError(await readProblem(response)) } if (response.status === 204) { return undefined as T } return (await response.json()) as T }