API REFERENCE

WebSocket

import { WebSocketRegistry } from '@rasenganjs/server'; import type { WebSocketConnection, WebSocketContext, WebSocketHandlers, } from '@rasenganjs/server';

Core WebSocket abstraction (RFC-0001) — runtime-agnostic types plus the registry ServerApp.websocket() populates during compile(). This is the low-level primitive; see WebSockets for app.websocket() usage and WebSocket Gateways for the higher-level @rasenganjs/ws Gateway abstraction built on top of it.

WebSocketRegistry

class WebSocketRegistry { register(path: string, handlers: WebSocketHandlers): void; match(pathname: string): WebSocketHandlers | undefined; readonly isEmpty: boolean; }
MemberDescription
register(path, handlers)Register handlers for a path. Throws if the path is already registered (no silent overwrite).
match(pathname)Look up the handlers for a pathname, or undefined if no route matches.
isEmptyWhether any WebSocket routes have been registered.

Built during ServerApp.compile() from every app.websocket(path, handlers) call, then handed to the runtime adapter (Node/Bun/...) so it can dispatch an incoming upgrade request by pathname. Retrieve the compiled registry with app.getWebSocketRegistry() — see ServerApp.

WebSocketConnection

interface WebSocketConnection { send(data: string | ArrayBuffer): void; close(code?: number, reason?: string): void; readonly readyState: number; readonly protocol: string; }

A single live connection, normalized across runtimes — Node's ws connections, Bun's ServerWebSocket, and workerd's WebSocketPair are each wrapped by their runtime adapter to satisfy this shape. readyState mirrors the standard WebSocket CONNECTING/OPEN/CLOSING/CLOSED values.

WebSocketContext

interface WebSocketContext { request: Request; socket: WebSocketConnection; }

Passed to every handler in WebSocketHandlers. request is the original upgrade request — read headers, cookies, or query params from it during open.

WebSocketHandlers

interface WebSocketHandlers { open?(ctx: WebSocketContext): void | Promise<void>; message?( ctx: WebSocketContext, data: string | ArrayBuffer ): void | Promise<void>; close?( ctx: WebSocketContext, code?: number, reason?: string ): void | Promise<void>; error?(ctx: WebSocketContext, error: Error): void | Promise<void>; }
HandlerCalled
open(ctx)Once the upgrade completes and the connection is open.
message(ctx, data)For every incoming message on the connection.
close(ctx, code?, reason?)When the connection closes, normally or otherwise.
error(ctx, error)When the underlying connection errors out.
app.websocket()
app.websocket('/chat', { open(ctx) { ctx.socket.send('welcome'); }, message(ctx, data) { ctx.socket.send(`echo: ${data}`); }, close(ctx, code, reason) { console.log('closed', code, reason); }, });
defineModule
Upload