Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
112 lines
4.1 KiB
TypeScript
112 lines
4.1 KiB
TypeScript
import type { ServerEvent } from "./types";
|
||
import { chunkedUpload } from "./uploads";
|
||
|
||
// Authentication uses an HttpOnly session cookie set by /api/auth/login.
|
||
|
||
export class ApiError extends Error {
|
||
constructor(
|
||
public status: number,
|
||
message: string,
|
||
) {
|
||
super(message);
|
||
}
|
||
}
|
||
|
||
export async function api<T = any>(path: string, init: RequestInit & { json?: unknown } = {}): Promise<T> {
|
||
const headers: Record<string, string> = { ...(init.headers as Record<string, string>) };
|
||
let body = init.body;
|
||
if (init.json !== undefined) {
|
||
headers["Content-Type"] = "application/json";
|
||
body = JSON.stringify(init.json);
|
||
}
|
||
const res = await fetch(`/api${path}`, { ...init, headers, body, credentials: "same-origin" });
|
||
if (res.status === 401 && !path.startsWith("/auth/") && path !== "/info") onUnauthorized?.();
|
||
const text = await res.text();
|
||
let data: any = null;
|
||
try {
|
||
data = text ? JSON.parse(text) : null;
|
||
} catch {
|
||
// Proxies answer with HTML error pages (e.g. 413 from nginx).
|
||
const hint = res.status === 413 ? "request too large – the reverse proxy rejected the upload (client_max_body_size)" : res.statusText || "unexpected response";
|
||
throw new ApiError(res.status, `HTTP ${res.status}: ${hint}`);
|
||
}
|
||
if (!res.ok) throw new ApiError(res.status, data?.error ?? res.statusText);
|
||
return data as T;
|
||
}
|
||
|
||
/** Called when the session expired (set by the app to show the login). */
|
||
let onUnauthorized: (() => void) | undefined;
|
||
export function setUnauthorizedHandler(fn: () => void) {
|
||
onUnauthorized = fn;
|
||
}
|
||
|
||
export const get = <T = any>(path: string) => api<T>(path);
|
||
export const post = <T = any>(path: string, json?: unknown) => api<T>(path, { method: "POST", json: json ?? {} });
|
||
export const patch = <T = any>(path: string, json: unknown) => api<T>(path, { method: "PATCH", json });
|
||
export const put = <T = any>(path: string, json: unknown) => api<T>(path, { method: "PUT", json });
|
||
export const del = <T = any>(path: string) => api<T>(path, { method: "DELETE" });
|
||
|
||
/** WebSocket with automatic reconnect. `onOpen` runs after every (re)connect so
|
||
* the caller can resync state that may have been missed. */
|
||
export function connectEvents(handlers: {
|
||
onEvent: (ev: ServerEvent) => void;
|
||
onOpen: () => void;
|
||
onClose: () => void;
|
||
}): () => void {
|
||
let ws: WebSocket | null = null;
|
||
let stopped = false;
|
||
let retry = 0;
|
||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||
|
||
const open = () => {
|
||
const proto = location.protocol === "https:" ? "wss" : "ws";
|
||
ws = new WebSocket(`${proto}://${location.host}/api/ws`);
|
||
ws.onopen = () => {
|
||
retry = 0;
|
||
reportVisibility();
|
||
handlers.onOpen();
|
||
};
|
||
ws.onmessage = (m) => {
|
||
try {
|
||
handlers.onEvent(JSON.parse(m.data));
|
||
} catch {
|
||
/* ignore malformed */
|
||
}
|
||
};
|
||
ws.onclose = () => {
|
||
handlers.onClose();
|
||
if (stopped) return;
|
||
retry = Math.min(retry + 1, 6);
|
||
timer = setTimeout(open, 500 * 2 ** retry);
|
||
};
|
||
};
|
||
open();
|
||
// Reconnect immediately when the app comes back to the foreground (mobile PWA).
|
||
// The server sends push notifications only while no app window is visible.
|
||
const reportVisibility = () => {
|
||
if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "visibility", visible: document.visibilityState === "visible" }));
|
||
};
|
||
const onVisible = () => {
|
||
reportVisibility();
|
||
if (document.visibilityState === "visible" && ws && ws.readyState > WebSocket.OPEN) {
|
||
clearTimeout(timer);
|
||
open();
|
||
}
|
||
};
|
||
document.addEventListener("visibilitychange", onVisible);
|
||
return () => {
|
||
stopped = true;
|
||
clearTimeout(timer);
|
||
document.removeEventListener("visibilitychange", onVisible);
|
||
ws?.close();
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Upload a single file in chunks (see uploads.ts). `onProgress` gets the uploaded fraction 0..1.
|
||
* Without the progress panel – use `uploadBatch` for user-visible uploads.
|
||
*/
|
||
export async function uploadFile(path: string, file: Blob, onProgress?: (fraction: number) => void): Promise<void> {
|
||
await chunkedUpload(`/api/files/upload?path=${encodeURIComponent(path)}`, file, (n) => onProgress?.(file.size ? n / file.size : 1));
|
||
}
|