// Client-safe fetchers for the app's own same-origin /api/* route handlers. // MUST NOT import any server module — this runs in the browser. // Route handlers respond with the data as JSON on success, or // `{ error: string, ... }` with a 4xx/5xx status on failure. // // Ported from solvway-customer-portal's app/lib/clientApi.ts (spec: "The Admin // Portal Is A Next.js Backend-For-Frontend" — the browser only ever calls // same-origin /api/* routes). The 401 -> /login redirect closes the // expired-but-present-cookie case: AdminAuthContext's own mount-time fetch to // /api/auth/session deliberately does NOT use this wrapper (a legitimate 401 on // a public page must not redirect-loop), but every other authenticated call a // page makes through this module does bounce to /login on a 401. import { loginUrl } from "@/app/lib/returnTo"; export class ApiError extends Error { status: number; data?: unknown; constructor(message: string, status: number, data?: unknown) { super(message); this.name = "ApiError"; this.status = status; this.data = data; } } function safeJson(text: string): unknown { try { return JSON.parse(text); } catch { return text; } } /** fetch + the shared error handling: a non-2xx response throws ApiError carrying the parsed body. */ async function fetchOrThrow(path: string, init?: RequestInit): Promise { let res: Response; try { res = await fetch(path, { ...init, headers: { ...(init?.body ? { "Content-Type": "application/json" } : {}), ...init?.headers }, }); } catch (err) { // An abort is the caller's own doing; let it through unchanged. if (err instanceof DOMException && err.name === "AbortError") throw err; // fetch only rejects when the request never got a response (offline, DNS, connection reset). throw new ApiError("Couldn't reach the server. Check your connection and retry.", 0); } if (res.ok) return res; const text = await res.text(); const body = text ? safeJson(text) : undefined; const message = (body && typeof body === "object" && "error" in body ? String((body as Record).error) : null) || `Request failed (${res.status})`; // 401 means the session is missing/expired — bounce to login. The login call itself is // exempt: its 401 is "bad credentials"/"account disabled", and the login page must show it. if (res.status === 401 && path !== "/api/auth/login" && typeof window !== "undefined") { window.location.assign(loginUrl(window.location.pathname + window.location.search)); } // A pending first-sign-in password reset blocks every admin API until it is completed. if ( res.status === 403 && (body as { code?: unknown } | undefined)?.code === "PASSWORD_RESET_REQUIRED" && typeof window !== "undefined" ) { window.location.assign("/reset-password"); } throw new ApiError(message, res.status, body); } async function clientFetch(path: string, init?: RequestInit): Promise { const text = await (await fetchOrThrow(path, init)).text(); return (text ? safeJson(text) : undefined) as T; } /** GET a file and save it through a temporary ; the name comes from Content-Disposition. */ export async function apiDownload(path: string, fallbackName: string): Promise { const res = await fetchOrThrow(path); const blob = await res.blob(); const name = /filename="?([^";]+)"?/i.exec(res.headers.get("Content-Disposition") ?? "")?.[1] ?? fallbackName; const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 0); // revoking synchronously can cancel the download in older browsers } export const apiGet = (path: string): Promise => clientFetch(path); export const apiPost = (path: string, body?: unknown): Promise => clientFetch(path, { method: "POST", body: body !== undefined ? JSON.stringify(body) : undefined }); export const apiPut = (path: string, body?: unknown, headers?: Record): Promise => clientFetch(path, { method: "PUT", body: body !== undefined ? JSON.stringify(body) : undefined, headers, }); export const apiDelete = (path: string, headers?: Record): Promise => clientFetch(path, { method: "DELETE", headers });