export class ApiError extends Error { status: number; constructor(status: number, detail: string) { super(detail); this.status = status; } } async function request(path: string, init?: RequestInit): Promise { const res = await fetch(`/api${path}`, { headers: init?.body ? { "Content-Type": "application/json" } : undefined, ...init, }); if (!res.ok) { let detail = res.statusText; try { detail = (await res.json()).detail ?? detail; } catch { /* non-JSON error body */ } throw new ApiError(res.status, detail); } return res.json() as Promise; } export const api = { get: (path: string) => request(path), post: (path: string, body?: unknown) => request(path, { method: "POST", body: body ? JSON.stringify(body) : undefined }), put: (path: string, body: unknown) => request(path, { method: "PUT", body: JSON.stringify(body) }), delete: (path: string) => request(path, { method: "DELETE" }), }; /** Mirrors backend/users.py `allowed()` — fnmatch-lite scope check. */ export function scopeAllowed(scopes: string[], needed: string): boolean { return scopes.some((grant) => { if (grant === "*" || grant === "admin") return true; const re = new RegExp( "^" + grant .split("*") .map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) .join(".*") + "$", ); return re.test(needed); }); } export const isAdmin = (scopes: string[]) => scopes.some((s) => s === "admin" || s === "*");