@danidoble/webserial 4.3.10 → 4.3.12

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.
@@ -1,20 +1,17 @@
1
- var V = Object.defineProperty, R = (n) => {
2
- throw TypeError(n);
3
- }, z = (n, e, t) => e in n ? V(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t, y = (n, e, t) => z(n, typeof e != "symbol" ? e + "" : e, t), T = (n, e, t) => e.has(n) || R("Cannot " + t), b = (n, e, t) => (T(n, e, "read from private field"), e.get(n)), S = (n, e, t) => e.has(n) ? R("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(n) : e.set(n, t), J = (n, e, t, i) => (T(n, e, "write to private field"), e.set(n, t), t), l = (n, e, t) => (T(n, e, "access private method"), t);
4
- class A extends CustomEvent {
1
+ class p extends CustomEvent {
5
2
  constructor(e, t) {
6
3
  super(e, t);
7
4
  }
8
5
  }
9
- class I extends EventTarget {
10
- constructor() {
11
- super(...arguments), y(this, "__listeners__", {
12
- debug: !1
13
- }), y(this, "__debug__", !1), y(this, "__listenersCallbacks__", []);
14
- }
6
+ class g extends EventTarget {
7
+ __listeners__ = {
8
+ debug: !1
9
+ };
10
+ __debug__ = !1;
11
+ __listenersCallbacks__ = [];
15
12
  dispatch(e, t = null) {
16
- const i = new A(e, { detail: t });
17
- this.dispatchEvent(i), this.__debug__ && this.dispatchEvent(new A("debug", { detail: { type: e, data: t } }));
13
+ const i = new p(e, { detail: t });
14
+ this.dispatchEvent(i), this.__debug__ && this.dispatchEvent(new p("debug", { detail: { type: e, data: t } }));
18
15
  }
19
16
  dispatchAsync(e, t = null, i = 100) {
20
17
  const s = this;
@@ -44,90 +41,90 @@ class I extends EventTarget {
44
41
  this.__listeners__[e] = !1;
45
42
  }
46
43
  }
47
- const C = class a extends I {
44
+ class n extends g {
45
+ static instance;
46
+ static devices = {};
48
47
  constructor() {
49
48
  super(), ["change"].forEach((e) => {
50
49
  this.serialRegisterAvailableListener(e);
51
50
  });
52
51
  }
53
52
  static $dispatchChange(e = null) {
54
- e && e.$checkAndDispatchConnection(), a.instance.dispatch("change", { devices: a.devices, dispatcher: e });
53
+ e && e.$checkAndDispatchConnection(), n.instance.dispatch("change", { devices: n.devices, dispatcher: e });
55
54
  }
56
55
  static typeError(e) {
57
56
  const t = new Error();
58
57
  throw t.message = `Type ${e} is not supported`, t.name = "DeviceTypeError", t;
59
58
  }
60
59
  static registerType(e) {
61
- typeof a.devices[e] > "u" && (a.devices = { ...a.devices, [e]: {} });
60
+ typeof n.devices[e] > "u" && (n.devices = { ...n.devices, [e]: {} });
62
61
  }
63
62
  static add(e) {
64
63
  const t = e.typeDevice;
65
- typeof a.devices[t] > "u" && a.registerType(t);
64
+ typeof n.devices[t] > "u" && n.registerType(t);
66
65
  const i = e.uuid;
67
- if (typeof a.devices[t] > "u" && a.typeError(t), a.devices[t][i])
66
+ if (typeof n.devices[t] > "u" && n.typeError(t), n.devices[t][i])
68
67
  throw new Error(`Device with id ${i} already exists`);
69
- return a.devices[t][i] = e, a.$dispatchChange(e), Object.keys(a.devices[t]).indexOf(i);
68
+ return n.devices[t][i] = e, n.$dispatchChange(e), Object.keys(n.devices[t]).indexOf(i);
70
69
  }
71
70
  static get(e, t) {
72
- return typeof a.devices[e] > "u" && a.registerType(e), typeof a.devices[e] > "u" && a.typeError(e), a.devices[e][t];
71
+ return typeof n.devices[e] > "u" && n.registerType(e), typeof n.devices[e] > "u" && n.typeError(e), n.devices[e][t];
73
72
  }
74
73
  static getAll(e = null) {
75
- return e === null ? a.devices : (typeof a.devices[e] > "u" && a.typeError(e), a.devices[e]);
74
+ return e === null ? n.devices : (typeof n.devices[e] > "u" && n.typeError(e), n.devices[e]);
76
75
  }
77
76
  static getList() {
78
- return Object.values(a.devices).map((e) => Object.values(e)).flat();
77
+ return Object.values(n.devices).map((e) => Object.values(e)).flat();
79
78
  }
80
79
  static getByNumber(e, t) {
81
- return typeof a.devices[e] > "u" && a.typeError(e), Object.values(a.devices[e]).find((i) => i.deviceNumber === t) ?? null;
80
+ return typeof n.devices[e] > "u" && n.typeError(e), Object.values(n.devices[e]).find((i) => i.deviceNumber === t) ?? null;
82
81
  }
83
82
  static getCustom(e, t = 1) {
84
- return typeof a.devices[e] > "u" && a.typeError(e), Object.values(a.devices[e]).find((i) => i.deviceNumber === t) ?? null;
83
+ return typeof n.devices[e] > "u" && n.typeError(e), Object.values(n.devices[e]).find((i) => i.deviceNumber === t) ?? null;
85
84
  }
86
85
  static async connectToAll() {
87
- const e = a.getList();
86
+ const e = n.getList();
88
87
  for (const t of e)
89
88
  t.isConnected || await t.connect().catch(console.warn);
90
- return Promise.resolve(a.areAllConnected());
89
+ return Promise.resolve(n.areAllConnected());
91
90
  }
92
91
  static async disconnectAll() {
93
- const e = a.getList();
92
+ const e = n.getList();
94
93
  for (const t of e)
95
94
  t.isDisconnected || await t.disconnect().catch(console.warn);
96
- return Promise.resolve(a.areAllDisconnected());
95
+ return Promise.resolve(n.areAllDisconnected());
97
96
  }
98
97
  static async areAllConnected() {
99
- const e = a.getList();
98
+ const e = n.getList();
100
99
  for (const t of e)
101
100
  if (!t.isConnected) return Promise.resolve(!1);
102
101
  return Promise.resolve(!0);
103
102
  }
104
103
  static async areAllDisconnected() {
105
- const e = a.getList();
104
+ const e = n.getList();
106
105
  for (const t of e)
107
106
  if (!t.isDisconnected) return Promise.resolve(!1);
108
107
  return Promise.resolve(!0);
109
108
  }
110
109
  static async getAllConnected() {
111
- const e = a.getList();
110
+ const e = n.getList();
112
111
  return Promise.resolve(e.filter((t) => t.isConnected));
113
112
  }
114
113
  static async getAllDisconnected() {
115
- const e = a.getList();
114
+ const e = n.getList();
116
115
  return Promise.resolve(e.filter((t) => t.isDisconnected));
117
116
  }
118
- };
119
- y(C, "instance"), y(C, "devices", {});
120
- let c = C;
121
- c.instance || (c.instance = new c());
122
- function M(n = 100) {
117
+ }
118
+ n.instance || (n.instance = new n());
119
+ function f(c = 100) {
123
120
  return new Promise(
124
- (e) => setTimeout(() => e(), n)
121
+ (e) => setTimeout(() => e(), c)
125
122
  );
126
123
  }
127
- function G() {
124
+ function y() {
128
125
  return "serial" in navigator;
129
126
  }
130
- const v = {
127
+ const u = {
131
128
  baudRate: 9600,
132
129
  dataBits: 8,
133
130
  stopBits: 1,
@@ -135,84 +132,86 @@ const v = {
135
132
  bufferSize: 32768,
136
133
  flowControl: "none"
137
134
  };
138
- var p, r, f, m, q, x, k, u, N, L, D, B, P, O, g, H, j, F, U, $, W, Q;
139
- class K extends I {
135
+ class b extends g {
136
+ __internal__ = {
137
+ bypassSerialBytesConnection: !1,
138
+ auto_response: !1,
139
+ device_number: 1,
140
+ aux_port_connector: 0,
141
+ last_error: {
142
+ message: null,
143
+ action: null,
144
+ code: null,
145
+ no_code: 0
146
+ },
147
+ serial: {
148
+ aux_connecting: "idle",
149
+ connecting: !1,
150
+ connected: !1,
151
+ port: null,
152
+ last_action: null,
153
+ response: {
154
+ length: null,
155
+ buffer: new Uint8Array([]),
156
+ as: "uint8",
157
+ replacer: /[\n\r]+/g,
158
+ limiter: null,
159
+ prefixLimiter: !1,
160
+ sufixLimiter: !0,
161
+ delimited: !1
162
+ },
163
+ reader: null,
164
+ input_done: null,
165
+ output_done: null,
166
+ input_stream: null,
167
+ output_stream: null,
168
+ keep_reading: !0,
169
+ time_until_send_bytes: void 0,
170
+ delay_first_connection: 200,
171
+ bytes_connection: null,
172
+ filters: [],
173
+ config_port: u,
174
+ queue: [],
175
+ running_queue: !1,
176
+ auto_response: ["DD", "DD"],
177
+ free_timeout_ms: 50,
178
+ // In previous versions 400 was used
179
+ useRTSCTS: !1
180
+ // Use RTS/CTS flow control
181
+ },
182
+ device: {
183
+ type: "unknown",
184
+ id: window.crypto.randomUUID(),
185
+ listen_on_port: null
186
+ },
187
+ time: {
188
+ response_connection: 500,
189
+ response_general: 2e3
190
+ },
191
+ timeout: {
192
+ until_response: 0
193
+ },
194
+ interval: {
195
+ reconnection: 0
196
+ }
197
+ };
198
+ #t = null;
140
199
  constructor({
141
200
  filters: e = null,
142
- config_port: t = v,
201
+ config_port: t = u,
143
202
  no_device: i = 1,
144
203
  device_listen_on_channel: s = 1,
145
- bypassSerialBytesConnection: o = !1
204
+ bypassSerialBytesConnection: r = !1
146
205
  } = {
147
206
  filters: null,
148
- config_port: v,
207
+ config_port: u,
149
208
  no_device: 1,
150
209
  device_listen_on_channel: 1,
151
210
  bypassSerialBytesConnection: !1
152
211
  }) {
153
- if (super(), S(this, r), y(this, "__internal__", {
154
- bypassSerialBytesConnection: !1,
155
- auto_response: !1,
156
- device_number: 1,
157
- aux_port_connector: 0,
158
- last_error: {
159
- message: null,
160
- action: null,
161
- code: null,
162
- no_code: 0
163
- },
164
- serial: {
165
- aux_connecting: "idle",
166
- connecting: !1,
167
- connected: !1,
168
- port: null,
169
- last_action: null,
170
- response: {
171
- length: null,
172
- buffer: new Uint8Array([]),
173
- as: "uint8",
174
- replacer: /[\n\r]+/g,
175
- limiter: null,
176
- prefixLimiter: !1,
177
- sufixLimiter: !0,
178
- delimited: !1
179
- },
180
- reader: null,
181
- input_done: null,
182
- output_done: null,
183
- input_stream: null,
184
- output_stream: null,
185
- keep_reading: !0,
186
- time_until_send_bytes: void 0,
187
- delay_first_connection: 200,
188
- bytes_connection: null,
189
- filters: [],
190
- config_port: v,
191
- queue: [],
192
- auto_response: ["DD", "DD"],
193
- free_timeout_ms: 50,
194
- // In previous versions 400 was used
195
- useRTSCTS: !1
196
- // Use RTS/CTS flow control
197
- },
198
- device: {
199
- type: "unknown",
200
- id: window.crypto.randomUUID(),
201
- listen_on_port: null
202
- },
203
- time: {
204
- response_connection: 500,
205
- response_general: 2e3
206
- },
207
- timeout: {
208
- until_response: 0
209
- },
210
- interval: {
211
- reconnection: 0
212
- }
213
- }), S(this, p, null), !("serial" in navigator))
212
+ if (super(), !("serial" in navigator))
214
213
  throw new Error("Web Serial not supported");
215
- e && (this.serialFilters = e), t && (this.serialConfigPort = t), o && (this.__internal__.bypassSerialBytesConnection = o), i && l(this, r, W).call(this, i), s && ["number", "string"].includes(typeof s) && (this.listenOnChannel = s), l(this, r, j).call(this), l(this, r, F).call(this);
214
+ e && (this.serialFilters = e), t && (this.serialConfigPort = t), r && (this.__internal__.bypassSerialBytesConnection = r), i && this.#m(i), s && ["number", "string"].includes(typeof s) && (this.listenOnChannel = s), this.#f(), this.#g();
216
215
  }
217
216
  set listenOnChannel(e) {
218
217
  if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
@@ -246,15 +245,15 @@ class K extends I {
246
245
  this.__internal__.serial.useRTSCTS = e;
247
246
  }
248
247
  get isConnected() {
249
- const e = this.__internal__.serial.connected, t = l(this, r, f).call(this, this.__internal__.serial.port);
250
- return e && !t && l(this, r, m).call(this, { error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
248
+ const e = this.__internal__.serial.connected, t = this.#i(this.__internal__.serial.port);
249
+ return e && !t && this.#s({ error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
251
250
  }
252
251
  get isConnecting() {
253
252
  return this.__internal__.serial.connecting;
254
253
  }
255
254
  get isDisconnected() {
256
- const e = this.__internal__.serial.connected, t = l(this, r, f).call(this, this.__internal__.serial.port);
257
- return !e && t && (this.dispatch("serial:connected"), l(this, r, g).call(this, !1), c.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
255
+ const e = this.__internal__.serial.connected, t = this.#i(this.__internal__.serial.port);
256
+ return !e && t && (this.dispatch("serial:connected"), this.#n(!1), n.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
258
257
  }
259
258
  get deviceNumber() {
260
259
  return this.__internal__.device_number;
@@ -324,21 +323,30 @@ class K extends I {
324
323
  throw new Error("bypassSerialBytesConnection must be a boolean");
325
324
  this.__internal__.bypassSerialBytesConnection = e;
326
325
  }
326
+ #i(e) {
327
+ return !!(e && e.readable && e.writable);
328
+ }
327
329
  async timeout(e, t) {
328
- this.__internal__.last_error.message = "Operation response timed out.", this.__internal__.last_error.action = t, this.__internal__.last_error.code = e, this.__internal__.timeout.until_response && (clearTimeout(this.__internal__.timeout.until_response), this.__internal__.timeout.until_response = 0), t === "connect" ? (this.__internal__.serial.connected = !1, this.dispatch("serial:reconnect", {}), c.$dispatchChange(this)) : t === "connection:start" && (await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector += 1, c.$dispatchChange(this), await this.serialConnect()), this.dispatch("serial:timeout", {
330
+ this.__internal__.last_error.message = "Operation response timed out.", this.__internal__.last_error.action = t, this.__internal__.last_error.code = e, this.__internal__.timeout.until_response && (clearTimeout(this.__internal__.timeout.until_response), this.__internal__.timeout.until_response = 0), t === "connect" ? (this.__internal__.serial.connected = !1, this.dispatch("serial:reconnect", {}), n.$dispatchChange(this)) : t === "connection:start" && (await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector += 1, n.$dispatchChange(this), await this.serialConnect()), this.__internal__.serial.queue.length > 0 && this.dispatch("internal:queue", {}), this.dispatch("serial:timeout", {
329
331
  ...this.__internal__.last_error,
330
332
  bytes: e,
331
333
  action: t
332
334
  });
333
335
  }
334
336
  async disconnect(e = null) {
335
- await this.serialDisconnect(), l(this, r, m).call(this, e);
337
+ await this.serialDisconnect(), this.#s(e);
338
+ }
339
+ #s(e = null) {
340
+ this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), n.$dispatchChange(this);
341
+ }
342
+ #a(e) {
343
+ this.__internal__.serial.aux_connecting = e.detail.active ? "connecting" : "finished";
336
344
  }
337
345
  async connect() {
338
346
  return this.isConnected ? !0 : (this.__internal__.serial.aux_connecting = "idle", new Promise((e, t) => {
339
- G() || t("Web Serial not supported"), b(this, p) || J(this, p, l(this, r, q).bind(this)), this.on("internal:connecting", b(this, p));
347
+ y() || t("Web Serial not supported"), this.#t || (this.#t = this.#a.bind(this)), this.on("internal:connecting", this.#t);
340
348
  const i = setInterval(() => {
341
- this.__internal__.serial.aux_connecting === "finished" ? (clearInterval(i), this.__internal__.serial.aux_connecting = "idle", b(this, p) !== null && this.off("internal:connecting", b(this, p)), this.isConnected ? e(!0) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`)) : this.__internal__.serial.aux_connecting === "connecting" && (this.__internal__.serial.aux_connecting = "idle", this.dispatch("internal:connecting", { active: !0 }), this.dispatch("serial:connecting", { active: !0 }));
349
+ this.__internal__.serial.aux_connecting === "finished" ? (clearInterval(i), this.__internal__.serial.aux_connecting = "idle", this.#t !== null && this.off("internal:connecting", this.#t), this.isConnected ? e(!0) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`)) : this.__internal__.serial.aux_connecting === "connecting" && (this.__internal__.serial.aux_connecting = "idle", this.dispatch("internal:connecting", { active: !0 }), this.dispatch("serial:connecting", { active: !0 }));
342
350
  }, 100);
343
351
  this.serialConnect();
344
352
  }));
@@ -350,9 +358,54 @@ class K extends I {
350
358
  } catch (e) {
351
359
  this.serialErrors(e);
352
360
  } finally {
353
- this.__internal__.serial.reader = null, this.__internal__.serial.input_done = null, this.__internal__.serial.output_stream = null, this.__internal__.serial.output_done = null, this.__internal__.serial.connected = !1, this.__internal__.serial.port = null, c.$dispatchChange(this);
361
+ this.__internal__.serial.reader = null, this.__internal__.serial.input_done = null, this.__internal__.serial.output_stream = null, this.__internal__.serial.output_done = null, this.__internal__.serial.connected = !1, this.__internal__.serial.port = null, n.$dispatchChange(this);
354
362
  }
355
363
  }
364
+ async #r(e) {
365
+ const t = this.__internal__.serial.port;
366
+ if (!t || t && (!t.readable || !t.writable))
367
+ throw this.#s({ error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
368
+ const i = this.validateBytes(e);
369
+ if (this.useRTSCTS && await this.#l(t, 5e3), t.writable === null) return;
370
+ const s = t.writable.getWriter();
371
+ await s.write(i), s.releaseLock();
372
+ }
373
+ async #l(e, t = 5e3) {
374
+ const i = Date.now();
375
+ for (; ; ) {
376
+ if (Date.now() - i > t)
377
+ throw new Error("Timeout waiting for clearToSend signal");
378
+ const { clearToSend: s } = await e.getSignals();
379
+ if (s) return;
380
+ await f(100);
381
+ }
382
+ }
383
+ #e(e = new Uint8Array([]), t = !1) {
384
+ if (e && e.length > 0) {
385
+ const i = this.__internal__.serial.connected;
386
+ if (this.__internal__.serial.connected = this.#i(this.__internal__.serial.port), n.$dispatchChange(this), !i && this.__internal__.serial.connected && (this.dispatch("serial:connected"), this.#n(!1)), this.__internal__.interval.reconnection && (clearInterval(this.__internal__.interval.reconnection), this.__internal__.interval.reconnection = 0), this.__internal__.timeout.until_response && (clearTimeout(this.__internal__.timeout.until_response), this.__internal__.timeout.until_response = 0), this.__internal__.serial.response.as === "hex")
387
+ t ? this.serialCorruptMessage(this.parseUint8ToHex(e)) : this.serialMessage(this.parseUint8ToHex(e));
388
+ else if (this.__internal__.serial.response.as === "uint8")
389
+ t ? this.serialCorruptMessage(e) : this.serialMessage(e);
390
+ else if (this.__internal__.serial.response.as === "string") {
391
+ const s = this.parseUint8ArrayToString(e);
392
+ if (this.__internal__.serial.response.limiter !== null) {
393
+ const r = s.split(this.__internal__.serial.response.limiter);
394
+ for (const o in r)
395
+ r[o] && (t ? this.serialCorruptMessage(r[o]) : this.serialMessage(r[o]));
396
+ } else
397
+ t ? this.serialCorruptMessage(s) : this.serialMessage(s);
398
+ } else {
399
+ const s = this.stringToArrayBuffer(this.parseUint8ArrayToString(e));
400
+ t ? this.serialCorruptMessage(s) : this.serialMessage(s);
401
+ }
402
+ }
403
+ if (this.__internal__.serial.queue.length === 0) {
404
+ this.__internal__.serial.running_queue = !1;
405
+ return;
406
+ }
407
+ this.dispatch("internal:queue", {});
408
+ }
356
409
  getResponseAsArrayBuffer() {
357
410
  this.__internal__.serial.response.as = "arraybuffer";
358
411
  }
@@ -365,6 +418,13 @@ class K extends I {
365
418
  getResponseAsString() {
366
419
  this.__internal__.serial.response.as = "string";
367
420
  }
421
+ async #o() {
422
+ const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
423
+ return e.length === 0 ? t : t.filter((i) => {
424
+ const s = i.getInfo();
425
+ return e.some((r) => s.usbProductId === r.usbProductId && s.usbVendorId === r.usbVendorId);
426
+ }).filter((i) => !this.#i(i));
427
+ }
368
428
  async serialPortsSaved(e) {
369
429
  const t = this.serialFilters;
370
430
  if (this.__internal__.aux_port_connector < e.length) {
@@ -390,7 +450,7 @@ class K extends I {
390
450
  case t.includes(
391
451
  "this readable stream reader has been released and cannot be used to cancel its previous owner stream"
392
452
  ):
393
- this.dispatch("serial:need-permission", {}), c.$dispatchChange(this);
453
+ this.dispatch("serial:need-permission", {}), n.$dispatchChange(this);
394
454
  break;
395
455
  case t.includes("the port is already open."):
396
456
  case t.includes("failed to open serial port"):
@@ -413,7 +473,7 @@ class K extends I {
413
473
  case t.includes("the port is already closed."):
414
474
  break;
415
475
  case t.includes("the device has been lost"):
416
- this.dispatch("serial:lost", {}), c.$dispatchChange(this);
476
+ this.dispatch("serial:lost", {}), n.$dispatchChange(this);
417
477
  break;
418
478
  case t.includes("navigator.serial is undefined"):
419
479
  this.dispatch("serial:unsupported", {});
@@ -424,10 +484,108 @@ class K extends I {
424
484
  }
425
485
  this.dispatch("serial:error", e);
426
486
  }
487
+ #_(e) {
488
+ if (e) {
489
+ const t = this.__internal__.serial.response.buffer, i = new Uint8Array(t.length + e.byteLength);
490
+ i.set(t, 0), i.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = i;
491
+ }
492
+ }
493
+ async #c() {
494
+ this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
495
+ this.__internal__.serial.response.buffer && this.#e(this.__internal__.serial.response.buffer), this.__internal__.serial.response.buffer = new Uint8Array(0);
496
+ }, this.__internal__.serial.free_timeout_ms || 50);
497
+ }
498
+ async #h() {
499
+ const e = this.__internal__.serial.response.length;
500
+ let t = this.__internal__.serial.response.buffer;
501
+ if (this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), !(e === null || !t || t.length === 0)) {
502
+ for (; t.length >= e; ) {
503
+ const i = t.slice(0, e);
504
+ this.#e(i), t = t.slice(e);
505
+ }
506
+ this.__internal__.serial.response.buffer = t, t.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
507
+ this.#e(this.__internal__.serial.response.buffer, !0);
508
+ }, this.__internal__.serial.free_timeout_ms || 50));
509
+ }
510
+ }
511
+ async #u() {
512
+ const {
513
+ limiter: e,
514
+ prefixLimiter: t = !1,
515
+ sufixLimiter: i = !0
516
+ } = this.__internal__.serial.response;
517
+ if (!e)
518
+ throw new Error("No limiter defined for delimited serial response");
519
+ const s = this.__internal__.serial.response.buffer;
520
+ if (!e || !s || s.length === 0) return;
521
+ this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0);
522
+ let r = new TextDecoder().decode(s);
523
+ const o = [];
524
+ if (typeof e == "string") {
525
+ let a;
526
+ if (t && i)
527
+ a = new RegExp(`${e}([^${e}]+)${e}`, "g");
528
+ else if (t)
529
+ a = new RegExp(`${e}([^${e}]*)`, "g");
530
+ else if (i)
531
+ a = new RegExp(`([^${e}]+)${e}`, "g");
532
+ else
533
+ return;
534
+ let _, l = 0;
535
+ for (; (_ = a.exec(r)) !== null; )
536
+ o.push(new TextEncoder().encode(_[1])), l = a.lastIndex;
537
+ r = r.slice(l);
538
+ } else if (e instanceof RegExp) {
539
+ let a, _ = 0;
540
+ if (t && i) {
541
+ const l = new RegExp(`${e.source}(.*?)${e.source}`, "g");
542
+ for (; (a = l.exec(r)) !== null; )
543
+ o.push(new TextEncoder().encode(a[1])), _ = l.lastIndex;
544
+ } else if (i)
545
+ for (; (a = e.exec(r)) !== null; ) {
546
+ const l = a.index, h = r.slice(_, l);
547
+ o.push(new TextEncoder().encode(h)), _ = e.lastIndex;
548
+ }
549
+ else if (t) {
550
+ const l = r.split(e);
551
+ l.shift();
552
+ for (const h of l)
553
+ o.push(new TextEncoder().encode(h));
554
+ r = "";
555
+ }
556
+ r = r.slice(_);
557
+ }
558
+ for (const a of o)
559
+ this.#e(a);
560
+ const d = new TextEncoder().encode(r);
561
+ this.__internal__.serial.response.buffer = d, d.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
562
+ this.#e(this.__internal__.serial.response.buffer, !0), this.__internal__.serial.response.buffer = new Uint8Array(0);
563
+ }, this.__internal__.serial.free_timeout_ms ?? 50));
564
+ }
565
+ async #d() {
566
+ const e = this.__internal__.serial.port;
567
+ if (!e || !e.readable) throw new Error("Port is not readable");
568
+ const t = e.readable.getReader();
569
+ this.__internal__.serial.reader = t;
570
+ try {
571
+ for (; this.__internal__.serial.keep_reading; ) {
572
+ const { value: i, done: s } = await t.read();
573
+ if (s) break;
574
+ this.#_(i), this.__internal__.serial.response.delimited ? await this.#u() : this.__internal__.serial.response.length === null ? await this.#c() : await this.#h();
575
+ }
576
+ } catch (i) {
577
+ this.serialErrors(i);
578
+ } finally {
579
+ t.releaseLock(), this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
580
+ }
581
+ }
582
+ #n(e) {
583
+ e !== this.__internal__.serial.connecting && (this.__internal__.serial.connecting = e, this.dispatch("serial:connecting", { active: e }), this.dispatch("internal:connecting", { active: e }));
584
+ }
427
585
  async serialConnect() {
428
586
  try {
429
- l(this, r, g).call(this, !0);
430
- const e = await l(this, r, N).call(this);
587
+ this.#n(!0);
588
+ const e = await this.#o();
431
589
  if (e.length > 0)
432
590
  await this.serialPortsSaved(e);
433
591
  else {
@@ -442,22 +600,24 @@ class K extends I {
442
600
  await t.open(this.serialConfigPort);
443
601
  const i = this;
444
602
  t.onconnect = (s) => {
445
- var o;
446
- i.dispatch("serial:connected", s), l(o = i, r, g).call(o, !1), c.$dispatchChange(this), i.__internal__.serial.queue.length > 0 && i.dispatch("internal:queue", {});
603
+ i.dispatch("serial:connected", s), i.#n(!1), n.$dispatchChange(this), i.__internal__.serial.queue.length > 0 ? i.dispatch("internal:queue", {}) : i.__internal__.serial.running_queue = !1;
447
604
  }, t.ondisconnect = async () => {
448
605
  await i.disconnect();
449
- }, await M(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
606
+ }, await f(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
450
607
  await i.timeout(i.__internal__.serial.bytes_connection ?? [], "connection:start");
451
- }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, r, x).call(this, this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
608
+ }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await this.#r(this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
452
609
  action: "connect",
453
610
  bytes: this.__internal__.serial.bytes_connection
454
- }), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response), await l(this, r, O).call(this);
611
+ }), this.__internal__.auto_response && this.#e(this.__internal__.serial.auto_response), await this.#d();
455
612
  } catch (e) {
456
- l(this, r, g).call(this, !1), this.serialErrors(e);
613
+ this.#n(!1), this.serialErrors(e);
457
614
  }
458
615
  }
616
+ async #p() {
617
+ return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
618
+ }
459
619
  async serialForget() {
460
- return await l(this, r, H).call(this);
620
+ return await this.#p();
461
621
  }
462
622
  decToHex(e) {
463
623
  return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
@@ -477,6 +637,70 @@ class K extends I {
477
637
  bytesToHex(e) {
478
638
  return this.add0x(Array.from(e, (t) => this.hexMaker(t)));
479
639
  }
640
+ #f() {
641
+ [
642
+ "serial:connected",
643
+ "serial:connecting",
644
+ "serial:reconnect",
645
+ "serial:timeout",
646
+ "serial:disconnected",
647
+ "serial:sent",
648
+ "serial:soft-reload",
649
+ "serial:message",
650
+ "serial:corrupt-message",
651
+ "unknown",
652
+ "serial:need-permission",
653
+ "serial:lost",
654
+ "serial:unsupported",
655
+ "serial:error",
656
+ "debug"
657
+ ].forEach((e) => {
658
+ this.serialRegisterAvailableListener(e);
659
+ });
660
+ }
661
+ #g() {
662
+ const e = this;
663
+ this.on("internal:queue", async () => {
664
+ await e.#b();
665
+ }), this.#y();
666
+ }
667
+ #y() {
668
+ const e = this;
669
+ navigator.serial.addEventListener("connect", async () => {
670
+ e.isDisconnected && await e.serialConnect().catch(() => {
671
+ });
672
+ });
673
+ }
674
+ async #b() {
675
+ if (!this.#i(this.__internal__.serial.port)) {
676
+ this.#s({ error: "Port is closed, not readable or writable." }), await this.serialConnect();
677
+ return;
678
+ }
679
+ if (this.__internal__.timeout.until_response) return;
680
+ if (this.__internal__.serial.queue.length === 0) {
681
+ this.__internal__.serial.running_queue = !1;
682
+ return;
683
+ }
684
+ this.__internal__.serial.running_queue = !0;
685
+ const e = this.__internal__.serial.queue[0];
686
+ let t = this.__internal__.time.response_general;
687
+ if (e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
688
+ await this.timeout(e.bytes, e.action);
689
+ }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await this.#r(e.bytes), this.dispatch("serial:sent", {
690
+ action: e.action,
691
+ bytes: e.bytes
692
+ }), this.__internal__.auto_response) {
693
+ let s = new Uint8Array(0);
694
+ try {
695
+ s = this.validateBytes(this.__internal__.serial.auto_response);
696
+ } catch (r) {
697
+ this.serialErrors(r);
698
+ }
699
+ this.#e(s);
700
+ }
701
+ const i = [...this.__internal__.serial.queue];
702
+ this.__internal__.serial.queue = i.splice(1), this.__internal__.serial.queue.length > 0 && (this.__internal__.serial.running_queue = !0);
703
+ }
480
704
  validateBytes(e) {
481
705
  let t = new Uint8Array(0);
482
706
  if (e instanceof Uint8Array)
@@ -500,6 +724,9 @@ class K extends I {
500
724
  }
501
725
  this.__internal__.serial.queue.push({ bytes: i, action: t }), this.dispatch("internal:queue", {});
502
726
  }
727
+ #m(e = 1) {
728
+ this.__internal__.device_number = e, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e));
729
+ }
503
730
  serialSetConnectionConstant(e = 1) {
504
731
  if (this.__internal__.bypassSerialBytesConnection) return this.__internal__.serial.bytes_connection;
505
732
  throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`);
@@ -510,6 +737,14 @@ class K extends I {
510
737
  serialCorruptMessage(e) {
511
738
  throw console.log(e), this.dispatch("serial:corrupt-message", { code: e }), new Error("Method not implemented 'serialCorruptMessage'");
512
739
  }
740
+ #w() {
741
+ this.__internal__.last_error = {
742
+ message: null,
743
+ action: null,
744
+ code: null,
745
+ no_code: 0
746
+ };
747
+ }
513
748
  clearSerialQueue() {
514
749
  this.__internal__.serial.queue = [];
515
750
  }
@@ -529,7 +764,7 @@ class K extends I {
529
764
  });
530
765
  }
531
766
  softReload() {
532
- l(this, r, Q).call(this), this.dispatch("serial:soft-reload", {});
767
+ this.#w(), this.dispatch("serial:soft-reload", {});
533
768
  }
534
769
  async sendConnect() {
535
770
  if (!this.__internal__.serial.bytes_connection)
@@ -587,8 +822,8 @@ class K extends I {
587
822
  asciiToHex(e) {
588
823
  const t = [];
589
824
  for (let i = 0, s = e.length; i < s; i++) {
590
- const o = Number(e.charCodeAt(i)).toString(16);
591
- t.push(o);
825
+ const r = Number(e.charCodeAt(i)).toString(16);
826
+ t.push(r);
592
827
  }
593
828
  return t.join("");
594
829
  }
@@ -596,217 +831,7 @@ class K extends I {
596
831
  return this.isConnected;
597
832
  }
598
833
  }
599
- p = /* @__PURE__ */ new WeakMap(), r = /* @__PURE__ */ new WeakSet(), f = function(n) {
600
- return !!(n && n.readable && n.writable);
601
- }, m = function(n = null) {
602
- this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", n), c.$dispatchChange(this);
603
- }, q = function(n) {
604
- this.__internal__.serial.aux_connecting = n.detail.active ? "connecting" : "finished";
605
- }, x = async function(n) {
606
- const e = this.__internal__.serial.port;
607
- if (!e || e && (!e.readable || !e.writable))
608
- throw l(this, r, m).call(this, { error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
609
- const t = this.validateBytes(n);
610
- if (this.useRTSCTS && await l(this, r, k).call(this, e, 5e3), e.writable === null) return;
611
- const i = e.writable.getWriter();
612
- await i.write(t), i.releaseLock();
613
- }, k = async function(n, e = 5e3) {
614
- const t = Date.now();
615
- for (; ; ) {
616
- if (Date.now() - t > e)
617
- throw new Error("Timeout waiting for clearToSend signal");
618
- const { clearToSend: i } = await n.getSignals();
619
- if (i) return;
620
- await M(100);
621
- }
622
- }, u = function(n = new Uint8Array([]), e = !1) {
623
- if (n && n.length > 0) {
624
- const t = this.__internal__.serial.connected;
625
- if (this.__internal__.serial.connected = l(this, r, f).call(this, this.__internal__.serial.port), c.$dispatchChange(this), !t && this.__internal__.serial.connected && (this.dispatch("serial:connected"), l(this, r, g).call(this, !1)), this.__internal__.interval.reconnection && (clearInterval(this.__internal__.interval.reconnection), this.__internal__.interval.reconnection = 0), this.__internal__.timeout.until_response && (clearTimeout(this.__internal__.timeout.until_response), this.__internal__.timeout.until_response = 0), this.__internal__.serial.response.as === "hex")
626
- e ? this.serialCorruptMessage(this.parseUint8ToHex(n)) : this.serialMessage(this.parseUint8ToHex(n));
627
- else if (this.__internal__.serial.response.as === "uint8")
628
- e ? this.serialCorruptMessage(n) : this.serialMessage(n);
629
- else if (this.__internal__.serial.response.as === "string") {
630
- const i = this.parseUint8ArrayToString(n);
631
- if (this.__internal__.serial.response.limiter !== null) {
632
- const s = i.split(this.__internal__.serial.response.limiter);
633
- for (const o in s)
634
- s[o] && (e ? this.serialCorruptMessage(s[o]) : this.serialMessage(s[o]));
635
- } else
636
- e ? this.serialCorruptMessage(i) : this.serialMessage(i);
637
- } else {
638
- const i = this.stringToArrayBuffer(this.parseUint8ArrayToString(n));
639
- e ? this.serialCorruptMessage(i) : this.serialMessage(i);
640
- }
641
- }
642
- this.__internal__.serial.queue.length !== 0 && this.dispatch("internal:queue", {});
643
- }, N = async function() {
644
- const n = this.serialFilters, e = await navigator.serial.getPorts({ filters: n });
645
- return n.length === 0 ? e : e.filter((t) => {
646
- const i = t.getInfo();
647
- return n.some((s) => i.usbProductId === s.usbProductId && i.usbVendorId === s.usbVendorId);
648
- }).filter((t) => !l(this, r, f).call(this, t));
649
- }, L = function(n) {
650
- if (n) {
651
- const e = this.__internal__.serial.response.buffer, t = new Uint8Array(e.length + n.byteLength);
652
- t.set(e, 0), t.set(new Uint8Array(n), e.length), this.__internal__.serial.response.buffer = t;
653
- }
654
- }, D = async function() {
655
- this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
656
- this.__internal__.serial.response.buffer && l(this, r, u).call(this, this.__internal__.serial.response.buffer), this.__internal__.serial.response.buffer = new Uint8Array(0);
657
- }, this.__internal__.serial.free_timeout_ms || 50);
658
- }, B = async function() {
659
- const n = this.__internal__.serial.response.length;
660
- let e = this.__internal__.serial.response.buffer;
661
- if (this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), !(n === null || !e || e.length === 0)) {
662
- for (; e.length >= n; ) {
663
- const t = e.slice(0, n);
664
- l(this, r, u).call(this, t), e = e.slice(n);
665
- }
666
- this.__internal__.serial.response.buffer = e, e.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
667
- l(this, r, u).call(this, this.__internal__.serial.response.buffer, !0);
668
- }, this.__internal__.serial.free_timeout_ms || 50));
669
- }
670
- }, P = async function() {
671
- const {
672
- limiter: n,
673
- prefixLimiter: e = !1,
674
- sufixLimiter: t = !0
675
- } = this.__internal__.serial.response;
676
- if (!n)
677
- throw new Error("No limiter defined for delimited serial response");
678
- const i = this.__internal__.serial.response.buffer;
679
- if (!n || !i || i.length === 0) return;
680
- this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0);
681
- let s = new TextDecoder().decode(i);
682
- const o = [];
683
- if (typeof n == "string") {
684
- let _;
685
- if (e && t)
686
- _ = new RegExp(`${n}([^${n}]+)${n}`, "g");
687
- else if (e)
688
- _ = new RegExp(`${n}([^${n}]*)`, "g");
689
- else if (t)
690
- _ = new RegExp(`([^${n}]+)${n}`, "g");
691
- else
692
- return;
693
- let d, h = 0;
694
- for (; (d = _.exec(s)) !== null; )
695
- o.push(new TextEncoder().encode(d[1])), h = _.lastIndex;
696
- s = s.slice(h);
697
- } else if (n instanceof RegExp) {
698
- let _, d = 0;
699
- if (e && t) {
700
- const h = new RegExp(`${n.source}(.*?)${n.source}`, "g");
701
- for (; (_ = h.exec(s)) !== null; )
702
- o.push(new TextEncoder().encode(_[1])), d = h.lastIndex;
703
- } else if (t)
704
- for (; (_ = n.exec(s)) !== null; ) {
705
- const h = _.index, w = s.slice(d, h);
706
- o.push(new TextEncoder().encode(w)), d = n.lastIndex;
707
- }
708
- else if (e) {
709
- const h = s.split(n);
710
- h.shift();
711
- for (const w of h)
712
- o.push(new TextEncoder().encode(w));
713
- s = "";
714
- }
715
- s = s.slice(d);
716
- }
717
- for (const _ of o)
718
- l(this, r, u).call(this, _);
719
- const E = new TextEncoder().encode(s);
720
- this.__internal__.serial.response.buffer = E, E.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
721
- l(this, r, u).call(this, this.__internal__.serial.response.buffer, !0), this.__internal__.serial.response.buffer = new Uint8Array(0);
722
- }, this.__internal__.serial.free_timeout_ms ?? 50));
723
- }, O = async function() {
724
- const n = this.__internal__.serial.port;
725
- if (!n || !n.readable) throw new Error("Port is not readable");
726
- const e = n.readable.getReader();
727
- this.__internal__.serial.reader = e;
728
- try {
729
- for (; this.__internal__.serial.keep_reading; ) {
730
- const { value: t, done: i } = await e.read();
731
- if (i) break;
732
- l(this, r, L).call(this, t), this.__internal__.serial.response.delimited ? await l(this, r, P).call(this) : this.__internal__.serial.response.length === null ? await l(this, r, D).call(this) : await l(this, r, B).call(this);
733
- }
734
- } catch (t) {
735
- this.serialErrors(t);
736
- } finally {
737
- e.releaseLock(), this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
738
- }
739
- }, g = function(n) {
740
- n !== this.__internal__.serial.connecting && (this.__internal__.serial.connecting = n, this.dispatch("serial:connecting", { active: n }), this.dispatch("internal:connecting", { active: n }));
741
- }, H = async function() {
742
- return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
743
- }, j = function() {
744
- [
745
- "serial:connected",
746
- "serial:connecting",
747
- "serial:reconnect",
748
- "serial:timeout",
749
- "serial:disconnected",
750
- "serial:sent",
751
- "serial:soft-reload",
752
- "serial:message",
753
- "serial:corrupt-message",
754
- "unknown",
755
- "serial:need-permission",
756
- "serial:lost",
757
- "serial:unsupported",
758
- "serial:error",
759
- "debug"
760
- ].forEach((n) => {
761
- this.serialRegisterAvailableListener(n);
762
- });
763
- }, F = function() {
764
- const n = this;
765
- this.on("internal:queue", async () => {
766
- var e;
767
- await l(e = n, r, $).call(e);
768
- }), l(this, r, U).call(this);
769
- }, U = function() {
770
- const n = this;
771
- navigator.serial.addEventListener("connect", async () => {
772
- n.isDisconnected && await n.serialConnect().catch(() => {
773
- });
774
- });
775
- }, $ = async function() {
776
- if (!l(this, r, f).call(this, this.__internal__.serial.port)) {
777
- l(this, r, m).call(this, { error: "Port is closed, not readable or writable." }), await this.serialConnect();
778
- return;
779
- }
780
- if (this.__internal__.timeout.until_response || this.__internal__.serial.queue.length === 0) return;
781
- const n = this.__internal__.serial.queue[0];
782
- let e = this.__internal__.time.response_general;
783
- if (n.action === "connect" && (e = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
784
- await this.timeout(n.bytes, n.action);
785
- }, e), this.__internal__.serial.last_action = n.action ?? "unknown", await l(this, r, x).call(this, n.bytes), this.dispatch("serial:sent", {
786
- action: n.action,
787
- bytes: n.bytes
788
- }), this.__internal__.auto_response) {
789
- let i = new Uint8Array(0);
790
- try {
791
- i = this.validateBytes(this.__internal__.serial.auto_response);
792
- } catch (s) {
793
- this.serialErrors(s);
794
- }
795
- l(this, r, u).call(this, i);
796
- }
797
- const t = [...this.__internal__.serial.queue];
798
- this.__internal__.serial.queue = t.splice(1);
799
- }, W = function(n = 1) {
800
- this.__internal__.device_number = n, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(n));
801
- }, Q = function() {
802
- this.__internal__.last_error = {
803
- message: null,
804
- action: null,
805
- code: null,
806
- no_code: 0
807
- };
808
- };
809
834
  export {
810
- K as Z,
811
- c as h
835
+ b,
836
+ n as s
812
837
  };