Files
trezor-suite/packages/websocket-client/src/ws-browser.ts
2025-03-25 16:42:57 +01:00

67 lines
1.8 KiB
TypeScript

import { EventEmitter } from 'events';
import { WebsocketError } from './client';
/**
* Provides `EventEmitter` interface for native browser `WebSocket`,
* same, as `ws` package provides.
*/
class WSWrapper extends EventEmitter {
private _ws: WebSocket;
static CONNECTING = 0;
static OPEN = 1;
static CLOSING = 2;
static CLOSED = 3;
constructor(url: string, _protocols: any, _websocketOptions: any) {
super();
this._ws = new WebSocket(url);
this._ws.onclose = () => {
this.emit('close');
};
this._ws.onopen = () => {
this.emit('open');
};
// WebSocket error Event does not contain any useful description.
// https://websockets.spec.whatwg.org//#dom-websocket-onerror
// If the user agent was required to fail the WebSocket connection,
// or if the WebSocket connection was closed after being flagged as full,
// fire an event named error at the WebSocket object.
// https://stackoverflow.com/a/31003057
this._ws.onerror = _event => {
this.emit(
'error',
new WebsocketError(`WsWrapper error. Ready state: ${this.readyState}`),
);
};
this._ws.onmessage = message => {
this.emit('message', message.data);
};
}
close() {
if (this.readyState === WSWrapper.OPEN) {
this._ws.close();
}
}
send(message: any) {
if (this.readyState !== WSWrapper.OPEN) {
throw new WebsocketError(`Connection is not open. state: ${this.readyState}`);
}
this._ws.send(message);
}
get readyState() {
return this._ws.readyState;
}
}
// eslint-disable-next-line import/no-default-export
export default WSWrapper;