@ayonli/jsext
Version:
A JavaScript extension package for building strong and modern applications.
66 lines (65 loc) • 2.19 kB
TypeScript
import { WebSocketConnection } from "./base.ts";
/**
* A `WebSocket` polyfill for Node.js before v21.
* See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
*
* NOTE: Must install the package from NPM to use this polyfill. If the runtime
* already supports the global `WebSocket` class, this variable will be that
* class instead of the polyfill one.
*/
export declare const WebSocket: {
new (url: string | URL, protocols?: string | string[] | undefined): WebSocket;
prototype: WebSocket;
readonly CONNECTING: 0;
readonly OPEN: 1;
readonly CLOSING: 2;
readonly CLOSED: 3;
};
declare const _ws: unique symbol;
export interface WebSocketStreamOptions {
protocols?: string | string[];
signal?: AbortSignal;
}
export interface WebSocketStreamPair {
readable: ReadableStream<string | Uint8Array>;
writable: WritableStream<string | Uint8Array>;
}
export interface WebSocketCloseInfo {
closeCode: number;
reason: string;
}
/**
* A `WebSocketStream` polyfill.
* See https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream
*
* NOTE: This API depends on the Web Streams API, in Node.js, it requires
* Node.js v18.0 or above.
*
* NOTE: This implementation is based on the `WebSocket` API and supports
* half-close, closing the writable stream will not close the connection, the
* connection will only be closed when the `close` method is called or the
* readable stream is canceled.
*
* @example
* ```ts
* // usage
* globalThis.WebSocketStream ??= (await import("@ayonli/jsext/ws")).WebSocketStream;
* ```
*/
export declare class WebSocketStream {
private [_ws];
get url(): string;
get opened(): Promise<WebSocketStreamPair & {
extensions: string;
protocol: string;
}>;
get closed(): Promise<WebSocketCloseInfo>;
constructor(url: string | URL, options?: WebSocketStreamOptions);
close(options?: Partial<WebSocketCloseInfo>): void;
}
/**
* Transforms a `WebSocket` or {@link WebSocketConnection} instance into a
* {@link WebSocketStream} instance.
*/
export declare function toWebSocketStream(ws: WebSocket | WebSocketConnection): WebSocketStream;
export {};