webserial-core 1.2.0 → 2.0.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/{LICENSE → LICENSE.md} +1 -1
  2. package/README.md +142 -287
  3. package/dist/adapters/web-bluetooth/WebBluetoothProvider.d.ts +19 -0
  4. package/dist/adapters/web-bluetooth/index.d.ts +6 -0
  5. package/dist/adapters/web-usb/WebUsbProvider.d.ts +127 -0
  6. package/dist/adapters/web-usb/index.d.ts +6 -0
  7. package/dist/adapters/websocket/WebSocketProvider.d.ts +20 -0
  8. package/dist/adapters/websocket/index.d.ts +6 -0
  9. package/dist/core/AbstractSerialDevice.d.ts +108 -0
  10. package/dist/core/SerialEventEmitter.d.ts +37 -0
  11. package/dist/core/SerialRegistry.d.ts +53 -0
  12. package/dist/errors/index.d.ts +40 -0
  13. package/dist/index.d.ts +10 -0
  14. package/dist/parsers/DelimiterParser.d.ts +22 -0
  15. package/dist/parsers/FixedLengthParser.d.ts +23 -0
  16. package/dist/parsers/RawParser.d.ts +22 -0
  17. package/dist/parsers/index.d.ts +7 -0
  18. package/dist/queue/CommandQueue.d.ts +98 -0
  19. package/dist/types/index.d.ts +124 -0
  20. package/dist/webserial-core.cjs +1 -0
  21. package/dist/webserial-core.mjs +853 -0
  22. package/dist/webserial-core.umd.js +1 -0
  23. package/package.json +62 -68
  24. package/dist/types/Core.d.ts +0 -268
  25. package/dist/types/Core.d.ts.map +0 -1
  26. package/dist/types/Devices.d.ts +0 -62
  27. package/dist/types/Devices.d.ts.map +0 -1
  28. package/dist/types/Dispatcher.d.ts +0 -98
  29. package/dist/types/Dispatcher.d.ts.map +0 -1
  30. package/dist/types/SerialError.d.ts +0 -61
  31. package/dist/types/SerialError.d.ts.map +0 -1
  32. package/dist/types/SerialEvent.d.ts +0 -4
  33. package/dist/types/SerialEvent.d.ts.map +0 -1
  34. package/dist/types/Socket.d.ts +0 -29
  35. package/dist/types/Socket.d.ts.map +0 -1
  36. package/dist/types/main.d.ts +0 -15
  37. package/dist/types/main.d.ts.map +0 -1
  38. package/dist/types/utils.d.ts +0 -3
  39. package/dist/types/utils.d.ts.map +0 -1
  40. package/dist/webserial-core.js +0 -1236
  41. package/dist/webserial-core.js.map +0 -1
  42. package/dist/webserial-core.umd.cjs +0 -5
  43. package/dist/webserial-core.umd.cjs.map +0 -1
@@ -0,0 +1,853 @@
1
+ //#region src/core/SerialEventEmitter.ts
2
+ var e = class {
3
+ listeners = {};
4
+ on(e, t) {
5
+ return this.listeners[e] || (this.listeners[e] = /* @__PURE__ */ new Set()), this.listeners[e].add(t), this;
6
+ }
7
+ off(e, t) {
8
+ return this.listeners[e] && this.listeners[e].delete(t), this;
9
+ }
10
+ emit(e, ...t) {
11
+ let n = this.listeners[e];
12
+ if (!n || n.size === 0) return !1;
13
+ for (let e of n) e(...t);
14
+ return !0;
15
+ }
16
+ }, t = class {
17
+ static instances = /* @__PURE__ */ new Set();
18
+ static portInstanceMap = /* @__PURE__ */ new WeakMap();
19
+ static getInstances() {
20
+ return Array.from(this.instances);
21
+ }
22
+ static register(e) {
23
+ this.instances.add(e);
24
+ }
25
+ static unregister(e) {
26
+ this.instances.delete(e);
27
+ }
28
+ static isPortInUse(e, t) {
29
+ let n = this.portInstanceMap.get(e);
30
+ return n !== void 0 && n !== t;
31
+ }
32
+ static lockPort(e, t) {
33
+ this.portInstanceMap.set(e, t);
34
+ }
35
+ static unlockPort(e) {
36
+ this.portInstanceMap.delete(e);
37
+ }
38
+ }, n = class {
39
+ queue = [];
40
+ isProcessing = !1;
41
+ isPaused = !0;
42
+ timeoutId = null;
43
+ commandTimeout;
44
+ onSend;
45
+ onTimeout;
46
+ constructor(e) {
47
+ this.commandTimeout = e.commandTimeout, this.onSend = e.onSend, this.onTimeout = e.onTimeout;
48
+ }
49
+ get queueSize() {
50
+ return this.queue.length;
51
+ }
52
+ enqueue(e) {
53
+ this.queue.push(e), this.tryProcessNext();
54
+ }
55
+ advance() {
56
+ this.clearCommandTimeout(), this.isProcessing = !1, this.tryProcessNext();
57
+ }
58
+ pause() {
59
+ this.isPaused = !0, this.clearCommandTimeout(), this.isProcessing = !1;
60
+ }
61
+ resume() {
62
+ this.isPaused = !1, this.tryProcessNext();
63
+ }
64
+ clear() {
65
+ this.queue = [], this.clearCommandTimeout(), this.isProcessing = !1;
66
+ }
67
+ snapshot() {
68
+ return [...this.queue];
69
+ }
70
+ restore(e) {
71
+ this.queue = [...e, ...this.queue];
72
+ }
73
+ tryProcessNext() {
74
+ if (this.isPaused || this.isProcessing || this.queue.length === 0) return;
75
+ this.isProcessing = !0;
76
+ let e = this.queue.shift();
77
+ this.commandTimeout > 0 && (this.timeoutId = setTimeout(() => {
78
+ this.timeoutId = null, this.onTimeout(e), this.advance();
79
+ }, this.commandTimeout)), this.onSend(e).catch(() => {
80
+ this.advance();
81
+ });
82
+ }
83
+ clearCommandTimeout() {
84
+ this.timeoutId !== null && (clearTimeout(this.timeoutId), this.timeoutId = null);
85
+ }
86
+ }, r = class e extends Error {
87
+ constructor(t) {
88
+ super(t), this.name = "SerialPortConflictError", Object.setPrototypeOf(this, e.prototype);
89
+ }
90
+ }, i = class e extends Error {
91
+ constructor(t) {
92
+ super(t), this.name = "SerialPermissionError", Object.setPrototypeOf(this, e.prototype);
93
+ }
94
+ }, a = class e extends Error {
95
+ constructor(t) {
96
+ super(t), this.name = "SerialTimeoutError", Object.setPrototypeOf(this, e.prototype);
97
+ }
98
+ }, o = class e extends Error {
99
+ constructor(t) {
100
+ super(t), this.name = "SerialReadError", Object.setPrototypeOf(this, e.prototype);
101
+ }
102
+ }, s = class e extends Error {
103
+ constructor(t) {
104
+ super(t), this.name = "SerialWriteError", Object.setPrototypeOf(this, e.prototype);
105
+ }
106
+ }, c = class r extends e {
107
+ port = null;
108
+ reader = null;
109
+ writer = null;
110
+ queue;
111
+ options;
112
+ isConnecting = !1;
113
+ abortController = null;
114
+ userInitiatedDisconnect = !1;
115
+ reconnectTimerId = null;
116
+ isHandshaking = !1;
117
+ static customProvider = null;
118
+ static polyfillOptions;
119
+ constructor(e) {
120
+ super(), this.options = {
121
+ baudRate: e.baudRate,
122
+ dataBits: e.dataBits ?? 8,
123
+ stopBits: e.stopBits ?? 1,
124
+ parity: e.parity ?? "none",
125
+ bufferSize: e.bufferSize ?? 255,
126
+ flowControl: e.flowControl ?? "none",
127
+ filters: e.filters ?? [],
128
+ commandTimeout: e.commandTimeout ?? 0,
129
+ parser: e.parser,
130
+ autoReconnect: e.autoReconnect ?? !1,
131
+ autoReconnectInterval: e.autoReconnectInterval ?? 1500,
132
+ handshakeTimeout: e.handshakeTimeout ?? 2e3,
133
+ provider: e.provider,
134
+ polyfillOptions: e.polyfillOptions
135
+ }, this.queue = new n({
136
+ commandTimeout: this.options.commandTimeout,
137
+ onSend: async (e) => {
138
+ await this.writeToPort(e), this.emit("serial:sent", e, this);
139
+ },
140
+ onTimeout: (e) => {
141
+ this.emit("serial:timeout", e, this);
142
+ }
143
+ }), this.on("serial:data", () => {
144
+ this.queue.advance();
145
+ }), t.register(this);
146
+ }
147
+ async handshake() {
148
+ return !0;
149
+ }
150
+ async connect() {
151
+ if (!this.isConnecting && !this.port) {
152
+ this.isConnecting = !0, this.emit("serial:connecting", this);
153
+ try {
154
+ let e = this.getSerial();
155
+ if (!e) throw Error("Web Serial API is not supported in this browser. Use AbstractSerialDevice.setProvider() to set a WebUSB polyfill.");
156
+ if (this.port = await this.findAndValidatePort(), !this.port) {
157
+ let t;
158
+ try {
159
+ t = await e.requestPort({ filters: this.options.filters }, this.options.polyfillOptions ?? r.polyfillOptions);
160
+ } catch (e) {
161
+ throw e instanceof DOMException && (e.name === "NotFoundError" || e.name === "SecurityError" || e.name === "AbortError") ? new i(e instanceof Error ? e.message : String(e)) : e instanceof Error ? e : Error(String(e));
162
+ }
163
+ if (!await this.openAndHandshake(t)) throw Error("Handshake failed: the selected device did not respond correctly.");
164
+ this.port = t;
165
+ }
166
+ this.abortController = new AbortController(), this.queue.resume(), this.emit("serial:connected", this);
167
+ } catch (e) {
168
+ if (e instanceof i ? this.emit("serial:need-permission", this) : this.emit("serial:error", e instanceof Error ? e : Error(String(e)), this), this.port) {
169
+ t.unlockPort(this.port);
170
+ try {
171
+ await this.port.close();
172
+ } catch {}
173
+ this.port = null;
174
+ }
175
+ throw e;
176
+ } finally {
177
+ this.isConnecting = !1;
178
+ }
179
+ }
180
+ }
181
+ async disconnect() {
182
+ this.port && (this.userInitiatedDisconnect = !0, this.stopReconnecting(), await this.cleanupPort());
183
+ }
184
+ async cleanupPort() {
185
+ if (this.port) {
186
+ this.queue.pause(), this.abortController?.abort(), this.abortController = null;
187
+ try {
188
+ let e = this.reader, t = this.writer;
189
+ if (this.reader = null, this.writer = null, e) {
190
+ try {
191
+ await e.cancel();
192
+ } catch {}
193
+ try {
194
+ e.releaseLock();
195
+ } catch {}
196
+ }
197
+ if (t) {
198
+ try {
199
+ await t.close();
200
+ } catch {}
201
+ try {
202
+ t.releaseLock();
203
+ } catch {}
204
+ }
205
+ try {
206
+ await this.port.close();
207
+ } catch {}
208
+ } catch (e) {
209
+ this.emit("serial:error", e instanceof Error ? e : Error(String(e)), this);
210
+ } finally {
211
+ this.port && t.unlockPort(this.port), this.port = null, this.options.parser?.reset?.(), this.emit("serial:disconnected", this), !this.userInitiatedDisconnect && this.options.autoReconnect && this.startReconnecting(), this.userInitiatedDisconnect = !1;
212
+ }
213
+ }
214
+ }
215
+ async forget() {
216
+ await this.disconnect(), this.port && typeof this.port.forget == "function" && await this.port.forget(), t.unregister(this);
217
+ }
218
+ async send(e) {
219
+ let t;
220
+ t = typeof e == "string" ? new TextEncoder().encode(e) : e, t.length > 0 && this.queue.enqueue(t);
221
+ }
222
+ clearQueue() {
223
+ this.queue.clear(), this.emit("serial:queue-empty", this);
224
+ }
225
+ async writeToPort(e) {
226
+ if (!this.port || !this.port.writable) throw new s("Port not writable.");
227
+ this.writer = this.port.writable.getWriter();
228
+ try {
229
+ await this.writer.write(e);
230
+ } catch (e) {
231
+ throw new s(e instanceof Error ? e.message : String(e));
232
+ } finally {
233
+ this.writer.releaseLock(), this.writer = null;
234
+ }
235
+ }
236
+ async readLoop() {
237
+ if (!(!this.port || !this.port.readable) && !this.reader) {
238
+ this.reader = this.port.readable.getReader();
239
+ try {
240
+ for (;;) {
241
+ let { value: e, done: t } = await this.reader.read();
242
+ if (t) break;
243
+ e && (this.options.parser ? this.options.parser.parse(e, (e) => {
244
+ this.emit("serial:data", e, this);
245
+ }) : this.emit("serial:data", e, this));
246
+ }
247
+ } catch (e) {
248
+ if (this.port) throw new o(e instanceof Error ? e.message : String(e));
249
+ } finally {
250
+ if (this.reader) {
251
+ try {
252
+ this.reader.releaseLock();
253
+ } catch {}
254
+ this.reader = null;
255
+ }
256
+ }
257
+ }
258
+ }
259
+ async openAndHandshake(e) {
260
+ let n = this;
261
+ if (t.isPortInUse(e, n)) return !1;
262
+ t.lockPort(e, n);
263
+ try {
264
+ await e.open({
265
+ baudRate: this.options.baudRate,
266
+ dataBits: this.options.dataBits,
267
+ stopBits: this.options.stopBits,
268
+ parity: this.options.parity,
269
+ bufferSize: this.options.bufferSize,
270
+ flowControl: this.options.flowControl
271
+ });
272
+ } catch (n) {
273
+ throw t.unlockPort(e), n instanceof Error ? n : Error(String(n));
274
+ }
275
+ this.port = e, this.abortController = new AbortController();
276
+ let r = this.queue.snapshot();
277
+ this.isHandshaking = !0, this.readLoop().catch((e) => {
278
+ !this.isHandshaking && this.port && (this.emit("serial:error", e, this), this.cleanupPort());
279
+ }), this.queue.resume();
280
+ try {
281
+ let t = await this.runHandshakeWithTimeout();
282
+ return this.isHandshaking = !1, t ? (this.queue.pause(), this.queue.clear(), this.queue.restore(r), this.options.parser?.reset?.(), !0) : (await this.teardownHandshake(e, r), !1);
283
+ } catch {
284
+ return this.isHandshaking = !1, await this.teardownHandshake(e, r), !1;
285
+ }
286
+ }
287
+ async teardownHandshake(e, n) {
288
+ this.queue.pause(), this.queue.clear(), this.queue.restore(n), await this.stopReader(), this.port = null, this.abortController = null, this.options.parser?.reset?.();
289
+ try {
290
+ await e.close();
291
+ } catch {}
292
+ t.unlockPort(e);
293
+ }
294
+ async stopReader() {
295
+ let e = this.reader;
296
+ if (this.reader = null, e) {
297
+ try {
298
+ await e.cancel();
299
+ } catch {}
300
+ try {
301
+ e.releaseLock();
302
+ } catch {}
303
+ }
304
+ }
305
+ async runHandshakeWithTimeout() {
306
+ let e = this.options.handshakeTimeout ?? 2e3;
307
+ return Promise.race([this.handshake(), new Promise((t) => setTimeout(() => t(!1), e))]);
308
+ }
309
+ async findAndValidatePort() {
310
+ let e = this.getSerial();
311
+ if (!e) return null;
312
+ let n = await e.getPorts(this.options.polyfillOptions ?? r.polyfillOptions);
313
+ if (n.length === 0) return null;
314
+ let i = this.options.filters ?? [], a = this;
315
+ for (let e of n) if (!t.isPortInUse(e, a)) {
316
+ if (i.length > 0) {
317
+ let t = e.getInfo();
318
+ if (!i.some((e) => {
319
+ let n = e.usbVendorId === void 0 || e.usbVendorId === t.usbVendorId, r = e.usbProductId === void 0 || e.usbProductId === t.usbProductId;
320
+ return n && r;
321
+ })) continue;
322
+ }
323
+ try {
324
+ if (await this.openAndHandshake(e)) return e;
325
+ } catch {}
326
+ }
327
+ return null;
328
+ }
329
+ startReconnecting() {
330
+ this.reconnectTimerId ||= (this.emit("serial:reconnecting", this), setInterval(async () => {
331
+ if (this.port || this.isConnecting) {
332
+ this.stopReconnecting();
333
+ return;
334
+ }
335
+ try {
336
+ let e = await this.findAndValidatePort();
337
+ e && (this.stopReconnecting(), await this.reconnect(e));
338
+ } catch {}
339
+ }, this.options.autoReconnectInterval));
340
+ }
341
+ stopReconnecting() {
342
+ this.reconnectTimerId &&= (clearInterval(this.reconnectTimerId), null);
343
+ }
344
+ async reconnect(e) {
345
+ if (!(this.isConnecting || this.port)) {
346
+ this.isConnecting = !0, this.emit("serial:connecting", this);
347
+ try {
348
+ this.port = e, this.abortController = new AbortController(), this.queue.resume(), this.emit("serial:connected", this);
349
+ } catch (e) {
350
+ this.emit("serial:error", e instanceof Error ? e : Error(String(e)), this), this.port &&= (t.unlockPort(this.port), null), this.options.autoReconnect && this.startReconnecting();
351
+ } finally {
352
+ this.isConnecting = !1;
353
+ }
354
+ }
355
+ }
356
+ static getInstances() {
357
+ return t.getInstances();
358
+ }
359
+ static async connectAll() {
360
+ let e = t.getInstances();
361
+ for (let t of e) try {
362
+ await t.connect();
363
+ } catch {}
364
+ }
365
+ static setProvider(e, t) {
366
+ r.customProvider = e, r.polyfillOptions = t;
367
+ }
368
+ getSerial() {
369
+ return this.options.provider ? this.options.provider : r.customProvider ? r.customProvider : typeof navigator < "u" && navigator.serial ? navigator.serial : null;
370
+ }
371
+ };
372
+ //#endregion
373
+ //#region src/parsers/FixedLengthParser.ts
374
+ function l(e) {
375
+ if (e <= 0) throw Error("FixedLengthParser: length must be greater than 0");
376
+ let t = new Uint8Array();
377
+ return {
378
+ parse(n, r) {
379
+ let i = new Uint8Array(t.length + n.length);
380
+ for (i.set(t), i.set(n, t.length), t = i; t.length >= e;) r(t.slice(0, e)), t = t.slice(e);
381
+ },
382
+ reset() {
383
+ t = new Uint8Array();
384
+ }
385
+ };
386
+ }
387
+ //#endregion
388
+ //#region src/parsers/DelimiterParser.ts
389
+ function u(e) {
390
+ let t = "", n = new TextDecoder();
391
+ return {
392
+ parse(r, i) {
393
+ t += n.decode(r, { stream: !0 });
394
+ let a;
395
+ for (; (a = t.indexOf(e)) !== -1;) i(t.slice(0, a)), t = t.slice(a + e.length);
396
+ },
397
+ reset() {
398
+ t = "", n = new TextDecoder();
399
+ }
400
+ };
401
+ }
402
+ //#endregion
403
+ //#region src/parsers/RawParser.ts
404
+ function d() {
405
+ return {
406
+ parse(e, t) {
407
+ t(e);
408
+ },
409
+ reset() {}
410
+ };
411
+ }
412
+ //#endregion
413
+ //#region src/adapters/web-usb/WebUsbProvider.ts
414
+ var f = 32, p = 34, m = 0, h = 30, g = 3, _ = 7, v = 1, y = 0, b = 771, x = 768, S = 255, C = 8, w = "none", T = 1, E = [
415
+ 16,
416
+ 8,
417
+ 7,
418
+ 6,
419
+ 5
420
+ ], D = [1, 2], O = [
421
+ "none",
422
+ "even",
423
+ "odd"
424
+ ], k = [
425
+ "none",
426
+ "odd",
427
+ "even"
428
+ ], A = [
429
+ 1,
430
+ 1.5,
431
+ 2
432
+ ], j = {
433
+ usbControlInterfaceClass: 2,
434
+ usbTransferInterfaceClass: 10,
435
+ protocol: void 0
436
+ };
437
+ function M(e, t) {
438
+ let n = e.configurations[0];
439
+ if (!n) return null;
440
+ for (let e of n.interfaces) if (e.alternates[0]?.interfaceClass === t) return e;
441
+ return null;
442
+ }
443
+ function N(e, t) {
444
+ let n = e.configurations[0];
445
+ if (!n) return null;
446
+ for (let e of n.interfaces) {
447
+ let n = e.alternates[0];
448
+ if (!n || n.interfaceClass !== t) continue;
449
+ let r = n.endpoints.some((e) => e.direction === "in"), i = n.endpoints.some((e) => e.direction === "out");
450
+ if (r && i) return e;
451
+ }
452
+ return null;
453
+ }
454
+ function P(e, t) {
455
+ let n = e.alternates[0];
456
+ if (n) {
457
+ for (let e of n.endpoints) if (e.direction === t) return e;
458
+ }
459
+ throw TypeError(`Interface ${e.interfaceNumber} does not have an ${t} endpoint.`);
460
+ }
461
+ function F(e, t) {
462
+ return t === 2 ? "cdc_acm" : e.vendorId === 4292 ? "cp210x" : "none";
463
+ }
464
+ var I = class {
465
+ device_;
466
+ endpoint_;
467
+ onError_;
468
+ constructor(e, t, n) {
469
+ this.device_ = e, this.endpoint_ = t, this.onError_ = n;
470
+ }
471
+ pull(e) {
472
+ (async () => {
473
+ let t = this.endpoint_.packetSize;
474
+ try {
475
+ let n = await this.device_.transferIn(this.endpoint_.endpointNumber, t);
476
+ if (n.status !== "ok") {
477
+ e.error(`USB error: ${n.status}`), this.onError_();
478
+ return;
479
+ }
480
+ if (n.data?.buffer && n.data.byteLength > 0) {
481
+ let t = new Uint8Array(n.data.buffer, n.data.byteOffset, n.data.byteLength);
482
+ t.length > 0 && e.enqueue(t);
483
+ }
484
+ } catch (t) {
485
+ e.error(String(t)), this.onError_();
486
+ }
487
+ })();
488
+ }
489
+ }, L = class {
490
+ device_;
491
+ endpoint_;
492
+ onError_;
493
+ constructor(e, t, n) {
494
+ this.device_ = e, this.endpoint_ = t, this.onError_ = n;
495
+ }
496
+ async write(e, t) {
497
+ try {
498
+ let n = await this.device_.transferOut(this.endpoint_.endpointNumber, e.buffer);
499
+ n.status !== "ok" && (t.error(n.status), this.onError_());
500
+ } catch (e) {
501
+ t.error(String(e)), this.onError_();
502
+ }
503
+ }
504
+ }, R = class {
505
+ device_;
506
+ protocol_;
507
+ controlInterface_;
508
+ transferInterface_;
509
+ inEndpoint_;
510
+ outEndpoint_;
511
+ serialOptions_;
512
+ readable_ = null;
513
+ writable_ = null;
514
+ cdcOutputSignals_ = {
515
+ dataTerminalReady: !1,
516
+ requestToSend: !1,
517
+ break: !1
518
+ };
519
+ constructor(e, t) {
520
+ this.device_ = e;
521
+ let n = {
522
+ ...j,
523
+ ...t
524
+ };
525
+ this.protocol_ = n.protocol ?? F(e, n.usbControlInterfaceClass);
526
+ let r = n.usbControlInterfaceClass, i = n.usbTransferInterfaceClass;
527
+ if (r === i) {
528
+ let t = N(e, i);
529
+ if (!t) throw TypeError(`Unable to find interface with class ${i} that has both IN and OUT endpoints.`);
530
+ this.controlInterface_ = t, this.transferInterface_ = t;
531
+ } else {
532
+ let t = M(e, r);
533
+ if (!t) throw TypeError(`Unable to find control interface with class ${r}.`);
534
+ let n = N(e, i) ?? M(e, i);
535
+ if (!n) throw TypeError(`Unable to find transfer interface with class ${i}.`);
536
+ this.controlInterface_ = t, this.transferInterface_ = n;
537
+ }
538
+ this.inEndpoint_ = P(this.transferInterface_, "in"), this.outEndpoint_ = P(this.transferInterface_, "out");
539
+ }
540
+ get readable() {
541
+ return !this.readable_ && this.device_.opened && (this.readable_ = new ReadableStream(new I(this.device_, this.inEndpoint_, () => {
542
+ this.readable_ = null;
543
+ }), { highWaterMark: this.serialOptions_?.bufferSize ?? S })), this.readable_;
544
+ }
545
+ get writable() {
546
+ return !this.writable_ && this.device_.opened && (this.writable_ = new WritableStream(new L(this.device_, this.outEndpoint_, () => {
547
+ this.writable_ = null;
548
+ }), new ByteLengthQueuingStrategy({ highWaterMark: this.serialOptions_?.bufferSize ?? S }))), this.writable_;
549
+ }
550
+ async open(e) {
551
+ this.serialOptions_ = e, this.validateOptions();
552
+ try {
553
+ switch (await this.device_.open(), this.device_.configuration === null && await this.device_.selectConfiguration(1), await this.device_.claimInterface(this.controlInterface_.interfaceNumber), this.controlInterface_ !== this.transferInterface_ && await this.device_.claimInterface(this.transferInterface_.interfaceNumber), this.protocol_) {
554
+ case "cdc_acm":
555
+ await this.cdcInit();
556
+ break;
557
+ case "cp210x":
558
+ await this.cp210xInit();
559
+ break;
560
+ case "none": break;
561
+ }
562
+ } catch (e) {
563
+ throw this.device_.opened && await this.device_.close(), Error("Error setting up device: " + (e instanceof Error ? e.message : String(e)), { cause: e });
564
+ }
565
+ }
566
+ async close() {
567
+ let e = [];
568
+ if (this.readable_ && e.push(this.readable_.cancel()), this.writable_ && e.push(this.writable_.abort()), await Promise.all(e), this.readable_ = null, this.writable_ = null, this.device_.opened) {
569
+ switch (this.protocol_) {
570
+ case "cdc_acm":
571
+ await this.cdcSetSignals({
572
+ dataTerminalReady: !1,
573
+ requestToSend: !1
574
+ });
575
+ break;
576
+ case "cp210x":
577
+ await this.cp210xDeinit();
578
+ break;
579
+ }
580
+ await this.device_.close();
581
+ }
582
+ }
583
+ async forget() {
584
+ return this.device_.forget();
585
+ }
586
+ getInfo() {
587
+ return {
588
+ usbVendorId: this.device_.vendorId,
589
+ usbProductId: this.device_.productId
590
+ };
591
+ }
592
+ async cdcInit() {
593
+ await this.cdcSetLineCoding(), await this.cdcSetSignals({ dataTerminalReady: !0 });
594
+ }
595
+ async cdcSetSignals(e) {
596
+ if (this.cdcOutputSignals_ = {
597
+ ...this.cdcOutputSignals_,
598
+ ...e
599
+ }, e.dataTerminalReady !== void 0 || e.requestToSend !== void 0) {
600
+ let e = (this.cdcOutputSignals_.dataTerminalReady ? 1 : 0) | (this.cdcOutputSignals_.requestToSend ? 2 : 0);
601
+ await this.device_.controlTransferOut({
602
+ requestType: "class",
603
+ recipient: "interface",
604
+ request: p,
605
+ value: e,
606
+ index: this.controlInterface_.interfaceNumber
607
+ });
608
+ }
609
+ }
610
+ async cdcSetLineCoding() {
611
+ let e = /* @__PURE__ */ new ArrayBuffer(7), t = new DataView(e);
612
+ if (t.setUint32(0, this.serialOptions_.baudRate, !0), t.setUint8(4, A.indexOf(this.serialOptions_.stopBits ?? T)), t.setUint8(5, k.indexOf(this.serialOptions_.parity ?? w)), t.setUint8(6, this.serialOptions_.dataBits ?? C), (await this.device_.controlTransferOut({
613
+ requestType: "class",
614
+ recipient: "interface",
615
+ request: f,
616
+ value: 0,
617
+ index: this.controlInterface_.interfaceNumber
618
+ }, e)).status !== "ok") throw new DOMException("Failed to set line coding.", "NetworkError");
619
+ }
620
+ async cp210xInit() {
621
+ let e = this.controlInterface_.interfaceNumber;
622
+ await this.device_.controlTransferOut({
623
+ requestType: "vendor",
624
+ recipient: "interface",
625
+ request: m,
626
+ value: v,
627
+ index: e
628
+ });
629
+ let t = /* @__PURE__ */ new ArrayBuffer(4);
630
+ new DataView(t).setUint32(0, this.serialOptions_.baudRate, !0), await this.device_.controlTransferOut({
631
+ requestType: "vendor",
632
+ recipient: "interface",
633
+ request: h,
634
+ value: 0,
635
+ index: e
636
+ }, t);
637
+ let n = this.serialOptions_.dataBits ?? C, r = {
638
+ none: 0,
639
+ odd: 16,
640
+ even: 32
641
+ }[this.serialOptions_.parity ?? w] ?? 0, i = ({
642
+ 1: 0,
643
+ 2: 2
644
+ }[this.serialOptions_.stopBits ?? T] ?? 0) << 8 | r | n;
645
+ await this.device_.controlTransferOut({
646
+ requestType: "vendor",
647
+ recipient: "interface",
648
+ request: g,
649
+ value: i,
650
+ index: e
651
+ }), await this.device_.controlTransferOut({
652
+ requestType: "vendor",
653
+ recipient: "interface",
654
+ request: _,
655
+ value: b,
656
+ index: e
657
+ });
658
+ }
659
+ async cp210xDeinit() {
660
+ let e = this.controlInterface_.interfaceNumber;
661
+ await this.device_.controlTransferOut({
662
+ requestType: "vendor",
663
+ recipient: "interface",
664
+ request: _,
665
+ value: x,
666
+ index: e
667
+ }), await this.device_.controlTransferOut({
668
+ requestType: "vendor",
669
+ recipient: "interface",
670
+ request: m,
671
+ value: y,
672
+ index: e
673
+ });
674
+ }
675
+ validateOptions() {
676
+ if (this.serialOptions_.baudRate % 1 != 0) throw RangeError(`Invalid baud rate: ${this.serialOptions_.baudRate}`);
677
+ if (this.serialOptions_.dataBits !== void 0 && !E.includes(this.serialOptions_.dataBits)) throw RangeError(`Invalid dataBits: ${this.serialOptions_.dataBits}`);
678
+ if (this.serialOptions_.stopBits !== void 0 && !D.includes(this.serialOptions_.stopBits)) throw RangeError(`Invalid stopBits: ${this.serialOptions_.stopBits}`);
679
+ if (this.serialOptions_.parity !== void 0 && !O.includes(this.serialOptions_.parity)) throw RangeError(`Invalid parity: ${this.serialOptions_.parity}`);
680
+ }
681
+ }, z = class {
682
+ options_;
683
+ constructor(e) {
684
+ this.options_ = {
685
+ ...j,
686
+ ...e
687
+ };
688
+ }
689
+ async requestPort(e, t) {
690
+ let n = {
691
+ ...this.options_,
692
+ ...t
693
+ }, r = [];
694
+ if (e?.filters && e.filters.length > 0) for (let t of e.filters) {
695
+ let e = {};
696
+ t.usbVendorId !== void 0 && (e.vendorId = t.usbVendorId), t.usbProductId !== void 0 && (e.productId = t.usbProductId), n.usbControlInterfaceClass !== void 0 && n.usbControlInterfaceClass !== 255 ? e.classCode = n.usbControlInterfaceClass : e.vendorId === void 0 && e.productId === void 0 && (e.classCode = n.usbControlInterfaceClass ?? 2), r.push(e);
697
+ }
698
+ else r.push({ classCode: n.usbControlInterfaceClass ?? 2 });
699
+ return new R(await navigator.usb.requestDevice({ filters: r }), n);
700
+ }
701
+ async getPorts(e) {
702
+ let t = {
703
+ ...this.options_,
704
+ ...e
705
+ }, n = await navigator.usb.getDevices(), r = [];
706
+ for (let e of n) try {
707
+ let n = new R(e, t);
708
+ r.push(n);
709
+ } catch {}
710
+ return r;
711
+ }
712
+ }, B = "6e400001-b5a3-f393-e0a9-e50e24dcca9e", V = "6e400003-b5a3-f393-e0a9-e50e24dcca9e", H = "6e400002-b5a3-f393-e0a9-e50e24dcca9e", U = 20, W = 10;
713
+ function G(e) {
714
+ let t = null, n = null, r = null;
715
+ return {
716
+ get readable() {
717
+ return t;
718
+ },
719
+ get writable() {
720
+ return n;
721
+ },
722
+ getInfo() {
723
+ return {};
724
+ },
725
+ async open() {
726
+ if (!e.gatt) throw Error("GATT not available on this Bluetooth device.");
727
+ r = await e.gatt.connect();
728
+ let i = await r.getPrimaryService(B), a = await i.getCharacteristic(V), o = await i.getCharacteristic(H);
729
+ await a.startNotifications(), t = new ReadableStream({ start(e) {
730
+ a.addEventListener("characteristicvaluechanged", (t) => {
731
+ let n = t.target.value.buffer;
732
+ e.enqueue(new Uint8Array(n));
733
+ });
734
+ } }), n = new WritableStream({ async write(e) {
735
+ for (let t = 0; t < e.length; t += U) {
736
+ let n = e.slice(t, t + U);
737
+ await o.writeValueWithoutResponse(n), t + U < e.length && await new Promise((e) => setTimeout(e, W));
738
+ }
739
+ } });
740
+ },
741
+ async close() {
742
+ r?.connected && r.disconnect(), t = null, n = null;
743
+ }
744
+ };
745
+ }
746
+ function K() {
747
+ return {
748
+ async requestPort() {
749
+ if (!navigator.bluetooth) throw Error("Web Bluetooth API is not supported in this browser. Use Chrome on Android, macOS, or ChromeOS.");
750
+ return G(await navigator.bluetooth.requestDevice({ filters: [{ services: [B] }] }));
751
+ },
752
+ async getPorts() {
753
+ return [];
754
+ }
755
+ };
756
+ }
757
+ //#endregion
758
+ //#region src/adapters/websocket/WebSocketProvider.ts
759
+ function q(e) {
760
+ return new Promise((t, n) => {
761
+ e.addEventListener("open", () => t(), { once: !0 }), e.addEventListener("error", (e) => n(e), { once: !0 });
762
+ });
763
+ }
764
+ function J(e, t) {
765
+ return new Promise((n) => {
766
+ let r = (i) => {
767
+ let a = JSON.parse(i.data);
768
+ a.type === t && (e.removeEventListener("message", r), n(a.payload));
769
+ };
770
+ e.addEventListener("message", r);
771
+ });
772
+ }
773
+ function Y(e, t) {
774
+ let n = null, r = null;
775
+ return {
776
+ get readable() {
777
+ return n;
778
+ },
779
+ get writable() {
780
+ return r;
781
+ },
782
+ getInfo() {
783
+ return {
784
+ usbVendorId: t.vendorId,
785
+ usbProductId: t.productId
786
+ };
787
+ },
788
+ async open(i) {
789
+ e.send(JSON.stringify({
790
+ type: "open",
791
+ path: t.path,
792
+ baudRate: i.baudRate,
793
+ dataBits: i.dataBits,
794
+ stopBits: i.stopBits,
795
+ parity: i.parity,
796
+ parser: {
797
+ type: "delimiter",
798
+ value: "\\n"
799
+ }
800
+ })), await J(e, "opened");
801
+ let a = [], o = null, s = !1;
802
+ function c(e) {
803
+ let t = JSON.parse(e.data);
804
+ if (t.type === "data" && t.bytes) {
805
+ let e = new Uint8Array(t.bytes);
806
+ o ? o.enqueue(e) : a.push(e);
807
+ }
808
+ t.type === "closed" && (s = !0, o && o.close());
809
+ }
810
+ e.addEventListener("message", c), n = new ReadableStream({
811
+ start(e) {
812
+ o = e;
813
+ for (let t of a) e.enqueue(t);
814
+ a.length = 0, s && e.close();
815
+ },
816
+ cancel() {
817
+ e.removeEventListener("message", c), o = null;
818
+ }
819
+ }), r = new WritableStream({ write(t) {
820
+ e.send(JSON.stringify({
821
+ type: "write",
822
+ bytes: Array.from(t)
823
+ }));
824
+ } });
825
+ },
826
+ async close() {
827
+ e.send(JSON.stringify({ type: "close" })), n = null, r = null, e.close();
828
+ }
829
+ };
830
+ }
831
+ function X(e) {
832
+ return {
833
+ async requestPort(t) {
834
+ let n = new WebSocket(e);
835
+ await q(n), n.send(JSON.stringify({
836
+ type: "list-ports",
837
+ filters: t?.filters ?? []
838
+ }));
839
+ let r = (await J(n, "port-list"))[0];
840
+ if (!r) throw Error("No ports available on the bridge server. Make sure the Node.js server is running and a device is connected.");
841
+ return Y(n, r);
842
+ },
843
+ async getPorts() {
844
+ let t = new WebSocket(e);
845
+ return await q(t), t.send(JSON.stringify({
846
+ type: "list-ports",
847
+ filters: []
848
+ })), (await J(t, "port-list")).map((e) => Y(t, e));
849
+ }
850
+ };
851
+ }
852
+ //#endregion
853
+ export { c as AbstractSerialDevice, n as CommandQueue, e as SerialEventEmitter, i as SerialPermissionError, r as SerialPortConflictError, o as SerialReadError, t as SerialRegistry, a as SerialTimeoutError, s as SerialWriteError, z as WebUsbProvider, K as createBluetoothProvider, X as createWebSocketProvider, u as delimiter, l as fixedLength, d as raw };