/** Thin client for the Study Desk API: JSON in, JSON out, typed errors, CSRF header on every call. */ export class ApiError extends Error { status: number; code: string; details?: unknown; constructor(status: number, code: string, message: string, details?: unknown) { super(message); this.name = 'ApiError'; this.status = status; this.code = code; this.details = details; } } /** Set by the app shell: called when any request comes back 401 so the login screen can appear. */ let onUnauthorized: (() => void) | null = null; export function setUnauthorizedHandler(fn: (() => void) | null): void { onUnauthorized = fn; } const BASE_HEADERS = { 'X-Requested-With': 'studydesk' }; async function toError(res: Response): Promise { let code = 'http_error'; let message = res.status >= 500 ? 'The server ran into a problem. Try again in a moment.' : `Request failed (${res.status})`; let details: unknown; try { const body = await res.json(); if (body?.error) { code = body.error.code ?? code; message = body.error.message ?? message; details = body.error.details; } } catch { /* not JSON */ } return new ApiError(res.status, code, message, details); } export async function request(method: string, url: string, body?: unknown, init: { signal?: AbortSignal; publicCall?: boolean } = {}): Promise { let res: Response; try { res = await fetch(url, { method, credentials: 'same-origin', signal: init.signal, headers: body instanceof FormData ? BASE_HEADERS : body !== undefined ? { ...BASE_HEADERS, 'Content-Type': 'application/json' } : BASE_HEADERS, body: body instanceof FormData ? body : body !== undefined ? JSON.stringify(body) : undefined, }); } catch (e) { if ((e as Error)?.name === 'AbortError') throw e; throw new ApiError(0, 'network', 'Could not reach the server. Check your connection and try again.'); } if (!res.ok) { const err = await toError(res); if (res.status === 401 && !init.publicCall && err.code === 'unauthorized') onUnauthorized?.(); throw err; } if (res.status === 204) return undefined as T; return (await res.json()) as T; } export const api = { get: (url: string, signal?: AbortSignal) => request('GET', url, undefined, { signal }), post: (url: string, body?: unknown) => request('POST', url, body ?? {}), put: (url: string, body?: unknown) => request('PUT', url, body ?? {}), patch: (url: string, body?: unknown) => request('PATCH', url, body ?? {}), del: (url: string) => request('DELETE', url), upload: (url: string, form: FormData) => request('POST', url, form), /** Public (share-link) calls never trigger the login screen. */ pub: (url: string, signal?: AbortSignal) => request('GET', url, undefined, { signal, publicCall: true }), pubPost: (url: string, body?: unknown) => request('POST', url, body ?? {}, { publicCall: true }), }; export function errorMessage(e: unknown, fallback = 'Something went wrong.'): string { if (e instanceof ApiError) return e.message; if (e instanceof Error && e.message) return e.message; return fallback; } /** Uploads with progress (fetch cannot report upload progress). A Blob or File is sent as the raw body. */ export function uploadWithProgress(url: string, form: FormData | Blob, onProgress: (fraction: number) => void): Promise { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST', url); xhr.setRequestHeader('X-Requested-With', 'studydesk'); if (form instanceof Blob) xhr.setRequestHeader('Content-Type', form.type || 'application/octet-stream'); xhr.upload.onprogress = (e) => { if (e.lengthComputable) onProgress(e.loaded / e.total); }; xhr.onerror = () => reject(new ApiError(0, 'network', 'The upload was interrupted. Check your connection and try again.')); xhr.onload = () => { let body: any = null; try { body = JSON.parse(xhr.responseText); } catch { /* ignore */ } if (xhr.status >= 200 && xhr.status < 300) resolve(body as T); else { if (xhr.status === 401) onUnauthorized?.(); reject(new ApiError(xhr.status, body?.error?.code ?? 'http_error', body?.error?.message ?? `Upload failed (${xhr.status})`, body?.error?.details)); } }; xhr.send(form); }); } /** POSTs JSON (or GETs, when `body` is undefined) and reads a server-sent event stream of JSON objects. */ export async function streamEvents(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise { const res = await fetch(url, { method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin', headers: body === undefined ? { ...BASE_HEADERS, Accept: 'text/event-stream' } : { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' }, body: body === undefined ? undefined : JSON.stringify(body), signal, }); if (!res.ok || !res.body) { const err = await toError(res); if (res.status === 401) onUnauthorized?.(); throw err; } const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; for (;;) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); let idx: number; while ((idx = buffer.search(/\r?\n\r?\n/)) >= 0) { const block = buffer.slice(0, idx); buffer = buffer.slice(idx).replace(/^\r?\n\r?\n/, ''); const data = block .split(/\r?\n/) .filter((l) => l.startsWith('data:')) .map((l) => l.slice(5).trimStart()) .join('\n'); if (!data) continue; try { const event = JSON.parse(data) as T; if (event.type !== 'ping') onEvent(event); } catch { /* skip malformed event */ } } } }