Something went wrong. Try again.
A lexicon-driven AppView for ATProto. happyview.dev
backfill firehose jetstream atproto appview oauth lexicon
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593import type { ApiKeySummary, CreateApiKeyResponse } from "@/types/api-keys";import type { StatsResponse } from "@/types/stats";import type { LexiconSummary, LexiconDetail } from "@/types/lexicons";import type { NetworkLexiconSummary } from "@/types/network-lexicons";import type { ResolvedIdentity } from "@/types/identity";import type { BackfillJob, BackfillReposResponse, PdsSummaryResponse, BackfillErrorsResponse,} from "@/types/backfill";import type { Job, JobLogsResponse, JobsListResponse } from "@/types/jobs";import type { CreateLinkedRepoBody, LinkedRepo, LinkedReposListResponse,} from "@/types/linked-repos";import type { UserSummary } from "@/types/users";import type { AdminListRecordsResponse } from "@/types/records";import type { AdminListSpaceRecordsResponse, AdminListSpacesResponse, AdminSpaceDetail, AccessGrant, GrantScope, InspectorStatus, AdminAccountSpace, AdminAccountRecord,} from "@/types/spaces";import type { EventLogEntry, EventsListResponse } from "@/types/events";import type { ScriptVariableSummary } from "@/types/script-variables";import type { Script, UpsertScriptBody, PatchScriptBody,} from "@/types/scripts";import type { LabelerSummary } from "@/types/labelers";import type { ApiClientSummary, CreateApiClientResponse, ApiClientAuthKey, ApiClientAuthProbe, ApiClientAuthKeysResponse, RevokeApiClientAuthKeyResult, RevokeAllApiClientAuthKeysResult, KeyRotationResult, InstanceOauthKeysResponse, RevokeInstanceKeyResult,} from "@/types/api-clients";import type { SettingEntry } from "@/types/settings";import type { ExternalProvider, LinkedAccount, AuthorizeResponse, SyncResponse, UnlinkResponse, ConnectResponse,} from "@/types/external-accounts";import type { DeadLettersListResponse, DeadLetterDetail, DeadLetterCountResponse, BulkActionResponse,} from "@/types/dead-letters";
export type { ApiKeySummary, CreateApiKeyResponse } from "@/types/api-keys";export type { CollectionStat, StatsResponse } from "@/types/stats";export type { LexiconSummary, LexiconDetail } from "@/types/lexicons";export type { NetworkLexiconSummary } from "@/types/network-lexicons";export type { BackfillJob, BackfillRepoEntry, BackfillReposResponse, PdsSummaryEntry, PdsSummaryResponse, BackfillEvent, BlueskyProfile,} from "@/types/backfill";export type { LinkedRepo, LinkedReposListResponse, CreateLinkedRepoBody,} from "@/types/linked-repos";export type { UserSummary } from "@/types/users";export type { AdminRecord, AdminListRecordsResponse } from "@/types/records";export type { EventLogEntry, EventsListResponse } from "@/types/events";export type { ScriptVariableSummary } from "@/types/script-variables";export type { Script, ScriptLanguage, TriggerKind, TriggerFamily, UpsertScriptBody, PatchScriptBody,} from "@/types/scripts";export { TRIGGER_KIND_LABELS, TRIGGER_FAMILY_LABELS, familyOf, parseTriggerId, DEFAULT_SCRIPT_BODY,} from "@/types/scripts";export type { LabelerSummary } from "@/types/labelers";export type { RecordLabel } from "@/types/records";export type { ApiClientSummary, CreateApiClientResponse, ApiClientAuthKey, ApiClientAuthProbe, ApiClientAuthKeysResponse, RevokeApiClientAuthKeyResult, RevokeAllApiClientAuthKeysResult, KeyRotationResult, InstanceOauthKey, InstanceOauthKeysResponse, RevokeInstanceKeyResult,} from "@/types/api-clients";export type { SettingEntry, InstanceSettings } from "@/types/settings";export { INSTANCE_SETTING_KEYS } from "@/types/settings";export type { ExternalProvider, LinkedAccount, AuthorizeResponse, SyncResponse, UnlinkResponse, ConnectResponse, ConfigSchema, ConfigProperty,} from "@/types/external-accounts";export type { DeadLetterSummary, DeadLetterDetail, DeadLettersListResponse, DeadLetterCountResponse, BulkActionResponse,} from "@/types/dead-letters";
const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH || "";
export class ApiError extends Error { status: number; constructor(status: number, message: string) { super(message); this.status = status; }}
async function apiFetch<T = unknown>( path: string, options?: RequestInit,): Promise<T> { const headers: Record<string, string> = {}; if ( options?.method === "POST" || options?.method === "PUT" || options?.method === "PATCH" ) { headers["Content-Type"] = "application/json"; }
const res = await fetch(`${BASE_PATH}${path}`, { ...options, headers: { ...headers, ...options?.headers }, credentials: "same-origin", });
if (!res.ok) { const text = await res.text().catch(() => res.statusText); let message = text; try { const parsed = JSON.parse(text); if (typeof parsed.error === "string") message = parsed.error; } catch { /* not JSON, use raw text */ } throw new ApiError(res.status, message); } if (res.status === 204) return null as T; const text = await res.text(); if (!text) return null as T; return JSON.parse(text);}
// Statsexport function getStats() { return apiFetch<StatsResponse>("/admin/stats");}
export function getCollections() { return apiFetch<{ collections: string[] }>("/admin/records/collections");}
// Lexiconsexport function getLexicons() { return apiFetch<LexiconSummary[]>("/admin/lexicons");}
export function getLexicon(id: string) { return apiFetch<LexiconDetail>(`/admin/lexicons/${encodeURIComponent(id)}`);}
export function uploadLexicon(body: { lexicon_json: unknown; backfill?: boolean; target_collection?: string; action?: string; token_cost?: number | null;}) { return apiFetch<{ id: string; revision: number }>("/admin/lexicons", { method: "POST", body: JSON.stringify(body), });}
export function deleteLexicon(id: string) { return apiFetch(`/admin/lexicons/${encodeURIComponent(id)}`, { method: "DELETE", });}
// Network Lexiconsexport function getNetworkLexicons() { return apiFetch<NetworkLexiconSummary[]>("/admin/network-lexicons");}
export function resolveNetworkLexicon(nsid: string, signal?: AbortSignal) { return apiFetch<{ nsid: string; authority_did: string; type: string | null; lexicon_json: Record<string, unknown>; }>(`/admin/network-lexicons/resolve/${encodeURIComponent(nsid)}`, { signal });}
export function addNetworkLexicon(body: { nsid: string; backfill?: boolean; target_collection?: string;}) { return apiFetch<{ nsid: string; authority_did: string; revision: number; backfill_job_id: string | null; }>( "/admin/network-lexicons", { method: "POST", body: JSON.stringify(body) }, );}
export function deleteNetworkLexicon(nsid: string) { return apiFetch(`/admin/network-lexicons/${encodeURIComponent(nsid)}`, { method: "DELETE", });}
// Backfillexport function getBackfillJobs() { return apiFetch<BackfillJob[]>("/admin/backfill/status");}
export function createBackfillJob(body: { collection?: string; dids?: string[] }) { return apiFetch<{ id: string; status: string }>("/admin/backfill", { method: "POST", body: JSON.stringify(body), });}
export function cancelBackfillJob(id: string) { return apiFetch<{ id: string; status: string }>( `/admin/backfill/${id}/cancel`, { method: "POST" }, );}
export function pauseBackfillJob(id: string) { return apiFetch<{ id: string; status: string }>( `/admin/backfill/${id}/pause`, { method: "POST" }, );}
export function resumeBackfillJob(id: string) { return apiFetch<{ id: string; status: string }>( `/admin/backfill/${id}/resume`, { method: "POST" }, );}
export function getBackfillRepos( jobId: string, params: { phase?: string; cursor?: string; limit?: number } = {},) { const search = new URLSearchParams(); if (params.phase) search.set("phase", params.phase); if (params.cursor) search.set("cursor", params.cursor); if (params.limit) search.set("limit", String(params.limit)); const qs = search.toString(); return apiFetch<BackfillReposResponse>( `/admin/backfill/${jobId}/repos${qs ? `?${qs}` : ""}`, );}
export function getBackfillPdsSummary(jobId: string) { return apiFetch<PdsSummaryResponse>(`/admin/backfill/${jobId}/pds-summary`);}
export function flushBackfillDetails(jobId: string) { return apiFetch(`/admin/backfill/${jobId}/details`, { method: "DELETE" });}
export function flushAllBackfillDetails() { return apiFetch(`/admin/backfill/details`, { method: "DELETE" });}
export function getBackfillErrors( jobId: string, params: { kind?: string; cursor?: string; limit?: number } = {},) { const search = new URLSearchParams(); if (params.kind) search.set("kind", params.kind); if (params.cursor) search.set("cursor", params.cursor); if (params.limit) search.set("limit", String(params.limit)); const qs = search.toString(); return apiFetch<BackfillErrorsResponse>( `/admin/backfill/${jobId}/errors${qs ? `?${qs}` : ""}`, );}
export function retryFailedBackfill(jobId: string, kinds?: string[]) { return apiFetch<{ id: string }>(`/admin/backfill/${jobId}/retry-failed`, { method: "POST", body: JSON.stringify(kinds ? { kinds } : {}), });}
// Jobsexport function getJobs( params: { status?: string; limit?: number; cursor?: string } = {},) { const qs = new URLSearchParams(); if (params.status) qs.set("status", params.status); if (params.limit) qs.set("limit", String(params.limit)); if (params.cursor) qs.set("cursor", params.cursor); const query = qs.toString(); return apiFetch<JobsListResponse>(`/admin/jobs${query ? `?${query}` : ""}`);}
export function getJob(id: string) { return apiFetch<Job>(`/admin/jobs/${id}`);}
export function cancelJob(id: string) { return apiFetch<{ status: string }>(`/admin/jobs/${id}/cancel`, { method: "POST", });}
export function pauseJob(id: string) { return apiFetch<{ status: string }>(`/admin/jobs/${id}/pause`, { method: "POST", });}
export function resumeJob(id: string) { return apiFetch<{ status: string }>(`/admin/jobs/${id}/resume`, { method: "POST", });}
export function getJobLogs( id: string, params: { limit?: number; cursor?: string } = {},) { const qs = new URLSearchParams(); if (params.limit) qs.set("limit", String(params.limit)); if (params.cursor) qs.set("cursor", params.cursor); const query = qs.toString(); return apiFetch<JobLogsResponse>( `/admin/jobs/${id}/logs${query ? `?${query}` : ""}`, );}
// Linked Reposexport function getLinkedRepos() { return apiFetch<LinkedReposListResponse>("/admin/linked-repos");}
export function createLinkedRepo(body: CreateLinkedRepoBody) { return apiFetch<LinkedRepo>("/admin/linked-repos", { method: "POST", body: JSON.stringify(body), });}
export function authorizeLinkedRepo(id: string) { return apiFetch<{ authorize_url: string }>( `/admin/linked-repos/${id}/authorize`, { method: "POST" }, );}
export function inviteLinkedRepo(id: string) { return apiFetch<{ invite_url: string; expires_at: string }>( `/admin/linked-repos/${id}/invite`, { method: "POST" }, );}
export function deleteLinkedRepo(id: string) { return apiFetch<{ deleted: boolean }>(`/admin/linked-repos/${id}`, { method: "DELETE", });}
// Linked Repos — outstanding invites. `invite_id` is the stored SHA-256 of// the token, not the token itself: the actual link is only ever returned// once, at mint time, so this list is metadata-only by design.export interface LinkedRepoInvite { invite_id: string; expires_at: string;}
export interface LinkedRepoInvitesResponse { invites: LinkedRepoInvite[];}
export function getLinkedRepoInvites(id: string) { return apiFetch<LinkedRepoInvitesResponse>( `/admin/linked-repos/${id}/invites`, );}
export function revokeLinkedRepoInvite(id: string, inviteId: string) { return apiFetch<{ revoked: boolean }>( `/admin/linked-repos/${id}/invites/${encodeURIComponent(inviteId)}`, { method: "DELETE" }, );}
// Linked Repos — public invite landing page (unauthenticated, token-gated)export interface LinkedRepoInviteInfo { valid: boolean; app_name: string; logo_url: string | null; scopes: string[]; reason: string | null; pinned_identifier: string | null; expires_at: string | null;}
export function getLinkedRepoInvite(token: string) { return apiFetch<LinkedRepoInviteInfo>( `/auth/linked-repo/info?token=${encodeURIComponent(token)}`, );}
// Usersexport function getUsers() { return apiFetch<UserSummary[]>("/admin/users");}
export function getUser(id: string) { return apiFetch<UserSummary>(`/admin/users/${encodeURIComponent(id)}`);}
export function addUser(body: { did: string; template?: string; permissions?: string[];}) { return apiFetch<{ id: string; did: string }>("/admin/users", { method: "POST", body: JSON.stringify(body), });}
export function resolveIdentity( identifier: string, options: { profile?: boolean } = {},) { const params = new URLSearchParams({ identifier }); if (options.profile) params.set("profile", "true"); const qs = params.toString(); return apiFetch<ResolvedIdentity>(`/admin/identity/resolve?${qs}`);}
export function deleteUser(id: string) { return apiFetch(`/admin/users/${encodeURIComponent(id)}`, { method: "DELETE", });}
export function updateUserPermissions( id: string, body: { grant?: string[]; revoke?: string[] },) { return apiFetch(`/admin/users/${encodeURIComponent(id)}/permissions`, { method: "PATCH", body: JSON.stringify(body), });}
export function transferSuper(body: { target_user_id: string }) { return apiFetch("/admin/users/transfer-super", { method: "POST", body: JSON.stringify(body), });}
// Permissions catalogexport type PermissionEntry = { key: string; name: string; description: string; category: string;};
export type PermissionTemplate = { key: string; label: string; permissions: string[];};
export type PermissionsCatalog = { permissions: PermissionEntry[]; templates: PermissionTemplate[];};
export function getPermissions() { return apiFetch<PermissionsCatalog>("/admin/permissions");}
// API Keysexport function getApiKeys() { return apiFetch<ApiKeySummary[]>("/admin/api-keys");}
export function createApiKey(body: { name: string; permissions: string[] }) { return apiFetch<CreateApiKeyResponse>("/admin/api-keys", { method: "POST", body: JSON.stringify(body), });}
export function revokeApiKey(id: string) { return apiFetch(`/admin/api-keys/${encodeURIComponent(id)}`, { method: "DELETE", });}
// XRPC (public, no auth needed)export async function xrpcQuery<T = unknown>( method: string, params?: Record<string, string>,): Promise<T> { const search = params ? `?${new URLSearchParams(params)}` : ""; const res = await fetch( `${BASE_PATH}/xrpc/${encodeURIComponent(method)}${search}`, ); if (!res.ok) { const text = await res.text().catch(() => res.statusText); let message = text; try { const parsed = JSON.parse(text); if (typeof parsed.error === "string") message = parsed.error; } catch { /* not JSON, use raw text */ } throw new ApiError(res.status, message); } return res.json();}
// Admin records browsingexport function getAdminRecords( collection: string, limit?: number, cursor?: string,) { const params = new URLSearchParams({ collection }); if (limit) params.set("limit", String(limit)); if (cursor) params.set("cursor", cursor); return apiFetch<AdminListRecordsResponse>(`/admin/records?${params}`);}
export function deleteRecord(uri: string) { return apiFetch(`/admin/records?${new URLSearchParams({ uri })}`, { method: "DELETE", });}
export function getAdminSpaces(limit?: number, cursor?: string) { const params = new URLSearchParams(); if (limit) params.set("limit", String(limit)); if (cursor) params.set("cursor", cursor); return apiFetch<AdminListSpacesResponse>(`/admin/spaces?${params}`);}
export function getAdminSpace(id: string) { return apiFetch<AdminSpaceDetail>(`/admin/spaces/${encodeURIComponent(id)}`);}
/** Reading a space's records is written to the event log. */export function getAdminSpaceRecords( id: string, options: { repo?: string; collection?: string; limit?: number; cursor?: string; } = {},) { const params = new URLSearchParams(); if (options.repo) params.set("repo", options.repo); if (options.collection) params.set("collection", options.collection); if (options.limit) params.set("limit", String(options.limit)); if (options.cursor) params.set("cursor", options.cursor); return apiFetch<AdminListSpaceRecordsResponse>( `/admin/spaces/${encodeURIComponent(id)}/records?${params}`, );}
/** Opening this URL is written to the event log. */export function adminSpaceBlobUrl(id: string, cid: string) { return `${BASE_PATH}/admin/spaces/${encodeURIComponent(id)}/blob?${new URLSearchParams({ cid })}`;}
export const SPACE_ACCESS_GRANT_REQUIRED = "SpaceAccessGrantRequired";export const SPACE_INSPECTOR_DISABLED = "SpaceInspectorDisabled";
export function getInspectorStatus() { return apiFetch<InspectorStatus>("/admin/spaces/inspector");}
/** The caller's active grant covering an account's records, if any. */export function getAccountAccess(did: string) { return apiFetch<{ grant: AccessGrant | null }>( `/admin/accounts/${encodeURIComponent(did)}/access`, );}
/** The caller's active grant covering a space's page, if any. */export function getSpaceAccess(id: string) { return apiFetch<{ grant: AccessGrant | null }>( `/admin/spaces/${encodeURIComponent(id)}/access`, );}
export function listAccessGrants(active = true) { return apiFetch<{ grants: AccessGrant[] }>( `/admin/spaces/access-grants?active=${active}`, );}
export function createAccessGrant(body: { scope: GrantScope; target: string; reason: string; duration_minutes: number;}) { return apiFetch<AccessGrant>("/admin/spaces/access-grants", { method: "POST", body: JSON.stringify(body), });}
export function revokeAccessGrant(id: string) { return apiFetch<AccessGrant>( `/admin/spaces/access-grants/${encodeURIComponent(id)}`, { method: "DELETE" }, );}
/** One page of the reads made under a grant, oldest first. */export function getGrantReads(id: string, cursor?: string) { const params = new URLSearchParams(); if (cursor) params.set("cursor", cursor); const qs = params.toString(); return apiFetch<{ events: EventLogEntry[]; cursor?: string }>( `/admin/spaces/access-grants/${encodeURIComponent(id)}/reads${qs ? `?${qs}` : ""}`, );}
export function getAccountSpaces(did: string) { return apiFetch<{ spaces: AdminAccountSpace[] }>( `/admin/accounts/${encodeURIComponent(did)}/spaces`, );}
/** Reading an account's records is written to the event log. */export function getAccountSpaceRecords( did: string, options: { space?: string; collection?: string; limit?: number; cursor?: string; } = {},) { const params = new URLSearchParams(); if (options.space) params.set("space", options.space); if (options.collection) params.set("collection", options.collection); if (options.limit) params.set("limit", String(options.limit)); if (options.cursor) params.set("cursor", options.cursor); return apiFetch<{ records: AdminAccountRecord[]; cursor?: string }>( `/admin/accounts/${encodeURIComponent(did)}/space-records?${params}`, );}
export function deleteCollectionRecords(collection: string) { return apiFetch<{ job_id: string }>( `/admin/records/collection?${new URLSearchParams({ collection })}`, { method: "DELETE" }, );}
export interface EventPurgeFilter { event_type?: string; category?: string; severity?: string; subject?: string; before?: string; after?: string;}
// Strips blank/undefined entries so `countEvents` and `purgeEvents` always// agree on what "no filter" means for a field — an explicit `""` (e.g. a// filter typed in then cleared) must be treated the same as an absent key,// not sent as a literal empty-string filter.function cleanEventPurgeFilter( filter: EventPurgeFilter,): Record<string, string> { const cleaned: Record<string, string> = {}; for (const [key, value] of Object.entries(filter)) { if (value) cleaned[key] = value; } return cleaned;}
export function countEvents(filter: EventPurgeFilter) { const params = new URLSearchParams(cleanEventPurgeFilter(filter)); return apiFetch<{ count: number }>(`/admin/events/count?${params}`);}
export function purgeEvents(filter: EventPurgeFilter) { return apiFetch<{ job_id: string }>("/admin/events/purge", { method: "POST", body: JSON.stringify(cleanEventPurgeFilter(filter)), });}
// Database (SQLite disk reclamation)export interface DatabaseDiskReport { db_bytes: number; wal_bytes: number; // `null` means free space could not be measured — NOT that it measured // zero. Render that case as "unknown", never as "0 B". db_fs_free: number | null; temp_fs_free: number | null; // Whether the database and temp directories share a filesystem, which // changes how much headroom a VACUUM needs (1.2x vs 2.2x the db size). same_filesystem: boolean; db_path: string; temp_path: string;}
export interface VacuumResult { status: "ok" | "failed"; at: string; db_bytes_before: number; db_bytes_after: number; reclaimed_bytes: number; error: string | null;}
export type VacuumFeasibility = | { status: "ok" } | { status: "insufficient"; needed: number; available: number; path: string } | { status: "unknown"; path: string };
export interface DatabaseStatus { backend: "sqlite" | "postgres"; disk: DatabaseDiskReport | null; feasibility: VacuumFeasibility | null; vacuum: { requested_at: string | null; attempt_started_at: string | null; completed_at: string | null; last_result: VacuumResult | null; }; journal_size_limit: number;}
export function getDatabaseStatus() { return apiFetch<DatabaseStatus>("/admin/database/status");}
export function scheduleVacuum() { return apiFetch<{ scheduled: boolean }>("/admin/database/vacuum/schedule", { method: "POST", });}
export function cancelVacuum() { return apiFetch<{ scheduled: boolean }>("/admin/database/vacuum/schedule", { method: "DELETE", });}
// Telemetry
export interface TelemetrySettings { mode: "off" | "manual" | "auto"; contact: string | null; lexicon_names: boolean; lexicon_structure: boolean; lexicon_documents: boolean; instance_id: string | null; collector_url: string; /** Whether anyone has ever answered the telemetry question on this * instance. False only for instances predating the setup wizard's * telemetry step, which is what the dashboard prompt exists to catch. */ prompted: boolean;}
export interface TelemetryBenchmarkEntry { p50: number; value: number; percentile: number;}
export interface TelemetryBenchmarks { cohort_size: number; metrics: Record<string, TelemetryBenchmarkEntry>;}
/** Every field optional: an omitted field means unchanged. */export interface TelemetryUpdate { mode?: "off" | "manual" | "auto"; contact?: string; lexicon_names?: boolean; lexicon_structure?: boolean; lexicon_documents?: boolean;}
export function getTelemetry() { return apiFetch<TelemetrySettings>("/admin/settings/telemetry");}
export function updateTelemetry(body: TelemetryUpdate) { return apiFetch<TelemetrySettings>("/admin/settings/telemetry", { method: "PUT", body: JSON.stringify(body), });}
/** Record that the telemetry question has been answered, without changing the * answer. Saving any telemetry setting stamps this too; this is the path for * declining — in the setup wizard or by dismissing the dashboard prompt. */export function dismissTelemetryPrompt() { return apiFetch<TelemetrySettings>("/admin/settings/telemetry/dismiss", { method: "POST", });}
export function getTelemetryPreview() { return apiFetch<Record<string, unknown>>("/admin/settings/telemetry/preview");}
export function sendTelemetry() { return apiFetch<{ sent: boolean; benchmarks: TelemetryBenchmarks | null }>( "/admin/settings/telemetry/send", { method: "POST" }, );}
// Script Variablesexport function getScriptVariables() { return apiFetch<ScriptVariableSummary[]>("/admin/script-variables");}
export function upsertScriptVariable(body: { key: string; value: string }) { return apiFetch("/admin/script-variables", { method: "POST", body: JSON.stringify(body), });}
export function deleteScriptVariable(key: string) { return apiFetch(`/admin/script-variables/${encodeURIComponent(key)}`, { method: "DELETE", });}
// Settingsexport function getSettings() { return apiFetch<SettingEntry[]>("/admin/settings");}
export type DbInfo = { backend: "sqlite" | "postgres"; server_max_connections: number | null; main_pool_size: number; backfill_pool_size: number; restart_recommended: boolean;};
export function getDbInfo() { return apiFetch<DbInfo>("/admin/settings/db-info");}
export function upsertSetting(key: string, value: string) { return apiFetch(`/admin/settings/${encodeURIComponent(key)}`, { method: "PUT", body: JSON.stringify({ value }), });}
export function deleteSetting(key: string) { return apiFetch(`/admin/settings/${encodeURIComponent(key)}`, { method: "DELETE", });}
export async function uploadLogo(file: File) { const formData = new FormData(); formData.append("file", file); const res = await fetch(`${BASE_PATH}/admin/settings/logo`, { method: "PUT", body: formData, credentials: "same-origin", }); if (!res.ok) { const text = await res.text().catch(() => res.statusText); let message = text; try { const parsed = JSON.parse(text); if (typeof parsed.error === "string") message = parsed.error; } catch { /* not JSON, use raw text */ } throw new ApiError(res.status, message); }}
export function deleteLogo() { return apiFetch("/admin/settings/logo", { method: "DELETE" });}
// Feature Flagsexport type FeatureFlag = { key: string; name: string; description: string; enabled: boolean;};
export function getFeatureFlags() { return apiFetch<FeatureFlag[]>("/admin/feature-flags");}
export function setFeatureFlag(key: string, enabled: boolean) { if (enabled) { return upsertSetting(key, "true"); } return deleteSetting(key);}
// Proxy configexport type ProxyRouting = "authority" | "serviceproxy";
export type ProxyConfig = { mode: "disabled" | "open" | "allowlist" | "blocklist"; nsids: string[]; /** * Omitted on save means "leave unchanged" — the server preserves the stored * value rather than resetting it, so a form that only edits the mode cannot * silently revert routing. */ routing?: ProxyRouting;};
export function getProxyConfig() { return apiFetch<ProxyConfig>("/admin/settings/xrpc-proxy");}
export function updateProxyConfig(config: ProxyConfig) { return apiFetch("/admin/settings/xrpc-proxy", { method: "PUT", body: JSON.stringify(config), });}
// Labelersexport function getLabelers() { return apiFetch<LabelerSummary[]>("/admin/labelers");}
export function addLabeler(body: { did: string }) { return apiFetch("/admin/labelers", { method: "POST", body: JSON.stringify(body), });}
export function updateLabeler(did: string, body: { status: string }) { return apiFetch(`/admin/labelers/${encodeURIComponent(did)}`, { method: "PATCH", body: JSON.stringify(body), });}
export function deleteLabeler(did: string) { return apiFetch(`/admin/labelers/${encodeURIComponent(did)}`, { method: "DELETE", });}
// API Clientsexport function getApiClients() { return apiFetch<ApiClientSummary[]>("/admin/api-clients");}
export function getApiClient(id: string) { return apiFetch<ApiClientSummary>( `/admin/api-clients/${encodeURIComponent(id)}`, );}
export function createApiClient(body: { name: string; client_id_url: string; client_uri: string; redirect_uris: string[]; scopes?: string; client_type?: string; allowed_origins?: string[]; rate_limit_capacity: number | null; rate_limit_refill_rate: number | null;}) { return apiFetch<CreateApiClientResponse>("/admin/api-clients", { method: "POST", body: JSON.stringify(body), });}
export function updateApiClient( id: string, body: { name?: string; client_uri?: string; redirect_uris?: string[]; scopes?: string; allowed_origins?: string[] | null; rate_limit_capacity?: number | null; rate_limit_refill_rate?: number | null; is_active?: boolean; },) { return apiFetch(`/admin/api-clients/${encodeURIComponent(id)}`, { method: "PUT", body: JSON.stringify(body), });}
export function deleteApiClient(id: string) { return apiFetch(`/admin/api-clients/${encodeURIComponent(id)}`, { method: "DELETE", });}
// API client AT Protocol authentication key (private_key_jwt confidentiality)export function getApiClientAuthKey(id: string) { return apiFetch<ApiClientAuthKey>( `/admin/api-clients/${encodeURIComponent(id)}/auth-key`, );}
export function provisionApiClientAuthKey(id: string) { return apiFetch<ApiClientAuthKey>( `/admin/api-clients/${encodeURIComponent(id)}/auth-key`, { method: "POST" }, );}
export function recheckApiClientAuthKey(id: string) { return apiFetch<ApiClientAuthProbe>( `/admin/api-clients/${encodeURIComponent(id)}/auth-key/recheck`, { method: "POST" }, );}
export function rotateApiClientAuthKey(id: string) { return apiFetch<KeyRotationResult>( `/admin/api-clients/${encodeURIComponent(id)}/auth-key/rotate`, { method: "POST" }, );}
export function listApiClientAuthKeys(id: string) { return apiFetch<ApiClientAuthKeysResponse>( `/admin/api-clients/${encodeURIComponent(id)}/auth-keys`, );}
export function revokeApiClientAuthKey(id: string, kid: string) { return apiFetch<RevokeApiClientAuthKeyResult>( `/admin/api-clients/${encodeURIComponent(id)}/auth-key/${encodeURIComponent(kid)}`, { method: "DELETE" }, );}
export function revokeAllApiClientAuthKeys(id: string) { return apiFetch<RevokeAllApiClientAuthKeysResult>( `/admin/api-clients/${encodeURIComponent(id)}/auth-keys`, { method: "DELETE" }, );}
export function rotateInstanceOauthKey() { return apiFetch<KeyRotationResult>("/admin/oauth/instance-key/rotate", { method: "POST", });}
export function listInstanceOauthKeys() { return apiFetch<InstanceOauthKeysResponse>("/admin/oauth/instance-key");}
export function revokeInstanceOauthKey(kid: string) { return apiFetch<RevokeInstanceKeyResult>( `/admin/oauth/instance-key/${encodeURIComponent(kid)}`, { method: "DELETE" }, );}
// Event Logsexport function getEvents(params?: { category?: string; severity?: string; subject?: string; cursor?: string; limit?: number;}) { const searchParams = new URLSearchParams(); if (params?.category) searchParams.set("category", params.category); if (params?.severity) searchParams.set("severity", params.severity); if (params?.subject) searchParams.set("subject", params.subject); if (params?.cursor) searchParams.set("cursor", params.cursor); if (params?.limit) searchParams.set("limit", String(params.limit)); const qs = searchParams.toString(); return apiFetch<EventsListResponse>(`/admin/events${qs ? `?${qs}` : ""}`);}
// External Accountsexport function getExternalProviders() { return apiFetch<ExternalProvider[]>("/external-auth/providers");}
export function getLinkedAccounts() { return apiFetch<LinkedAccount[]>("/external-auth/accounts");}
export function authorizeExternal(pluginId: string, redirectUri: string) { const params = new URLSearchParams({ redirect_uri: redirectUri }); return apiFetch<AuthorizeResponse>( `/external-auth/${encodeURIComponent(pluginId)}/authorize?${params}`, );}
export function syncExternal(pluginId: string) { return apiFetch<SyncResponse>( `/external-auth/${encodeURIComponent(pluginId)}/sync`, { method: "POST" }, );}
export function unlinkExternal(pluginId: string) { return apiFetch<UnlinkResponse>( `/external-auth/${encodeURIComponent(pluginId)}/unlink`, { method: "POST" }, );}
export function connectWithConfig( pluginId: string, config: Record<string, unknown>,) { return apiFetch<ConnectResponse>( `/external-auth/${encodeURIComponent(pluginId)}/connect`, { method: "POST", body: JSON.stringify({ config }) }, );}
// Pluginsimport type { PluginSummary, PluginsListResponse, OfficialPluginsListResponse,} from "@/types/plugins";export type { PluginSummary, PluginsListResponse, OfficialPluginSummary, OfficialPluginsListResponse, ReleaseEntry,} from "@/types/plugins";
export function getPlugins() { return apiFetch<PluginsListResponse>("/admin/plugins");}
export function addPlugin(body: { url: string; sha256?: string }) { return apiFetch<PluginSummary>("/admin/plugins", { method: "POST", body: JSON.stringify(body), });}
export function removePlugin(id: string) { return apiFetch(`/admin/plugins/${encodeURIComponent(id)}`, { method: "DELETE", });}
export function reloadPlugin(id: string, body?: { url?: string }) { return apiFetch<PluginSummary>( `/admin/plugins/${encodeURIComponent(id)}/reload`, { method: "POST", body: body ? JSON.stringify(body) : undefined, }, );}
export function getOfficialPlugins() { return apiFetch<OfficialPluginsListResponse>("/admin/plugins/official");}
export function checkPluginUpdate(id: string) { return apiFetch<PluginSummary>( `/admin/plugins/${encodeURIComponent(id)}/check-update`, { method: "POST" }, );}
export interface PluginSecretsResponse { plugin_id: string; secrets: Record<string, string>;}
export function getPluginSecrets(id: string) { return apiFetch<PluginSecretsResponse>( `/admin/plugins/${encodeURIComponent(id)}/secrets`, );}
export function updatePluginSecrets( id: string, secrets: Record<string, string>,) { return apiFetch<void>(`/admin/plugins/${encodeURIComponent(id)}/secrets`, { method: "PUT", body: JSON.stringify({ secrets }), });}
export interface SecretDefinition { key: string; name: string; description: string | null;}
export interface PluginPreview { id: string; name: string; version: string; description: string | null; icon_url: string | null; auth_type: string; required_secrets: SecretDefinition[]; manifest_url: string; wasm_url: string;}
export function previewPlugin(url: string, signal?: AbortSignal) { return apiFetch<PluginPreview>("/admin/plugins/preview", { method: "POST", body: JSON.stringify({ url }), signal, });}
// ---------------------------------------------------------------------------// Dead Letters// ---------------------------------------------------------------------------
export function getDeadLetters(params?: { collection?: string; resolved?: string; cursor?: string; limit?: number;}) { const searchParams = new URLSearchParams(); if (params?.collection) searchParams.set("collection", params.collection); if (params?.resolved) searchParams.set("resolved", params.resolved); if (params?.cursor) searchParams.set("cursor", params.cursor); if (params?.limit) searchParams.set("limit", String(params.limit)); const qs = searchParams.toString(); return apiFetch<DeadLettersListResponse>( `/admin/dead-letters${qs ? `?${qs}` : ""}`, );}
export function getDeadLetterCount(resolved?: string) { const searchParams = new URLSearchParams(); if (resolved) searchParams.set("resolved", resolved); const qs = searchParams.toString(); return apiFetch<DeadLetterCountResponse>( `/admin/dead-letters/count${qs ? `?${qs}` : ""}`, );}
export function getDeadLetter(id: string) { return apiFetch<DeadLetterDetail>( `/admin/dead-letters/${encodeURIComponent(id)}`, );}
export function retryDeadLetter(id: string) { return apiFetch(`/admin/dead-letters/${encodeURIComponent(id)}/retry`, { method: "POST", });}
export function reindexDeadLetter(id: string) { return apiFetch(`/admin/dead-letters/${encodeURIComponent(id)}/reindex`, { method: "POST", });}
export function dismissDeadLetter(id: string) { return apiFetch(`/admin/dead-letters/${encodeURIComponent(id)}/dismiss`, { method: "POST", });}
export function bulkDismissDeadLetters(body: { ids?: string[]; all?: boolean; collection?: string;}) { return apiFetch<BulkActionResponse>("/admin/dead-letters/bulk/dismiss", { method: "POST", body: JSON.stringify(body), });}
export function bulkRetryDeadLetters(body: { ids?: string[]; all?: boolean; collection?: string;}) { return apiFetch<BulkActionResponse>("/admin/dead-letters/bulk/retry", { method: "POST", body: JSON.stringify(body), });}
export function bulkReindexDeadLetters(body: { ids?: string[]; all?: boolean; collection?: string;}) { return apiFetch<BulkActionResponse>("/admin/dead-letters/bulk/reindex", { method: "POST", body: JSON.stringify(body), });}
// Scripts (trigger-keyed)export function getScripts(opts?: { suffix?: string }) { const params = new URLSearchParams(); if (opts?.suffix) params.set("suffix", opts.suffix); const qs = params.toString(); return apiFetch<Script[]>(`/admin/scripts${qs ? `?${qs}` : ""}`);}
export function getScript(id: string) { return apiFetch<Script>(`/admin/scripts/${encodeURIComponent(id)}`);}
export function upsertScript(body: UpsertScriptBody) { return apiFetch<Script>("/admin/scripts", { method: "POST", body: JSON.stringify(body), });}
export function patchScript(id: string, body: PatchScriptBody) { return apiFetch<Script>(`/admin/scripts/${encodeURIComponent(id)}`, { method: "PATCH", body: JSON.stringify(body), });}
export function deleteScript(id: string) { return apiFetch(`/admin/scripts/${encodeURIComponent(id)}`, { method: "DELETE", });}
// Setupexport interface SetupStatus { identity_mode: | "did_web" | "did_plc" | "attach_account" | "not_exposed" | null; identity_configured: boolean; plc_verified: boolean; setup_complete: boolean;}
export interface ServiceIdentityResponse { mode: string; did: string | null; attached_account_did: string | null; setup_complete: boolean; created_at: string; updated_at: string;}
export interface ServiceEntry { id: number; fragment_id: string; service_type: string; access_mode: string; created_at: string; updated_at: string;}
export function getSetupStatus() { return apiFetch<SetupStatus>("/api/setup/status");}
export function setSetupIdentity(body: { mode: string; did?: string; attached_account_did?: string;}) { return apiFetch("/api/setup/identity", { method: "POST", body: JSON.stringify(body), });}
export function completeSetup() { return apiFetch("/api/setup/complete", { method: "POST" });}
export interface ResolveResult { did: string; handle: string | null; display_name: string | null; avatar: string | null;}
export function resolveSetupIdentity(q: string) { return apiFetch<ResolveResult[]>( `/api/setup/resolve?q=${encodeURIComponent(q)}`, );}
export function confirmAttachAuth(body: { original_did: string }) { return apiFetch("/api/setup/attach-auth/confirm", { method: "POST", body: JSON.stringify(body), });}
export function plcRequest() { return apiFetch("/api/setup/plc/request", { method: "POST" });}
export function plcSubmit(token: string) { return apiFetch("/api/setup/plc/submit", { method: "POST", body: JSON.stringify({ token }), });}
export function plcRegister() { return apiFetch<{ did: string }>("/api/setup/plc/register", { method: "POST", });}
// Service Identityexport function getServiceIdentity() { return apiFetch<ServiceIdentityResponse | null>("/admin/service-identity");}
export function updateServiceIdentity(body: { mode: string; did?: string; signing_key_enc?: string; rotation_key_enc?: string; attached_account_did?: string;}) { return apiFetch("/admin/service-identity", { method: "PUT", body: JSON.stringify(body), });}
// Service Entriesexport function getServiceEntries() { return apiFetch<ServiceEntry[]>("/admin/service-entries");}
export function createServiceEntry(body: { fragment_id: string; service_type: string;}) { return apiFetch<ServiceEntry>("/admin/service-entries", { method: "POST", body: JSON.stringify(body), });}
export function updateServiceEntry( id: number, body: { fragment_id?: string; service_type?: string; access_mode?: string; },) { return apiFetch(`/admin/service-entries/${id}`, { method: "PUT", body: JSON.stringify(body), });}
export function deleteServiceEntry(id: number) { return apiFetch(`/admin/service-entries/${id}`, { method: "DELETE" });}
export function getServiceEntryXrpcs(id: number) { return apiFetch<string[]>(`/admin/service-entries/${id}/xrpcs`);}
export function addServiceEntryXrpcs(id: number, lexicon_ids: string[]) { return apiFetch(`/admin/service-entries/${id}/xrpcs`, { method: "POST", body: JSON.stringify({ lexicon_ids }), });}
export function removeServiceEntryXrpcs(id: number, lexicon_ids: string[]) { return apiFetch(`/admin/service-entries/${id}/xrpcs`, { method: "DELETE", body: JSON.stringify({ lexicon_ids }), });}
export function getLexiconServices(lexiconId: string) { return apiFetch<ServiceEntry[]>( `/admin/lexicons/${encodeURIComponent(lexiconId)}/services`, );}
// Service Entry PLC Syncexport function syncPlc() { return apiFetch("/admin/service-entries/sync-plc", { method: "POST" });}
export function syncPlcRequest() { return apiFetch("/admin/service-entries/sync-plc/request", { method: "POST", });}
export function syncPlcSubmit(token: string) { return apiFetch("/admin/service-entries/sync-plc/submit", { method: "POST", body: JSON.stringify({ token }), });}