Files
codecraft/web/src/api.ts
T
Richard ZinkandClaude Opus 5.5 a0d0e707f2 Add Web Push, guided start screen, SVG icons, chunked uploads, rename
- Web Push (VAPID + RFC 8291, pure Rust): permission/question/finished
  notifications while no app window is visible; settings with test button
- Guided new-session flow: task, craft target (website/app/game/old
  software/fresh), clean room or deep, description, model, folder
  (new, existing or cloned git repository); originals upload to original/
- Craft phase bar (craft_phase tool) for study/specify/build/check/ready
- Chunked uploads (8 MB) up to server.max_upload_mb (default 500 MB)
- All UI glyphs and emojis replaced by themeable SVG icons
- Rename dialog with manual name or model-generated suggestion

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:03:26 +01:00

128 lines
4.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { ServerEvent } from "./types";
// 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();
};
}
const CHUNK = 8 * 1024 * 1024;
/**
* Upload a file in 8 MB chunks (stays below reverse proxy body limits; up to the
* server's max_upload_mb). `onProgress` gets the uploaded fraction 0..1.
*/
export async function uploadFile(path: string, file: Blob, onProgress?: (fraction: number) => void): Promise<void> {
let offset = 0;
do {
const chunk = file.slice(offset, offset + CHUNK);
const res = await fetch(`/api/files/upload?path=${encodeURIComponent(path)}&offset=${offset}`, { method: "PUT", body: chunk, credentials: "same-origin" });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try {
msg = (await res.json()).error ?? msg;
} catch {
if (res.status === 413) msg = "too large for the reverse proxy";
}
throw new Error(msg);
}
offset += chunk.size;
onProgress?.(file.size ? offset / file.size : 1);
} while (offset < file.size);
}