// Minimal typed client around fetch. Every call returns a neverthrow // `ResultAsync` instead of throwing - callers handle both arms // explicitly (`.match(...)`), so a forgotten error path is a type error, not a // silent runtime throw. import { ResultAsync } from 'neverthrow'; export class ApiError extends Error { status: number; constructor(message: string, status: number) { super(message); this.status = status; } } // Server origin and credentials. The hosted web app keeps the defaults: // same-origin relative paths and the session cookie. Native shells (Tauri) // point apiBase at their configured server and authenticate with the opaque // session token instead of a cookie. let apiBase = ''; let authToken: string | null = null; export function setApiBase(base: string): void { apiBase = base.replace(/\/+$/, ''); } export function setAuthToken(token: string | null): void { authToken = token; } export function apiUrl(path: string): string { return apiBase ? `${apiBase}${path}` : path; } // Whether a server is reachable through relative paths. In the browser the app // is served by its own origin, so relative /api works; in a native shell with // no configured server there is no backend, and hitting /api only yields a // connection-refused against the webview origin. export function hasServerBase(): boolean { return apiBase !== '' || !isNativeShell(); } // The shell exposes the Tauri global; the hosted web app does not. Inlined // rather than imported from platform.ts, which depends on this module. function isNativeShell(): boolean { return typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window; } // Raw fetch with the same origin/credentials/token handling as the typed // client, for byte payloads (blobs) that don't parse as JSON. export function apiFetch(path: string, init: RequestInit = {}): Promise { return fetch(apiUrl(path), { ...init, headers: { ...baseHeaders(false), ...(init.headers ?? {}) }, credentials: 'include', }); } function baseHeaders(json: boolean): Record { const h: Record = {}; if (json) h['Content-Type'] = 'application/json'; if (authToken) h.Authorization = `Bearer ${authToken}`; return h; } // A 401 means the session is missing/expired. The auth store registers a // callback here so an expired session anywhere in the app bounces the user // back to the login screen. Kept as an injected callback (not an import of the // auth store) so api.ts stays dependency-free and there's no import cycle. let onUnauthorized: (() => void) | null = null; export function setUnauthorizedHandler(handler: () => void): void { onUnauthorized = handler; } async function toError(res: Response): Promise { let msg = `Error ${res.status}`; try { const data = await res.json(); if (data?.error) msg = data.error; } catch { /* non-JSON response */ } return new ApiError(msg, res.status); } // Opt out of the global 401 handler for endpoints where a 401 is a normal // answer (wrong current password) rather than an expired session. export interface RequestOptions { handleUnauthorized?: boolean; } async function parse(res: Response, handleUnauthorized = true): Promise { if (!res.ok) { // Notify the auth layer before failing so it can flip to "logged out". if (res.status === 401 && handleUnauthorized) onUnauthorized?.(); throw await toError(res); } return res.status === 204 ? (null as T) : ((await res.json()) as T); } // Wrap a fetch/parse promise into a ResultAsync, normalising every rejection to // an ApiError (network failures included) so the error arm is always typed. function request(run: () => Promise): ResultAsync { return ResultAsync.fromPromise(run(), (e) => e instanceof ApiError ? e : new ApiError((e as Error)?.message ?? 'Network error', 0), ); } export const api = { get(url: string, opts?: RequestOptions): ResultAsync { return request(() => fetch(apiUrl(url), { headers: baseHeaders(false), credentials: 'include' }).then((r) => parse(r, opts?.handleUnauthorized ?? true), ), ); }, post(url: string, body?: unknown, opts?: RequestOptions): ResultAsync { return request(() => fetch(apiUrl(url), { method: 'POST', headers: baseHeaders(true), credentials: 'include', body: JSON.stringify(body ?? {}), }).then((r) => parse(r, opts?.handleUnauthorized ?? true)), ); }, put(url: string, body?: unknown): ResultAsync { return request(() => fetch(apiUrl(url), { method: 'PUT', headers: baseHeaders(true), credentials: 'include', body: JSON.stringify(body ?? {}), }).then((r) => parse(r)), ); }, del(url: string): ResultAsync { return request(() => fetch(apiUrl(url), { method: 'DELETE', headers: baseHeaders(false), credentials: 'include', }).then((r) => parse(r)), ); }, upload(url: string, formData: FormData): ResultAsync { return request(() => fetch(apiUrl(url), { method: 'POST', headers: baseHeaders(false), credentials: 'include', body: formData, }).then((r) => parse(r)), ); }, /** * Multipart upload with transfer progress (XMLHttpRequest - fetch cannot * observe upload progress). onProgress receives 0..100; 100 means the * transfer is done while the server may still be processing (conversion). */ uploadWithProgress( url: string, formData: FormData, onProgress: (percent: number) => void, ): ResultAsync { return request( () => new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST', apiUrl(url)); xhr.withCredentials = true; if (authToken) xhr.setRequestHeader('Authorization', `Bearer ${authToken}`); xhr.responseType = 'json'; xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100)); }; xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response as T); else { // Mirror parse(): a 401 means the session lapsed - bounce to login. if (xhr.status === 401) onUnauthorized?.(); const body = xhr.response as { error?: string } | null; reject(new ApiError(body?.error ?? `Error ${xhr.status}`, xhr.status)); } }; xhr.onerror = () => reject(new ApiError('Network error', 0)); xhr.send(formData); }), ); }, };