171 lines
5.3 KiB
JavaScript
171 lines
5.3 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.WebsocketClient = void 0;
|
|
const tslib_1 = require("tslib");
|
|
const ws_1 = tslib_1.__importDefault(require("ws"));
|
|
const utils_1 = require("@trezor/utils");
|
|
const DEFAULT_TIMEOUT = 20 * 1000;
|
|
const DEFAULT_PING_TIMEOUT = 50 * 1000;
|
|
class WebsocketClient extends utils_1.TypedEmitter {
|
|
options;
|
|
messages;
|
|
emitter = this;
|
|
ws;
|
|
pingTimeout;
|
|
connectPromise;
|
|
constructor(options) {
|
|
super();
|
|
this.options = options;
|
|
this.messages = (0, utils_1.createDeferredManager)({
|
|
timeout: this.options.timeout || DEFAULT_TIMEOUT,
|
|
onTimeout: this.onTimeout.bind(this),
|
|
});
|
|
}
|
|
initWebsocket({ url, timeout, headers, agent }) {
|
|
if (typeof url !== 'string') {
|
|
throw new Error('websocket_no_url');
|
|
}
|
|
if (url.startsWith('http')) {
|
|
url = url.replace('http', 'ws');
|
|
}
|
|
return new ws_1.default(url, { timeout, headers, agent });
|
|
}
|
|
setPingTimeout() {
|
|
clearTimeout(this.pingTimeout);
|
|
const doPing = () => {
|
|
if (this.isConnected()) {
|
|
return this.onPing().catch(() => { });
|
|
}
|
|
};
|
|
this.pingTimeout = this.isConnected()
|
|
? setTimeout(doPing, this.options.pingTimeout || DEFAULT_PING_TIMEOUT)
|
|
: undefined;
|
|
}
|
|
onPing() {
|
|
return this.ping();
|
|
}
|
|
onTimeout() {
|
|
const { ws } = this;
|
|
if (!ws)
|
|
return;
|
|
this.messages.rejectAll(new Error('websocket_timeout'));
|
|
ws.close();
|
|
}
|
|
onError() {
|
|
this.onClose();
|
|
}
|
|
sendMessage(message) {
|
|
const { ws } = this;
|
|
if (!ws || !this.isConnected())
|
|
throw new Error('websocket_not_initialized');
|
|
const { promiseId, promise } = this.messages.create();
|
|
const req = { id: promiseId.toString(), ...message };
|
|
this.setPingTimeout();
|
|
this.options.onSending?.(message);
|
|
ws.send(JSON.stringify(req));
|
|
return promise;
|
|
}
|
|
sendRawMessage(message) {
|
|
const { ws } = this;
|
|
if (!ws || !this.isConnected())
|
|
throw new Error('websocket_not_initialized');
|
|
ws.send(message, {
|
|
binary: typeof message !== 'string',
|
|
});
|
|
this.setPingTimeout();
|
|
}
|
|
onMessage(message, messageValidation) {
|
|
try {
|
|
const data = JSON.parse(message.toString());
|
|
const messageId = Number(data.id);
|
|
try {
|
|
const payload = messageValidation ? messageValidation(data) : data;
|
|
if (payload) {
|
|
this.messages.resolve(messageId, payload);
|
|
}
|
|
}
|
|
catch (error) {
|
|
this.messages.reject(messageId, error);
|
|
}
|
|
}
|
|
catch {
|
|
}
|
|
finally {
|
|
this.setPingTimeout();
|
|
}
|
|
}
|
|
async connect() {
|
|
if (this.connectPromise) {
|
|
return this.connectPromise;
|
|
}
|
|
if (this.isConnected())
|
|
return Promise.resolve();
|
|
if (this.ws?.readyState === ws_1.default.CLOSING) {
|
|
await new Promise(resolve => this.emitter.once('disconnected', resolve));
|
|
}
|
|
const dfd = (0, utils_1.createDeferred)();
|
|
this.connectPromise = dfd.promise;
|
|
const ws = this.createWebsocket();
|
|
const connectionTimeout = setTimeout(() => {
|
|
ws.emit('error', new Error('websocket_timeout'));
|
|
try {
|
|
ws.once('error', () => { });
|
|
ws.close();
|
|
}
|
|
catch {
|
|
}
|
|
}, this.options.connectionTimeout || this.options.timeout || DEFAULT_TIMEOUT);
|
|
ws.once('error', error => {
|
|
clearTimeout(connectionTimeout);
|
|
this.onClose();
|
|
dfd.reject(new Error(error.message));
|
|
});
|
|
ws.on('open', () => {
|
|
clearTimeout(connectionTimeout);
|
|
this.init();
|
|
dfd.resolve();
|
|
});
|
|
this.ws = ws;
|
|
return dfd.promise.finally(() => {
|
|
this.connectPromise = undefined;
|
|
});
|
|
}
|
|
init() {
|
|
const { ws } = this;
|
|
if (!ws || !this.isConnected()) {
|
|
throw Error('Websocket init cannot be called');
|
|
}
|
|
ws.removeAllListeners();
|
|
ws.on('error', _error => this.onError());
|
|
ws.on('message', message => this.onMessage(message));
|
|
ws.on('close', () => {
|
|
this.emitter.emit('disconnected');
|
|
this.onClose();
|
|
});
|
|
}
|
|
disconnect() {
|
|
if (this.isConnected()) {
|
|
const disconnectPromise = new Promise(resolve => {
|
|
this.ws?.once('close', resolve);
|
|
});
|
|
this.ws?.close();
|
|
return disconnectPromise;
|
|
}
|
|
return Promise.resolve();
|
|
}
|
|
isConnected() {
|
|
return this.ws?.readyState === ws_1.default.OPEN;
|
|
}
|
|
onClose() {
|
|
clearTimeout(this.pingTimeout);
|
|
this.ws?.removeAllListeners();
|
|
this.messages.rejectAll(new Error('Websocket closed unexpectedly'));
|
|
}
|
|
dispose() {
|
|
this.removeAllListeners();
|
|
this.disconnect();
|
|
this.onClose();
|
|
}
|
|
}
|
|
exports.WebsocketClient = WebsocketClient;
|
|
//# sourceMappingURL=client.js.map
|