UNPKG

1.47 kBTypeScriptView Raw
1import type { ServerRequest, Params } from 'worktop/request';
2
3declare global {
4 const WebSocketPair: {
5 new(): {
6 /** the `client` socket */
7 0: WebSocket,
8 /** the `server` socket */
9 1: WebSocket,
10 };
11 };
12
13 interface ResponseInit {
14 webSocket?: WebSocket;
15 }
16}
17
18export interface WebSocket {
19 accept(): void;
20 send(message: number | string): void;
21 close(code?: number, reason?: string): void;
22 addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any): void;
23 addEventListener(type: string, listener: EventListener): void;
24}
25
26type Context = Record<string, any>;
27export interface Socket<C extends Context = Context> {
28 send: WebSocket['send'];
29 close: WebSocket['close'];
30 context: C;
31 event:
32 | { type: 'open' } & Event
33 | { type: 'close' } & CloseEvent
34 | { type: 'message' } & MessageEvent<string>
35 | { type: 'error' } & Event;
36}
37
38export type SocketHandler<
39 P extends Params = Params,
40 C extends Context = Context,
41> = (req: ServerRequest<P>, socket: Socket<C>) => Promise<void>|void;
42
43/**
44 * Ensure the incoming `Request` can be upgraded to a Websocket connection.
45 * @NOTE This is called automatically within the `listen()` method.
46 */
47export const connect: Handler;
48
49/**
50 * Establish a Websocket connection.
51 * Attach the `handler` as the 'message' event listener.
52 * @NOTE Invokes the `connect()` middleware automatically.
53 */
54export function listen(handler: SocketHandler): Handler;