Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192// Minimal typed client around fetch. Every call returns a neverthrow// `ResultAsync<T, ApiError>` 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<Response> { return fetch(apiUrl(path), { ...init, headers: { ...baseHeaders(false), ...(init.headers ?? {}) }, credentials: 'include', });}
function baseHeaders(json: boolean): Record<string, string> { const h: Record<string, string> = {}; 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<ApiError> { 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<T>(res: Response, handleUnauthorized = true): Promise<T> { 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<T>(run: () => Promise<T>): ResultAsync<T, ApiError> { return ResultAsync.fromPromise(run(), (e) => e instanceof ApiError ? e : new ApiError((e as Error)?.message ?? 'Network error', 0), );}
export const api = { get<T>(url: string, opts?: RequestOptions): ResultAsync<T, ApiError> { return request(() => fetch(apiUrl(url), { headers: baseHeaders(false), credentials: 'include' }).then((r) => parse<T>(r, opts?.handleUnauthorized ?? true), ), ); }, post<T>(url: string, body?: unknown, opts?: RequestOptions): ResultAsync<T, ApiError> { return request(() => fetch(apiUrl(url), { method: 'POST', headers: baseHeaders(true), credentials: 'include', body: JSON.stringify(body ?? {}), }).then((r) => parse<T>(r, opts?.handleUnauthorized ?? true)), ); }, put<T>(url: string, body?: unknown): ResultAsync<T, ApiError> { return request(() => fetch(apiUrl(url), { method: 'PUT', headers: baseHeaders(true), credentials: 'include', body: JSON.stringify(body ?? {}), }).then((r) => parse<T>(r)), ); }, del(url: string): ResultAsync<null, ApiError> { return request(() => fetch(apiUrl(url), { method: 'DELETE', headers: baseHeaders(false), credentials: 'include', }).then((r) => parse<null>(r)), ); }, upload<T>(url: string, formData: FormData): ResultAsync<T, ApiError> { return request(() => fetch(apiUrl(url), { method: 'POST', headers: baseHeaders(false), credentials: 'include', body: formData, }).then((r) => parse<T>(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<T>( url: string, formData: FormData, onProgress: (percent: number) => void, ): ResultAsync<T, ApiError> { return request( () => new Promise<T>((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); }), ); },};