import { ok } from "@atcute/client"; import type { BobbinContext } from "$lib/api/client"; import { mainSchema as getPreferencesSchema } from "$lib/api/lexicons/types/com/bad-example/pocket/getPreferences"; import { mainSchema as putPreferencesSchema } from "$lib/api/lexicons/types/com/bad-example/pocket/putPreferences"; const KNOT_PREF = "org.tangled.temp.actor.defs#savedKnotPref"; const SPINDLE_PREF = "org.tangled.temp.actor.defs#savedSpindlePref"; export type ServiceKind = "knots" | "spindles"; export interface Preferences { knots: string[]; spindles: string[]; } export const hostOf = (input: string): string => input .trim() .replace(/^[a-z]+:\/\//i, "") .replace(/\/.*$/, "") .toLowerCase(); export const getPreferences = async (ctx: BobbinContext): Promise => { try { const { preferences } = await ok(ctx.xrpc.call(getPreferencesSchema, { params: {} })); const values = (type: string): string[] => preferences .filter((pref) => pref.$type === type) .flatMap((pref) => pref.items.map((item) => item.value)); return { knots: values(KNOT_PREF), spindles: values(SPINDLE_PREF) }; } catch { return { knots: [], spindles: [] }; } }; export const putPreferences = async (ctx: BobbinContext, preferences: Preferences): Promise => { const items = (hosts: string[]) => hosts.map((host) => ({ id: host, value: host })); await ok( ctx.xrpc.call(putPreferencesSchema, { input: { preferences: [ { $type: KNOT_PREF, items: items(preferences.knots) }, { $type: SPINDLE_PREF, items: items(preferences.spindles) } ] } }) ); }; /** rewrites one of the two lists and answers with what it saved */ export const editSavedServices = async ( ctx: BobbinContext, kind: ServiceKind, edit: (hosts: string[]) => string[] ): Promise => { const targets = await getPreferences(ctx); const next = { ...targets, [kind]: edit(targets[kind]) }; await putPreferences(ctx, next); return next[kind]; };