import { ref } from "vue"; import { useEventsStore } from "@/stores/events"; import { api } from "@/lib/api"; import type { Source, SourceRefusals } from "./source-signing"; /** * The sources list and its writes. A write that generates a secret keeps the * returned source in `revealed` until dismissed: it is the only time the * browser ever holds that secret. */ export function useSources() { // null means loading, [] means loaded and empty. const sources = ref(null); const failure = ref(null); const revealed = ref(null); const refusals = ref>({}); const busy = ref(false); function message(err: unknown): string { return err instanceof Error && err.message ? err.message : String(err); } async function load(): Promise { try { const res = await api.sources<{ sources?: Source[]; refusals?: Record; }>(useEventsStore().workspace); sources.value = res.sources || []; refusals.value = res.refusals || {}; failure.value = null; } catch (err) { failure.value = message(err); } } async function run(write: () => Promise): Promise { busy.value = true; failure.value = null; try { const result = await write(); if (result?.secret) revealed.value = result; await load(); } catch (err) { failure.value = message(err); } finally { busy.value = false; } } return { sources, failure, revealed, refusals, busy, load, create: (path: string) => run(() => api.sourceCreate(path.trim(), useEventsStore().workspace)), newSecret: (source: Source) => run(() => api.sourceSecret(source.path)), requestUnsigned: (source: Source) => run(() => api.sourceSigning(source.path, false)), requireSigning: (source: Source) => run(() => api.sourceSigning(source.path, true)), approveUnsigned: (source: Source) => run(() => api.sourceApproveUnsigned(source.path)), rename: (source: Source, name: string) => run(() => api.sourceName(source.path, name.trim())), setDeliveryHeader: (source: Source, header: string) => run(() => api.sourceDeliveryHeader(source.path, header.trim())), // An armed binding on the source refuses the delete; the refusal shows // as the panel's failure. remove: (source: Source) => run(() => api.sourceDelete(source.path)), }; }