Dough Git

commit

Remove the PluralKit importer and the doughmination-api package

commit
ec7c639178863dd2883195c23072a5a99fa1c64a
author
Clove Twilight <[email protected]>
date
2026-11-20 12:44
The importer was only for the one-off move. The site now uses its own
types and a small client for its own /api/plural, so it no longer
depends on the API project's package.

Co-Authored-By: Sandrone <[email protected]>

diff --git a/README.md b/README.md
index d06dbfc..6262093 100644
--- a/README.md
+++ b/README.md
@@ -1,14 +1,14 @@
 # Doughmination System
 
 A real-time plural system tracker for the Doughmination System — current fronters,
-system members, and switching patterns. Member data is pulled live from PluralKit
-through the Doughmination API, so pages render fresh on every request.
+system members, and switching patterns. Member data lives in this site's own API and
+D1 database, so pages render fresh on every request.
 
 ## Tech stack
 
 - [SvelteKit](https://svelte.dev/docs/kit) (Svelte 5)
 - Plain CSS, shared with [doughmination.gay](https://doughmination.gay)
-- `doughmination-api/server`'s typed client for data, plus its live socket
+- Its own API (Hono, D1, R2) at `/api/plural`, with a small typed client in `src/lib/api.ts` and a live socket
 - Deployed to **Cloudflare Workers** via `@sveltejs/adapter-cloudflare`
 
 ## Local development
diff --git a/bun.lock b/bun.lock
index 439ad11..228ff2a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6,7 +6,6 @@
       "name": "doughmination-system",
       "dependencies": {
         "@hono/zod-openapi": "^1.6.3",
-        "doughmination-api": "^1.6.0",
         "hono": "^4.13.18",
         "simple-icons": "npm:@icons-pack/svelte-simple-icons@^7.2.0",
         "zod": "^4.6.7",
@@ -235,10 +234,6 @@
 
     "@sveltejs/vite-plugin-svelte": ["@sveltejs/[email protected]", "", { "dependencies": { "deepmerge": "^4.3.1", "magic-string": "^1.0.0", "obug": "^2.1.0", "vitefu": "^1.1.2" }, "peerDependencies": { "svelte": "^5.46.4", "vite": "^8.0.0-beta.7 || ^8.0.0" } }, "sha512-ZPsLN8B1e/En+Ak5s4V7srFDT532oS0qieLsQwu63NGKsS+iAjoO2Js1BochlHlglcU+Pt7WAO3C5Ee+4f6gVA=="],
 
-    "@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-7p56vRmT/z4UJ6sctGIdl5WRUQyUv53IUpUwEKi2g97zMbO7zh8ZsCLffGAvCPBR4xD72e3VXsDyLwXHhoNTMQ=="],
-
-    "@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.105.0" }, "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-y+hMuDERvgg6ay1da0V1a6ZC0ZONt7dELxSFkqRZuwm7p1TTZs0MoXrPlBRflIpRoYjvzQVYxycnLImpFLhWrw=="],
-
     "@types/estree": ["@types/[email protected]", "", {}, "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g=="],
 
     "acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="],
@@ -263,8 +258,6 @@
 
     "devalue": ["[email protected]", "", {}, "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg=="],
 
-    "doughmination-api": ["[email protected]", "", { "peerDependencies": { "@tanstack/react-query": "^5.0.0", "react": "^18.0.0 || ^19.0.0" } }, "sha512-WZCSzY3pmn0gZVHRUidTBCz1jXuyHlEArfUM9fl5xJMHjK5FntpJMo3fUYzA6OpvBNgwwhQNFctYYfDm50hXag=="],
-
     "error-stack-parser-es": ["[email protected]", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="],
 
     "esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
@@ -347,8 +340,6 @@
 
     "quansync": ["[email protected]", "", {}, "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA=="],
 
-    "react": ["[email protected]", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="],
-
     "readdirp": ["[email protected]", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="],
 
     "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.155.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.15", "@rolldown/binding-android-arm64": "1.2.15", "@rolldown/binding-darwin-arm64": "1.2.15", "@rolldown/binding-darwin-x64": "1.2.15", "@rolldown/binding-freebsd-x64": "1.2.15", "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", "@rolldown/binding-linux-arm64-gnu": "1.2.15", "@rolldown/binding-linux-arm64-musl": "1.2.15", "@rolldown/binding-linux-ppc64-gnu": "1.2.15", "@rolldown/binding-linux-s390x-gnu": "1.2.15", "@rolldown/binding-linux-x64-gnu": "1.2.15", "@rolldown/binding-linux-x64-musl": "1.2.15", "@rolldown/binding-openharmony-arm64": "1.2.15", "@rolldown/binding-win32-arm64-msvc": "1.2.15", "@rolldown/binding-win32-x64-msvc": "1.2.15" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g=="],
diff --git a/package.json b/package.json
index 7286172..32e76fe 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,6 @@
   },
   "dependencies": {
     "@hono/zod-openapi": "^1.6.3",
-    "doughmination-api": "^1.6.0",
     "hono": "^4.13.18",
     "simple-icons": "npm:@icons-pack/svelte-simple-icons@^7.2.0",
     "zod": "^4.6.7"
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 5894cbc..1326b43 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -4,7 +4,16 @@
  * See LICENCE.md in the project root for full licence information.
  */
 
-import { DoughminationClient } from "doughmination-api/server";
+import type {
+  FrontersResponse,
+  MemberStatusResponse,
+  MentalState,
+  PluralMember,
+  PluralSystem,
+  RelationshipsResponse,
+  SwitchResponse,
+  UserResponse,
+} from "./types.ts";
 import { siteUrl } from "./index.ts";
 
 const TOKEN_KEY = "token";
@@ -33,35 +42,210 @@ export function apiBase(origin: string): string {
   return `${origin}/api`;
 }
 
-// Live updates come from the shared hub on the api Worker
+// Live updates come from this site's own hub
 export const socketUrl = "wss://doughmination.co.uk/api/plural/ws";
 
 /** A client for load functions: SvelteKit's fetch, no token */
-export function publicClient(fetcher: typeof fetch, origin: string): DoughminationClient {
-  return new DoughminationClient({
+export function publicClient(fetcher: typeof fetch, origin: string): SiteClient {
+  return new SiteClient({
     fetch: fetcher,
     baseUrl: apiBase(origin),
   });
 }
 
-/** The browser's client: every request carries the current token */
-export const client = new DoughminationClient({
-  baseUrl: apiBase(typeof location === "undefined" ? siteUrl : location.origin),
-  token: () => readToken(),
-});
-
 function apiErrorMessage(body: unknown, fallback: string): string {
   if (body && typeof body === "object") {
     const b = body as {
-      error?: { message?: string };
-      detail?: string;
+      error?: string | { message?: string };
+      detail?: string | { message?: string }[];
       message?: string;
     };
+    if (typeof b.error === "string") return b.error;
+    // Validation errors arrive as a list of issues
+    if (Array.isArray(b.detail)) return b.detail.map((issue) => issue.message).join("; ");
     return b.error?.message || b.detail || b.message || fallback;
   }
   return fallback;
 }
 
+interface ClientOptions {
+  baseUrl: string;
+  fetch?: typeof fetch;
+  token?: () => string | null;
+}
+
+interface RequestOptions {
+  method?: "GET" | "POST" | "DELETE";
+  body?: unknown;
+  signedIn?: boolean;
+}
+
+// This site's API, with only the calls the pages use
+export class SiteClient {
+  readonly baseUrl: string;
+  private readonly doFetch: typeof fetch;
+  private readonly token: () => string | null;
+
+  constructor(options: ClientOptions) {
+    this.baseUrl = options.baseUrl.replace(/\/+$/, "");
+    this.doFetch = (options.fetch ?? fetch).bind(globalThis);
+    this.token = options.token ?? (() => null);
+  }
+
+  private async request<T>(path: string, options: RequestOptions = {}): Promise<T> {
+    const headers = new Headers();
+    if (options.body !== undefined) headers.set("Content-Type", "application/json");
+
+    if (options.signedIn) {
+      const token = this.token();
+      if (!token) throw new Error("Sign in first");
+      headers.set("Authorization", `Bearer ${token}`);
+    }
+
+    const response = await this.doFetch(`${this.baseUrl}${path}`, {
+      method: options.method ?? "GET",
+      headers,
+      body: options.body === undefined ? undefined : JSON.stringify(options.body),
+    });
+    const text = await response.text();
+    let parsed: unknown = null;
+    try {
+      parsed = text ? JSON.parse(text) : null;
+    } catch {
+      parsed = text;
+    }
+
+    if (!response.ok) {
+      const fallback = typeof parsed === "string" && parsed ? parsed : `Request failed with ${response.status}`;
+      throw new Error(apiErrorMessage(parsed, fallback));
+    }
+    return parsed as T;
+  }
+
+  getFronters() {
+    return this.request<FrontersResponse>("/plural/fronters");
+  }
+
+  getMembers() {
+    return this.request<PluralMember[]>("/plural/members");
+  }
+
+  getMember(memberId: string) {
+    return this.request<PluralMember>(`/plural/member/${encodeURIComponent(memberId)}`);
+  }
+
+  getSystem() {
+    return this.request<PluralSystem>("/plural/system");
+  }
+
+  getMentalState() {
+    return this.request<MentalState>("/plural/mental-state");
+  }
+
+  getMemberStatus(identifier: string) {
+    return this.request<MemberStatusResponse>(`/plural/members/${encodeURIComponent(identifier)}/status`);
+  }
+
+  getRelationships() {
+    return this.request<RelationshipsResponse>("/plural/relationships");
+  }
+
+  loginUrl(from?: string): string {
+    const url = new URL(`${this.baseUrl}/plural/auth/sso/login`);
+    if (from) url.searchParams.set("from", from);
+    return url.toString();
+  }
+
+  getUserInfo() {
+    return this.request<UserResponse>("/plural/user_info", {
+      signedIn: true,
+    });
+  }
+
+  multiSwitch(memberIds: string[]) {
+    return this.request<SwitchResponse>("/plural/multi_switch", {
+      method: "POST",
+      signedIn: true,
+      body: {
+        member_ids: memberIds,
+      },
+    });
+  }
+
+  setMentalState(input: { level: string; notes?: string }) {
+    return this.request<unknown>("/plural/mental-state", {
+      method: "POST",
+      signedIn: true,
+      body: {
+        level: input.level,
+        notes: input.notes ?? null,
+      },
+    });
+  }
+
+  setMemberStatus(identifier: string, input: { text: string; emoji?: string }) {
+    return this.request<unknown>(`/plural/members/${encodeURIComponent(identifier)}/status`, {
+      method: "POST",
+      signedIn: true,
+      body: {
+        text: input.text,
+        emoji: input.emoji ?? null,
+      },
+    });
+  }
+
+  forceRefresh() {
+    return this.request<unknown>("/plural/admin/refresh", {
+      method: "POST",
+      signedIn: true,
+    });
+  }
+
+  addMemberPride(identifier: string, identity: string) {
+    return this.request<unknown>(`/plural/member-pride/${encodeURIComponent(identifier)}/add`, {
+      method: "POST",
+      signedIn: true,
+      body: {
+        identity,
+      },
+    });
+  }
+
+  removeMemberPride(identifier: string, identity: string) {
+    const path = `/plural/member-pride/${encodeURIComponent(identifier)}/${encodeURIComponent(identity)}`;
+    return this.request<unknown>(path, {
+      method: "DELETE",
+      signedIn: true,
+    });
+  }
+
+  addRelationship(input: { memberA: string; memberB: string; type?: string; since?: string | null }) {
+    return this.request<unknown>("/plural/relationships", {
+      method: "POST",
+      signedIn: true,
+      body: {
+        memberA: input.memberA,
+        memberB: input.memberB,
+        ...(input.type ? { type: input.type } : {}),
+        ...(input.since !== undefined ? { since: input.since } : {}),
+      },
+    });
+  }
+
+  removeRelationship(id: string) {
+    return this.request<unknown>(`/plural/relationships/${encodeURIComponent(id)}`, {
+      method: "DELETE",
+      signedIn: true,
+    });
+  }
+}
+
+/** The browser's client: every request carries the current token */
+export const client = new SiteClient({
+  baseUrl: apiBase(typeof location === "undefined" ? siteUrl : location.origin),
+  token: () => readToken(),
+});
+
 /** For the endpoints the client has no method for. Throws with the API's own message */
 export async function authFetch<T = unknown>(path: string, init: RequestInit = {}, fallback = "Request failed"): Promise<T> {
   const token = readToken();
diff --git a/src/lib/auth.svelte.ts b/src/lib/auth.svelte.ts
index 182119d..c70cc21 100644
--- a/src/lib/auth.svelte.ts
+++ b/src/lib/auth.svelte.ts
@@ -4,7 +4,7 @@
  * See LICENCE.md in the project root for full licence information.
  */
 
-import type { UserResponse } from "doughmination-api/server";
+import type { UserResponse } from "#lib/types.ts";
 import { client, readToken, writeToken } from "./api.ts";
 
 // Who is signed in, shared by every page. Filled on the client only: the token lives in localStorage
diff --git a/src/lib/components/Home.svelte b/src/lib/components/Home.svelte
index 13146a5..e55ec4f 100644
--- a/src/lib/components/Home.svelte
+++ b/src/lib/components/Home.svelte
@@ -13,7 +13,7 @@
   import IcReportProblem from "~icons/ic/outline-report-problem";
   import IcSearch from "~icons/ic/outline-search";
   import IcWarningAmber from "~icons/ic/outline-warning-amber";
-  import type { FrontersResponse, PluralMember, PluralSystem } from "doughmination-api/server";
+  import type { FrontersResponse, PluralMember, PluralSystem } from "#lib/types.ts";
   import { replaceState } from "$app/navigation";
   import { page } from "$app/state";
   import { avatarFallback, fallbackAvatar, memberName, sortMembers, siteUrl } from "#lib";
diff --git a/src/lib/components/MemberSelect.svelte b/src/lib/components/MemberSelect.svelte
index 059cb23..97c05ac 100644
--- a/src/lib/components/MemberSelect.svelte
+++ b/src/lib/components/MemberSelect.svelte
@@ -5,7 +5,7 @@
 -->
 
 <script lang="ts">
-  import type { PluralMember } from "doughmination-api/server";
+  import type { PluralMember } from "#lib/types.ts";
   import { memberName } from "#lib";
 
   // A native picker keyed by member name, the identifier the admin endpoints take
diff --git a/src/lib/components/RelationshipGraph.svelte b/src/lib/components/RelationshipGraph.svelte
index f0c3601..baf55b8 100644
--- a/src/lib/components/RelationshipGraph.svelte
+++ b/src/lib/components/RelationshipGraph.svelte
@@ -6,7 +6,7 @@
 
 <script lang="ts">
   import { onMount } from "svelte";
-  import type { PluralMember, Relationship } from "doughmination-api/server";
+  import type { PluralMember, Relationship } from "#lib/types.ts";
   import { fallbackAvatar, memberName } from "#lib";
   import { normalizeColor } from "#lib/colour.ts";
   import { layout, project } from "#lib/graph.ts";
diff --git a/src/lib/index.ts b/src/lib/index.ts
index b87bd30..0416993 100644
--- a/src/lib/index.ts
+++ b/src/lib/index.ts
@@ -4,7 +4,7 @@
  * See LICENCE.md in the project root for full licence information.
  */
 
-import type { PluralMember } from "doughmination-api/server";
+import type { PluralMember } from "#lib/types.ts";
 
 export const siteName = "Doughmination System";
 
diff --git a/src/lib/server/plural/routes/admin.ts b/src/lib/server/plural/routes/admin.ts
index 3104c6b..274586b 100644
--- a/src/lib/server/plural/routes/admin.ts
+++ b/src/lib/server/plural/routes/admin.ts
@@ -6,11 +6,10 @@
 
 import { createRoute, z } from "@hono/zod-openapi";
 
-import { router, ok, jsonBody, signedIn } from "../openapi";
+import { router, ok, signedIn } from "../openapi";
 import { MessageSchema } from "../schemas";
-import { requireAuth, requireAdmin, requireOwner } from "../middleware/auth";
+import { requireAuth, requireAdmin } from "../middleware/auth";
 import { broadcastFrontendUpdate } from "../ws";
-import { importPluralKitExport } from "../services/importer";
 import { rt } from "../runtime";
 
 export const adminRoutes = router();
@@ -31,46 +30,7 @@ adminRoutes.openapi(
   },
 );
 
-adminRoutes.openapi(
-  createRoute({
-    method: "post",
-    path: "/admin/import/pluralkit",
-    tags: ["Admin"],
-    summary: "Import a PluralKit export file (owner). Images are copied into this site's storage",
-    security: signedIn,
-    middleware: [requireAuth, requireOwner] as const,
-    request: {
-      query: z.object({
-        replace: z
-          .enum(["true", "false"])
-          .default("false")
-          .openapi({ description: "Overwrite an already-imported system, members and switch history" }),
-        copy_media: z.enum(["true", "false"]).default("true"),
-      }),
-      ...jsonBody(z.looseObject({}).openapi({ description: "The JSON file from pk;export, unchanged" })),
-    },
-    responses: ok(
-      z.object({
-        system: z.string(),
-        members: z.number(),
-        switches: z.number(),
-        media_copied: z.number(),
-        media_failed: z.array(z.string()),
-      }),
-    ),
-  }),
-  async (c) => {
-    const query = c.req.valid("query");
-    const report = await importPluralKitExport(c.req.valid("json"), {
-      replace: query.replace === "true",
-      copyMedia: query.copy_media === "true",
-    });
-    await broadcastFrontendUpdate("members_update", {});
-    return c.json(report, 200);
-  },
-);
-
-// Images copied in by the importer. Public, like the PluralKit CDN was
+// Member avatars uploaded from the admin page. Public, so Discord and browsers can load them
 adminRoutes.openapi(
   createRoute({
     method: "get",
diff --git a/src/lib/server/plural/routes/members.ts b/src/lib/server/plural/routes/members.ts
index 1aa4254..6be3eb4 100644
--- a/src/lib/server/plural/routes/members.ts
+++ b/src/lib/server/plural/routes/members.ts
@@ -20,7 +20,7 @@ import { enrichMembersWithStatus } from "../services/status";
 import { getMemberPride, addMemberPride, removeMemberPride, enrichMembersWithPride } from "../services/pride";
 import { requireAuth, requireOwner } from "../middleware/auth";
 import { HttpError } from "../errors";
-import { MAX_MEDIA_BYTES, mediaUrl } from "../services/importer";
+import { MAX_MEDIA_BYTES, mediaUrl } from "../services/media";
 import { rt } from "../runtime";
 import { broadcastFrontendUpdate } from "../ws";
 import type { JsonObject } from "../types";
@@ -138,7 +138,7 @@ membersRoutes.openapi(
     if (body.byteLength === 0) throw new HttpError(400, "The image is empty");
     if (body.byteLength > MAX_MEDIA_BYTES) throw new HttpError(413, "The image is over 10 MB");
 
-    // Same key the importer uses, so an upload overwrites the imported image
+    // One fixed key per member, so each upload overwrites the last
     const key = `member-${member.id}-avatar_url`;
     await rt().env.MEDIA.put(key, body, {
       httpMetadata: {
diff --git a/src/lib/server/plural/services/importer.ts b/src/lib/server/plural/services/importer.ts
deleted file mode 100644
index 977a9f9..0000000
--- a/src/lib/server/plural/services/importer.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-/* src/lib/server/plural/services/importer.ts
- * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
- * Licensed under the DASL-1.2 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-import { rt } from "../runtime";
-import { HttpError } from "../errors";
-import { frontendUrl } from "../config";
-import type { JsonObject } from "../types";
-
-const MEDIA_FIELDS = ["avatar_url", "webhook_avatar_url", "banner"] as const;
-export const MAX_MEDIA_BYTES = 10 * 1024 * 1024;
-
-// D1 caps how much one batch may carry, so big switch histories go in slices
-const BATCH_SIZE = 200;
-
-export interface ImportReport {
-  system: string;
-  members: number;
-  switches: number;
-  media_copied: number;
-  media_failed: string[];
-}
-
-function text(value: unknown): string | null {
-  return typeof value === "string" && value !== "" ? value : null;
-}
-
-export function mediaUrl(key: string): string {
-  return `${frontendUrl()}/api/plural/media/${key}`;
-}
-
-// Copy one image into R2. Returns the new URL, or null when the source is gone or not an image
-async function copyMedia(source: string, key: string): Promise<string | null> {
-  if (source.startsWith(mediaUrl(""))) return source;
-
-  try {
-    const response = await fetch(source);
-    const type = response.headers.get("Content-Type") ?? "";
-    if (!response.ok || !type.startsWith("image/")) return null;
-
-    const body = await response.arrayBuffer();
-    if (body.byteLength > MAX_MEDIA_BYTES) return null;
-
-    await rt().env.MEDIA.put(key, body, { httpMetadata: { contentType: type } });
-    return mediaUrl(key);
-  } catch {
-    return null;
-  }
-}
-
-async function copyAllMedia(owner: JsonObject, prefix: string, report: ImportReport): Promise<void> {
-  for (const field of MEDIA_FIELDS) {
-    const source = text(owner[field]);
-    if (!source) continue;
-
-    const copied = await copyMedia(source, `${prefix}-${field}`);
-    if (copied) {
-      owner[field] = copied;
-      report.media_copied += 1;
-    } else {
-      // Keep the old URL so nothing disappears; it can be re-uploaded by hand
-      report.media_failed.push(`${prefix}.${field}`);
-    }
-  }
-}
-
-async function runBatches(statements: D1PreparedStatement[]): Promise<void> {
-  for (let start = 0; start < statements.length; start += BATCH_SIZE) {
-    await rt().db.batch(statements.slice(start, start + BATCH_SIZE));
-  }
-}
-
-// A PluralKit export file (pk;export). `replace` must be set to overwrite an existing system
-export async function importPluralKitExport(
-  data: JsonObject,
-  options: { replace: boolean; copyMedia: boolean },
-): Promise<ImportReport> {
-  const systemHid = text(data.id);
-  if (!systemHid || !Array.isArray(data.members) || !Array.isArray(data.switches)) {
-    throw new HttpError(422, "That doesn't look like a PluralKit export (needs id, members and switches)");
-  }
-
-  const existing = await rt().db.prepare("SELECT id FROM systems LIMIT 1").first<{ id: string }>();
-  if (existing && !options.replace) {
-    throw new HttpError(409, "A system is already imported. Send replace=true to overwrite it.");
-  }
-
-  const report: ImportReport = {
-    system: systemHid,
-    members: 0,
-    switches: 0,
-    media_copied: 0,
-    media_failed: [],
-  };
-
-  const members = data.members as JsonObject[];
-  if (options.copyMedia) {
-    await copyAllMedia(data, "system", report);
-    for (const member of members) await copyAllMedia(member, `member-${member.id}`, report);
-  }
-
-  const db = rt().db;
-  const statements: D1PreparedStatement[] = [
-    db.prepare("DELETE FROM switches"),
-    db.prepare("DELETE FROM members"),
-    db.prepare("DELETE FROM systems"),
-    db
-      .prepare(
-        `INSERT INTO systems (id, uuid, name, description, tag, pronouns, avatar_url, banner, color, timezone, created, privacy)
-         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
-      )
-      .bind(
-        systemHid,
-        text(data.uuid) ?? crypto.randomUUID(),
-        text(data.name),
-        text(data.description),
-        text(data.tag),
-        text(data.pronouns),
-        text(data.avatar_url),
-        text(data.banner),
-        text(data.color),
-        text(data.config?.timezone) ?? text(data.timezone),
-        text(data.created) ?? new Date().toISOString(),
-        JSON.stringify(data.privacy ?? {}),
-      ),
-  ];
-
-  for (const member of members) {
-    const id = text(member.id);
-    const name = text(member.name);
-    if (!id || !name) continue;
-
-    statements.push(
-      db
-        .prepare(
-          `INSERT INTO members (id, uuid, system_id, name, display_name, color, birthday, pronouns, avatar_url,
-             webhook_avatar_url, banner, description, created, proxy_tags, keep_proxy, autoproxy_enabled,
-             message_count, last_message_timestamp, privacy)
-           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
-        )
-        .bind(
-          id,
-          text(member.uuid) ?? crypto.randomUUID(),
-          systemHid,
-          name,
-          text(member.display_name),
-          text(member.color),
-          text(member.birthday),
-          text(member.pronouns),
-          text(member.avatar_url),
-          text(member.webhook_avatar_url),
-          text(member.banner),
-          text(member.description),
-          text(member.created) ?? new Date().toISOString(),
-          JSON.stringify(Array.isArray(member.proxy_tags) ? member.proxy_tags : []),
-          member.keep_proxy ? 1 : 0,
-          member.autoproxy_enabled == null ? null : member.autoproxy_enabled ? 1 : 0,
-          Number(member.message_count) || 0,
-          text(member.last_message_timestamp),
-          JSON.stringify(member.privacy ?? {}),
-        ),
-    );
-    report.members += 1;
-  }
-
-  for (const entry of data.switches as JsonObject[]) {
-    const timestamp = text(entry.timestamp);
-    if (!timestamp || !Array.isArray(entry.members)) continue;
-
-    statements.push(
-      db
-        .prepare("INSERT INTO switches (id, system_id, timestamp, members) VALUES (?, ?, ?, ?)")
-        .bind(text(entry.id) ?? crypto.randomUUID(), systemHid, timestamp, JSON.stringify(entry.members.map(String))),
-    );
-    report.switches += 1;
-  }
-
-  // shortcut: batches commit one slice at a time, so a failure part-way leaves a partial import. Re-run with replace=true
-  await runBatches(statements);
-  return report;
-}
diff --git a/src/lib/server/plural/services/media.ts b/src/lib/server/plural/services/media.ts
new file mode 100644
index 0000000..7a2ae67
--- /dev/null
+++ b/src/lib/server/plural/services/media.ts
@@ -0,0 +1,13 @@
+/* src/lib/server/plural/services/media.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+import { frontendUrl } from "../config";
+
+export const MAX_MEDIA_BYTES = 10 * 1024 * 1024;
+
+export function mediaUrl(key: string): string {
+  return `${frontendUrl()}/api/plural/media/${key}`;
+}
diff --git a/src/lib/types.ts b/src/lib/types.ts
new file mode 100644
index 0000000..88d0002
--- /dev/null
+++ b/src/lib/types.ts
@@ -0,0 +1,112 @@
+/* src/lib/types.ts
+ * Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+ * Licensed under the DASL-1.2 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+// The shapes this site's own /api/plural sends back
+
+export interface PluralProxyTag {
+  prefix: string | null;
+  suffix: string | null;
+}
+
+export interface PluralMemberStatus {
+  text: string;
+  emoji: string | null;
+  updated_at: string;
+}
+
+export interface PluralMember {
+  id: string;
+  uuid?: string;
+  name?: string;
+  display_name?: string | null;
+  // Hex without the "#"
+  color?: string | null;
+  // "YYYY-MM-DD"; year 0004 means the year is hidden
+  birthday?: string | null;
+  pronouns?: string | null;
+  avatar_url?: string | null;
+  webhook_avatar_url?: string | null;
+  banner?: string | null;
+  description?: string | null;
+  created?: string | null;
+  proxy_tags?: PluralProxyTag[];
+  keep_proxy?: boolean;
+  autoproxy_enabled?: boolean | null;
+  tags?: string[];
+  pride?: string[];
+  status?: PluralMemberStatus | null;
+  is_special?: boolean;
+  original_name?: string;
+  [key: string]: unknown;
+}
+
+// `members` is missing, not empty, when nobody is fronting
+export interface FrontersResponse {
+  timestamp?: string;
+  members?: PluralMember[];
+  [key: string]: unknown;
+}
+
+export interface MentalState {
+  level: string;
+  updated_at: string;
+  notes?: string | null;
+}
+
+export interface PluralSystem {
+  id?: string;
+  uuid?: string;
+  name?: string | null;
+  description?: string | null;
+  tag?: string | null;
+  avatar_url?: string | null;
+  banner?: string | null;
+  color?: string | null;
+  created?: string | null;
+  timezone?: string | null;
+  mental_state?: MentalState;
+  [key: string]: unknown;
+}
+
+export interface MemberStatusResponse {
+  success: boolean;
+  member_identifier: string;
+  status: PluralMemberStatus | null;
+}
+
+export interface UserResponse {
+  id: string;
+  username: string;
+  display_name?: string | null;
+  email?: string | null;
+  email_verified?: boolean;
+  pending_email?: string | null;
+  created_at?: string | null;
+  is_admin: boolean;
+  is_owner: boolean;
+  is_pet: boolean;
+  avatar_url?: string | null;
+}
+
+export interface Relationship {
+  id: string;
+  members: [string, string];
+  type: string;
+  since: string | null;
+}
+
+export interface RelationshipsResponse {
+  status: string;
+  relationships: Relationship[];
+}
+
+export interface SwitchResponse {
+  status?: string;
+  success?: boolean;
+  message?: string;
+  count?: number;
+  [key: string]: unknown;
+}
diff --git a/src/routes/[member_id]/+page.ts b/src/routes/[member_id]/+page.ts
index 2659c44..8245c04 100644
--- a/src/routes/[member_id]/+page.ts
+++ b/src/routes/[member_id]/+page.ts
@@ -5,7 +5,7 @@
  */
 
 import { error } from "@sveltejs/kit";
-import type { PluralMember } from "doughmination-api/server";
+import type { PluralMember } from "#lib/types.ts";
 import type { PageLoad } from "./$types";
 import { publicClient } from "#lib/api.ts";
 
diff --git a/src/routes/admin/members/+page.svelte b/src/routes/admin/members/+page.svelte
index 8934547..b5c20fd 100644
--- a/src/routes/admin/members/+page.svelte
+++ b/src/routes/admin/members/+page.svelte
@@ -6,7 +6,7 @@
 
 <script lang="ts">
   import { onMount } from "svelte";
-  import type { PluralMember, PluralProxyTag } from "doughmination-api/server";
+  import type { PluralMember, PluralProxyTag } from "#lib/types.ts";
   import { avatarFallback, errorText, fallbackAvatar, memberName, sortMembers, type Message as MessageType } from "#lib";
   import { authFetch, client } from "#lib/api.ts";
   import { auth } from "#lib/auth.svelte.ts";
@@ -62,9 +62,7 @@
   let saving = $state(false);
   let message = $state<MessageType>(null);
 
-  let importFile = $state<FileList | null>(null);
   let avatarFile = $state<FileList | null>(null);
-  let replaceExisting = $state(false);
 
   const chosen = $derived(members.find((member) => member.id === chosenId) ?? null);
 
@@ -208,28 +206,6 @@
       return "Member deleted";
     }, "Failed to delete member");
   }
-
-  function importExport(event: SubmitEvent) {
-    event.preventDefault();
-    const file = importFile?.[0];
-    if (!file) return;
-
-    void run(async () => {
-      const query = `replace=${replaceExisting}`;
-      const report = await authFetch<{
-        members: number;
-        switches: number;
-        media_copied: number;
-        media_failed: string[];
-      }>(`/plural/admin/import/pluralkit?${query}`, {
-        method: "POST",
-        body: await file.text(),
-      }, "Import failed");
-      await reload();
-      const failed = report.media_failed.length ? `, ${report.media_failed.length} image(s) kept their old URL` : "";
-      return `Imported ${report.members} members and ${report.switches} switches, copied ${report.media_copied} image(s)${failed}`;
-    }, "Import failed");
-  }
 </script>
 
 <svelte:head>
@@ -310,31 +286,12 @@
                 </span>
               </button>
             {:else}
-              <p class="muted">No members yet. Import a PluralKit export below.</p>
+              <p class="muted">No members yet. Create one with the form.</p>
             {/each}
           </div>
         </section>
       </div>
 
-      {#if auth.isOwner}
-        <section class="panel stack import">
-          <h2>Import</h2>
-
-          <form class="stack" onsubmit={importExport}>
-            <label class="field">
-              <span>PluralKit export file (from pk;export)</span>
-              <input type="file" accept="application/json,.json" bind:files={importFile} />
-            </label>
-            <label class="check">
-              <input type="checkbox" bind:checked={replaceExisting} />
-              Replace the system already here, with its members and switch history
-            </label>
-            <div class="buttons">
-              <button type="submit" class="primary" disabled={saving || !importFile?.length}>Import export</button>
-            </div>
-          </form>
-        </section>
-      {/if}
     {/if}
   </div>
 </Protected>
@@ -349,7 +306,4 @@
     font-size: 1.05rem;
   }
 
-  .import {
-    margin-top: 1.25rem;
-  }
 </style>
diff --git a/src/routes/admin/mental/+page.svelte b/src/routes/admin/mental/+page.svelte
index 06dad1a..e8bbc19 100644
--- a/src/routes/admin/mental/+page.svelte
+++ b/src/routes/admin/mental/+page.svelte
@@ -11,7 +11,7 @@
   import IcReportProblem from "~icons/ic/outline-report-problem";
   import IcWarningAmber from "~icons/ic/outline-warning-amber";
   import { onMount } from "svelte";
-  import type { MentalState } from "doughmination-api/server";
+  import type { MentalState } from "#lib/types.ts";
   import { errorText, type Message as MessageType } from "#lib";
   import { client } from "#lib/api.ts";
   import Protected from "#lib/components/Protected.svelte";
diff --git a/src/routes/admin/pride/+page.svelte b/src/routes/admin/pride/+page.svelte
index 0cae3a2..77190eb 100644
--- a/src/routes/admin/pride/+page.svelte
+++ b/src/routes/admin/pride/+page.svelte
@@ -6,7 +6,7 @@
 
 <script lang="ts">
   import { onMount } from "svelte";
-  import type { PluralMember } from "doughmination-api/server";
+  import type { PluralMember } from "#lib/types.ts";
   import { avatarFallback, errorText, fallbackAvatar, memberName, sortMembers, type Message as MessageType } from "#lib";
   import { client } from "#lib/api.ts";
   import { PRIDE_FLAGS } from "#lib/pride.ts";
diff --git a/src/routes/admin/relationships/+page.svelte b/src/routes/admin/relationships/+page.svelte
index ba2e7f5..b087fb9 100644
--- a/src/routes/admin/relationships/+page.svelte
+++ b/src/routes/admin/relationships/+page.svelte
@@ -7,7 +7,7 @@
 <script lang="ts">
   import IcFavorite from "~icons/ic/outline-favorite";
   import { onMount } from "svelte";
-  import type { PluralMember, Relationship } from "doughmination-api/server";
+  import type { PluralMember, Relationship } from "#lib/types.ts";
   import { errorText, memberName, sortMembers, type Message as MessageType } from "#lib";
   import { client } from "#lib/api.ts";
   import Protected from "#lib/components/Protected.svelte";
diff --git a/src/routes/admin/status/+page.svelte b/src/routes/admin/status/+page.svelte
index ad78fe0..a1b4e2c 100644
--- a/src/routes/admin/status/+page.svelte
+++ b/src/routes/admin/status/+page.svelte
@@ -6,7 +6,7 @@
 
 <script lang="ts">
   import { onMount } from "svelte";
-  import type { PluralMember } from "doughmination-api/server";
+  import type { PluralMember } from "#lib/types.ts";
   import { avatarFallback, errorText, fallbackAvatar, memberName, sortMembers, type Message as MessageType } from "#lib";
   import { authFetch, client } from "#lib/api.ts";
   import Protected from "#lib/components/Protected.svelte";
diff --git a/src/routes/admin/switch/+page.svelte b/src/routes/admin/switch/+page.svelte
index e17bad4..415db60 100644
--- a/src/routes/admin/switch/+page.svelte
+++ b/src/routes/admin/switch/+page.svelte
@@ -6,7 +6,7 @@
 
 <script lang="ts">
   import { onMount } from "svelte";
-  import type { PluralMember } from "doughmination-api/server";
+  import type { PluralMember } from "#lib/types.ts";
   import { avatarFallback, errorText, fallbackAvatar, memberName, sortMembers, type Message as MessageType } from "#lib";
   import { client } from "#lib/api.ts";
   import Protected from "#lib/components/Protected.svelte";
diff --git a/src/routes/admin/tags/+page.svelte b/src/routes/admin/tags/+page.svelte
index 75404b7..0a56ef6 100644
--- a/src/routes/admin/tags/+page.svelte
+++ b/src/routes/admin/tags/+page.svelte
@@ -6,7 +6,7 @@
 
 <script lang="ts">
   import { onMount } from "svelte";
-  import type { PluralMember } from "doughmination-api/server";
+  import type { PluralMember } from "#lib/types.ts";
   import { avatarFallback, errorText, fallbackAvatar, memberName, sortMembers, type Message as MessageType } from "#lib";
   import { authFetch, client } from "#lib/api.ts";
   import Protected from "#lib/components/Protected.svelte";
diff --git a/src/routes/relationships/+page.svelte b/src/routes/relationships/+page.svelte
index c95b0b5..742cf3d 100644
--- a/src/routes/relationships/+page.svelte
+++ b/src/routes/relationships/+page.svelte
@@ -5,7 +5,7 @@
 -->
 
 <script lang="ts">
-  import type { PluralMember } from "doughmination-api/server";
+  import type { PluralMember } from "#lib/types.ts";
   import { avatarFallback, fallbackAvatar, memberName } from "#lib";
   import PageHead from "#lib/components/PageHead.svelte";
   import RelationshipGraph from "#lib/components/RelationshipGraph.svelte";
diff --git a/src/routes/user/login/+page.svelte b/src/routes/user/login/+page.svelte
index 8f79921..f4f87fb 100644
--- a/src/routes/user/login/+page.svelte
+++ b/src/routes/user/login/+page.svelte
@@ -19,7 +19,7 @@
   // A full navigation: the API redirects to the SSO, which comes back to /user/login/callback
   function signIn() {
     redirecting = true;
-    location.href = client.pocketIdLoginUrl(from);
+    location.href = client.loginUrl(from);
   }
 </script>