robin/laufey

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

bfredlMerge pull request #40772 from Rawan10101/wasm-browser0abc9ccc19

master
1.8 KiB62 linesraw
1if (typeof msgpackr === 'undefined') {
2  throw new Error(
3    'msgpackr library not loaded. ' +
4    'Check that the script tag for msgpackr is present and loads correctly.'
5  );
6}
7
8// Buffer/Window/Tabpage handles come back as msgpack EXT values.
9// - Type code: not fixed across builds, so read it from
10//   nvim_get_api_info()'s types metadata at runtime instead of
11//   hardcoding it.
12// - Payload: itself a variable length msgpack integer,
13//   so it needs a real unpack call, not a fixed width DataView read.
14function registerNvimHandleTypes(types) {
15  for (const [name, info] of Object.entries(types)) {
16    msgpackr.addExtension({
17      type: info.id,
18      unpack(payload) {
19        return { __nvimType: name, id: msgpackr.unpack(payload) };
20      },
21      pack(value) {
22        return msgpackr.pack(value.id);
23      },
24    });
25    console.log(`[msgpack] registered Nvim EXT type ${info.id} -> ${name}`);
26  }
27}
28
29const MsgpackCodec = {
30  encode(value) {
31    const encoded = msgpackr.pack(value);
32    const prefix = Array.from(encoded.slice(0, Math.min(encoded.length, 8)))
33      .map(b => b.toString(16).padStart(2, '0'))
34      .join(' ');
35    console.log(`[MsgpackCodec.encode] ${encoded.length} bytes, prefix: ${prefix}`);
36    return encoded;
37  },
38
39  decodeMultiple(bytes) {
40    const messages = [];
41    let consumed = 0;
42
43    try {
44      msgpackr.unpackMultiple(bytes, (value, start, end) => {
45        messages.push(value);
46        consumed = end;
47      });
48      consumed = bytes.length;
49    } catch (e) {
50      if (!isIncompleteDataError(e)) {
51        console.error('[MsgpackCodec.decodeMultiple] fatal decode error', e, 'consumed so far:', consumed);
52        throw e;
53      }
54    }
55
56    return { messages, consumed };
57  },
58};
59
60function isIncompleteDataError(e) {
61  return /unexpected end|incomplete|out of bounds|out of range/i.test(e?.message || '');
62}