robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

bfredlMerge pull request #40772 from Rawan10101/wasm-browser0abc9ccc19

master
1.1 KiB34 linesraw
1// msgpack-rpc message shapes:
2//   request:      [0, msgid, method, params]
3//   response:     [1, msgid, error, result]
4//   notification: [2, method, params]
5
6const Protocol = {
7  encodeRequest(msgid, method, params) {
8    return MsgpackCodec.encode([0, msgid, method, params]);
9  },
10
11  encodeNotification(method, params) {
12    return MsgpackCodec.encode([2, method, params]);
13  },
14
15  // classifies a decoded msgpack-rpc array into a tagged object.
16  // throws if msg doesn't look like a valid rpc message.
17  parseMessage(msg) {
18    if (!Array.isArray(msg)) throw new Error("rpc message is not an array");
19    const [type, ...rest] = msg;
20    if (type === 0) {
21      const [msgid, method, params] = rest;
22      return { kind: "request", msgid, method, params };
23    }
24    if (type === 1) {
25      const [msgid, error, result] = rest;
26      return { kind: "response", msgid, error, result };
27    }
28    if (type === 2) {
29      const [method, params] = rest;
30      return { kind: "notification", method, params };
31    }
32    throw new Error("unknown rpc message type: " + type);
33  },
34};