-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmicro-repl.js
More file actions
156 lines (142 loc) · 3.83 KB
/
micro-repl.js
File metadata and controls
156 lines (142 loc) · 3.83 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
const ENTER = '\r\n';
const CONTROL_C = '\x03';
const CONTROL_E = '\x05';
const CONTROL_D = '\x04';
const LINE_SEPARATOR = /(?:\r|\n|\r\n)/;
/**
* Common error for `read` or `write` when the REPL
* is not active anymore.
* @param {string} action
*/
const error = action => {
throw new Error(`Unable to ${action} a closed SerialPort`);
};
// default `init(options)` values
const options = {
baudRate: 115200,
/**
* Invoked once the repl has been closed or an
* error occurred. In the former case `error` is `null`,
* in every other case the `error` is what the REPL produced.
* @param {Error?} error
*/
onceClosed(error) {
if (error) console.error(error);
},
};
export default async ({
baudRate = options.baudRate,
onceClosed = options.onceClosed,
} = options) => {
let port;
try {
port = await navigator.serial.requestPort();
await port.open({ baudRate });
}
catch (error) {
onceClosed(error);
throw error;
}
// create the reader
const decoder = new TextDecoderStream;
const readerClosed = port.readable.pipeTo(decoder.writable);
const reader = decoder.readable.getReader();
// create the writer
const encoder = new TextEncoderStream;
const writerClosed = encoder.readable.pipeTo(port.writable);
const writer = encoder.writable.getWriter();
// internal helpers
const uuid = `# ${crypto.randomUUID()}`;
const eop = `${uuid}${ENTER}`;
const ignore = new Set([
'=== ',
'paste mode; Ctrl-C to cancel, Ctrl-D to finish',
]);
let output = '';
let result = '';
let active = true;
let wait = Promise.withResolvers();
try {
await writer.write(CONTROL_C);
await writer.write(eop);
}
catch (error) {
onceClosed(error);
throw error;
}
(async () => {
while (true) {
const { value, done } = await reader.read();
if (done) {
wait.resolve('');
reader.releaseLock();
break;
}
output += value;
if (output.endsWith(`${eop}>>> `))
output = output.slice(0, -4);
if (output.endsWith(eop)) {
const out = [];
for (const line of output.split(ENTER)) {
if (ignore.has(line) || line.includes(uuid)) continue;
out.push(line.replace(/^=== \n/, ''));
}
output = '';
if (out[0] === '>>> ') {
out.shift();
out[0] = out[0].replace(/^=== /, '>>> ');
}
result = out.at(-2);
wait.resolve(out.join(ENTER).trimStart());
}
}
})().catch(async error => {
active = false;
onceClosed(error);
});
return {
/** @type {boolean} */
get active() { return active; },
/** @type {Promise<string>} */
get output() {
if (!active) error('read');
return wait.promise;
},
/** @type {Promise<string>} */
get result() {
return wait.promise.then(() => result);
},
/**
* Flag the port as inactive and closes it.
* This dance without unknown errors has been brought to you by:
* https://stackoverflow.com/questions/71262432/how-can-i-close-a-web-serial-port-that-ive-piped-through-a-transformstream
*/
close: async () => {
if (active) {
active = false;
reader.cancel();
await readerClosed.catch(Object); // no-op - expected
writer.close();
await writerClosed;
await port.close();
output = '';
onceClosed(null);
}
},
/**
* Write code to the active port, throws otherwise.
* @param {string} code
*/
write: async code => {
if (!active) error('write');
await wait.promise;
wait = Promise.withResolvers();
await writer.write(CONTROL_E);
for (const line of code.split(LINE_SEPARATOR))
await writer.write(line + ENTER);
await writer.write(CONTROL_D);
await writer.write(eop);
await wait.promise;
},
};
};