@furystack/websocket-api
Version:
WebSocket API implementation for FuryStack
66 lines • 2.67 kB
TypeScript
import type { Injector } from '@furystack/inject';
import { type ServerApi } from '@furystack/rest-service';
import { EventHub, type ListenerErrorPayload } from '@furystack/utils';
import type { IncomingMessage } from 'http';
import type WebSocket from 'ws';
import { WebSocketServer } from 'ws';
import type { WebSocketAction } from './models/websocket-action.js';
/**
* Events emitted by a {@link WebSocketApi} handle. Per-connection lifecycle
* events stay on the handle — each `useWebSocketApi` call returns its own
* EventHub — while action-execution errors are forwarded to the shared
* `ServerTelemetryToken` under `onWebSocketActionFailed`.
*/
export type WebSocketApiEvents = {
onClientConnected: {
ws: WebSocket;
message: IncomingMessage;
};
/** Fires after the per-connection scope has been disposed. */
onClientDisconnected: {
ws: WebSocket;
};
onListenerError: ListenerErrorPayload;
};
/**
* Callback payload supplied to {@link WebSocketApi.broadcast}.
*/
export interface WebSocketBroadcastContext {
injector: Injector;
ws: WebSocket;
message: IncomingMessage;
}
/**
* Handle returned by {@link useWebSocketApi}. Exposes the underlying
* `WebSocketServer`, a `broadcast` helper and the `ServerApi` that was
* pushed onto the pooled HTTP server. Extends {@link EventHub} so callers
* can subscribe to per-connection lifecycle events.
*/
export interface WebSocketApi extends EventHub<WebSocketApiEvents> {
readonly socket: WebSocketServer;
readonly serverApi: ServerApi;
broadcast(callback: (options: WebSocketBroadcastContext) => void | Promise<void>): Promise<void>;
}
/**
* Options accepted by {@link useWebSocketApi}.
*/
export interface UseWebSocketApiOptions {
/** Injector whose HTTP server pool should host the websocket endpoint. */
injector: Injector;
/** Port of the pooled HTTP server. */
port: number;
/** Optional host name; defaults to `localhost`. */
hostName?: string;
/** URL path the websocket endpoint answers on. Defaults to `/socket`. */
path?: string;
/** Action descriptors consulted for every incoming message (first match wins). */
actions?: WebSocketAction[];
}
/**
* Opens a websocket endpoint on the pooled HTTP server identified by
* `port` / `hostName`. Returns the {@link WebSocketApi} handle; disposal
* is tied to the injector scope that owns it — closing open clients,
* tearing down per-connection scopes and closing the `WebSocketServer`.
*/
export declare const useWebSocketApi: (options: UseWebSocketApiOptions) => Promise<WebSocketApi>;
//# sourceMappingURL=websocket-api.d.ts.map