const BASE_URL = "/api"; export class ApiError extends Error { constructor( public status: number, public detail: string, public code?: string ) { super(detail); } } let onUnauthorizedCallback: (() => void) | null = null; export function setUnauthorizedHandler(cb: () => void) { onUnauthorizedCallback = cb; } function handleUnauthorized(path: string) { sessionStorage.removeItem("access_token"); if (!path.startsWith("/auth/login")) { onUnauthorizedCallback?.(); } } async function request(path: string, options: RequestInit = {}): Promise { const token = sessionStorage.getItem("access_token"); const isFormData = typeof FormData !== "undefined" && options.body instanceof FormData; const headers: Record = { ...(isFormData ? {} : { "Content-Type": "application/json" }), ...(options.headers as Record), }; if (token) headers["Authorization"] = `Bearer ${token}`; const res = await fetch(`${BASE_URL}${path}`, { ...options, headers }); if (!res.ok) { const body = await res.json().catch(() => ({ detail: res.statusText })); if (res.status === 401) handleUnauthorized(path); throw new ApiError(res.status, body.detail ?? res.statusText, body.code); } if (res.status === 204) return undefined as T; return res.json(); } async function downloadBlob(path: string): Promise<{ blob: Blob; contentType: string }> { const token = sessionStorage.getItem("access_token"); const headers: Record = {}; if (token) headers["Authorization"] = `Bearer ${token}`; const res = await fetch(`${BASE_URL}${path}`, { headers }); if (!res.ok) { const body = await res.json().catch(() => ({ detail: res.statusText })); if (res.status === 401) handleUnauthorized(path); throw new ApiError(res.status, body.detail ?? res.statusText, body.code); } const blob = await res.blob(); const contentType = res.headers.get("Content-Type") || blob.type || "application/octet-stream"; return { blob, contentType }; } export const api = { get: (path: string) => request(path), post: (path: string, data?: unknown) => request(path, { method: "POST", body: data !== undefined ? JSON.stringify(data) : undefined }), patch: (path: string, data: unknown) => request(path, { method: "PATCH", body: JSON.stringify(data) }), put: (path: string, data: unknown) => request(path, { method: "PUT", body: JSON.stringify(data) }), delete: (path: string) => request(path, { method: "DELETE" }), upload: (path: string, formData: FormData) => request(path, { method: "POST", body: formData }), downloadBlob, };