oweme/apps/web/src/lib/api.ts
agent 8fbbb4933e Add Svelte web client and service worker
Mobile-first PWA: groups via key-in-fragment links, encrypted outbox and
sync over SSE, all split modes, currencies with ECB rate prefill, photos,
comments, history and rewind, stats, recurring expenses, CSV and backup,
EN/CS, dark/light theme, Web Push decrypted in the service worker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:59:16 +00:00

90 lines
3.8 KiB
TypeScript

// Thin wrappers around the server API (SPEC.md §8.1).
import type { StoredEvent } from './idb.ts';
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
/** True for errors that mean "try again later" rather than "this is wrong". */
export const isOffline = (e: unknown) => !(e instanceof ApiError) || e.status >= 500 || e.status === 429;
async function req<T>(method: string, path: string, opts: { token?: string; json?: unknown; body?: BodyInit; signal?: AbortSignal } = {}): Promise<T> {
const headers: Record<string, string> = {};
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
if (opts.json !== undefined) headers['Content-Type'] = 'application/json';
const res = await fetch(path, {
method,
headers,
body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body,
signal: opts.signal,
cache: 'no-store',
});
if (!res.ok) {
let msg = res.statusText;
try {
msg = (await res.json()).error ?? msg;
} catch { /* not JSON */ }
throw new ApiError(res.status, msg);
}
const type = res.headers.get('content-type') ?? '';
return (type.includes('application/json') ? res.json() : res.arrayBuffer()) as Promise<T>;
}
export interface ServerConfig {
vapidPublicKey: string | null;
maxPhotoBytes: number;
maxGroupBytes: number;
}
let configP: Promise<ServerConfig> | null = null;
export function serverConfig(): Promise<ServerConfig> {
configP ??= req<ServerConfig>('GET', '/api/config').catch((e) => {
configP = null;
throw e;
});
return configP;
}
export const api = {
createGroup: (id: string, authHash: string) => req('POST', '/api/groups', { json: { id, authHash } }),
deleteGroup: (id: string, token: string) => req('DELETE', `/api/groups/${id}`, { token }),
events: (id: string, token: string, after: number) =>
req<{ events: Omit<StoredEvent, 'g'>[]; latest: number }>('GET', `/api/groups/${id}/events?after=${after}&limit=500`, { token }),
append: (id: string, token: string, events: Omit<StoredEvent, 'g' | 'seq'>[]) =>
req<{ seqs: number[] }>('POST', `/api/groups/${id}/events`, { token, json: { events } }),
putBlob: (id: string, token: string, blobId: string, data: ArrayBuffer) =>
req('PUT', `/api/groups/${id}/blobs/${blobId}`, { token, body: data }),
getBlob: (id: string, token: string, blobId: string) => req<ArrayBuffer>('GET', `/api/groups/${id}/blobs/${blobId}`, { token }),
pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) =>
req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }),
pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }),
rates: (date: string) => req<{ base: string; date: string; rates: Record<string, string> }>('GET', `/api/rates?date=${date}`),
};
/**
* Listen for "new seq" pings on the group's SSE stream. EventSource can't
* send an Authorization header, so this reads the stream with fetch.
* Resolves when the stream ends; throws on errors.
*/
export async function listen(id: string, token: string, signal: AbortSignal, onSeq: (seq: number) => void): Promise<void> {
const res = await fetch(`/api/groups/${id}/stream`, { headers: { Authorization: `Bearer ${token}` }, signal, cache: 'no-store' });
if (!res.ok || !res.body) throw new ApiError(res.status, 'stream failed');
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = '';
for (;;) {
const { value, done } = await reader.read();
if (done) return;
buf += value;
let i: number;
while ((i = buf.indexOf('\n\n')) >= 0) {
const msg = buf.slice(0, i);
buf = buf.slice(i + 2);
const m = /^data: (\d+)$/m.exec(msg);
if (m) onSeq(Number(m[1]));
}
}
}