-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
96 lines (75 loc) · 3.06 KB
/
index.js
File metadata and controls
96 lines (75 loc) · 3.06 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const { logError } = require('./utils');
/**
* Initialize the native messaging host.
*
* @returns {Object} An object with two keys `send` and `addOnMessageListener`
*/
module.exports = function init() {
let onMessageCallback = null;
function startNativeMessagingHost() {
// The extension will send 4 bytes representing the payload size as header to each
// message.
let payloadSize = null;
// A queue to store the chunks as we read them from stdin.
// This queue can be flushed when `payloadSize` data has been read
let chunks = [];
// Only read the size once for each payload
const sizeHasBeenRead = () => Boolean(payloadSize);
// All the data has been read, reset everything for the next message
const flushChunksQueue = () => {
payloadSize = null;
chunks.splice(0);
};
const processData = () => {
// Create one big buffer with all all the chunks
const stringData = Buffer.concat(chunks);
// The browser will emit the size as a header of the payload,
// if it hasn't been read yet, do it.
// The next time we'll need to read the payload size is when all of the data
// of the current payload has been read (ie. data.length >= payloadSize + 4)
if (!sizeHasBeenRead()) {
payloadSize = stringData.readUInt32LE(0);
}
// If the data we have read so far is >= to the size advertised in the header,
// it means we have all of the data sent.
// We add 4 here because that's the size of the bytes that old the payloadSize
if (stringData.length >= (payloadSize + 4)) {
// Remove the header
const contentWithoutSize = stringData.slice(4, (payloadSize + 4));
// Reset the read size and the queued chunks
flushChunksQueue();
let json = null;
try {
json = JSON.parse(contentWithoutSize);
} catch (e) {
logError(`Failed to parse JSON object from extension: ${e}`);
return;
}
if (onMessageCallback) {
onMessageCallback(null, json);
}
return;
}
};
process.stdin.on('readable', () => {
// A temporary variable holding the nodejs.Buffer of each
// chunk of data read off stdin
let chunk = null;
// Read all of the available data
while ((chunk = process.stdin.read()) !== null) {
chunks.push(chunk);
}
processData();
});
}
startNativeMessagingHost();
return {
send: msg => {
const header = Buffer.alloc(4);
header.writeUInt32LE(msg.length, 0);
process.stdout.write(header);
process.stdout.write(msg);
},
addOnMessageListener: cb => onMessageCallback = cb,
};
}