import { buildUrl, toResponseError } from "$lib/api/_request"; const BEGIN_SIGNUP = "org.tangled.temp.account.beginSignup"; const RESEND_SIGNUP = "org.tangled.temp.account.resendSignup"; const COMPLETE_SIGNUP = "org.tangled.temp.account.completeSignup"; const errorMessage = async (response: Response, fallback: string): Promise => { const err = await toResponseError(response); if (err.description) return err.description; // "XRPCError" is toResponseError's sentinel for non-JSON bodies, not a service code if (err.error && err.error !== "XRPCError") return err.error; return fallback; }; // open endpoints: no service auth, the turnstile challenge guards beginSignup export const beginSignup = async ( serviceUrl: string, email: string, turnstileToken: string, fetchFn: typeof globalThis.fetch = fetch ): Promise => { const response = await fetchFn(buildUrl(serviceUrl, BEGIN_SIGNUP), { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify({ email, turnstileToken }) }); if (!response.ok) { throw new Error(await errorMessage(response, `could not begin signup: ${response.status}`)); } }; export const resendSignup = async ( serviceUrl: string, email: string, fetchFn: typeof globalThis.fetch = fetch ): Promise => { const response = await fetchFn(buildUrl(serviceUrl, RESEND_SIGNUP), { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify({ email }) }); if (!response.ok) { throw new Error( await errorMessage(response, `could not resend signup: ${response.status}`) ); } }; export const completeSignup = async ( serviceUrl: string, token: string, username: string, password: string, fetchFn: typeof globalThis.fetch = fetch ): Promise<{ did: string; handle: string }> => { const response = await fetchFn(buildUrl(serviceUrl, COMPLETE_SIGNUP), { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify({ token, username, password }) }); if (!response.ok) { throw new Error( await errorMessage(response, `could not complete signup: ${response.status}`) ); } // a successful signup must return both fields; anything else is a broken // response, and the pages must not render "Account created" for it const body: unknown = await response.json().catch(() => null); const did = (body as { did?: unknown } | null)?.did; const handle = (body as { handle?: unknown } | null)?.handle; if (typeof did !== "string" || typeof handle !== "string") { throw new Error("could not complete signup: the service returned an invalid response"); } return { did, handle }; };