import { CancellationError } from "@repo/common/errors.ts"; import { errorHandler } from "./handler-error.ts"; import { preauthHandler } from "./handler-preauth.ts"; import { realmHandler } from "./handler-realm.ts"; import { attachSocket, detachSocket } from "./state.ts"; export async function socketHandler(this: WebSocket) { const controller = new AbortController(); this.addEventListener("close", () => queueMicrotask(() => { controller.abort(new CancellationError("socket closed")); })); try { const { realm, ...auth } = await preauthHandler(this, controller.signal); try { attachSocket(realm, auth.identid, this); await realmHandler(this, realm, auth, controller.signal); } finally { detachSocket(realm, auth.identid, this); } } catch (e) { errorHandler(this, e); } finally { if (this.readyState !== this.CLOSED) { this.send(`kthkbye\n`); this.close(); } } }