// Single API client: one place for fetch, JSON, the error envelope, and request // cancellation. Every method accepts an optional { signal } from cancellable(). export const BASE = "/api/v1"; // The API refuses every request without the session cookie, and every mutation // without this token echoed back. The token is readable only same-origin, which is // what makes it proof that the caller is this app and not another page. let csrfToken = null; async function session() { if (csrfToken === null) { const response = await fetch(BASE + "/session", { credentials: "same-origin" }); const body = await response.json().catch(() => null); csrfToken = (body && body.csrf_token) || null; } return csrfToken || ""; } async function send(path, { signal, ...options }) { return fetch(BASE + path, { credentials: "same-origin", signal, ...options, headers: { "Content-Type": "application/json", "X-CSRF-Token": await session(), ...(options.headers || {}), }, }); } async function request(path, { signal, ...options } = {}) { let response; try { response = await send(path, { signal, ...options }); // A restarted server issues a new session; re-bootstrap once rather than // stranding an open tab on 401. if (response.status === 401) { csrfToken = null; response = await send(path, { signal, ...options }); } } catch (error) { // A caller-cancelled fetch is not a failure; tag it so views can ignore it. if (error.name === "AbortError") { error.code = "cancelled"; } throw error; } let body = null; try { body = await response.json(); } catch (_) { body = null; } if (!response.ok) { const envelope = body && body.error ? body.error : {}; const error = new Error(envelope.message || response.statusText); error.status = response.status; error.code = envelope.code || "error"; throw error; } return body; } // Cancellation: hand callers a signal to pass into any request and a cancel() to // abort the in-flight fetch. Aborted requests reject with code "cancelled". export function cancellable() { const controller = new AbortController(); return { signal: controller.signal, cancel: () => controller.abort() }; } export const api = { listAssets: (params = {}, opts = {}) => request("/inventory/assets?" + new URLSearchParams(params).toString(), opts), listClusters: (params = {}, opts = {}) => request("/duplicates/clusters?" + new URLSearchParams(params).toString(), opts), getCluster: (id, params = {}, opts = {}) => { const query = new URLSearchParams(params).toString(); return request(`/duplicates/clusters/${encodeURIComponent(id)}${query ? `?${query}` : ""}`, opts); }, decide: (id, payload, opts = {}) => request(`/duplicates/clusters/${encodeURIComponent(id)}/decision`, { method: "POST", body: JSON.stringify(payload), ...opts, }), thumbnailUrl: (assetId, size = 512) => `${BASE}/assets/${encodeURIComponent(assetId)}/thumbnail?size=${size}`, // ── Jobs ──────────────────────────────────────────────────────────────── startJob: (payload, opts = {}) => request("/jobs", { method: "POST", body: JSON.stringify(payload), ...opts }), getJob: (id, opts = {}) => request(`/jobs/${encodeURIComponent(id)}`, opts), cancelJob: (id, opts = {}) => request(`/jobs/${encodeURIComponent(id)}/cancel`, { method: "POST", ...opts }), jobEvents: (id, after = 0, opts = {}) => request(`/jobs/${encodeURIComponent(id)}/events?after=${after}`, opts), jobEventsStreamUrl: (id, after = 0) => `${BASE}/jobs/${encodeURIComponent(id)}/events/stream?after=${after}`, // ── Workflow / safety / analysis / library ────────────────────────────── workflow: (opts = {}) => request("/workflow", opts), safetyQueue: (params = {}, opts = {}) => request("/safety/queue?" + new URLSearchParams(params).toString(), opts), safetyDecide: (payload, opts = {}) => request("/safety/decisions", { method: "POST", body: JSON.stringify(payload), ...opts }), safetyScoreJob: (opts = {}) => request("/safety/jobs", { method: "POST", ...opts }), analysisCounts: (opts = {}) => request("/analysis/counts", opts), analysisJob: (opts = {}) => request("/analysis/jobs", { method: "POST", ...opts }), libraryAssets: (params = {}, opts = {}) => request("/library/assets?" + new URLSearchParams(params).toString(), opts), libraryStats: (opts = {}) => request("/library/stats", opts), // ── Albums: evidence and naming proposals ─────────────────────────────── albumEvidence: (params = {}, opts = {}) => request("/albums/evidence?" + new URLSearchParams(params).toString(), opts), albumProposals: (params = {}, opts = {}) => request("/albums/proposals?" + new URLSearchParams(params).toString(), opts), generateProposals: (payload = {}, opts = {}) => request("/albums/proposals", { method: "POST", body: JSON.stringify(payload), ...opts }), editProposal: (album, payload, opts = {}) => request(`/albums/proposals/${encodeURIComponent(album)}/edit`, { method: "POST", body: JSON.stringify(payload), ...opts, }), approveProposal: (album, payload, opts = {}) => request(`/albums/proposals/${encodeURIComponent(album)}/approve`, { method: "POST", body: JSON.stringify(payload), ...opts, }), // ── Renames: plan, confirm, apply, recover ────────────────────────────── listPlans: (opts = {}) => request("/rename-plans", opts), buildPlan: (opts = {}) => request("/rename-plans", { method: "POST", ...opts }), getPlan: (id, opts = {}) => request(`/rename-plans/${encodeURIComponent(id)}`, opts), applyPlan: (id, payload, opts = {}) => request(`/rename-plans/${encodeURIComponent(id)}/apply`, { method: "POST", body: JSON.stringify(payload), ...opts, }), rollbackPlan: (id, opts = {}) => request(`/rename-plans/${encodeURIComponent(id)}/rollback`, { method: "POST", ...opts }), renameRecovery: (opts = {}) => request("/rename-recovery", opts), resolveRecovery: (opts = {}) => request("/rename-recovery/resolve", { method: "POST", ...opts }), // ── Uploads: preflight, batches, verification ─────────────────────────── // The API key never travels through here: preflight reports only whether one is // configured, and every command preview arrives already redacted. uploadPreflight: (payload = {}, opts = {}) => request("/upload-preflight", { method: "POST", body: JSON.stringify(payload), ...opts }), createUploadBatches: (payload, opts = {}) => request("/upload-batches", { method: "POST", body: JSON.stringify(payload), ...opts }), listUploadBatches: (opts = {}) => request("/upload-batches", opts), getUploadBatch: (id, opts = {}) => request(`/upload-batches/${encodeURIComponent(id)}`, opts), startUploadBatch: (id, opts = {}) => request(`/upload-batches/${encodeURIComponent(id)}/start`, { method: "POST", ...opts }), cancelUploadBatch: (id, opts = {}) => request(`/upload-batches/${encodeURIComponent(id)}/cancel`, { method: "POST", ...opts }), verifyUploadBatch: (id, opts = {}) => request(`/upload-batches/${encodeURIComponent(id)}/verify`, { method: "POST", ...opts }), resolveUploadItem: (id, payload, opts = {}) => request(`/upload-batches/${encodeURIComponent(id)}/resolve`, { method: "POST", body: JSON.stringify(payload), ...opts, }), uploadVerifications: (id, opts = {}) => request(`/upload-batches/${encodeURIComponent(id)}/verifications`, opts), // ── Archive and restore: destinations, preflight, plans, recovery ──────── archiveLocations: (opts = {}) => request("/archive-locations", opts), registerArchiveLocation: (payload, opts = {}) => request("/archive-locations", { method: "POST", body: JSON.stringify(payload), ...opts }), archivePreflight: (payload, opts = {}) => request("/archive-preflight", { method: "POST", body: JSON.stringify(payload), ...opts }), createArchivePlan: (payload, opts = {}) => request("/archive-plans", { method: "POST", body: JSON.stringify(payload), ...opts }), listArchivePlans: (opts = {}) => request("/archive-plans", opts), getArchivePlan: (id, opts = {}) => request(`/archive-plans/${encodeURIComponent(id)}`, opts), applyArchivePlan: (id, opts = {}) => request(`/archive-plans/${encodeURIComponent(id)}/apply`, { method: "POST", ...opts }), archiveRecovery: (opts = {}) => request("/archive-recovery", opts), resolveArchiveRecovery: (opts = {}) => request("/archive-recovery/resolve", { method: "POST", ...opts }), restorePreflight: (payload, opts = {}) => request("/restore-preflight", { method: "POST", body: JSON.stringify(payload), ...opts }), createRestorePlan: (payload, opts = {}) => request("/restore-plans", { method: "POST", body: JSON.stringify(payload), ...opts }), listRestorePlans: (opts = {}) => request("/restore-plans", opts), getRestorePlan: (id, opts = {}) => request(`/restore-plans/${encodeURIComponent(id)}`, opts), applyRestorePlan: (id, opts = {}) => request(`/restore-plans/${encodeURIComponent(id)}/apply`, { method: "POST", ...opts }), restoreRecovery: (opts = {}) => request("/restore-recovery", opts), resolveRestoreRecovery: (opts = {}) => request("/restore-recovery/resolve", { method: "POST", ...opts }), };