"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RpcProcessor = void 0;
class RpcProcessor {
    constructor(child) {
        this.child = child;
        this.handlers = {};
        this.isClosed = false;
    }
    handler(method, handler) {
        this.handlers[method] = handler;
    }
    onMessage(callback) {
        this.messageCallback = callback;
    }
    async handle(method, input) {
        const handler = this.handlers[method];
        if (!handler) {
            throw new Error(`Handler for method ${method} not found`);
        }
        return handler(input);
    }
    response(id, result, error) {
        if (id && !this.isClosed && this.child.send && this.child.connected) {
            const responseMessage = {
                type: 'rpc_response',
                id,
                result: error ? undefined : result,
                error: error ? String(error) : undefined
            };
            this.child.send(responseMessage);
        }
    }
    async init() {
        this.child.on('message', (msg) => {
            // Call generic message callback if registered
            if (this.messageCallback) {
                this.messageCallback(msg);
            }
            // Handle RPC requests specifically
            if (msg && msg.type === 'rpc_request') {
                const { id, method, args } = msg;
                this.handle(method, args)
                    .then((result) => this.response(id, result, null))
                    .catch((error) => this.response(id, null, error));
            }
        });
        this.child.on('exit', () => {
            this.isClosed = true;
        });
        this.child.on('close', () => {
            this.isClosed = true;
        });
        this.child.on('disconnect', () => {
            this.isClosed = true;
        });
    }
    close() {
        this.isClosed = true;
        this.messageCallback = undefined;
    }
}
exports.RpcProcessor = RpcProcessor;
