-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathx.js
236 lines (210 loc) · 6.22 KB
/
x.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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
const CONTROL_C = '\x03';
const CONTROL_D = '\x04';
const ENTER = '\r\n';
const MACHINE = `import sys;print(sys.implementation._machine)${ENTER}`;
const createWriter = writer => chunk => writer.write(chunk);
/**
* 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 each time the terminal receives data as buffer.
* @param {Uint8Array} buffer
*/
onData(buffer) {},
/**
* 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);
},
};
/**
* @typedef {Object} Options
* @prop {Element} target
* @prop {number} [baudRate=115200]
* @prop {(buffer:Uint8Array) => void} [onData]
* @prop {(error?:Error) => void} [onceClosed]
*/
export default async (/** @type {Options} */{
target,
baudRate = options.baudRate,
onData = options.onData,
onceClosed = options.onceClosed,
} = options) => {
if (!(target instanceof Element))
throw new Error("The `target` property is not a valid DOM element.");
// optimistic AOT dynamic import for all dependencies
const dependencies = [
import('https://cdn.jsdelivr.net/npm/[email protected]/+esm'),
import('https://cdn.jsdelivr.net/npm/@xterm/addon-fit/+esm'),
import('https://cdn.jsdelivr.net/npm/@xterm/addon-web-links/+esm'),
];
// bring in the CSS too if not already present
if (!document.querySelector('link[rel="stylesheet"][href$="/css/xterm.min.css"]')) {
document.head.append(
Object.assign(
document.createElement('link'),
{
rel: 'stylesheet',
href: 'https://cdn.jsdelivr.net/npm/[email protected]/css/xterm.min.css',
}
)
);
}
let port;
try {
port = await navigator.serial.requestPort();
await port.open({ baudRate });
port.ondisconnect = onceClosed;
}
catch (error) {
onceClosed(error);
throw error;
}
const [
{ Terminal },
{ FitAddon },
{ WebLinksAddon },
] = await Promise.all(dependencies);
const terminal = new Terminal({
cursorBlink: true,
cursorStyle: "block",
theme: {
background: "#191A19",
foreground: "#F5F2E7",
},
});
// create the writer
const encoder = new TextEncoderStream;
const writerClosed = encoder.readable.pipeTo(port.writable);
const writer = encoder.writable.getWriter();
const decoder = new TextDecoder;
const machine = Promise.withResolvers();
let waitForMachine = true;
let accMachine = '';
// forward the reader
const writable = new WritableStream({
write: createWriter({
write(chunk) {
if (waitForMachine) {
const text = decoder.decode(chunk);
if (accMachine === '' && text.startsWith(ENTER))
chunk = new Uint8Array(chunk.slice(ENTER.length));
accMachine += text;
const i = accMachine.indexOf(MACHINE);
if (-1 < i) {
const gotIt = accMachine.slice(i + MACHINE.length).split(ENTER);
if (gotIt.length === 2) {
waitForMachine = false;
accMachine = '.';
machine.resolve(gotIt[0]);
}
}
}
else onData(chunk);
terminal.write(chunk);
if (accMachine === '.') {
accMachine = '';
terminal.write('\x1b[A'.repeat(2));
terminal.write('\x1b[2K'.repeat(2));
terminal.write('\x1b[B'.repeat(2));
}
}
})
});
const aborter = new AbortController;
const readerClosed = port.readable.pipeTo(writable, aborter);
let pastMode = false;
terminal.attachCustomKeyEventHandler(event => {
const { type, code, composed, ctrlKey, shiftKey } = event;
if (type === 'keydown' && composed && ctrlKey && !shiftKey) {
if (pastMode)
pastMode = code !== 'KeyD';
else {
if (code === 'KeyE')
pastMode = true;
else if (code === 'KeyD') {
event.preventDefault();
writer.write(CONTROL_D);
// this is needed to boards losing the REPL mode
// the SPIKE Prime takes ~ 1.5s to boot but it could be
// interactive before that ... other boards might never
// need this, hence the RegExp check.
(async function hardReboot() {
await new Promise(res => setTimeout(res, 1500));
if (/\n $/.test(target.innerText)) {
writer.write(CONTROL_C);
await hardReboot();
}
})();
return false;
}
}
}
return true;
});
terminal.onData(createWriter(writer));
const fitAddon = new FitAddon;
terminal.loadAddon(fitAddon);
terminal.loadAddon(new WebLinksAddon);
terminal.open(target);
fitAddon.fit();
terminal.focus();
let active = true;
try {
await writer.write(CONTROL_C);
await writer.write(MACHINE);
}
catch (error) {
onceClosed(error);
throw error;
}
return machine.promise.then(name => ({
/** @type {string} */
get name() { return name },
/** @type {Terminal} */
get terminal() { return terminal },
/** @type {boolean} */
get active() { return active; },
/** @type {string} */
get output() {
if (!active) error('read');
return target.innerText;
},
/**
* 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;
aborter.abort();
writer.close();
await writerClosed;
await readerClosed.catch(Object); // no-op - expected
await port.close();
onceClosed(null);
}
},
/**
* Write code to the active port, throws otherwise.
* @param {string} code
*/
write: async code => {
if (!active) error('write');
await writer.write(code);
},
}));
};