// Same API as the desktop clients: cookie session + CSRF header for the web admin (BRIEF ยง14.2). import { culture } from "./i18n.js"; export class ApiFailure extends Error { constructor(status, code, message, details) { super(message); this.status = status; this.code = code; this.details = details; } } let currentUser = null; function csrfToken() { const m = document.cookie.match(/(?:^|; )titano_csrf=([^;]+)/); return m ? decodeURIComponent(m[1]) : ""; } async function request(method, url, body) { const headers = { Accept: "application/json", "Accept-Language": culture() }; if (body !== undefined) headers["Content-Type"] = "application/json"; if (method !== "GET") headers["X-CSRF-Token"] = csrfToken(); let res; try { res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) }); } catch { throw new ApiFailure(0, "unreachable", ""); } if (res.status === 401 && url !== "/api/v1/auth/login") { currentUser = null; window.dispatchEvent(new Event("titano:signed-out")); } if (!res.ok) { let err = { code: "http_" + res.status, message: res.statusText }; try { err = await res.json(); } catch { // Not a JSON error body. } throw new ApiFailure(res.status, err.code, err.message, err.details); } return res.status === 204 ? null : res.json(); } export const api = { get: (url) => request("GET", url), post: (url, body) => request("POST", url, body ?? {}), put: (url, body) => request("PUT", url, body), patch: (url, body) => request("PATCH", url, body), del: (url) => request("DELETE", url), user: () => currentUser, /** Restores the session from the cookie; null when signed out. */ async resume() { try { currentUser = await request("GET", "/api/v1/auth/me"); } catch { currentUser = null; } return currentUser; }, async signIn(username, password) { const r = await request("POST", "/api/v1/auth/login", { username, password, clientName: "admin-web", cookie: true }); currentUser = r.user; return r; }, async changePassword(currentPassword, newPassword) { await request("POST", "/api/v1/auth/password", { currentPassword, newPassword }); currentUser = await request("GET", "/api/v1/auth/me"); }, async signOut() { try { await request("POST", "/api/v1/auth/logout", {}); } catch { // Already signed out. } currentUser = null; }, /** Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. */ events(onEvent) { let socket = null; let stopped = false; let delay = 1000; const connect = () => { if (stopped) return; socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/v1/events`); socket.onopen = () => { delay = 1000; }; socket.onmessage = (m) => { try { onEvent(JSON.parse(m.data)); } catch { // Ignore malformed or unknown events. } }; socket.onclose = () => { if (stopped) return; setTimeout(connect, delay); delay = Math.min(delay * 2, 30000); }; }; connect(); return { stop() { stopped = true; socket?.close(); }, }; }, };