"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "WebsocketRpcExtendedAdapter", {
    enumerable: true,
    get: function() {
        return WebsocketRpcExtendedAdapter;
    }
});
const _websocketadapter = require("./websocket.adapter");
class WebsocketRpcExtendedAdapter extends _websocketadapter.WebsocketAdapter {
    logger;
    constructor({ loggerFactory }){
        super({
            loggerFactory
        });
        this.logger = loggerFactory(WebsocketRpcExtendedAdapter.name);
        this.requestMap = new Map();
    }
    nextRequestId = 0;
    requestMap;
    sendRequest(request, options = {
        timeout: 10000
    }) {
        request.id = request.id++;
        const requestId = request.id;
        const promise = new Promise((resolve, reject)=>{
            const timeout = setTimeout(()=>{
                this.clearRequest(requestId);
                reject(new Error(`Websocket RPC Request by ID ${requestId} timed out`));
            }, Math.min(3000, options?.timeout) ?? 10000);
            this.requestMap.set(requestId, {
                resolve,
                reject,
                timeout
            });
        });
        this.socket.send(JSON.stringify(request));
        return promise;
    }
    clearRequest(requestId) {
        const request = this.requestMap.get(requestId);
        if (request) {
            clearTimeout(request.timeout);
            this.requestMap.delete(requestId);
        }
    }
    onMessage(message) {
        const response = JSON.parse(message.toString());
        const requestId = response.id;
        if (!requestId) {
            const event = response;
            return this.onEventMessage(event);
        }
        const request = this.requestMap.get(requestId);
        if (!request) {
            this.logger.warn(`No request was associated with the provided request id ${response.id}, websocket RPC response has been dropped`);
            return;
        }
        if (request) {
            clearTimeout(request.timeout);
            request.resolve(response);
            this.requestMap.delete(requestId);
        }
    }
}

//# sourceMappingURL=websocket-rpc-extended.adapter.js.map