summaryrefslogtreecommitdiff
path: root/src/dist/classes/CLIDispatcher.js
blob: 35195af2203e1a3a98c175e1915eb96a368424ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLIDispatcher = void 0;
const crypto_1 = require("crypto");
const SignalAPIError_1 = require("./SignalAPIError");
/**
 * A dispatcher used to send requests to signal-cli and receive a response
 */
class CLIDispatcher {
    /**
     * Dispatch a request to signal-cli
     *
     * @param method - The method to associate with the request.
     * Use `signal-cli --help` to get a full list
     * @param params - The parameters to pass with the request.
     * Use `signal-cli <method> --help` to get a full list for the current method
     * @param proc - The signal-cli process to dispatch to
     */
    static dispatch(method, params, proc) {
        return new Promise((res, rej) => {
            let id = (0, crypto_1.randomUUID)();
            let payload = {
                jsonrpc: "2.0", method, params, id
            };
            let lastData;
            let callback = (chunk) => {
                if (chunk.toString().trim() === "")
                    return;
                for (let line of chunk.toString().trim().replaceAll("\r\n").split("\n")) {
                    try {
                        JSON.parse(line);
                        lastData = null;
                    }
                    catch (e) {
                        if (lastData) {
                            line = lastData + line;
                            try {
                                JSON.parse(line);
                                lastData = null;
                            }
                            catch (e) {
                                lastData = line;
                            }
                        }
                        else {
                            lastData = line;
                        }
                    }
                    if (!lastData) {
                        let data = JSON.parse(line);
                        if (data.error) {
                            rej(new SignalAPIError_1.SignalAPIError(data.error.message ?? null, data.error.code ?? null));
                        }
                        if (data.id === id) {
                            res(data);
                            proc.stdout.removeListener("data", callback);
                        }
                    }
                }
            };
            proc.stdout.addListener('data', callback);
            proc.stdin.write(JSON.stringify(payload) + "\n");
        });
    }
}
exports.CLIDispatcher = CLIDispatcher;
//# sourceMappingURL=CLIDispatcher.js.map