-
Notifications
You must be signed in to change notification settings - Fork 0
/
nm_nodejs.js
76 lines (71 loc) · 1.62 KB
/
nm_nodejs.js
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
68
69
70
71
72
73
74
75
76
#!/usr/bin/env -S /path/to/node
// Node.js Native Messaging host
// guest271314, 10-9-2022
import process from "node:process";
const buffer = new ArrayBuffer(0, {
maxByteLength: 1024 ** 2
});
const view = new DataView(buffer);
const encoder = new TextEncoder();
const readable = process.stdin;
const writable = new WritableStream({
write(value) {
process.stdout.write(value);
}
});
const {
exit
} = process;
function encodeMessage(message) {
return encoder.encode(JSON.stringify(message));
}
async function* getMessage() {
let messageLength = 0;
let readOffset = 0;
for await (let message of readable) {
if (buffer.byteLength === 0 && messageLength === 0) {
buffer.resize(4);
for (let i = 0; i < 4; i++) {
view.setUint8(i, message[i]);
}
messageLength = view.getUint32(0, true);
message = message.subarray(4);
buffer.resize(0);
}
buffer.resize(buffer.byteLength + message.length);
for (let i = 0; i < message.length; i++, readOffset++) {
view.setUint8(readOffset, message[i]);
}
if (buffer.byteLength === messageLength) {
yield new Uint8Array(buffer);
messageLength = 0;
readOffset = 0;
buffer.resize(0);
}
}
}
async function sendMessage(message) {
await new Blob([
new Uint8Array(new Uint32Array([message.length]).buffer),
message,
])
.stream()
.pipeTo(writable, {
preventClose: true
});
}
try {
for await (const message of getMessage()) {
await sendMessage(message);
}
} catch (e) {
exit();
}
export {
encodeMessage,
exit,
getMessage,
readable,
sendMessage,
writable,
};