// The workspace's side of HUD's appview: its XRPC methods // (`/xrpc/place.hud.*`, same origin, as the web session's // cookie), typed by the lexicons under schemas/, which `npm run lex` makes // into lib/lexicons, and the web session's own (`/workspace/signin`, // `switch`, `signout`). As knotless's web/src/lib/data.ts. A method that // answers 401 (`AuthRequired`) means the session is gone: whoever listens // (the app) shows the sign-in dialog. import type { InferInput, InferMethodInputBody, InferMethodOutputBody, LexErrorData, Procedure, Query } from '@atproto/lex'; /** What the method `M` answers. */ export type Answer = InferMethodOutputBody; /** What the query `Q` is asked with, its defaults left to the server. */ export type Asked = InferInput; /** What the procedure `P` takes. */ export type Given

= InferMethodInputBody; /** A method's failure, by its lexicon error's name (`NotFound`, `Forbidden`…), in the server's words. */ export class XrpcError extends Error { constructor( readonly error: string, message: string ) { super(message); } } /** The session is gone: sign in again. */ export class SignedOut extends Error { constructor() { super('Signed out.'); } } let signedOut: () => void = () => {}; /** Hear when any method finds the session gone. */ export function onSignedOut(listener: () => void) { signedOut = listener; } async function answer(res: Response): Promise { if (res.status === 401) { signedOut(); throw new SignedOut(); } if (!res.ok) { const failure: Partial | null = await res.json().catch(() => null); throw new XrpcError(failure?.error ?? 'InternalServerError', failure?.message ?? `HUD answered ${res.status}.`); } return res.json(); } /** A query's parameters as its address has them: an array's values each under its name. */ function searched(params: object): string { const query = new URLSearchParams(); for (const [k, v] of Object.entries(params)) for (const one of v === undefined ? [] : [v].flat()) query.append(k, String(one)); return query.size ? `?${query}` : ''; } /** What the XRPC query `Q`, by its NSID, answers `params` with. */ export async function xrpc(nsid: Q['nsid'], params: Asked): Promise> { const res = await fetch(`/xrpc/${nsid}${searched(params)}`, { credentials: 'same-origin', cache: 'no-cache' }); return (await answer(res)) as Answer; } /** What the XRPC procedure `P`, by its NSID, answers `input` with; with the header HUD asks of the workspace's writes. */ export async function procedure

(nsid: P['nsid'], input: Given

): Promise> { const res = await fetch(`/xrpc/${nsid}`, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-HUD': '1' }, body: JSON.stringify(input) }); return (await answer(res)) as Answer

; } /** What the XRPC procedure `nsid` answers `bytes` with, sent as its body (a * picture), with the header HUD asks of the workspace's writes; `onprogress` * hears how much has gone, from 0 to 1, as `fetch` cannot say. */ export function upload(nsid: string, bytes: Blob, onprogress: (fraction: number) => void): Promise { const { promise, resolve, reject } = Promise.withResolvers(); const request = new XMLHttpRequest(); request.open('POST', `/xrpc/${nsid}`); request.withCredentials = true; request.setRequestHeader('Content-Type', bytes.type || 'application/octet-stream'); request.setRequestHeader('X-HUD', '1'); request.upload.onprogress = (event) => { if (event.lengthComputable) onprogress(event.loaded / event.total); }; request.onload = () => resolve(answer(new Response(request.responseText || null, { status: request.status }))); request.onerror = () => reject(new Error('The upload could not reach HUD.')); request.send(bytes); return promise; } /** A step of the web session's own, `/workspace/`, given `input`, with the header HUD asks of the workspace's writes: what it answers, or an `XrpcError` saying why not. */ async function session(step: 'signin' | 'switch' | 'signout', input: object): Promise { const res = await fetch(`/workspace/${step}`, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-HUD': '1' }, body: JSON.stringify(input) }); return answer(res); } /** Sign in as the account a handle (or a DID) names, here or as another account beside the one signed in: the address of its account server's page to approve it on. */ export async function signIn(handle: string): Promise { const { url } = (await session('signin', { handle })) as { url: string }; return url; } /** Where to make a new account, on the sign-up PDS: its page, which sends the browser back here signed in as it. */ export async function signUp(): Promise { const { url } = (await session('signin', { create: true })) as { url: string }; return url; } /** Go on as another account this browser is signed in to, without signing in again: the page is read again as it. */ export async function switchAccount(did: string) { await session('switch', { did }); location.reload(); } /** Leave: the web session ends, and the page is read again, as the account this browser used before it if it holds one, else signed out. */ export async function signOut() { await session('signout', {}).catch(() => null); location.reload(); }