export class APIError extends Error { status: number constructor(status: number, message: string) { super(message); this.status = status } } export async function api(path: string, init: RequestInit = {}): Promise { const response = await fetch(`/admin/api/${path}`, { ...init, credentials: "same-origin", headers: { "Content-Type": "application/json", ...init.headers }, }) const data = await response.json() if (response.status === 401 && path !== "login" && path !== "session") window.dispatchEvent(new Event("session-expired")) if (!response.ok) throw new APIError(response.status, data.error ?? "request failed") return data as T } export const message = (error: unknown) => error instanceof Error ? error.message : "something went wrong; try again" export const pretty = (value: unknown) => typeof value === "string" ? value : JSON.stringify(value, null, 2) export const number = (value: number) => new Intl.NumberFormat().format(value) export const usd = (value: number) => value < 0.01 ? `${(value * 100).toFixed(value < 0.001 ? 3 : 2)}ยข` : `$${value.toFixed(2)}` export const time = (value: number) => new Date(value * 1000).toLocaleString() export function safeURL(value: string): string | undefined { try { const url = new URL(value); return /^(https?:)$/.test(url.protocol) ? url.href : undefined } catch { return undefined } }