~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
132 lines · 5.4 KB Raw History
// 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<M extends Query | Procedure> = InferMethodOutputBody<M, never>;

/** What the query `Q` is asked with, its defaults left to the server. */
export type Asked<Q extends Query> = InferInput<Q['parameters']>;

/** What the procedure `P` takes. */
export type Given<P extends Procedure> = InferMethodInputBody<P, never>;

/** 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<unknown> {
	if (res.status === 401) {
		signedOut();
		throw new SignedOut();
	}
	if (!res.ok) {
		const failure: Partial<LexErrorData> | 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<Q extends Query>(nsid: Q['nsid'], params: Asked<Q>): Promise<Answer<Q>> {
	const res = await fetch(`/xrpc/${nsid}${searched(params)}`, { credentials: 'same-origin', cache: 'no-cache' });
	return (await answer(res)) as Answer<Q>;
}

/** 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<P extends Procedure>(nsid: P['nsid'], input: Given<P>): Promise<Answer<P>> {
	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<P>;
}

/** 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<unknown> {
	const { promise, resolve, reject } = Promise.withResolvers<unknown>();
	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/<step>`, 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<unknown> {
	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<string> {
	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<string> {
	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();
}