@danidoble/webserial 4.3.13 → 4.4.0-beta.2

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.
@@ -0,0 +1,3325 @@
1
+ class Y extends CustomEvent {
2
+ constructor(e, t) {
3
+ super(e, t);
4
+ }
5
+ }
6
+ class te extends EventTarget {
7
+ __listeners__ = {
8
+ debug: !1
9
+ };
10
+ __debug__ = !1;
11
+ __listenersCallbacks__ = [];
12
+ dispatch(e, t = null) {
13
+ const n = new Y(e, { detail: t });
14
+ this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new Y("debug", { detail: { type: e, data: t } }));
15
+ }
16
+ dispatchAsync(e, t = null, n = 100) {
17
+ const r = this;
18
+ setTimeout(() => {
19
+ r.dispatch(e, t);
20
+ }, n);
21
+ }
22
+ on(e, t) {
23
+ typeof this.__listeners__[e] < "u" && !this.__listeners__[e] && (this.__listeners__[e] = !0), this.__listenersCallbacks__.push({ key: e, callback: t }), this.addEventListener(e, t);
24
+ }
25
+ off(e, t) {
26
+ this.__listenersCallbacks__ = this.__listenersCallbacks__.filter((n) => !(n.key === e && n.callback === t)), this.removeEventListener(e, t);
27
+ }
28
+ serialRegisterAvailableListener(e) {
29
+ this.__listeners__[e] || (this.__listeners__[e] = !1);
30
+ }
31
+ get availableListeners() {
32
+ return Object.keys(this.__listeners__).sort().map((e) => ({
33
+ type: e,
34
+ listening: this.__listeners__[e]
35
+ }));
36
+ }
37
+ removeAllListeners() {
38
+ for (const e of this.__listenersCallbacks__)
39
+ ["internal:queue"].includes(e.key) || (this.__listenersCallbacks__ = this.__listenersCallbacks__.filter((t) => !(t.key === e.key && t.callback === e.callback)), this.removeEventListener(e.key, e.callback));
40
+ for (const e of Object.keys(this.__listeners__))
41
+ this.__listeners__[e] = !1;
42
+ }
43
+ }
44
+ class a extends te {
45
+ static instance;
46
+ static devices = {};
47
+ constructor() {
48
+ super(), ["change"].forEach((e) => {
49
+ this.serialRegisterAvailableListener(e);
50
+ });
51
+ }
52
+ static $dispatchChange(e = null) {
53
+ e && e.$checkAndDispatchConnection(), a.instance.dispatch("change", { devices: a.devices, dispatcher: e });
54
+ }
55
+ static typeError(e) {
56
+ const t = new Error();
57
+ throw t.message = `Type ${e} is not supported`, t.name = "DeviceTypeError", t;
58
+ }
59
+ static registerType(e) {
60
+ typeof a.devices[e] > "u" && (a.devices = { ...a.devices, [e]: {} });
61
+ }
62
+ static add(e) {
63
+ const t = e.typeDevice;
64
+ typeof a.devices[t] > "u" && a.registerType(t);
65
+ const n = e.uuid;
66
+ if (typeof a.devices[t] > "u" && a.typeError(t), a.devices[t][n])
67
+ throw new Error(`Device with id ${n} already exists`);
68
+ return a.devices[t][n] = e, a.$dispatchChange(e), Object.keys(a.devices[t]).indexOf(n);
69
+ }
70
+ static get(e, t) {
71
+ return typeof a.devices[e] > "u" && a.registerType(e), typeof a.devices[e] > "u" && a.typeError(e), a.devices[e][t];
72
+ }
73
+ static getAll(e = null) {
74
+ return e === null ? a.devices : (typeof a.devices[e] > "u" && a.typeError(e), a.devices[e]);
75
+ }
76
+ static getList() {
77
+ return Object.values(a.devices).map((e) => Object.values(e)).flat();
78
+ }
79
+ static getByNumber(e, t) {
80
+ return typeof a.devices[e] > "u" && a.typeError(e), Object.values(a.devices[e]).find((n) => n.deviceNumber === t) ?? null;
81
+ }
82
+ static getCustom(e, t = 1) {
83
+ return typeof a.devices[e] > "u" && a.typeError(e), Object.values(a.devices[e]).find((n) => n.deviceNumber === t) ?? null;
84
+ }
85
+ static async connectToAll() {
86
+ const e = a.getList();
87
+ for (const t of e)
88
+ t.isConnected || await t.connect().catch(console.warn);
89
+ return Promise.resolve(a.areAllConnected());
90
+ }
91
+ static async disconnectAll() {
92
+ const e = a.getList();
93
+ for (const t of e)
94
+ t.isDisconnected || await t.disconnect().catch(console.warn);
95
+ return Promise.resolve(a.areAllDisconnected());
96
+ }
97
+ static async areAllConnected() {
98
+ const e = a.getList();
99
+ for (const t of e)
100
+ if (!t.isConnected) return Promise.resolve(!1);
101
+ return Promise.resolve(!0);
102
+ }
103
+ static async areAllDisconnected() {
104
+ const e = a.getList();
105
+ for (const t of e)
106
+ if (!t.isDisconnected) return Promise.resolve(!1);
107
+ return Promise.resolve(!0);
108
+ }
109
+ static async getAllConnected() {
110
+ const e = a.getList();
111
+ return Promise.resolve(e.filter((t) => t.isConnected));
112
+ }
113
+ static async getAllDisconnected() {
114
+ const e = a.getList();
115
+ return Promise.resolve(e.filter((t) => t.isDisconnected));
116
+ }
117
+ }
118
+ a.instance || (a.instance = new a());
119
+ function J(s = 100) {
120
+ return new Promise(
121
+ (e) => setTimeout(() => e(), s)
122
+ );
123
+ }
124
+ const m = /* @__PURE__ */ Object.create(null);
125
+ m.open = "0";
126
+ m.close = "1";
127
+ m.ping = "2";
128
+ m.pong = "3";
129
+ m.message = "4";
130
+ m.upgrade = "5";
131
+ m.noop = "6";
132
+ const x = /* @__PURE__ */ Object.create(null);
133
+ Object.keys(m).forEach((s) => {
134
+ x[m[s]] = s;
135
+ });
136
+ const D = { type: "error", data: "parser error" }, se = typeof Blob == "function" || typeof Blob < "u" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]", ne = typeof ArrayBuffer == "function", re = (s) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(s) : s && s.buffer instanceof ArrayBuffer, V = ({ type: s, data: e }, t, n) => se && e instanceof Blob ? t ? n(e) : Q(e, n) : ne && (e instanceof ArrayBuffer || re(e)) ? t ? n(e) : Q(new Blob([e]), n) : n(m[s] + (e || "")), Q = (s, e) => {
137
+ const t = new FileReader();
138
+ return t.onload = function() {
139
+ const n = t.result.split(",")[1];
140
+ e("b" + (n || ""));
141
+ }, t.readAsDataURL(s);
142
+ };
143
+ function X(s) {
144
+ return s instanceof Uint8Array ? s : s instanceof ArrayBuffer ? new Uint8Array(s) : new Uint8Array(s.buffer, s.byteOffset, s.byteLength);
145
+ }
146
+ let P;
147
+ function fe(s, e) {
148
+ if (se && s.data instanceof Blob)
149
+ return s.data.arrayBuffer().then(X).then(e);
150
+ if (ne && (s.data instanceof ArrayBuffer || re(s.data)))
151
+ return e(X(s.data));
152
+ V(s, !1, (t) => {
153
+ P || (P = new TextEncoder()), e(P.encode(t));
154
+ });
155
+ }
156
+ const G = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", E = typeof Uint8Array > "u" ? [] : new Uint8Array(256);
157
+ for (let s = 0; s < G.length; s++)
158
+ E[G.charCodeAt(s)] = s;
159
+ const ye = (s) => {
160
+ let e = s.length * 0.75, t = s.length, n, r = 0, i, o, h, c;
161
+ s[s.length - 1] === "=" && (e--, s[s.length - 2] === "=" && e--);
162
+ const p = new ArrayBuffer(e), u = new Uint8Array(p);
163
+ for (n = 0; n < t; n += 4)
164
+ i = E[s.charCodeAt(n)], o = E[s.charCodeAt(n + 1)], h = E[s.charCodeAt(n + 2)], c = E[s.charCodeAt(n + 3)], u[r++] = i << 2 | o >> 4, u[r++] = (o & 15) << 4 | h >> 2, u[r++] = (h & 3) << 6 | c & 63;
165
+ return p;
166
+ }, ge = typeof ArrayBuffer == "function", H = (s, e) => {
167
+ if (typeof s != "string")
168
+ return {
169
+ type: "message",
170
+ data: ie(s, e)
171
+ };
172
+ const t = s.charAt(0);
173
+ return t === "b" ? {
174
+ type: "message",
175
+ data: me(s.substring(1), e)
176
+ } : x[t] ? s.length > 1 ? {
177
+ type: x[t],
178
+ data: s.substring(1)
179
+ } : {
180
+ type: x[t]
181
+ } : D;
182
+ }, me = (s, e) => {
183
+ if (ge) {
184
+ const t = ye(s);
185
+ return ie(t, e);
186
+ } else
187
+ return { base64: !0, data: s };
188
+ }, ie = (s, e) => {
189
+ switch (e) {
190
+ case "blob":
191
+ return s instanceof Blob ? s : new Blob([s]);
192
+ case "arraybuffer":
193
+ default:
194
+ return s instanceof ArrayBuffer ? s : s.buffer;
195
+ }
196
+ }, oe = "", be = (s, e) => {
197
+ const t = s.length, n = new Array(t);
198
+ let r = 0;
199
+ s.forEach((i, o) => {
200
+ V(i, !1, (h) => {
201
+ n[o] = h, ++r === t && e(n.join(oe));
202
+ });
203
+ });
204
+ }, we = (s, e) => {
205
+ const t = s.split(oe), n = [];
206
+ for (let r = 0; r < t.length; r++) {
207
+ const i = H(t[r], e);
208
+ if (n.push(i), i.type === "error")
209
+ break;
210
+ }
211
+ return n;
212
+ };
213
+ function ve() {
214
+ return new TransformStream({
215
+ transform(s, e) {
216
+ fe(s, (t) => {
217
+ const n = t.length;
218
+ let r;
219
+ if (n < 126)
220
+ r = new Uint8Array(1), new DataView(r.buffer).setUint8(0, n);
221
+ else if (n < 65536) {
222
+ r = new Uint8Array(3);
223
+ const i = new DataView(r.buffer);
224
+ i.setUint8(0, 126), i.setUint16(1, n);
225
+ } else {
226
+ r = new Uint8Array(9);
227
+ const i = new DataView(r.buffer);
228
+ i.setUint8(0, 127), i.setBigUint64(1, BigInt(n));
229
+ }
230
+ s.data && typeof s.data != "string" && (r[0] |= 128), e.enqueue(r), e.enqueue(t);
231
+ });
232
+ }
233
+ });
234
+ }
235
+ let N;
236
+ function C(s) {
237
+ return s.reduce((e, t) => e + t.length, 0);
238
+ }
239
+ function T(s, e) {
240
+ if (s[0].length === e)
241
+ return s.shift();
242
+ const t = new Uint8Array(e);
243
+ let n = 0;
244
+ for (let r = 0; r < e; r++)
245
+ t[r] = s[0][n++], n === s[0].length && (s.shift(), n = 0);
246
+ return s.length && n < s[0].length && (s[0] = s[0].slice(n)), t;
247
+ }
248
+ function ke(s, e) {
249
+ N || (N = new TextDecoder());
250
+ const t = [];
251
+ let n = 0, r = -1, i = !1;
252
+ return new TransformStream({
253
+ transform(o, h) {
254
+ for (t.push(o); ; ) {
255
+ if (n === 0) {
256
+ if (C(t) < 1)
257
+ break;
258
+ const c = T(t, 1);
259
+ i = (c[0] & 128) === 128, r = c[0] & 127, r < 126 ? n = 3 : r === 126 ? n = 1 : n = 2;
260
+ } else if (n === 1) {
261
+ if (C(t) < 2)
262
+ break;
263
+ const c = T(t, 2);
264
+ r = new DataView(c.buffer, c.byteOffset, c.length).getUint16(0), n = 3;
265
+ } else if (n === 2) {
266
+ if (C(t) < 8)
267
+ break;
268
+ const c = T(t, 8), p = new DataView(c.buffer, c.byteOffset, c.length), u = p.getUint32(0);
269
+ if (u > Math.pow(2, 21) - 1) {
270
+ h.enqueue(D);
271
+ break;
272
+ }
273
+ r = u * Math.pow(2, 32) + p.getUint32(4), n = 3;
274
+ } else {
275
+ if (C(t) < r)
276
+ break;
277
+ const c = T(t, r);
278
+ h.enqueue(H(i ? c : N.decode(c), e)), n = 0;
279
+ }
280
+ if (r === 0 || r > s) {
281
+ h.enqueue(D);
282
+ break;
283
+ }
284
+ }
285
+ }
286
+ });
287
+ }
288
+ const ae = 4;
289
+ function _(s) {
290
+ if (s) return Ee(s);
291
+ }
292
+ function Ee(s) {
293
+ for (var e in _.prototype)
294
+ s[e] = _.prototype[e];
295
+ return s;
296
+ }
297
+ _.prototype.on = _.prototype.addEventListener = function(s, e) {
298
+ return this._callbacks = this._callbacks || {}, (this._callbacks["$" + s] = this._callbacks["$" + s] || []).push(e), this;
299
+ };
300
+ _.prototype.once = function(s, e) {
301
+ function t() {
302
+ this.off(s, t), e.apply(this, arguments);
303
+ }
304
+ return t.fn = e, this.on(s, t), this;
305
+ };
306
+ _.prototype.off = _.prototype.removeListener = _.prototype.removeAllListeners = _.prototype.removeEventListener = function(s, e) {
307
+ if (this._callbacks = this._callbacks || {}, arguments.length == 0)
308
+ return this._callbacks = {}, this;
309
+ var t = this._callbacks["$" + s];
310
+ if (!t) return this;
311
+ if (arguments.length == 1)
312
+ return delete this._callbacks["$" + s], this;
313
+ for (var n, r = 0; r < t.length; r++)
314
+ if (n = t[r], n === e || n.fn === e) {
315
+ t.splice(r, 1);
316
+ break;
317
+ }
318
+ return t.length === 0 && delete this._callbacks["$" + s], this;
319
+ };
320
+ _.prototype.emit = function(s) {
321
+ this._callbacks = this._callbacks || {};
322
+ for (var e = new Array(arguments.length - 1), t = this._callbacks["$" + s], n = 1; n < arguments.length; n++)
323
+ e[n - 1] = arguments[n];
324
+ if (t) {
325
+ t = t.slice(0);
326
+ for (var n = 0, r = t.length; n < r; ++n)
327
+ t[n].apply(this, e);
328
+ }
329
+ return this;
330
+ };
331
+ _.prototype.emitReserved = _.prototype.emit;
332
+ _.prototype.listeners = function(s) {
333
+ return this._callbacks = this._callbacks || {}, this._callbacks["$" + s] || [];
334
+ };
335
+ _.prototype.hasListeners = function(s) {
336
+ return !!this.listeners(s).length;
337
+ };
338
+ const O = typeof Promise == "function" && typeof Promise.resolve == "function" ? (s) => Promise.resolve().then(s) : (s, e) => e(s, 0), d = typeof self < "u" ? self : typeof window < "u" ? window : Function("return this")(), Ce = "arraybuffer";
339
+ function ce(s, ...e) {
340
+ return e.reduce((t, n) => (s.hasOwnProperty(n) && (t[n] = s[n]), t), {});
341
+ }
342
+ const Te = d.setTimeout, Ae = d.clearTimeout;
343
+ function L(s, e) {
344
+ e.useNativeTimers ? (s.setTimeoutFn = Te.bind(d), s.clearTimeoutFn = Ae.bind(d)) : (s.setTimeoutFn = d.setTimeout.bind(d), s.clearTimeoutFn = d.clearTimeout.bind(d));
345
+ }
346
+ const xe = 1.33;
347
+ function Se(s) {
348
+ return typeof s == "string" ? Re(s) : Math.ceil((s.byteLength || s.size) * xe);
349
+ }
350
+ function Re(s) {
351
+ let e = 0, t = 0;
352
+ for (let n = 0, r = s.length; n < r; n++)
353
+ e = s.charCodeAt(n), e < 128 ? t += 1 : e < 2048 ? t += 2 : e < 55296 || e >= 57344 ? t += 3 : (n++, t += 4);
354
+ return t;
355
+ }
356
+ function le() {
357
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
358
+ }
359
+ function Be(s) {
360
+ let e = "";
361
+ for (let t in s)
362
+ s.hasOwnProperty(t) && (e.length && (e += "&"), e += encodeURIComponent(t) + "=" + encodeURIComponent(s[t]));
363
+ return e;
364
+ }
365
+ function Oe(s) {
366
+ let e = {}, t = s.split("&");
367
+ for (let n = 0, r = t.length; n < r; n++) {
368
+ let i = t[n].split("=");
369
+ e[decodeURIComponent(i[0])] = decodeURIComponent(i[1]);
370
+ }
371
+ return e;
372
+ }
373
+ class Le extends Error {
374
+ constructor(e, t, n) {
375
+ super(e), this.description = t, this.context = n, this.type = "TransportError";
376
+ }
377
+ }
378
+ class W extends _ {
379
+ /**
380
+ * Transport abstract constructor.
381
+ *
382
+ * @param {Object} opts - options
383
+ * @protected
384
+ */
385
+ constructor(e) {
386
+ super(), this.writable = !1, L(this, e), this.opts = e, this.query = e.query, this.socket = e.socket, this.supportsBinary = !e.forceBase64;
387
+ }
388
+ /**
389
+ * Emits an error.
390
+ *
391
+ * @param {String} reason
392
+ * @param description
393
+ * @param context - the error context
394
+ * @return {Transport} for chaining
395
+ * @protected
396
+ */
397
+ onError(e, t, n) {
398
+ return super.emitReserved("error", new Le(e, t, n)), this;
399
+ }
400
+ /**
401
+ * Opens the transport.
402
+ */
403
+ open() {
404
+ return this.readyState = "opening", this.doOpen(), this;
405
+ }
406
+ /**
407
+ * Closes the transport.
408
+ */
409
+ close() {
410
+ return (this.readyState === "opening" || this.readyState === "open") && (this.doClose(), this.onClose()), this;
411
+ }
412
+ /**
413
+ * Sends multiple packets.
414
+ *
415
+ * @param {Array} packets
416
+ */
417
+ send(e) {
418
+ this.readyState === "open" && this.write(e);
419
+ }
420
+ /**
421
+ * Called upon open
422
+ *
423
+ * @protected
424
+ */
425
+ onOpen() {
426
+ this.readyState = "open", this.writable = !0, super.emitReserved("open");
427
+ }
428
+ /**
429
+ * Called with data.
430
+ *
431
+ * @param {String} data
432
+ * @protected
433
+ */
434
+ onData(e) {
435
+ const t = H(e, this.socket.binaryType);
436
+ this.onPacket(t);
437
+ }
438
+ /**
439
+ * Called with a decoded packet.
440
+ *
441
+ * @protected
442
+ */
443
+ onPacket(e) {
444
+ super.emitReserved("packet", e);
445
+ }
446
+ /**
447
+ * Called upon close.
448
+ *
449
+ * @protected
450
+ */
451
+ onClose(e) {
452
+ this.readyState = "closed", super.emitReserved("close", e);
453
+ }
454
+ /**
455
+ * Pauses the transport, in order not to lose packets during an upgrade.
456
+ *
457
+ * @param onPause
458
+ */
459
+ pause(e) {
460
+ }
461
+ createUri(e, t = {}) {
462
+ return e + "://" + this._hostname() + this._port() + this.opts.path + this._query(t);
463
+ }
464
+ _hostname() {
465
+ const e = this.opts.hostname;
466
+ return e.indexOf(":") === -1 ? e : "[" + e + "]";
467
+ }
468
+ _port() {
469
+ return this.opts.port && (this.opts.secure && +(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80) ? ":" + this.opts.port : "";
470
+ }
471
+ _query(e) {
472
+ const t = Be(e);
473
+ return t.length ? "?" + t : "";
474
+ }
475
+ }
476
+ class Pe extends W {
477
+ constructor() {
478
+ super(...arguments), this._polling = !1;
479
+ }
480
+ get name() {
481
+ return "polling";
482
+ }
483
+ /**
484
+ * Opens the socket (triggers polling). We write a PING message to determine
485
+ * when the transport is open.
486
+ *
487
+ * @protected
488
+ */
489
+ doOpen() {
490
+ this._poll();
491
+ }
492
+ /**
493
+ * Pauses polling.
494
+ *
495
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
496
+ * @package
497
+ */
498
+ pause(e) {
499
+ this.readyState = "pausing";
500
+ const t = () => {
501
+ this.readyState = "paused", e();
502
+ };
503
+ if (this._polling || !this.writable) {
504
+ let n = 0;
505
+ this._polling && (n++, this.once("pollComplete", function() {
506
+ --n || t();
507
+ })), this.writable || (n++, this.once("drain", function() {
508
+ --n || t();
509
+ }));
510
+ } else
511
+ t();
512
+ }
513
+ /**
514
+ * Starts polling cycle.
515
+ *
516
+ * @private
517
+ */
518
+ _poll() {
519
+ this._polling = !0, this.doPoll(), this.emitReserved("poll");
520
+ }
521
+ /**
522
+ * Overloads onData to detect payloads.
523
+ *
524
+ * @protected
525
+ */
526
+ onData(e) {
527
+ const t = (n) => {
528
+ if (this.readyState === "opening" && n.type === "open" && this.onOpen(), n.type === "close")
529
+ return this.onClose({ description: "transport closed by the server" }), !1;
530
+ this.onPacket(n);
531
+ };
532
+ we(e, this.socket.binaryType).forEach(t), this.readyState !== "closed" && (this._polling = !1, this.emitReserved("pollComplete"), this.readyState === "open" && this._poll());
533
+ }
534
+ /**
535
+ * For polling, send a close packet.
536
+ *
537
+ * @protected
538
+ */
539
+ doClose() {
540
+ const e = () => {
541
+ this.write([{ type: "close" }]);
542
+ };
543
+ this.readyState === "open" ? e() : this.once("open", e);
544
+ }
545
+ /**
546
+ * Writes a packets payload.
547
+ *
548
+ * @param {Array} packets - data packets
549
+ * @protected
550
+ */
551
+ write(e) {
552
+ this.writable = !1, be(e, (t) => {
553
+ this.doWrite(t, () => {
554
+ this.writable = !0, this.emitReserved("drain");
555
+ });
556
+ });
557
+ }
558
+ /**
559
+ * Generates uri for connection.
560
+ *
561
+ * @private
562
+ */
563
+ uri() {
564
+ const e = this.opts.secure ? "https" : "http", t = this.query || {};
565
+ return this.opts.timestampRequests !== !1 && (t[this.opts.timestampParam] = le()), !this.supportsBinary && !t.sid && (t.b64 = 1), this.createUri(e, t);
566
+ }
567
+ }
568
+ let he = !1;
569
+ try {
570
+ he = typeof XMLHttpRequest < "u" && "withCredentials" in new XMLHttpRequest();
571
+ } catch {
572
+ }
573
+ const Ne = he;
574
+ function Ie() {
575
+ }
576
+ class qe extends Pe {
577
+ /**
578
+ * XHR Polling constructor.
579
+ *
580
+ * @param {Object} opts
581
+ * @package
582
+ */
583
+ constructor(e) {
584
+ if (super(e), typeof location < "u") {
585
+ const t = location.protocol === "https:";
586
+ let n = location.port;
587
+ n || (n = t ? "443" : "80"), this.xd = typeof location < "u" && e.hostname !== location.hostname || n !== e.port;
588
+ }
589
+ }
590
+ /**
591
+ * Sends data.
592
+ *
593
+ * @param {String} data to send.
594
+ * @param {Function} called upon flush.
595
+ * @private
596
+ */
597
+ doWrite(e, t) {
598
+ const n = this.request({
599
+ method: "POST",
600
+ data: e
601
+ });
602
+ n.on("success", t), n.on("error", (r, i) => {
603
+ this.onError("xhr post error", r, i);
604
+ });
605
+ }
606
+ /**
607
+ * Starts a poll cycle.
608
+ *
609
+ * @private
610
+ */
611
+ doPoll() {
612
+ const e = this.request();
613
+ e.on("data", this.onData.bind(this)), e.on("error", (t, n) => {
614
+ this.onError("xhr poll error", t, n);
615
+ }), this.pollXhr = e;
616
+ }
617
+ }
618
+ class g extends _ {
619
+ /**
620
+ * Request constructor
621
+ *
622
+ * @param {Object} options
623
+ * @package
624
+ */
625
+ constructor(e, t, n) {
626
+ super(), this.createRequest = e, L(this, n), this._opts = n, this._method = n.method || "GET", this._uri = t, this._data = n.data !== void 0 ? n.data : null, this._create();
627
+ }
628
+ /**
629
+ * Creates the XHR object and sends the request.
630
+ *
631
+ * @private
632
+ */
633
+ _create() {
634
+ var e;
635
+ const t = ce(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
636
+ t.xdomain = !!this._opts.xd;
637
+ const n = this._xhr = this.createRequest(t);
638
+ try {
639
+ n.open(this._method, this._uri, !0);
640
+ try {
641
+ if (this._opts.extraHeaders) {
642
+ n.setDisableHeaderCheck && n.setDisableHeaderCheck(!0);
643
+ for (let r in this._opts.extraHeaders)
644
+ this._opts.extraHeaders.hasOwnProperty(r) && n.setRequestHeader(r, this._opts.extraHeaders[r]);
645
+ }
646
+ } catch {
647
+ }
648
+ if (this._method === "POST")
649
+ try {
650
+ n.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
651
+ } catch {
652
+ }
653
+ try {
654
+ n.setRequestHeader("Accept", "*/*");
655
+ } catch {
656
+ }
657
+ (e = this._opts.cookieJar) === null || e === void 0 || e.addCookies(n), "withCredentials" in n && (n.withCredentials = this._opts.withCredentials), this._opts.requestTimeout && (n.timeout = this._opts.requestTimeout), n.onreadystatechange = () => {
658
+ var r;
659
+ n.readyState === 3 && ((r = this._opts.cookieJar) === null || r === void 0 || r.parseCookies(
660
+ // @ts-ignore
661
+ n.getResponseHeader("set-cookie")
662
+ )), n.readyState === 4 && (n.status === 200 || n.status === 1223 ? this._onLoad() : this.setTimeoutFn(() => {
663
+ this._onError(typeof n.status == "number" ? n.status : 0);
664
+ }, 0));
665
+ }, n.send(this._data);
666
+ } catch (r) {
667
+ this.setTimeoutFn(() => {
668
+ this._onError(r);
669
+ }, 0);
670
+ return;
671
+ }
672
+ typeof document < "u" && (this._index = g.requestsCount++, g.requests[this._index] = this);
673
+ }
674
+ /**
675
+ * Called upon error.
676
+ *
677
+ * @private
678
+ */
679
+ _onError(e) {
680
+ this.emitReserved("error", e, this._xhr), this._cleanup(!0);
681
+ }
682
+ /**
683
+ * Cleans up house.
684
+ *
685
+ * @private
686
+ */
687
+ _cleanup(e) {
688
+ if (!(typeof this._xhr > "u" || this._xhr === null)) {
689
+ if (this._xhr.onreadystatechange = Ie, e)
690
+ try {
691
+ this._xhr.abort();
692
+ } catch {
693
+ }
694
+ typeof document < "u" && delete g.requests[this._index], this._xhr = null;
695
+ }
696
+ }
697
+ /**
698
+ * Called upon load.
699
+ *
700
+ * @private
701
+ */
702
+ _onLoad() {
703
+ const e = this._xhr.responseText;
704
+ e !== null && (this.emitReserved("data", e), this.emitReserved("success"), this._cleanup());
705
+ }
706
+ /**
707
+ * Aborts the request.
708
+ *
709
+ * @package
710
+ */
711
+ abort() {
712
+ this._cleanup();
713
+ }
714
+ }
715
+ g.requestsCount = 0;
716
+ g.requests = {};
717
+ if (typeof document < "u") {
718
+ if (typeof attachEvent == "function")
719
+ attachEvent("onunload", Z);
720
+ else if (typeof addEventListener == "function") {
721
+ const s = "onpagehide" in d ? "pagehide" : "unload";
722
+ addEventListener(s, Z, !1);
723
+ }
724
+ }
725
+ function Z() {
726
+ for (let s in g.requests)
727
+ g.requests.hasOwnProperty(s) && g.requests[s].abort();
728
+ }
729
+ const De = (function() {
730
+ const s = ue({
731
+ xdomain: !1
732
+ });
733
+ return s && s.responseType !== null;
734
+ })();
735
+ class Ue extends qe {
736
+ constructor(e) {
737
+ super(e);
738
+ const t = e && e.forceBase64;
739
+ this.supportsBinary = De && !t;
740
+ }
741
+ request(e = {}) {
742
+ return Object.assign(e, { xd: this.xd }, this.opts), new g(ue, this.uri(), e);
743
+ }
744
+ }
745
+ function ue(s) {
746
+ const e = s.xdomain;
747
+ try {
748
+ if (typeof XMLHttpRequest < "u" && (!e || Ne))
749
+ return new XMLHttpRequest();
750
+ } catch {
751
+ }
752
+ if (!e)
753
+ try {
754
+ return new d[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
755
+ } catch {
756
+ }
757
+ }
758
+ const _e = typeof navigator < "u" && typeof navigator.product == "string" && navigator.product.toLowerCase() === "reactnative";
759
+ class je extends W {
760
+ get name() {
761
+ return "websocket";
762
+ }
763
+ doOpen() {
764
+ const e = this.uri(), t = this.opts.protocols, n = _e ? {} : ce(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
765
+ this.opts.extraHeaders && (n.headers = this.opts.extraHeaders);
766
+ try {
767
+ this.ws = this.createSocket(e, t, n);
768
+ } catch (r) {
769
+ return this.emitReserved("error", r);
770
+ }
771
+ this.ws.binaryType = this.socket.binaryType, this.addEventListeners();
772
+ }
773
+ /**
774
+ * Adds event listeners to the socket
775
+ *
776
+ * @private
777
+ */
778
+ addEventListeners() {
779
+ this.ws.onopen = () => {
780
+ this.opts.autoUnref && this.ws._socket.unref(), this.onOpen();
781
+ }, this.ws.onclose = (e) => this.onClose({
782
+ description: "websocket connection closed",
783
+ context: e
784
+ }), this.ws.onmessage = (e) => this.onData(e.data), this.ws.onerror = (e) => this.onError("websocket error", e);
785
+ }
786
+ write(e) {
787
+ this.writable = !1;
788
+ for (let t = 0; t < e.length; t++) {
789
+ const n = e[t], r = t === e.length - 1;
790
+ V(n, this.supportsBinary, (i) => {
791
+ try {
792
+ this.doWrite(n, i);
793
+ } catch {
794
+ }
795
+ r && O(() => {
796
+ this.writable = !0, this.emitReserved("drain");
797
+ }, this.setTimeoutFn);
798
+ });
799
+ }
800
+ }
801
+ doClose() {
802
+ typeof this.ws < "u" && (this.ws.onerror = () => {
803
+ }, this.ws.close(), this.ws = null);
804
+ }
805
+ /**
806
+ * Generates uri for connection.
807
+ *
808
+ * @private
809
+ */
810
+ uri() {
811
+ const e = this.opts.secure ? "wss" : "ws", t = this.query || {};
812
+ return this.opts.timestampRequests && (t[this.opts.timestampParam] = le()), this.supportsBinary || (t.b64 = 1), this.createUri(e, t);
813
+ }
814
+ }
815
+ const I = d.WebSocket || d.MozWebSocket;
816
+ class Me extends je {
817
+ createSocket(e, t, n) {
818
+ return _e ? new I(e, t, n) : t ? new I(e, t) : new I(e);
819
+ }
820
+ doWrite(e, t) {
821
+ this.ws.send(t);
822
+ }
823
+ }
824
+ class Fe extends W {
825
+ get name() {
826
+ return "webtransport";
827
+ }
828
+ doOpen() {
829
+ try {
830
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
831
+ } catch (e) {
832
+ return this.emitReserved("error", e);
833
+ }
834
+ this._transport.closed.then(() => {
835
+ this.onClose();
836
+ }).catch((e) => {
837
+ this.onError("webtransport error", e);
838
+ }), this._transport.ready.then(() => {
839
+ this._transport.createBidirectionalStream().then((e) => {
840
+ const t = ke(Number.MAX_SAFE_INTEGER, this.socket.binaryType), n = e.readable.pipeThrough(t).getReader(), r = ve();
841
+ r.readable.pipeTo(e.writable), this._writer = r.writable.getWriter();
842
+ const i = () => {
843
+ n.read().then(({ done: h, value: c }) => {
844
+ h || (this.onPacket(c), i());
845
+ }).catch((h) => {
846
+ });
847
+ };
848
+ i();
849
+ const o = { type: "open" };
850
+ this.query.sid && (o.data = `{"sid":"${this.query.sid}"}`), this._writer.write(o).then(() => this.onOpen());
851
+ });
852
+ });
853
+ }
854
+ write(e) {
855
+ this.writable = !1;
856
+ for (let t = 0; t < e.length; t++) {
857
+ const n = e[t], r = t === e.length - 1;
858
+ this._writer.write(n).then(() => {
859
+ r && O(() => {
860
+ this.writable = !0, this.emitReserved("drain");
861
+ }, this.setTimeoutFn);
862
+ });
863
+ }
864
+ }
865
+ doClose() {
866
+ var e;
867
+ (e = this._transport) === null || e === void 0 || e.close();
868
+ }
869
+ }
870
+ const $e = {
871
+ websocket: Me,
872
+ webtransport: Fe,
873
+ polling: Ue
874
+ }, Ve = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, He = [
875
+ "source",
876
+ "protocol",
877
+ "authority",
878
+ "userInfo",
879
+ "user",
880
+ "password",
881
+ "host",
882
+ "port",
883
+ "relative",
884
+ "path",
885
+ "directory",
886
+ "file",
887
+ "query",
888
+ "anchor"
889
+ ];
890
+ function U(s) {
891
+ if (s.length > 8e3)
892
+ throw "URI too long";
893
+ const e = s, t = s.indexOf("["), n = s.indexOf("]");
894
+ t != -1 && n != -1 && (s = s.substring(0, t) + s.substring(t, n).replace(/:/g, ";") + s.substring(n, s.length));
895
+ let r = Ve.exec(s || ""), i = {}, o = 14;
896
+ for (; o--; )
897
+ i[He[o]] = r[o] || "";
898
+ return t != -1 && n != -1 && (i.source = e, i.host = i.host.substring(1, i.host.length - 1).replace(/;/g, ":"), i.authority = i.authority.replace("[", "").replace("]", "").replace(/;/g, ":"), i.ipv6uri = !0), i.pathNames = We(i, i.path), i.queryKey = ze(i, i.query), i;
899
+ }
900
+ function We(s, e) {
901
+ const t = /\/{2,9}/g, n = e.replace(t, "/").split("/");
902
+ return (e.slice(0, 1) == "/" || e.length === 0) && n.splice(0, 1), e.slice(-1) == "/" && n.splice(n.length - 1, 1), n;
903
+ }
904
+ function ze(s, e) {
905
+ const t = {};
906
+ return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function(n, r, i) {
907
+ r && (t[r] = i);
908
+ }), t;
909
+ }
910
+ const j = typeof addEventListener == "function" && typeof removeEventListener == "function", S = [];
911
+ j && addEventListener("offline", () => {
912
+ S.forEach((s) => s());
913
+ }, !1);
914
+ class b extends _ {
915
+ /**
916
+ * Socket constructor.
917
+ *
918
+ * @param {String|Object} uri - uri or options
919
+ * @param {Object} opts - options
920
+ */
921
+ constructor(e, t) {
922
+ if (super(), this.binaryType = Ce, this.writeBuffer = [], this._prevBufferLen = 0, this._pingInterval = -1, this._pingTimeout = -1, this._maxPayload = -1, this._pingTimeoutTime = 1 / 0, e && typeof e == "object" && (t = e, e = null), e) {
923
+ const n = U(e);
924
+ t.hostname = n.host, t.secure = n.protocol === "https" || n.protocol === "wss", t.port = n.port, n.query && (t.query = n.query);
925
+ } else t.host && (t.hostname = U(t.host).host);
926
+ L(this, t), this.secure = t.secure != null ? t.secure : typeof location < "u" && location.protocol === "https:", t.hostname && !t.port && (t.port = this.secure ? "443" : "80"), this.hostname = t.hostname || (typeof location < "u" ? location.hostname : "localhost"), this.port = t.port || (typeof location < "u" && location.port ? location.port : this.secure ? "443" : "80"), this.transports = [], this._transportsByName = {}, t.transports.forEach((n) => {
927
+ const r = n.prototype.name;
928
+ this.transports.push(r), this._transportsByName[r] = n;
929
+ }), this.opts = Object.assign({
930
+ path: "/engine.io",
931
+ agent: !1,
932
+ withCredentials: !1,
933
+ upgrade: !0,
934
+ timestampParam: "t",
935
+ rememberUpgrade: !1,
936
+ addTrailingSlash: !0,
937
+ rejectUnauthorized: !0,
938
+ perMessageDeflate: {
939
+ threshold: 1024
940
+ },
941
+ transportOptions: {},
942
+ closeOnBeforeunload: !1
943
+ }, t), this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : ""), typeof this.opts.query == "string" && (this.opts.query = Oe(this.opts.query)), j && (this.opts.closeOnBeforeunload && (this._beforeunloadEventListener = () => {
944
+ this.transport && (this.transport.removeAllListeners(), this.transport.close());
945
+ }, addEventListener("beforeunload", this._beforeunloadEventListener, !1)), this.hostname !== "localhost" && (this._offlineEventListener = () => {
946
+ this._onClose("transport close", {
947
+ description: "network connection lost"
948
+ });
949
+ }, S.push(this._offlineEventListener))), this.opts.withCredentials && (this._cookieJar = void 0), this._open();
950
+ }
951
+ /**
952
+ * Creates transport of the given type.
953
+ *
954
+ * @param {String} name - transport name
955
+ * @return {Transport}
956
+ * @private
957
+ */
958
+ createTransport(e) {
959
+ const t = Object.assign({}, this.opts.query);
960
+ t.EIO = ae, t.transport = e, this.id && (t.sid = this.id);
961
+ const n = Object.assign({}, this.opts, {
962
+ query: t,
963
+ socket: this,
964
+ hostname: this.hostname,
965
+ secure: this.secure,
966
+ port: this.port
967
+ }, this.opts.transportOptions[e]);
968
+ return new this._transportsByName[e](n);
969
+ }
970
+ /**
971
+ * Initializes transport to use and starts probe.
972
+ *
973
+ * @private
974
+ */
975
+ _open() {
976
+ if (this.transports.length === 0) {
977
+ this.setTimeoutFn(() => {
978
+ this.emitReserved("error", "No transports available");
979
+ }, 0);
980
+ return;
981
+ }
982
+ const e = this.opts.rememberUpgrade && b.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
983
+ this.readyState = "opening";
984
+ const t = this.createTransport(e);
985
+ t.open(), this.setTransport(t);
986
+ }
987
+ /**
988
+ * Sets the current transport. Disables the existing one (if any).
989
+ *
990
+ * @private
991
+ */
992
+ setTransport(e) {
993
+ this.transport && this.transport.removeAllListeners(), this.transport = e, e.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (t) => this._onClose("transport close", t));
994
+ }
995
+ /**
996
+ * Called when connection is deemed open.
997
+ *
998
+ * @private
999
+ */
1000
+ onOpen() {
1001
+ this.readyState = "open", b.priorWebsocketSuccess = this.transport.name === "websocket", this.emitReserved("open"), this.flush();
1002
+ }
1003
+ /**
1004
+ * Handles a packet.
1005
+ *
1006
+ * @private
1007
+ */
1008
+ _onPacket(e) {
1009
+ if (this.readyState === "opening" || this.readyState === "open" || this.readyState === "closing")
1010
+ switch (this.emitReserved("packet", e), this.emitReserved("heartbeat"), e.type) {
1011
+ case "open":
1012
+ this.onHandshake(JSON.parse(e.data));
1013
+ break;
1014
+ case "ping":
1015
+ this._sendPacket("pong"), this.emitReserved("ping"), this.emitReserved("pong"), this._resetPingTimeout();
1016
+ break;
1017
+ case "error":
1018
+ const t = new Error("server error");
1019
+ t.code = e.data, this._onError(t);
1020
+ break;
1021
+ case "message":
1022
+ this.emitReserved("data", e.data), this.emitReserved("message", e.data);
1023
+ break;
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Called upon handshake completion.
1028
+ *
1029
+ * @param {Object} data - handshake obj
1030
+ * @private
1031
+ */
1032
+ onHandshake(e) {
1033
+ this.emitReserved("handshake", e), this.id = e.sid, this.transport.query.sid = e.sid, this._pingInterval = e.pingInterval, this._pingTimeout = e.pingTimeout, this._maxPayload = e.maxPayload, this.onOpen(), this.readyState !== "closed" && this._resetPingTimeout();
1034
+ }
1035
+ /**
1036
+ * Sets and resets ping timeout timer based on server pings.
1037
+ *
1038
+ * @private
1039
+ */
1040
+ _resetPingTimeout() {
1041
+ this.clearTimeoutFn(this._pingTimeoutTimer);
1042
+ const e = this._pingInterval + this._pingTimeout;
1043
+ this._pingTimeoutTime = Date.now() + e, this._pingTimeoutTimer = this.setTimeoutFn(() => {
1044
+ this._onClose("ping timeout");
1045
+ }, e), this.opts.autoUnref && this._pingTimeoutTimer.unref();
1046
+ }
1047
+ /**
1048
+ * Called on `drain` event
1049
+ *
1050
+ * @private
1051
+ */
1052
+ _onDrain() {
1053
+ this.writeBuffer.splice(0, this._prevBufferLen), this._prevBufferLen = 0, this.writeBuffer.length === 0 ? this.emitReserved("drain") : this.flush();
1054
+ }
1055
+ /**
1056
+ * Flush write buffers.
1057
+ *
1058
+ * @private
1059
+ */
1060
+ flush() {
1061
+ if (this.readyState !== "closed" && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
1062
+ const e = this._getWritablePackets();
1063
+ this.transport.send(e), this._prevBufferLen = e.length, this.emitReserved("flush");
1064
+ }
1065
+ }
1066
+ /**
1067
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
1068
+ * long-polling)
1069
+ *
1070
+ * @private
1071
+ */
1072
+ _getWritablePackets() {
1073
+ if (!(this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1))
1074
+ return this.writeBuffer;
1075
+ let e = 1;
1076
+ for (let t = 0; t < this.writeBuffer.length; t++) {
1077
+ const n = this.writeBuffer[t].data;
1078
+ if (n && (e += Se(n)), t > 0 && e > this._maxPayload)
1079
+ return this.writeBuffer.slice(0, t);
1080
+ e += 2;
1081
+ }
1082
+ return this.writeBuffer;
1083
+ }
1084
+ /**
1085
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
1086
+ *
1087
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
1088
+ * `write()` method then the message would not be buffered by the Socket.IO client.
1089
+ *
1090
+ * @return {boolean}
1091
+ * @private
1092
+ */
1093
+ /* private */
1094
+ _hasPingExpired() {
1095
+ if (!this._pingTimeoutTime)
1096
+ return !0;
1097
+ const e = Date.now() > this._pingTimeoutTime;
1098
+ return e && (this._pingTimeoutTime = 0, O(() => {
1099
+ this._onClose("ping timeout");
1100
+ }, this.setTimeoutFn)), e;
1101
+ }
1102
+ /**
1103
+ * Sends a message.
1104
+ *
1105
+ * @param {String} msg - message.
1106
+ * @param {Object} options.
1107
+ * @param {Function} fn - callback function.
1108
+ * @return {Socket} for chaining.
1109
+ */
1110
+ write(e, t, n) {
1111
+ return this._sendPacket("message", e, t, n), this;
1112
+ }
1113
+ /**
1114
+ * Sends a message. Alias of {@link Socket#write}.
1115
+ *
1116
+ * @param {String} msg - message.
1117
+ * @param {Object} options.
1118
+ * @param {Function} fn - callback function.
1119
+ * @return {Socket} for chaining.
1120
+ */
1121
+ send(e, t, n) {
1122
+ return this._sendPacket("message", e, t, n), this;
1123
+ }
1124
+ /**
1125
+ * Sends a packet.
1126
+ *
1127
+ * @param {String} type: packet type.
1128
+ * @param {String} data.
1129
+ * @param {Object} options.
1130
+ * @param {Function} fn - callback function.
1131
+ * @private
1132
+ */
1133
+ _sendPacket(e, t, n, r) {
1134
+ if (typeof t == "function" && (r = t, t = void 0), typeof n == "function" && (r = n, n = null), this.readyState === "closing" || this.readyState === "closed")
1135
+ return;
1136
+ n = n || {}, n.compress = n.compress !== !1;
1137
+ const i = {
1138
+ type: e,
1139
+ data: t,
1140
+ options: n
1141
+ };
1142
+ this.emitReserved("packetCreate", i), this.writeBuffer.push(i), r && this.once("flush", r), this.flush();
1143
+ }
1144
+ /**
1145
+ * Closes the connection.
1146
+ */
1147
+ close() {
1148
+ const e = () => {
1149
+ this._onClose("forced close"), this.transport.close();
1150
+ }, t = () => {
1151
+ this.off("upgrade", t), this.off("upgradeError", t), e();
1152
+ }, n = () => {
1153
+ this.once("upgrade", t), this.once("upgradeError", t);
1154
+ };
1155
+ return (this.readyState === "opening" || this.readyState === "open") && (this.readyState = "closing", this.writeBuffer.length ? this.once("drain", () => {
1156
+ this.upgrading ? n() : e();
1157
+ }) : this.upgrading ? n() : e()), this;
1158
+ }
1159
+ /**
1160
+ * Called upon transport error
1161
+ *
1162
+ * @private
1163
+ */
1164
+ _onError(e) {
1165
+ if (b.priorWebsocketSuccess = !1, this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening")
1166
+ return this.transports.shift(), this._open();
1167
+ this.emitReserved("error", e), this._onClose("transport error", e);
1168
+ }
1169
+ /**
1170
+ * Called upon transport close.
1171
+ *
1172
+ * @private
1173
+ */
1174
+ _onClose(e, t) {
1175
+ if (this.readyState === "opening" || this.readyState === "open" || this.readyState === "closing") {
1176
+ if (this.clearTimeoutFn(this._pingTimeoutTimer), this.transport.removeAllListeners("close"), this.transport.close(), this.transport.removeAllListeners(), j && (this._beforeunloadEventListener && removeEventListener("beforeunload", this._beforeunloadEventListener, !1), this._offlineEventListener)) {
1177
+ const n = S.indexOf(this._offlineEventListener);
1178
+ n !== -1 && S.splice(n, 1);
1179
+ }
1180
+ this.readyState = "closed", this.id = null, this.emitReserved("close", e, t), this.writeBuffer = [], this._prevBufferLen = 0;
1181
+ }
1182
+ }
1183
+ }
1184
+ b.protocol = ae;
1185
+ class Ke extends b {
1186
+ constructor() {
1187
+ super(...arguments), this._upgrades = [];
1188
+ }
1189
+ onOpen() {
1190
+ if (super.onOpen(), this.readyState === "open" && this.opts.upgrade)
1191
+ for (let e = 0; e < this._upgrades.length; e++)
1192
+ this._probe(this._upgrades[e]);
1193
+ }
1194
+ /**
1195
+ * Probes a transport.
1196
+ *
1197
+ * @param {String} name - transport name
1198
+ * @private
1199
+ */
1200
+ _probe(e) {
1201
+ let t = this.createTransport(e), n = !1;
1202
+ b.priorWebsocketSuccess = !1;
1203
+ const r = () => {
1204
+ n || (t.send([{ type: "ping", data: "probe" }]), t.once("packet", (y) => {
1205
+ if (!n)
1206
+ if (y.type === "pong" && y.data === "probe") {
1207
+ if (this.upgrading = !0, this.emitReserved("upgrading", t), !t)
1208
+ return;
1209
+ b.priorWebsocketSuccess = t.name === "websocket", this.transport.pause(() => {
1210
+ n || this.readyState !== "closed" && (u(), this.setTransport(t), t.send([{ type: "upgrade" }]), this.emitReserved("upgrade", t), t = null, this.upgrading = !1, this.flush());
1211
+ });
1212
+ } else {
1213
+ const v = new Error("probe error");
1214
+ v.transport = t.name, this.emitReserved("upgradeError", v);
1215
+ }
1216
+ }));
1217
+ };
1218
+ function i() {
1219
+ n || (n = !0, u(), t.close(), t = null);
1220
+ }
1221
+ const o = (y) => {
1222
+ const v = new Error("probe error: " + y);
1223
+ v.transport = t.name, i(), this.emitReserved("upgradeError", v);
1224
+ };
1225
+ function h() {
1226
+ o("transport closed");
1227
+ }
1228
+ function c() {
1229
+ o("socket closed");
1230
+ }
1231
+ function p(y) {
1232
+ t && y.name !== t.name && i();
1233
+ }
1234
+ const u = () => {
1235
+ t.removeListener("open", r), t.removeListener("error", o), t.removeListener("close", h), this.off("close", c), this.off("upgrading", p);
1236
+ };
1237
+ t.once("open", r), t.once("error", o), t.once("close", h), this.once("close", c), this.once("upgrading", p), this._upgrades.indexOf("webtransport") !== -1 && e !== "webtransport" ? this.setTimeoutFn(() => {
1238
+ n || t.open();
1239
+ }, 200) : t.open();
1240
+ }
1241
+ onHandshake(e) {
1242
+ this._upgrades = this._filterUpgrades(e.upgrades), super.onHandshake(e);
1243
+ }
1244
+ /**
1245
+ * Filters upgrades, returning only those matching client transports.
1246
+ *
1247
+ * @param {Array} upgrades - server upgrades
1248
+ * @private
1249
+ */
1250
+ _filterUpgrades(e) {
1251
+ const t = [];
1252
+ for (let n = 0; n < e.length; n++)
1253
+ ~this.transports.indexOf(e[n]) && t.push(e[n]);
1254
+ return t;
1255
+ }
1256
+ }
1257
+ let Ye = class extends Ke {
1258
+ constructor(s, e = {}) {
1259
+ const t = typeof s == "object" ? s : e;
1260
+ (!t.transports || t.transports && typeof t.transports[0] == "string") && (t.transports = (t.transports || ["polling", "websocket", "webtransport"]).map((n) => $e[n]).filter((n) => !!n)), super(s, t);
1261
+ }
1262
+ };
1263
+ function Je(s, e = "", t) {
1264
+ let n = s;
1265
+ t = t || typeof location < "u" && location, s == null && (s = t.protocol + "//" + t.host), typeof s == "string" && (s.charAt(0) === "/" && (s.charAt(1) === "/" ? s = t.protocol + s : s = t.host + s), /^(https?|wss?):\/\//.test(s) || (typeof t < "u" ? s = t.protocol + "//" + s : s = "https://" + s), n = U(s)), n.port || (/^(http|ws)$/.test(n.protocol) ? n.port = "80" : /^(http|ws)s$/.test(n.protocol) && (n.port = "443")), n.path = n.path || "/";
1266
+ const r = n.host.indexOf(":") !== -1 ? "[" + n.host + "]" : n.host;
1267
+ return n.id = n.protocol + "://" + r + ":" + n.port + e, n.href = n.protocol + "://" + r + (t && t.port === n.port ? "" : ":" + n.port), n;
1268
+ }
1269
+ const Qe = typeof ArrayBuffer == "function", Xe = (s) => typeof ArrayBuffer.isView == "function" ? ArrayBuffer.isView(s) : s.buffer instanceof ArrayBuffer, pe = Object.prototype.toString, Ge = typeof Blob == "function" || typeof Blob < "u" && pe.call(Blob) === "[object BlobConstructor]", Ze = typeof File == "function" || typeof File < "u" && pe.call(File) === "[object FileConstructor]";
1270
+ function z(s) {
1271
+ return Qe && (s instanceof ArrayBuffer || Xe(s)) || Ge && s instanceof Blob || Ze && s instanceof File;
1272
+ }
1273
+ function R(s, e) {
1274
+ if (!s || typeof s != "object")
1275
+ return !1;
1276
+ if (Array.isArray(s)) {
1277
+ for (let t = 0, n = s.length; t < n; t++)
1278
+ if (R(s[t]))
1279
+ return !0;
1280
+ return !1;
1281
+ }
1282
+ if (z(s))
1283
+ return !0;
1284
+ if (s.toJSON && typeof s.toJSON == "function" && arguments.length === 1)
1285
+ return R(s.toJSON(), !0);
1286
+ for (const t in s)
1287
+ if (Object.prototype.hasOwnProperty.call(s, t) && R(s[t]))
1288
+ return !0;
1289
+ return !1;
1290
+ }
1291
+ function et(s) {
1292
+ const e = [], t = s.data, n = s;
1293
+ return n.data = M(t, e), n.attachments = e.length, { packet: n, buffers: e };
1294
+ }
1295
+ function M(s, e) {
1296
+ if (!s)
1297
+ return s;
1298
+ if (z(s)) {
1299
+ const t = { _placeholder: !0, num: e.length };
1300
+ return e.push(s), t;
1301
+ } else if (Array.isArray(s)) {
1302
+ const t = new Array(s.length);
1303
+ for (let n = 0; n < s.length; n++)
1304
+ t[n] = M(s[n], e);
1305
+ return t;
1306
+ } else if (typeof s == "object" && !(s instanceof Date)) {
1307
+ const t = {};
1308
+ for (const n in s)
1309
+ Object.prototype.hasOwnProperty.call(s, n) && (t[n] = M(s[n], e));
1310
+ return t;
1311
+ }
1312
+ return s;
1313
+ }
1314
+ function tt(s, e) {
1315
+ return s.data = F(s.data, e), delete s.attachments, s;
1316
+ }
1317
+ function F(s, e) {
1318
+ if (!s)
1319
+ return s;
1320
+ if (s && s._placeholder === !0) {
1321
+ if (typeof s.num == "number" && s.num >= 0 && s.num < e.length)
1322
+ return e[s.num];
1323
+ throw new Error("illegal attachments");
1324
+ } else if (Array.isArray(s))
1325
+ for (let t = 0; t < s.length; t++)
1326
+ s[t] = F(s[t], e);
1327
+ else if (typeof s == "object")
1328
+ for (const t in s)
1329
+ Object.prototype.hasOwnProperty.call(s, t) && (s[t] = F(s[t], e));
1330
+ return s;
1331
+ }
1332
+ const st = [
1333
+ "connect",
1334
+ "connect_error",
1335
+ "disconnect",
1336
+ "disconnecting",
1337
+ "newListener",
1338
+ "removeListener"
1339
+ // used by the Node.js EventEmitter
1340
+ ], nt = 5;
1341
+ var l;
1342
+ (function(s) {
1343
+ s[s.CONNECT = 0] = "CONNECT", s[s.DISCONNECT = 1] = "DISCONNECT", s[s.EVENT = 2] = "EVENT", s[s.ACK = 3] = "ACK", s[s.CONNECT_ERROR = 4] = "CONNECT_ERROR", s[s.BINARY_EVENT = 5] = "BINARY_EVENT", s[s.BINARY_ACK = 6] = "BINARY_ACK";
1344
+ })(l || (l = {}));
1345
+ class rt {
1346
+ /**
1347
+ * Encoder constructor
1348
+ *
1349
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
1350
+ */
1351
+ constructor(e) {
1352
+ this.replacer = e;
1353
+ }
1354
+ /**
1355
+ * Encode a packet as a single string if non-binary, or as a
1356
+ * buffer sequence, depending on packet type.
1357
+ *
1358
+ * @param {Object} obj - packet object
1359
+ */
1360
+ encode(e) {
1361
+ return (e.type === l.EVENT || e.type === l.ACK) && R(e) ? this.encodeAsBinary({
1362
+ type: e.type === l.EVENT ? l.BINARY_EVENT : l.BINARY_ACK,
1363
+ nsp: e.nsp,
1364
+ data: e.data,
1365
+ id: e.id
1366
+ }) : [this.encodeAsString(e)];
1367
+ }
1368
+ /**
1369
+ * Encode packet as string.
1370
+ */
1371
+ encodeAsString(e) {
1372
+ let t = "" + e.type;
1373
+ return (e.type === l.BINARY_EVENT || e.type === l.BINARY_ACK) && (t += e.attachments + "-"), e.nsp && e.nsp !== "/" && (t += e.nsp + ","), e.id != null && (t += e.id), e.data != null && (t += JSON.stringify(e.data, this.replacer)), t;
1374
+ }
1375
+ /**
1376
+ * Encode packet as 'buffer sequence' by removing blobs, and
1377
+ * deconstructing packet into object with placeholders and
1378
+ * a list of buffers.
1379
+ */
1380
+ encodeAsBinary(e) {
1381
+ const t = et(e), n = this.encodeAsString(t.packet), r = t.buffers;
1382
+ return r.unshift(n), r;
1383
+ }
1384
+ }
1385
+ function ee(s) {
1386
+ return Object.prototype.toString.call(s) === "[object Object]";
1387
+ }
1388
+ class K extends _ {
1389
+ /**
1390
+ * Decoder constructor
1391
+ *
1392
+ * @param {function} reviver - custom reviver to pass down to JSON.stringify
1393
+ */
1394
+ constructor(e) {
1395
+ super(), this.reviver = e;
1396
+ }
1397
+ /**
1398
+ * Decodes an encoded packet string into packet JSON.
1399
+ *
1400
+ * @param {String} obj - encoded packet
1401
+ */
1402
+ add(e) {
1403
+ let t;
1404
+ if (typeof e == "string") {
1405
+ if (this.reconstructor)
1406
+ throw new Error("got plaintext data when reconstructing a packet");
1407
+ t = this.decodeString(e);
1408
+ const n = t.type === l.BINARY_EVENT;
1409
+ n || t.type === l.BINARY_ACK ? (t.type = n ? l.EVENT : l.ACK, this.reconstructor = new it(t), t.attachments === 0 && super.emitReserved("decoded", t)) : super.emitReserved("decoded", t);
1410
+ } else if (z(e) || e.base64)
1411
+ if (this.reconstructor)
1412
+ t = this.reconstructor.takeBinaryData(e), t && (this.reconstructor = null, super.emitReserved("decoded", t));
1413
+ else
1414
+ throw new Error("got binary data when not reconstructing a packet");
1415
+ else
1416
+ throw new Error("Unknown type: " + e);
1417
+ }
1418
+ /**
1419
+ * Decode a packet String (JSON data)
1420
+ *
1421
+ * @param {String} str
1422
+ * @return {Object} packet
1423
+ */
1424
+ decodeString(e) {
1425
+ let t = 0;
1426
+ const n = {
1427
+ type: Number(e.charAt(0))
1428
+ };
1429
+ if (l[n.type] === void 0)
1430
+ throw new Error("unknown packet type " + n.type);
1431
+ if (n.type === l.BINARY_EVENT || n.type === l.BINARY_ACK) {
1432
+ const i = t + 1;
1433
+ for (; e.charAt(++t) !== "-" && t != e.length; )
1434
+ ;
1435
+ const o = e.substring(i, t);
1436
+ if (o != Number(o) || e.charAt(t) !== "-")
1437
+ throw new Error("Illegal attachments");
1438
+ n.attachments = Number(o);
1439
+ }
1440
+ if (e.charAt(t + 1) === "/") {
1441
+ const i = t + 1;
1442
+ for (; ++t && !(e.charAt(t) === "," || t === e.length); )
1443
+ ;
1444
+ n.nsp = e.substring(i, t);
1445
+ } else
1446
+ n.nsp = "/";
1447
+ const r = e.charAt(t + 1);
1448
+ if (r !== "" && Number(r) == r) {
1449
+ const i = t + 1;
1450
+ for (; ++t; ) {
1451
+ const o = e.charAt(t);
1452
+ if (o == null || Number(o) != o) {
1453
+ --t;
1454
+ break;
1455
+ }
1456
+ if (t === e.length)
1457
+ break;
1458
+ }
1459
+ n.id = Number(e.substring(i, t + 1));
1460
+ }
1461
+ if (e.charAt(++t)) {
1462
+ const i = this.tryParse(e.substr(t));
1463
+ if (K.isPayloadValid(n.type, i))
1464
+ n.data = i;
1465
+ else
1466
+ throw new Error("invalid payload");
1467
+ }
1468
+ return n;
1469
+ }
1470
+ tryParse(e) {
1471
+ try {
1472
+ return JSON.parse(e, this.reviver);
1473
+ } catch {
1474
+ return !1;
1475
+ }
1476
+ }
1477
+ static isPayloadValid(e, t) {
1478
+ switch (e) {
1479
+ case l.CONNECT:
1480
+ return ee(t);
1481
+ case l.DISCONNECT:
1482
+ return t === void 0;
1483
+ case l.CONNECT_ERROR:
1484
+ return typeof t == "string" || ee(t);
1485
+ case l.EVENT:
1486
+ case l.BINARY_EVENT:
1487
+ return Array.isArray(t) && (typeof t[0] == "number" || typeof t[0] == "string" && st.indexOf(t[0]) === -1);
1488
+ case l.ACK:
1489
+ case l.BINARY_ACK:
1490
+ return Array.isArray(t);
1491
+ }
1492
+ }
1493
+ /**
1494
+ * Deallocates a parser's resources
1495
+ */
1496
+ destroy() {
1497
+ this.reconstructor && (this.reconstructor.finishedReconstruction(), this.reconstructor = null);
1498
+ }
1499
+ }
1500
+ class it {
1501
+ constructor(e) {
1502
+ this.packet = e, this.buffers = [], this.reconPack = e;
1503
+ }
1504
+ /**
1505
+ * Method to be called when binary data received from connection
1506
+ * after a BINARY_EVENT packet.
1507
+ *
1508
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
1509
+ * @return {null | Object} returns null if more binary data is expected or
1510
+ * a reconstructed packet object if all buffers have been received.
1511
+ */
1512
+ takeBinaryData(e) {
1513
+ if (this.buffers.push(e), this.buffers.length === this.reconPack.attachments) {
1514
+ const t = tt(this.reconPack, this.buffers);
1515
+ return this.finishedReconstruction(), t;
1516
+ }
1517
+ return null;
1518
+ }
1519
+ /**
1520
+ * Cleans up binary packet reconstruction variables.
1521
+ */
1522
+ finishedReconstruction() {
1523
+ this.reconPack = null, this.buffers = [];
1524
+ }
1525
+ }
1526
+ const ot = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1527
+ __proto__: null,
1528
+ Decoder: K,
1529
+ Encoder: rt,
1530
+ get PacketType() {
1531
+ return l;
1532
+ },
1533
+ protocol: nt
1534
+ }, Symbol.toStringTag, { value: "Module" }));
1535
+ function f(s, e, t) {
1536
+ return s.on(e, t), function() {
1537
+ s.off(e, t);
1538
+ };
1539
+ }
1540
+ const at = Object.freeze({
1541
+ connect: 1,
1542
+ connect_error: 1,
1543
+ disconnect: 1,
1544
+ disconnecting: 1,
1545
+ // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
1546
+ newListener: 1,
1547
+ removeListener: 1
1548
+ });
1549
+ let de = class extends _ {
1550
+ /**
1551
+ * `Socket` constructor.
1552
+ */
1553
+ constructor(s, e, t) {
1554
+ super(), this.connected = !1, this.recovered = !1, this.receiveBuffer = [], this.sendBuffer = [], this._queue = [], this._queueSeq = 0, this.ids = 0, this.acks = {}, this.flags = {}, this.io = s, this.nsp = e, t && t.auth && (this.auth = t.auth), this._opts = Object.assign({}, t), this.io._autoConnect && this.open();
1555
+ }
1556
+ /**
1557
+ * Whether the socket is currently disconnected
1558
+ *
1559
+ * @example
1560
+ * const socket = io();
1561
+ *
1562
+ * socket.on("connect", () => {
1563
+ * console.log(socket.disconnected); // false
1564
+ * });
1565
+ *
1566
+ * socket.on("disconnect", () => {
1567
+ * console.log(socket.disconnected); // true
1568
+ * });
1569
+ */
1570
+ get disconnected() {
1571
+ return !this.connected;
1572
+ }
1573
+ /**
1574
+ * Subscribe to open, close and packet events
1575
+ *
1576
+ * @private
1577
+ */
1578
+ subEvents() {
1579
+ if (this.subs)
1580
+ return;
1581
+ const s = this.io;
1582
+ this.subs = [
1583
+ f(s, "open", this.onopen.bind(this)),
1584
+ f(s, "packet", this.onpacket.bind(this)),
1585
+ f(s, "error", this.onerror.bind(this)),
1586
+ f(s, "close", this.onclose.bind(this))
1587
+ ];
1588
+ }
1589
+ /**
1590
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
1591
+ *
1592
+ * @example
1593
+ * const socket = io();
1594
+ *
1595
+ * console.log(socket.active); // true
1596
+ *
1597
+ * socket.on("disconnect", (reason) => {
1598
+ * if (reason === "io server disconnect") {
1599
+ * // the disconnection was initiated by the server, you need to manually reconnect
1600
+ * console.log(socket.active); // false
1601
+ * }
1602
+ * // else the socket will automatically try to reconnect
1603
+ * console.log(socket.active); // true
1604
+ * });
1605
+ */
1606
+ get active() {
1607
+ return !!this.subs;
1608
+ }
1609
+ /**
1610
+ * "Opens" the socket.
1611
+ *
1612
+ * @example
1613
+ * const socket = io({
1614
+ * autoConnect: false
1615
+ * });
1616
+ *
1617
+ * socket.connect();
1618
+ */
1619
+ connect() {
1620
+ return this.connected ? this : (this.subEvents(), this.io._reconnecting || this.io.open(), this.io._readyState === "open" && this.onopen(), this);
1621
+ }
1622
+ /**
1623
+ * Alias for {@link connect()}.
1624
+ */
1625
+ open() {
1626
+ return this.connect();
1627
+ }
1628
+ /**
1629
+ * Sends a `message` event.
1630
+ *
1631
+ * This method mimics the WebSocket.send() method.
1632
+ *
1633
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
1634
+ *
1635
+ * @example
1636
+ * socket.send("hello");
1637
+ *
1638
+ * // this is equivalent to
1639
+ * socket.emit("message", "hello");
1640
+ *
1641
+ * @return self
1642
+ */
1643
+ send(...s) {
1644
+ return s.unshift("message"), this.emit.apply(this, s), this;
1645
+ }
1646
+ /**
1647
+ * Override `emit`.
1648
+ * If the event is in `events`, it's emitted normally.
1649
+ *
1650
+ * @example
1651
+ * socket.emit("hello", "world");
1652
+ *
1653
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
1654
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
1655
+ *
1656
+ * // with an acknowledgement from the server
1657
+ * socket.emit("hello", "world", (val) => {
1658
+ * // ...
1659
+ * });
1660
+ *
1661
+ * @return self
1662
+ */
1663
+ emit(s, ...e) {
1664
+ var t, n, r;
1665
+ if (at.hasOwnProperty(s))
1666
+ throw new Error('"' + s.toString() + '" is a reserved event name');
1667
+ if (e.unshift(s), this._opts.retries && !this.flags.fromQueue && !this.flags.volatile)
1668
+ return this._addToQueue(e), this;
1669
+ const i = {
1670
+ type: l.EVENT,
1671
+ data: e
1672
+ };
1673
+ if (i.options = {}, i.options.compress = this.flags.compress !== !1, typeof e[e.length - 1] == "function") {
1674
+ const c = this.ids++, p = e.pop();
1675
+ this._registerAckCallback(c, p), i.id = c;
1676
+ }
1677
+ const o = (n = (t = this.io.engine) === null || t === void 0 ? void 0 : t.transport) === null || n === void 0 ? void 0 : n.writable, h = this.connected && !(!((r = this.io.engine) === null || r === void 0) && r._hasPingExpired());
1678
+ return this.flags.volatile && !o || (h ? (this.notifyOutgoingListeners(i), this.packet(i)) : this.sendBuffer.push(i)), this.flags = {}, this;
1679
+ }
1680
+ /**
1681
+ * @private
1682
+ */
1683
+ _registerAckCallback(s, e) {
1684
+ var t;
1685
+ const n = (t = this.flags.timeout) !== null && t !== void 0 ? t : this._opts.ackTimeout;
1686
+ if (n === void 0) {
1687
+ this.acks[s] = e;
1688
+ return;
1689
+ }
1690
+ const r = this.io.setTimeoutFn(() => {
1691
+ delete this.acks[s];
1692
+ for (let o = 0; o < this.sendBuffer.length; o++)
1693
+ this.sendBuffer[o].id === s && this.sendBuffer.splice(o, 1);
1694
+ e.call(this, new Error("operation has timed out"));
1695
+ }, n), i = (...o) => {
1696
+ this.io.clearTimeoutFn(r), e.apply(this, o);
1697
+ };
1698
+ i.withError = !0, this.acks[s] = i;
1699
+ }
1700
+ /**
1701
+ * Emits an event and waits for an acknowledgement
1702
+ *
1703
+ * @example
1704
+ * // without timeout
1705
+ * const response = await socket.emitWithAck("hello", "world");
1706
+ *
1707
+ * // with a specific timeout
1708
+ * try {
1709
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
1710
+ * } catch (err) {
1711
+ * // the server did not acknowledge the event in the given delay
1712
+ * }
1713
+ *
1714
+ * @return a Promise that will be fulfilled when the server acknowledges the event
1715
+ */
1716
+ emitWithAck(s, ...e) {
1717
+ return new Promise((t, n) => {
1718
+ const r = (i, o) => i ? n(i) : t(o);
1719
+ r.withError = !0, e.push(r), this.emit(s, ...e);
1720
+ });
1721
+ }
1722
+ /**
1723
+ * Add the packet to the queue.
1724
+ * @param args
1725
+ * @private
1726
+ */
1727
+ _addToQueue(s) {
1728
+ let e;
1729
+ typeof s[s.length - 1] == "function" && (e = s.pop());
1730
+ const t = {
1731
+ id: this._queueSeq++,
1732
+ tryCount: 0,
1733
+ pending: !1,
1734
+ args: s,
1735
+ flags: Object.assign({ fromQueue: !0 }, this.flags)
1736
+ };
1737
+ s.push((n, ...r) => t !== this._queue[0] ? void 0 : (n !== null ? t.tryCount > this._opts.retries && (this._queue.shift(), e && e(n)) : (this._queue.shift(), e && e(null, ...r)), t.pending = !1, this._drainQueue())), this._queue.push(t), this._drainQueue();
1738
+ }
1739
+ /**
1740
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
1741
+ * @param force - whether to resend a packet that has not been acknowledged yet
1742
+ *
1743
+ * @private
1744
+ */
1745
+ _drainQueue(s = !1) {
1746
+ if (!this.connected || this._queue.length === 0)
1747
+ return;
1748
+ const e = this._queue[0];
1749
+ e.pending && !s || (e.pending = !0, e.tryCount++, this.flags = e.flags, this.emit.apply(this, e.args));
1750
+ }
1751
+ /**
1752
+ * Sends a packet.
1753
+ *
1754
+ * @param packet
1755
+ * @private
1756
+ */
1757
+ packet(s) {
1758
+ s.nsp = this.nsp, this.io._packet(s);
1759
+ }
1760
+ /**
1761
+ * Called upon engine `open`.
1762
+ *
1763
+ * @private
1764
+ */
1765
+ onopen() {
1766
+ typeof this.auth == "function" ? this.auth((s) => {
1767
+ this._sendConnectPacket(s);
1768
+ }) : this._sendConnectPacket(this.auth);
1769
+ }
1770
+ /**
1771
+ * Sends a CONNECT packet to initiate the Socket.IO session.
1772
+ *
1773
+ * @param data
1774
+ * @private
1775
+ */
1776
+ _sendConnectPacket(s) {
1777
+ this.packet({
1778
+ type: l.CONNECT,
1779
+ data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, s) : s
1780
+ });
1781
+ }
1782
+ /**
1783
+ * Called upon engine or manager `error`.
1784
+ *
1785
+ * @param err
1786
+ * @private
1787
+ */
1788
+ onerror(s) {
1789
+ this.connected || this.emitReserved("connect_error", s);
1790
+ }
1791
+ /**
1792
+ * Called upon engine `close`.
1793
+ *
1794
+ * @param reason
1795
+ * @param description
1796
+ * @private
1797
+ */
1798
+ onclose(s, e) {
1799
+ this.connected = !1, delete this.id, this.emitReserved("disconnect", s, e), this._clearAcks();
1800
+ }
1801
+ /**
1802
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
1803
+ * the server.
1804
+ *
1805
+ * @private
1806
+ */
1807
+ _clearAcks() {
1808
+ Object.keys(this.acks).forEach((s) => {
1809
+ if (!this.sendBuffer.some((e) => String(e.id) === s)) {
1810
+ const e = this.acks[s];
1811
+ delete this.acks[s], e.withError && e.call(this, new Error("socket has been disconnected"));
1812
+ }
1813
+ });
1814
+ }
1815
+ /**
1816
+ * Called with socket packet.
1817
+ *
1818
+ * @param packet
1819
+ * @private
1820
+ */
1821
+ onpacket(s) {
1822
+ if (s.nsp === this.nsp)
1823
+ switch (s.type) {
1824
+ case l.CONNECT:
1825
+ s.data && s.data.sid ? this.onconnect(s.data.sid, s.data.pid) : this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
1826
+ break;
1827
+ case l.EVENT:
1828
+ case l.BINARY_EVENT:
1829
+ this.onevent(s);
1830
+ break;
1831
+ case l.ACK:
1832
+ case l.BINARY_ACK:
1833
+ this.onack(s);
1834
+ break;
1835
+ case l.DISCONNECT:
1836
+ this.ondisconnect();
1837
+ break;
1838
+ case l.CONNECT_ERROR:
1839
+ this.destroy();
1840
+ const e = new Error(s.data.message);
1841
+ e.data = s.data.data, this.emitReserved("connect_error", e);
1842
+ break;
1843
+ }
1844
+ }
1845
+ /**
1846
+ * Called upon a server event.
1847
+ *
1848
+ * @param packet
1849
+ * @private
1850
+ */
1851
+ onevent(s) {
1852
+ const e = s.data || [];
1853
+ s.id != null && e.push(this.ack(s.id)), this.connected ? this.emitEvent(e) : this.receiveBuffer.push(Object.freeze(e));
1854
+ }
1855
+ emitEvent(s) {
1856
+ if (this._anyListeners && this._anyListeners.length) {
1857
+ const e = this._anyListeners.slice();
1858
+ for (const t of e)
1859
+ t.apply(this, s);
1860
+ }
1861
+ super.emit.apply(this, s), this._pid && s.length && typeof s[s.length - 1] == "string" && (this._lastOffset = s[s.length - 1]);
1862
+ }
1863
+ /**
1864
+ * Produces an ack callback to emit with an event.
1865
+ *
1866
+ * @private
1867
+ */
1868
+ ack(s) {
1869
+ const e = this;
1870
+ let t = !1;
1871
+ return function(...n) {
1872
+ t || (t = !0, e.packet({
1873
+ type: l.ACK,
1874
+ id: s,
1875
+ data: n
1876
+ }));
1877
+ };
1878
+ }
1879
+ /**
1880
+ * Called upon a server acknowledgement.
1881
+ *
1882
+ * @param packet
1883
+ * @private
1884
+ */
1885
+ onack(s) {
1886
+ const e = this.acks[s.id];
1887
+ typeof e == "function" && (delete this.acks[s.id], e.withError && s.data.unshift(null), e.apply(this, s.data));
1888
+ }
1889
+ /**
1890
+ * Called upon server connect.
1891
+ *
1892
+ * @private
1893
+ */
1894
+ onconnect(s, e) {
1895
+ this.id = s, this.recovered = e && this._pid === e, this._pid = e, this.connected = !0, this.emitBuffered(), this.emitReserved("connect"), this._drainQueue(!0);
1896
+ }
1897
+ /**
1898
+ * Emit buffered events (received and emitted).
1899
+ *
1900
+ * @private
1901
+ */
1902
+ emitBuffered() {
1903
+ this.receiveBuffer.forEach((s) => this.emitEvent(s)), this.receiveBuffer = [], this.sendBuffer.forEach((s) => {
1904
+ this.notifyOutgoingListeners(s), this.packet(s);
1905
+ }), this.sendBuffer = [];
1906
+ }
1907
+ /**
1908
+ * Called upon server disconnect.
1909
+ *
1910
+ * @private
1911
+ */
1912
+ ondisconnect() {
1913
+ this.destroy(), this.onclose("io server disconnect");
1914
+ }
1915
+ /**
1916
+ * Called upon forced client/server side disconnections,
1917
+ * this method ensures the manager stops tracking us and
1918
+ * that reconnections don't get triggered for this.
1919
+ *
1920
+ * @private
1921
+ */
1922
+ destroy() {
1923
+ this.subs && (this.subs.forEach((s) => s()), this.subs = void 0), this.io._destroy(this);
1924
+ }
1925
+ /**
1926
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
1927
+ *
1928
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
1929
+ *
1930
+ * @example
1931
+ * const socket = io();
1932
+ *
1933
+ * socket.on("disconnect", (reason) => {
1934
+ * // console.log(reason); prints "io client disconnect"
1935
+ * });
1936
+ *
1937
+ * socket.disconnect();
1938
+ *
1939
+ * @return self
1940
+ */
1941
+ disconnect() {
1942
+ return this.connected && this.packet({ type: l.DISCONNECT }), this.destroy(), this.connected && this.onclose("io client disconnect"), this;
1943
+ }
1944
+ /**
1945
+ * Alias for {@link disconnect()}.
1946
+ *
1947
+ * @return self
1948
+ */
1949
+ close() {
1950
+ return this.disconnect();
1951
+ }
1952
+ /**
1953
+ * Sets the compress flag.
1954
+ *
1955
+ * @example
1956
+ * socket.compress(false).emit("hello");
1957
+ *
1958
+ * @param compress - if `true`, compresses the sending data
1959
+ * @return self
1960
+ */
1961
+ compress(s) {
1962
+ return this.flags.compress = s, this;
1963
+ }
1964
+ /**
1965
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
1966
+ * ready to send messages.
1967
+ *
1968
+ * @example
1969
+ * socket.volatile.emit("hello"); // the server may or may not receive it
1970
+ *
1971
+ * @returns self
1972
+ */
1973
+ get volatile() {
1974
+ return this.flags.volatile = !0, this;
1975
+ }
1976
+ /**
1977
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
1978
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
1979
+ *
1980
+ * @example
1981
+ * socket.timeout(5000).emit("my-event", (err) => {
1982
+ * if (err) {
1983
+ * // the server did not acknowledge the event in the given delay
1984
+ * }
1985
+ * });
1986
+ *
1987
+ * @returns self
1988
+ */
1989
+ timeout(s) {
1990
+ return this.flags.timeout = s, this;
1991
+ }
1992
+ /**
1993
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
1994
+ * callback.
1995
+ *
1996
+ * @example
1997
+ * socket.onAny((event, ...args) => {
1998
+ * console.log(`got ${event}`);
1999
+ * });
2000
+ *
2001
+ * @param listener
2002
+ */
2003
+ onAny(s) {
2004
+ return this._anyListeners = this._anyListeners || [], this._anyListeners.push(s), this;
2005
+ }
2006
+ /**
2007
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2008
+ * callback. The listener is added to the beginning of the listeners array.
2009
+ *
2010
+ * @example
2011
+ * socket.prependAny((event, ...args) => {
2012
+ * console.log(`got event ${event}`);
2013
+ * });
2014
+ *
2015
+ * @param listener
2016
+ */
2017
+ prependAny(s) {
2018
+ return this._anyListeners = this._anyListeners || [], this._anyListeners.unshift(s), this;
2019
+ }
2020
+ /**
2021
+ * Removes the listener that will be fired when any event is emitted.
2022
+ *
2023
+ * @example
2024
+ * const catchAllListener = (event, ...args) => {
2025
+ * console.log(`got event ${event}`);
2026
+ * }
2027
+ *
2028
+ * socket.onAny(catchAllListener);
2029
+ *
2030
+ * // remove a specific listener
2031
+ * socket.offAny(catchAllListener);
2032
+ *
2033
+ * // or remove all listeners
2034
+ * socket.offAny();
2035
+ *
2036
+ * @param listener
2037
+ */
2038
+ offAny(s) {
2039
+ if (!this._anyListeners)
2040
+ return this;
2041
+ if (s) {
2042
+ const e = this._anyListeners;
2043
+ for (let t = 0; t < e.length; t++)
2044
+ if (s === e[t])
2045
+ return e.splice(t, 1), this;
2046
+ } else
2047
+ this._anyListeners = [];
2048
+ return this;
2049
+ }
2050
+ /**
2051
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
2052
+ * e.g. to remove listeners.
2053
+ */
2054
+ listenersAny() {
2055
+ return this._anyListeners || [];
2056
+ }
2057
+ /**
2058
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2059
+ * callback.
2060
+ *
2061
+ * Note: acknowledgements sent to the server are not included.
2062
+ *
2063
+ * @example
2064
+ * socket.onAnyOutgoing((event, ...args) => {
2065
+ * console.log(`sent event ${event}`);
2066
+ * });
2067
+ *
2068
+ * @param listener
2069
+ */
2070
+ onAnyOutgoing(s) {
2071
+ return this._anyOutgoingListeners = this._anyOutgoingListeners || [], this._anyOutgoingListeners.push(s), this;
2072
+ }
2073
+ /**
2074
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2075
+ * callback. The listener is added to the beginning of the listeners array.
2076
+ *
2077
+ * Note: acknowledgements sent to the server are not included.
2078
+ *
2079
+ * @example
2080
+ * socket.prependAnyOutgoing((event, ...args) => {
2081
+ * console.log(`sent event ${event}`);
2082
+ * });
2083
+ *
2084
+ * @param listener
2085
+ */
2086
+ prependAnyOutgoing(s) {
2087
+ return this._anyOutgoingListeners = this._anyOutgoingListeners || [], this._anyOutgoingListeners.unshift(s), this;
2088
+ }
2089
+ /**
2090
+ * Removes the listener that will be fired when any event is emitted.
2091
+ *
2092
+ * @example
2093
+ * const catchAllListener = (event, ...args) => {
2094
+ * console.log(`sent event ${event}`);
2095
+ * }
2096
+ *
2097
+ * socket.onAnyOutgoing(catchAllListener);
2098
+ *
2099
+ * // remove a specific listener
2100
+ * socket.offAnyOutgoing(catchAllListener);
2101
+ *
2102
+ * // or remove all listeners
2103
+ * socket.offAnyOutgoing();
2104
+ *
2105
+ * @param [listener] - the catch-all listener (optional)
2106
+ */
2107
+ offAnyOutgoing(s) {
2108
+ if (!this._anyOutgoingListeners)
2109
+ return this;
2110
+ if (s) {
2111
+ const e = this._anyOutgoingListeners;
2112
+ for (let t = 0; t < e.length; t++)
2113
+ if (s === e[t])
2114
+ return e.splice(t, 1), this;
2115
+ } else
2116
+ this._anyOutgoingListeners = [];
2117
+ return this;
2118
+ }
2119
+ /**
2120
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
2121
+ * e.g. to remove listeners.
2122
+ */
2123
+ listenersAnyOutgoing() {
2124
+ return this._anyOutgoingListeners || [];
2125
+ }
2126
+ /**
2127
+ * Notify the listeners for each packet sent
2128
+ *
2129
+ * @param packet
2130
+ *
2131
+ * @private
2132
+ */
2133
+ notifyOutgoingListeners(s) {
2134
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
2135
+ const e = this._anyOutgoingListeners.slice();
2136
+ for (const t of e)
2137
+ t.apply(this, s.data);
2138
+ }
2139
+ }
2140
+ };
2141
+ function w(s) {
2142
+ s = s || {}, this.ms = s.min || 100, this.max = s.max || 1e4, this.factor = s.factor || 2, this.jitter = s.jitter > 0 && s.jitter <= 1 ? s.jitter : 0, this.attempts = 0;
2143
+ }
2144
+ w.prototype.duration = function() {
2145
+ var s = this.ms * Math.pow(this.factor, this.attempts++);
2146
+ if (this.jitter) {
2147
+ var e = Math.random(), t = Math.floor(e * this.jitter * s);
2148
+ s = (Math.floor(e * 10) & 1) == 0 ? s - t : s + t;
2149
+ }
2150
+ return Math.min(s, this.max) | 0;
2151
+ };
2152
+ w.prototype.reset = function() {
2153
+ this.attempts = 0;
2154
+ };
2155
+ w.prototype.setMin = function(s) {
2156
+ this.ms = s;
2157
+ };
2158
+ w.prototype.setMax = function(s) {
2159
+ this.max = s;
2160
+ };
2161
+ w.prototype.setJitter = function(s) {
2162
+ this.jitter = s;
2163
+ };
2164
+ class $ extends _ {
2165
+ constructor(e, t) {
2166
+ var n;
2167
+ super(), this.nsps = {}, this.subs = [], e && typeof e == "object" && (t = e, e = void 0), t = t || {}, t.path = t.path || "/socket.io", this.opts = t, L(this, t), this.reconnection(t.reconnection !== !1), this.reconnectionAttempts(t.reconnectionAttempts || 1 / 0), this.reconnectionDelay(t.reconnectionDelay || 1e3), this.reconnectionDelayMax(t.reconnectionDelayMax || 5e3), this.randomizationFactor((n = t.randomizationFactor) !== null && n !== void 0 ? n : 0.5), this.backoff = new w({
2168
+ min: this.reconnectionDelay(),
2169
+ max: this.reconnectionDelayMax(),
2170
+ jitter: this.randomizationFactor()
2171
+ }), this.timeout(t.timeout == null ? 2e4 : t.timeout), this._readyState = "closed", this.uri = e;
2172
+ const r = t.parser || ot;
2173
+ this.encoder = new r.Encoder(), this.decoder = new r.Decoder(), this._autoConnect = t.autoConnect !== !1, this._autoConnect && this.open();
2174
+ }
2175
+ reconnection(e) {
2176
+ return arguments.length ? (this._reconnection = !!e, e || (this.skipReconnect = !0), this) : this._reconnection;
2177
+ }
2178
+ reconnectionAttempts(e) {
2179
+ return e === void 0 ? this._reconnectionAttempts : (this._reconnectionAttempts = e, this);
2180
+ }
2181
+ reconnectionDelay(e) {
2182
+ var t;
2183
+ return e === void 0 ? this._reconnectionDelay : (this._reconnectionDelay = e, (t = this.backoff) === null || t === void 0 || t.setMin(e), this);
2184
+ }
2185
+ randomizationFactor(e) {
2186
+ var t;
2187
+ return e === void 0 ? this._randomizationFactor : (this._randomizationFactor = e, (t = this.backoff) === null || t === void 0 || t.setJitter(e), this);
2188
+ }
2189
+ reconnectionDelayMax(e) {
2190
+ var t;
2191
+ return e === void 0 ? this._reconnectionDelayMax : (this._reconnectionDelayMax = e, (t = this.backoff) === null || t === void 0 || t.setMax(e), this);
2192
+ }
2193
+ timeout(e) {
2194
+ return arguments.length ? (this._timeout = e, this) : this._timeout;
2195
+ }
2196
+ /**
2197
+ * Starts trying to reconnect if reconnection is enabled and we have not
2198
+ * started reconnecting yet
2199
+ *
2200
+ * @private
2201
+ */
2202
+ maybeReconnectOnOpen() {
2203
+ !this._reconnecting && this._reconnection && this.backoff.attempts === 0 && this.reconnect();
2204
+ }
2205
+ /**
2206
+ * Sets the current transport `socket`.
2207
+ *
2208
+ * @param {Function} fn - optional, callback
2209
+ * @return self
2210
+ * @public
2211
+ */
2212
+ open(e) {
2213
+ if (~this._readyState.indexOf("open"))
2214
+ return this;
2215
+ this.engine = new Ye(this.uri, this.opts);
2216
+ const t = this.engine, n = this;
2217
+ this._readyState = "opening", this.skipReconnect = !1;
2218
+ const r = f(t, "open", function() {
2219
+ n.onopen(), e && e();
2220
+ }), i = (h) => {
2221
+ this.cleanup(), this._readyState = "closed", this.emitReserved("error", h), e ? e(h) : this.maybeReconnectOnOpen();
2222
+ }, o = f(t, "error", i);
2223
+ if (this._timeout !== !1) {
2224
+ const h = this._timeout, c = this.setTimeoutFn(() => {
2225
+ r(), i(new Error("timeout")), t.close();
2226
+ }, h);
2227
+ this.opts.autoUnref && c.unref(), this.subs.push(() => {
2228
+ this.clearTimeoutFn(c);
2229
+ });
2230
+ }
2231
+ return this.subs.push(r), this.subs.push(o), this;
2232
+ }
2233
+ /**
2234
+ * Alias for open()
2235
+ *
2236
+ * @return self
2237
+ * @public
2238
+ */
2239
+ connect(e) {
2240
+ return this.open(e);
2241
+ }
2242
+ /**
2243
+ * Called upon transport open.
2244
+ *
2245
+ * @private
2246
+ */
2247
+ onopen() {
2248
+ this.cleanup(), this._readyState = "open", this.emitReserved("open");
2249
+ const e = this.engine;
2250
+ this.subs.push(
2251
+ f(e, "ping", this.onping.bind(this)),
2252
+ f(e, "data", this.ondata.bind(this)),
2253
+ f(e, "error", this.onerror.bind(this)),
2254
+ f(e, "close", this.onclose.bind(this)),
2255
+ // @ts-ignore
2256
+ f(this.decoder, "decoded", this.ondecoded.bind(this))
2257
+ );
2258
+ }
2259
+ /**
2260
+ * Called upon a ping.
2261
+ *
2262
+ * @private
2263
+ */
2264
+ onping() {
2265
+ this.emitReserved("ping");
2266
+ }
2267
+ /**
2268
+ * Called with data.
2269
+ *
2270
+ * @private
2271
+ */
2272
+ ondata(e) {
2273
+ try {
2274
+ this.decoder.add(e);
2275
+ } catch (t) {
2276
+ this.onclose("parse error", t);
2277
+ }
2278
+ }
2279
+ /**
2280
+ * Called when parser fully decodes a packet.
2281
+ *
2282
+ * @private
2283
+ */
2284
+ ondecoded(e) {
2285
+ O(() => {
2286
+ this.emitReserved("packet", e);
2287
+ }, this.setTimeoutFn);
2288
+ }
2289
+ /**
2290
+ * Called upon socket error.
2291
+ *
2292
+ * @private
2293
+ */
2294
+ onerror(e) {
2295
+ this.emitReserved("error", e);
2296
+ }
2297
+ /**
2298
+ * Creates a new socket for the given `nsp`.
2299
+ *
2300
+ * @return {Socket}
2301
+ * @public
2302
+ */
2303
+ socket(e, t) {
2304
+ let n = this.nsps[e];
2305
+ return n ? this._autoConnect && !n.active && n.connect() : (n = new de(this, e, t), this.nsps[e] = n), n;
2306
+ }
2307
+ /**
2308
+ * Called upon a socket close.
2309
+ *
2310
+ * @param socket
2311
+ * @private
2312
+ */
2313
+ _destroy(e) {
2314
+ const t = Object.keys(this.nsps);
2315
+ for (const n of t)
2316
+ if (this.nsps[n].active)
2317
+ return;
2318
+ this._close();
2319
+ }
2320
+ /**
2321
+ * Writes a packet.
2322
+ *
2323
+ * @param packet
2324
+ * @private
2325
+ */
2326
+ _packet(e) {
2327
+ const t = this.encoder.encode(e);
2328
+ for (let n = 0; n < t.length; n++)
2329
+ this.engine.write(t[n], e.options);
2330
+ }
2331
+ /**
2332
+ * Clean up transport subscriptions and packet buffer.
2333
+ *
2334
+ * @private
2335
+ */
2336
+ cleanup() {
2337
+ this.subs.forEach((e) => e()), this.subs.length = 0, this.decoder.destroy();
2338
+ }
2339
+ /**
2340
+ * Close the current socket.
2341
+ *
2342
+ * @private
2343
+ */
2344
+ _close() {
2345
+ this.skipReconnect = !0, this._reconnecting = !1, this.onclose("forced close");
2346
+ }
2347
+ /**
2348
+ * Alias for close()
2349
+ *
2350
+ * @private
2351
+ */
2352
+ disconnect() {
2353
+ return this._close();
2354
+ }
2355
+ /**
2356
+ * Called when:
2357
+ *
2358
+ * - the low-level engine is closed
2359
+ * - the parser encountered a badly formatted packet
2360
+ * - all sockets are disconnected
2361
+ *
2362
+ * @private
2363
+ */
2364
+ onclose(e, t) {
2365
+ var n;
2366
+ this.cleanup(), (n = this.engine) === null || n === void 0 || n.close(), this.backoff.reset(), this._readyState = "closed", this.emitReserved("close", e, t), this._reconnection && !this.skipReconnect && this.reconnect();
2367
+ }
2368
+ /**
2369
+ * Attempt a reconnection.
2370
+ *
2371
+ * @private
2372
+ */
2373
+ reconnect() {
2374
+ if (this._reconnecting || this.skipReconnect)
2375
+ return this;
2376
+ const e = this;
2377
+ if (this.backoff.attempts >= this._reconnectionAttempts)
2378
+ this.backoff.reset(), this.emitReserved("reconnect_failed"), this._reconnecting = !1;
2379
+ else {
2380
+ const t = this.backoff.duration();
2381
+ this._reconnecting = !0;
2382
+ const n = this.setTimeoutFn(() => {
2383
+ e.skipReconnect || (this.emitReserved("reconnect_attempt", e.backoff.attempts), !e.skipReconnect && e.open((r) => {
2384
+ r ? (e._reconnecting = !1, e.reconnect(), this.emitReserved("reconnect_error", r)) : e.onreconnect();
2385
+ }));
2386
+ }, t);
2387
+ this.opts.autoUnref && n.unref(), this.subs.push(() => {
2388
+ this.clearTimeoutFn(n);
2389
+ });
2390
+ }
2391
+ }
2392
+ /**
2393
+ * Called upon successful reconnect.
2394
+ *
2395
+ * @private
2396
+ */
2397
+ onreconnect() {
2398
+ const e = this.backoff.attempts;
2399
+ this._reconnecting = !1, this.backoff.reset(), this.emitReserved("reconnect", e);
2400
+ }
2401
+ }
2402
+ const k = {};
2403
+ function B(s, e) {
2404
+ typeof s == "object" && (e = s, s = void 0), e = e || {};
2405
+ const t = Je(s, e.path || "/socket.io"), n = t.source, r = t.id, i = t.path, o = k[r] && i in k[r].nsps, h = e.forceNew || e["force new connection"] || e.multiplex === !1 || o;
2406
+ let c;
2407
+ return h ? c = new $(n, e) : (k[r] || (k[r] = new $(n, e)), c = k[r]), t.query && !e.query && (e.query = t.queryKey), c.socket(t.path, e);
2408
+ }
2409
+ Object.assign(B, {
2410
+ Manager: $,
2411
+ Socket: de,
2412
+ io: B,
2413
+ connect: B
2414
+ });
2415
+ class ct {
2416
+ #t = "http://localhost:3000";
2417
+ #s = {
2418
+ transports: ["websocket"]
2419
+ };
2420
+ #e;
2421
+ #i = !1;
2422
+ #o = {};
2423
+ set uri(e) {
2424
+ const t = new URL(e);
2425
+ if (!["http:", "https:", "ws:", "wss:"].includes(t.protocol))
2426
+ throw new Error("URI must start with http://, https://, ws://, or wss://");
2427
+ this.#t = e;
2428
+ }
2429
+ get uri() {
2430
+ return this.#t;
2431
+ }
2432
+ set options(e) {
2433
+ if (typeof e != "object")
2434
+ throw new Error("Options must be an object");
2435
+ this.#s = e;
2436
+ }
2437
+ get options() {
2438
+ return this.#s;
2439
+ }
2440
+ constructor() {
2441
+ this.#o.onResponse = this.onResponse.bind(this);
2442
+ }
2443
+ disconnect() {
2444
+ this.#e && (this.#e.off("response", this.#o.onResponse), this.#e.disconnect(), this.#e = null), this.#i = !1;
2445
+ }
2446
+ prepare() {
2447
+ this.#i || (this.#e = B(this.#t, this.#s), this.#i = !0, this.#e.on("response", this.#o.onResponse));
2448
+ }
2449
+ connectDevice(e) {
2450
+ this.#e.emit("connectDevice", { config: e });
2451
+ }
2452
+ disconnectDevice(e) {
2453
+ this.#e.emit("disconnectDevice", { config: e });
2454
+ }
2455
+ disconnectAllDevices() {
2456
+ this.#e.emit("disconnectAll");
2457
+ }
2458
+ write(e) {
2459
+ this.#e.emit("cmd", e);
2460
+ }
2461
+ onResponse(e) {
2462
+ let t = a.get(e.name, e.uuid);
2463
+ t || (t = a.getByNumber(e.name, e.deviceNumber)), t && t.socketResponse(e);
2464
+ }
2465
+ }
2466
+ const A = new ct(), q = {
2467
+ baudRate: 9600,
2468
+ dataBits: 8,
2469
+ stopBits: 1,
2470
+ parity: "none",
2471
+ bufferSize: 32768,
2472
+ flowControl: "none"
2473
+ };
2474
+ class lt extends te {
2475
+ __internal__ = {
2476
+ bypassSerialBytesConnection: !1,
2477
+ auto_response: !1,
2478
+ device_number: 1,
2479
+ aux_port_connector: 0,
2480
+ last_error: {
2481
+ message: null,
2482
+ action: null,
2483
+ code: null,
2484
+ no_code: 0
2485
+ },
2486
+ serial: {
2487
+ socket: !1,
2488
+ portInfo: {
2489
+ path: null,
2490
+ vendorId: null,
2491
+ productId: null,
2492
+ parser: {
2493
+ name: "inter-byte-timeout",
2494
+ interval: 50
2495
+ }
2496
+ },
2497
+ aux_connecting: "idle",
2498
+ connecting: !1,
2499
+ connected: !1,
2500
+ port: null,
2501
+ last_action: null,
2502
+ response: {
2503
+ length: null,
2504
+ buffer: new Uint8Array([]),
2505
+ as: "uint8",
2506
+ replacer: /[\n\r]+/g,
2507
+ limiter: null,
2508
+ prefixLimiter: !1,
2509
+ sufixLimiter: !0,
2510
+ delimited: !1
2511
+ },
2512
+ reader: null,
2513
+ input_done: null,
2514
+ output_done: null,
2515
+ input_stream: null,
2516
+ output_stream: null,
2517
+ keep_reading: !0,
2518
+ time_until_send_bytes: void 0,
2519
+ delay_first_connection: 200,
2520
+ bytes_connection: null,
2521
+ filters: [],
2522
+ config_port: q,
2523
+ queue: [],
2524
+ running_queue: !1,
2525
+ auto_response: null,
2526
+ free_timeout_ms: 50,
2527
+ // In previous versions 400 was used
2528
+ useRTSCTS: !1
2529
+ // Use RTS/CTS flow control
2530
+ },
2531
+ device: {
2532
+ type: "unknown",
2533
+ id: window.crypto.randomUUID(),
2534
+ listen_on_port: null
2535
+ },
2536
+ time: {
2537
+ response_connection: 500,
2538
+ response_engines: 2e3,
2539
+ response_general: 2e3
2540
+ },
2541
+ timeout: {
2542
+ until_response: 0
2543
+ },
2544
+ interval: {
2545
+ reconnection: 0
2546
+ }
2547
+ };
2548
+ #t = null;
2549
+ constructor({
2550
+ filters: e = null,
2551
+ config_port: t = q,
2552
+ no_device: n = 1,
2553
+ device_listen_on_channel: r = 1,
2554
+ bypassSerialBytesConnection: i = !1,
2555
+ socket: o = !1
2556
+ } = {
2557
+ filters: null,
2558
+ config_port: q,
2559
+ no_device: 1,
2560
+ device_listen_on_channel: 1,
2561
+ bypassSerialBytesConnection: !1,
2562
+ socket: !1
2563
+ }) {
2564
+ if (super(), !("serial" in navigator))
2565
+ throw new Error("Web Serial not supported");
2566
+ e && (this.serialFilters = e), t && (this.serialConfigPort = t), i && (this.__internal__.bypassSerialBytesConnection = i), n && this.#w(n), r && ["number", "string"].includes(typeof r) && (this.listenOnChannel = r), this.__internal__.serial.socket = o, this.#y(), this.#g();
2567
+ }
2568
+ set listenOnChannel(e) {
2569
+ if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
2570
+ throw new Error("Invalid port number");
2571
+ this.__internal__.device.listen_on_port = e, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e));
2572
+ }
2573
+ get lastAction() {
2574
+ return this.__internal__.serial.last_action;
2575
+ }
2576
+ get listenOnChannel() {
2577
+ return this.__internal__.device.listen_on_port ?? 1;
2578
+ }
2579
+ set serialFilters(e) {
2580
+ if (this.isConnected) throw new Error("Cannot change serial filters while connected");
2581
+ this.__internal__.serial.filters = e;
2582
+ }
2583
+ get serialFilters() {
2584
+ return this.__internal__.serial.filters;
2585
+ }
2586
+ set serialConfigPort(e) {
2587
+ if (this.isConnected) throw new Error("Cannot change serial filters while connected");
2588
+ this.__internal__.serial.config_port = e;
2589
+ }
2590
+ get serialConfigPort() {
2591
+ return this.__internal__.serial.config_port;
2592
+ }
2593
+ get useRTSCTS() {
2594
+ return this.__internal__.serial.useRTSCTS;
2595
+ }
2596
+ set useRTSCTS(e) {
2597
+ this.__internal__.serial.useRTSCTS = e;
2598
+ }
2599
+ get isConnected() {
2600
+ const e = this.__internal__.serial.connected, t = this.#s(this.__internal__.serial.port);
2601
+ return e && !t && this.#e({ error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
2602
+ }
2603
+ get isConnecting() {
2604
+ return this.__internal__.serial.connecting;
2605
+ }
2606
+ get isDisconnected() {
2607
+ const e = this.__internal__.serial.connected, t = this.#s(this.__internal__.serial.port);
2608
+ return !e && t && (this.dispatch("serial:connected"), this.#r(!1), a.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
2609
+ }
2610
+ get deviceNumber() {
2611
+ return this.__internal__.device_number;
2612
+ }
2613
+ get uuid() {
2614
+ return this.__internal__.device.id;
2615
+ }
2616
+ get typeDevice() {
2617
+ return this.__internal__.device.type;
2618
+ }
2619
+ get queue() {
2620
+ return this.__internal__.serial.queue;
2621
+ }
2622
+ get responseDelimited() {
2623
+ return this.__internal__.serial.response.delimited;
2624
+ }
2625
+ set responseDelimited(e) {
2626
+ if (typeof e != "boolean")
2627
+ throw new Error("responseDelimited must be a boolean");
2628
+ this.__internal__.serial.response.delimited = e;
2629
+ }
2630
+ get responsePrefixLimited() {
2631
+ return this.__internal__.serial.response.prefixLimiter;
2632
+ }
2633
+ set responsePrefixLimited(e) {
2634
+ if (typeof e != "boolean")
2635
+ throw new Error("responsePrefixLimited must be a boolean");
2636
+ this.__internal__.serial.response.prefixLimiter = e;
2637
+ }
2638
+ get responseSufixLimited() {
2639
+ return this.__internal__.serial.response.sufixLimiter;
2640
+ }
2641
+ set responseSufixLimited(e) {
2642
+ if (typeof e != "boolean")
2643
+ throw new Error("responseSufixLimited must be a boolean");
2644
+ this.__internal__.serial.response.sufixLimiter = e;
2645
+ }
2646
+ get responseLimiter() {
2647
+ return this.__internal__.serial.response.limiter;
2648
+ }
2649
+ set responseLimiter(e) {
2650
+ if (typeof e != "string" && !(e instanceof RegExp))
2651
+ throw new Error("responseLimiter must be a string or a RegExp");
2652
+ this.__internal__.serial.response.limiter = e;
2653
+ }
2654
+ get fixedBytesMessage() {
2655
+ return this.__internal__.serial.response.length;
2656
+ }
2657
+ set fixedBytesMessage(e) {
2658
+ if (e !== null && (typeof e != "number" || e < 1))
2659
+ throw new Error("Invalid length for fixed bytes message");
2660
+ this.__internal__.serial.response.length = e;
2661
+ }
2662
+ get timeoutBeforeResponseBytes() {
2663
+ return this.__internal__.serial.free_timeout_ms || 50;
2664
+ }
2665
+ set timeoutBeforeResponseBytes(e) {
2666
+ if (e !== void 0 && (typeof e != "number" || e < 1))
2667
+ throw new Error("Invalid timeout for response bytes");
2668
+ this.__internal__.serial.free_timeout_ms = e ?? 50;
2669
+ }
2670
+ get bypassSerialBytesConnection() {
2671
+ return this.__internal__.bypassSerialBytesConnection;
2672
+ }
2673
+ set bypassSerialBytesConnection(e) {
2674
+ if (typeof e != "boolean")
2675
+ throw new Error("bypassSerialBytesConnection must be a boolean");
2676
+ this.__internal__.bypassSerialBytesConnection = e;
2677
+ }
2678
+ get useSocket() {
2679
+ return this.__internal__.serial.socket;
2680
+ }
2681
+ get connectionBytes() {
2682
+ const e = this.__internal__.serial.bytes_connection;
2683
+ return e instanceof Uint8Array ? e : typeof e == "string" ? this.stringArrayToUint8Array(this.parseStringToBytes(e, "")) : Array.isArray(e) && typeof e[0] == "string" ? this.stringArrayToUint8Array(e) : Array.isArray(e) && typeof e[0] == "number" ? new Uint8Array(e) : new Uint8Array([]);
2684
+ }
2685
+ set portPath(e) {
2686
+ if (this.isConnected) throw new Error("Cannot change port path while connected");
2687
+ if (typeof e != "string" && e !== null)
2688
+ throw new TypeError("vendorId must be string or null");
2689
+ this.__internal__.serial.portInfo.path = e;
2690
+ }
2691
+ get portPath() {
2692
+ return this.__internal__.serial.portInfo.path;
2693
+ }
2694
+ set portVendorId(e) {
2695
+ if (this.isConnected) throw new Error("Cannot change port vendorId while connected");
2696
+ if (typeof e == "number" && typeof e != "string" && e !== null)
2697
+ throw new TypeError("vendorId must be a number, string or null");
2698
+ this.__internal__.serial.portInfo.vendorId = e;
2699
+ }
2700
+ get portVendorId() {
2701
+ return this.__internal__.serial.portInfo.vendorId;
2702
+ }
2703
+ set portProductId(e) {
2704
+ if (this.isConnected) throw new Error("Cannot change port productId while connected");
2705
+ if (typeof e == "number" && typeof e != "string" && e !== null)
2706
+ throw new TypeError("productId must be a number, string or null");
2707
+ this.__internal__.serial.portInfo.productId = e;
2708
+ }
2709
+ get portProductId() {
2710
+ return this.__internal__.serial.portInfo.productId;
2711
+ }
2712
+ set socketPortParser(e) {
2713
+ if (["byte-length", "inter-byte-timeout"].includes(e))
2714
+ throw new TypeError("socketPortParser must be a string, either 'byte-length' or 'inter-byte-timeout'");
2715
+ this.__internal__.serial.portInfo.parser.name = e;
2716
+ }
2717
+ get socketPortParser() {
2718
+ return this.__internal__.serial.portInfo.parser.name;
2719
+ }
2720
+ set socketPortParserInterval(e) {
2721
+ if (typeof e != "number" || e < 1)
2722
+ throw new TypeError("Interval must be a positive number");
2723
+ this.__internal__.serial.portInfo.parser.interval = e;
2724
+ }
2725
+ get socketPortParserInterval() {
2726
+ return this.__internal__.serial.portInfo.parser.interval || 50;
2727
+ }
2728
+ set socketPortParserLength(e) {
2729
+ if (typeof e != "number" || e < 1)
2730
+ throw new TypeError("Length must be a positive number or null");
2731
+ this.__internal__.serial.portInfo.parser.length = e;
2732
+ }
2733
+ get socketPortParserLength() {
2734
+ return this.__internal__.serial.portInfo.parser.length || 14;
2735
+ }
2736
+ get parserForSocket() {
2737
+ return this.socketPortParser === "byte-length" ? {
2738
+ name: this.socketPortParser,
2739
+ length: this.socketPortParserLength
2740
+ } : {
2741
+ name: this.socketPortParser,
2742
+ interval: this.socketPortParserInterval
2743
+ };
2744
+ }
2745
+ get configDeviceSocket() {
2746
+ return {
2747
+ uuid: this.uuid,
2748
+ name: this.typeDevice,
2749
+ deviceNumber: this.deviceNumber,
2750
+ connectionBytes: Array.from(this.connectionBytes),
2751
+ config: {
2752
+ baudRate: this.__internal__.serial.config_port.baudRate,
2753
+ dataBits: this.__internal__.serial.config_port.dataBits,
2754
+ stopBits: this.__internal__.serial.config_port.stopBits,
2755
+ parity: this.__internal__.serial.config_port.parity,
2756
+ bufferSize: this.__internal__.serial.config_port.bufferSize,
2757
+ flowControl: this.__internal__.serial.config_port.flowControl
2758
+ },
2759
+ info: {
2760
+ vendorId: this.portVendorId,
2761
+ // vendor ID or null for auto-detect
2762
+ productId: this.portProductId,
2763
+ // product ID or null for auto-detect
2764
+ portName: this.portPath
2765
+ // COM3, /dev/ttyUSB0, etc. null for auto-detect
2766
+ },
2767
+ response: {
2768
+ automatic: this.__internal__.auto_response,
2769
+ // true to auto-respond to commands this only for devices that doesn't respond nothing
2770
+ autoResponse: this.__internal__.serial.auto_response,
2771
+ // null or data to respond automatically, ie. [0x02, 0x06, 0xdd, 0xdd, 0xf0, 0xcf, 0x03] for relay
2772
+ parser: this.parserForSocket,
2773
+ timeout: {
2774
+ general: this.__internal__.time.response_general,
2775
+ engines: this.__internal__.time.response_engines,
2776
+ connection: this.__internal__.time.response_connection
2777
+ }
2778
+ }
2779
+ };
2780
+ }
2781
+ #s(e) {
2782
+ return this.useSocket ? this.__internal__.serial.connected : !!(e && e.readable && e.writable);
2783
+ }
2784
+ async timeout(e, t) {
2785
+ 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", {}), a.$dispatchChange(this)) : t === "connection:start" && (await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector += 1, a.$dispatchChange(this), await this.serialConnect()), this.__internal__.serial.queue.length > 0 && this.dispatch("internal:queue", {}), this.dispatch("serial:timeout", {
2786
+ ...this.__internal__.last_error,
2787
+ bytes: e,
2788
+ action: t
2789
+ });
2790
+ }
2791
+ async disconnect(e = null) {
2792
+ await this.serialDisconnect(), this.#e(e);
2793
+ }
2794
+ #e(e = null) {
2795
+ this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), a.$dispatchChange(this);
2796
+ }
2797
+ #i(e) {
2798
+ this.__internal__.serial.aux_connecting = e.detail.active ? "connecting" : "finished";
2799
+ }
2800
+ socketResponse(e) {
2801
+ const t = this.__internal__.serial.connected;
2802
+ if (e.type === "disconnect" || e.type === "error" && e.data === "DISCONNECTED" ? this.__internal__.serial.connected = !1 : e.type === "success" && (this.__internal__.serial.connected = !0), a.$dispatchChange(this), !t && this.__internal__.serial.connected && (this.dispatch("serial:connected"), this.#r(!1)), e.type === "success")
2803
+ this.#n(new Uint8Array(e.data));
2804
+ else if (e.type === "error") {
2805
+ const n = new Error("The port is closed or is not readable/writable");
2806
+ this.serialErrors(n);
2807
+ } else e.type === "timeout" && this.timeout(e.data.bytes ?? [], this.lastAction || "unknown");
2808
+ this.__internal__.serial.last_action = null;
2809
+ }
2810
+ async connect() {
2811
+ return this.isConnected ? !0 : (this.__internal__.serial.aux_connecting = "idle", new Promise((e, t) => {
2812
+ this.#t || (this.#t = this.#i.bind(this)), this.on("internal:connecting", this.#t);
2813
+ const n = setInterval(() => {
2814
+ this.__internal__.serial.aux_connecting === "finished" ? (clearInterval(n), 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 }));
2815
+ }, 100);
2816
+ this.serialConnect();
2817
+ }));
2818
+ }
2819
+ async serialDisconnect() {
2820
+ try {
2821
+ if (this.useSocket)
2822
+ A.disconnectDevice(this.configDeviceSocket);
2823
+ else {
2824
+ const e = this.__internal__.serial.reader, t = this.__internal__.serial.output_stream;
2825
+ e && (await e.cancel().catch((n) => this.serialErrors(n)), await this.__internal__.serial.input_done), t && (await t.getWriter().close(), await this.__internal__.serial.output_done), this.__internal__.serial.connected && this.__internal__.serial && this.__internal__.serial.port && await this.__internal__.serial.port.close();
2826
+ }
2827
+ } catch (e) {
2828
+ this.serialErrors(e);
2829
+ } finally {
2830
+ 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, a.$dispatchChange(this);
2831
+ }
2832
+ }
2833
+ async #o(e) {
2834
+ if (this.isDisconnected)
2835
+ throw this.#e({ error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
2836
+ const t = this.validateBytes(e);
2837
+ A.write({ config: this.configDeviceSocket, bytes: Array.from(t) });
2838
+ }
2839
+ async #a(e) {
2840
+ if (this.useSocket) {
2841
+ await this.#o(e);
2842
+ return;
2843
+ }
2844
+ const t = this.__internal__.serial.port;
2845
+ if (!t || t && (!t.readable || !t.writable))
2846
+ throw this.#e({ error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
2847
+ const n = this.validateBytes(e);
2848
+ if (this.useRTSCTS && await this.#c(t, 5e3), t.writable === null) return;
2849
+ const r = t.writable.getWriter();
2850
+ await r.write(n), r.releaseLock();
2851
+ }
2852
+ async #c(e, t = 5e3) {
2853
+ const n = Date.now();
2854
+ for (; ; ) {
2855
+ if (Date.now() - n > t)
2856
+ throw new Error("Timeout waiting for clearToSend signal");
2857
+ const { clearToSend: r } = await e.getSignals();
2858
+ if (r) return;
2859
+ await J(100);
2860
+ }
2861
+ }
2862
+ #n(e = new Uint8Array([]), t = !1) {
2863
+ if (e && e.length > 0) {
2864
+ const n = this.__internal__.serial.connected;
2865
+ if (this.__internal__.serial.connected = this.#s(this.__internal__.serial.port), a.$dispatchChange(this), !n && this.__internal__.serial.connected && (this.dispatch("serial:connected"), this.#r(!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")
2866
+ t ? this.serialCorruptMessage(this.parseUint8ToHex(e)) : this.serialMessage(this.parseUint8ToHex(e));
2867
+ else if (this.__internal__.serial.response.as === "uint8")
2868
+ t ? this.serialCorruptMessage(e) : this.serialMessage(e);
2869
+ else if (this.__internal__.serial.response.as === "string") {
2870
+ const r = this.parseUint8ArrayToString(e);
2871
+ if (this.__internal__.serial.response.limiter !== null) {
2872
+ const i = r.split(this.__internal__.serial.response.limiter);
2873
+ for (const o in i)
2874
+ i[o] && (t ? this.serialCorruptMessage(i[o]) : this.serialMessage(i[o]));
2875
+ } else
2876
+ t ? this.serialCorruptMessage(r) : this.serialMessage(r);
2877
+ } else {
2878
+ const r = this.stringToArrayBuffer(this.parseUint8ArrayToString(e));
2879
+ t ? this.serialCorruptMessage(r) : this.serialMessage(r);
2880
+ }
2881
+ }
2882
+ if (this.__internal__.serial.queue.length === 0) {
2883
+ this.__internal__.serial.running_queue = !1;
2884
+ return;
2885
+ }
2886
+ this.dispatch("internal:queue", {});
2887
+ }
2888
+ getResponseAsArrayBuffer() {
2889
+ this.__internal__.serial.response.as = "arraybuffer";
2890
+ }
2891
+ getResponseAsArrayHex() {
2892
+ this.__internal__.serial.response.as = "hex";
2893
+ }
2894
+ getResponseAsUint8Array() {
2895
+ this.__internal__.serial.response.as = "uint8";
2896
+ }
2897
+ getResponseAsString() {
2898
+ this.__internal__.serial.response.as = "string";
2899
+ }
2900
+ async #l() {
2901
+ const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
2902
+ return e.length === 0 ? t : t.filter((n) => {
2903
+ const r = n.getInfo();
2904
+ return e.some((i) => r.usbProductId === i.usbProductId && r.usbVendorId === i.usbVendorId);
2905
+ }).filter((n) => !this.#s(n));
2906
+ }
2907
+ async serialPortsSaved(e) {
2908
+ const t = this.serialFilters;
2909
+ if (this.__internal__.aux_port_connector < e.length) {
2910
+ const n = this.__internal__.aux_port_connector;
2911
+ this.__internal__.serial.port = e[n];
2912
+ } else
2913
+ this.__internal__.aux_port_connector = 0, this.__internal__.serial.port = await navigator.serial.requestPort({
2914
+ filters: t
2915
+ });
2916
+ if (!this.__internal__.serial.port)
2917
+ throw new Error("Select another port please");
2918
+ }
2919
+ serialErrors(e) {
2920
+ const t = e.toString().toLowerCase();
2921
+ switch (!0) {
2922
+ case t.includes("must be handling a user gesture to show a permission request"):
2923
+ case t.includes("the port is closed."):
2924
+ case t.includes("the port is closed or is not writable"):
2925
+ case t.includes("the port is closed or is not readable"):
2926
+ case t.includes("the port is closed or is not readable/writable"):
2927
+ case t.includes("select another port please"):
2928
+ case t.includes("no port selected by the user"):
2929
+ case t.includes(
2930
+ "this readable stream reader has been released and cannot be used to cancel its previous owner stream"
2931
+ ):
2932
+ this.dispatch("serial:need-permission", {}), a.$dispatchChange(this);
2933
+ break;
2934
+ case t.includes("the port is already open."):
2935
+ case t.includes("failed to open serial port"):
2936
+ this.serialDisconnect().then(async () => {
2937
+ this.__internal__.aux_port_connector += 1, await this.serialConnect();
2938
+ });
2939
+ break;
2940
+ case t.includes("cannot read properties of undefined (reading 'writable')"):
2941
+ case t.includes("cannot read properties of null (reading 'writable')"):
2942
+ case t.includes("cannot read property 'writable' of null"):
2943
+ case t.includes("cannot read property 'writable' of undefined"):
2944
+ this.serialDisconnect().then(async () => {
2945
+ await this.serialConnect();
2946
+ });
2947
+ break;
2948
+ case t.includes("'close' on 'serialport': a call to close() is already in progress."):
2949
+ break;
2950
+ case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):
2951
+ break;
2952
+ case t.includes("the port is already closed."):
2953
+ break;
2954
+ case t.includes("the device has been lost"):
2955
+ this.dispatch("serial:lost", {}), a.$dispatchChange(this);
2956
+ break;
2957
+ case t.includes("navigator.serial is undefined"):
2958
+ this.dispatch("serial:unsupported", {});
2959
+ break;
2960
+ default:
2961
+ console.error(e);
2962
+ break;
2963
+ }
2964
+ this.dispatch("serial:error", e);
2965
+ }
2966
+ #h(e) {
2967
+ if (e) {
2968
+ const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
2969
+ n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
2970
+ }
2971
+ }
2972
+ async #u() {
2973
+ 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(() => {
2974
+ this.__internal__.serial.response.buffer && this.#n(this.__internal__.serial.response.buffer), this.__internal__.serial.response.buffer = new Uint8Array(0);
2975
+ }, this.__internal__.serial.free_timeout_ms || 50);
2976
+ }
2977
+ async #_() {
2978
+ const e = this.__internal__.serial.response.length;
2979
+ let t = this.__internal__.serial.response.buffer;
2980
+ 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)) {
2981
+ for (; t.length >= e; ) {
2982
+ const n = t.slice(0, e);
2983
+ this.#n(n), t = t.slice(e);
2984
+ }
2985
+ this.__internal__.serial.response.buffer = t, t.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
2986
+ this.#n(this.__internal__.serial.response.buffer, !0);
2987
+ }, this.__internal__.serial.free_timeout_ms || 50));
2988
+ }
2989
+ }
2990
+ async #p() {
2991
+ const {
2992
+ limiter: e,
2993
+ prefixLimiter: t = !1,
2994
+ sufixLimiter: n = !0
2995
+ } = this.__internal__.serial.response;
2996
+ if (!e)
2997
+ throw new Error("No limiter defined for delimited serial response");
2998
+ const r = this.__internal__.serial.response.buffer;
2999
+ if (!e || !r || r.length === 0) return;
3000
+ this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0);
3001
+ let i = new TextDecoder().decode(r);
3002
+ const o = [];
3003
+ if (typeof e == "string") {
3004
+ let c;
3005
+ if (t && n)
3006
+ c = new RegExp(`${e}([^${e}]+)${e}`, "g");
3007
+ else if (t)
3008
+ c = new RegExp(`${e}([^${e}]*)`, "g");
3009
+ else if (n)
3010
+ c = new RegExp(`([^${e}]+)${e}`, "g");
3011
+ else
3012
+ return;
3013
+ let p, u = 0;
3014
+ for (; (p = c.exec(i)) !== null; )
3015
+ o.push(new TextEncoder().encode(p[1])), u = c.lastIndex;
3016
+ i = i.slice(u);
3017
+ } else if (e instanceof RegExp) {
3018
+ let c, p = 0;
3019
+ if (t && n) {
3020
+ const u = new RegExp(`${e.source}(.*?)${e.source}`, "g");
3021
+ for (; (c = u.exec(i)) !== null; )
3022
+ o.push(new TextEncoder().encode(c[1])), p = u.lastIndex;
3023
+ } else if (n)
3024
+ for (; (c = e.exec(i)) !== null; ) {
3025
+ const u = c.index, y = i.slice(p, u);
3026
+ o.push(new TextEncoder().encode(y)), p = e.lastIndex;
3027
+ }
3028
+ else if (t) {
3029
+ const u = i.split(e);
3030
+ u.shift();
3031
+ for (const y of u)
3032
+ o.push(new TextEncoder().encode(y));
3033
+ i = "";
3034
+ }
3035
+ i = i.slice(p);
3036
+ }
3037
+ for (const c of o)
3038
+ this.#n(c);
3039
+ const h = new TextEncoder().encode(i);
3040
+ this.__internal__.serial.response.buffer = h, h.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
3041
+ this.#n(this.__internal__.serial.response.buffer, !0), this.__internal__.serial.response.buffer = new Uint8Array(0);
3042
+ }, this.__internal__.serial.free_timeout_ms ?? 50));
3043
+ }
3044
+ async #d() {
3045
+ const e = this.__internal__.serial.port;
3046
+ if (!e || !e.readable) throw new Error("Port is not readable");
3047
+ const t = e.readable.getReader();
3048
+ this.__internal__.serial.reader = t;
3049
+ try {
3050
+ for (; this.__internal__.serial.keep_reading; ) {
3051
+ const { value: n, done: r } = await t.read();
3052
+ if (r) break;
3053
+ this.#h(n), this.__internal__.serial.response.delimited ? await this.#p() : this.__internal__.serial.response.length === null ? await this.#u() : await this.#_();
3054
+ }
3055
+ } catch (n) {
3056
+ this.serialErrors(n);
3057
+ } finally {
3058
+ t.releaseLock(), this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
3059
+ }
3060
+ }
3061
+ #r(e) {
3062
+ e !== this.__internal__.serial.connecting && (this.__internal__.serial.connecting = e, this.dispatch("serial:connecting", { active: e }), this.dispatch("internal:connecting", { active: e }));
3063
+ }
3064
+ async serialConnect() {
3065
+ try {
3066
+ if (this.#r(!0), this.useSocket)
3067
+ A.prepare(), this.__internal__.serial.last_action = "connect", this.__internal__.timeout.until_response = setTimeout(async () => {
3068
+ await this.timeout(this.__internal__.serial.bytes_connection ?? [], "connection:start");
3069
+ }, this.__internal__.time.response_connection), A.connectDevice(this.configDeviceSocket), this.dispatch("serial:sent", {
3070
+ action: "connect",
3071
+ bytes: this.__internal__.serial.bytes_connection
3072
+ });
3073
+ else {
3074
+ const e = await this.#l();
3075
+ if (e.length > 0)
3076
+ await this.serialPortsSaved(e);
3077
+ else {
3078
+ const r = this.serialFilters;
3079
+ this.__internal__.serial.port = await navigator.serial.requestPort({
3080
+ filters: r
3081
+ });
3082
+ }
3083
+ const t = this.__internal__.serial.port;
3084
+ if (!t)
3085
+ throw new Error("No port selected by the user");
3086
+ await t.open(this.serialConfigPort);
3087
+ const n = this;
3088
+ t.onconnect = (r) => {
3089
+ n.dispatch("serial:connected", r), n.#r(!1), a.$dispatchChange(this), n.__internal__.serial.queue.length > 0 ? n.dispatch("internal:queue", {}) : n.__internal__.serial.running_queue = !1;
3090
+ }, t.ondisconnect = async () => {
3091
+ await n.disconnect();
3092
+ }, await J(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
3093
+ await n.timeout(n.__internal__.serial.bytes_connection ?? [], "connection:start");
3094
+ }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await this.#a(this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
3095
+ action: "connect",
3096
+ bytes: this.__internal__.serial.bytes_connection
3097
+ }), this.__internal__.auto_response && this.#n(this.__internal__.serial.auto_response), await this.#d();
3098
+ }
3099
+ } catch (e) {
3100
+ this.#r(!1), this.serialErrors(e);
3101
+ }
3102
+ }
3103
+ async #f() {
3104
+ return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
3105
+ }
3106
+ async serialForget() {
3107
+ return await this.#f();
3108
+ }
3109
+ decToHex(e) {
3110
+ return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
3111
+ }
3112
+ hexToDec(e) {
3113
+ return parseInt(e, 16);
3114
+ }
3115
+ hexMaker(e = "00", t = 2) {
3116
+ return e.toString().padStart(t, "0").toLowerCase();
3117
+ }
3118
+ add0x(e) {
3119
+ const t = [];
3120
+ return e.forEach((n, r) => {
3121
+ t[r] = "0x" + n;
3122
+ }), t;
3123
+ }
3124
+ bytesToHex(e) {
3125
+ return this.add0x(Array.from(e, (t) => this.hexMaker(t)));
3126
+ }
3127
+ #y() {
3128
+ [
3129
+ "serial:connected",
3130
+ "serial:connecting",
3131
+ "serial:reconnect",
3132
+ "serial:timeout",
3133
+ "serial:disconnected",
3134
+ "serial:sent",
3135
+ "serial:soft-reload",
3136
+ "serial:message",
3137
+ "serial:corrupt-message",
3138
+ "unknown",
3139
+ "serial:need-permission",
3140
+ "serial:lost",
3141
+ "serial:unsupported",
3142
+ "serial:error",
3143
+ "debug"
3144
+ ].forEach((e) => {
3145
+ this.serialRegisterAvailableListener(e);
3146
+ });
3147
+ }
3148
+ #g() {
3149
+ const e = this;
3150
+ this.on("internal:queue", async () => {
3151
+ await e.#b();
3152
+ }), this.#m();
3153
+ }
3154
+ #m() {
3155
+ const e = this;
3156
+ navigator.serial.addEventListener("connect", async () => {
3157
+ e.isDisconnected && await e.serialConnect().catch(() => {
3158
+ });
3159
+ });
3160
+ }
3161
+ async #b() {
3162
+ if (!this.#s(this.__internal__.serial.port)) {
3163
+ this.#e({ error: "Port is closed, not readable or writable." }), await this.serialConnect();
3164
+ return;
3165
+ }
3166
+ if (this.__internal__.timeout.until_response) return;
3167
+ if (this.__internal__.serial.queue.length === 0) {
3168
+ this.__internal__.serial.running_queue = !1;
3169
+ return;
3170
+ }
3171
+ this.__internal__.serial.running_queue = !0;
3172
+ const e = this.__internal__.serial.queue[0];
3173
+ let t = this.__internal__.time.response_general;
3174
+ if (e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
3175
+ await this.timeout(e.bytes, e.action);
3176
+ }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await this.#a(e.bytes), this.dispatch("serial:sent", {
3177
+ action: e.action,
3178
+ bytes: e.bytes
3179
+ }), this.__internal__.auto_response) {
3180
+ let r = new Uint8Array(0);
3181
+ try {
3182
+ r = this.validateBytes(this.__internal__.serial.auto_response);
3183
+ } catch (i) {
3184
+ this.serialErrors(i);
3185
+ }
3186
+ this.#n(r);
3187
+ }
3188
+ const n = [...this.__internal__.serial.queue];
3189
+ this.__internal__.serial.queue = n.splice(1), this.__internal__.serial.queue.length > 0 && (this.__internal__.serial.running_queue = !0);
3190
+ }
3191
+ validateBytes(e) {
3192
+ let t = new Uint8Array(0);
3193
+ if (e instanceof Uint8Array)
3194
+ t = e;
3195
+ else if (typeof e == "string")
3196
+ t = this.parseStringToTextEncoder(e);
3197
+ else if (Array.isArray(e) && typeof e[0] == "string")
3198
+ t = this.stringArrayToUint8Array(e);
3199
+ else if (Array.isArray(e) && typeof e[0] == "number")
3200
+ t = new Uint8Array(e);
3201
+ else
3202
+ throw new Error("Invalid data type");
3203
+ return t;
3204
+ }
3205
+ async appendToQueue(e, t) {
3206
+ const n = this.validateBytes(e);
3207
+ if (["connect", "connection:start"].includes(t)) {
3208
+ if (this.__internal__.serial.connected) return;
3209
+ await this.serialConnect();
3210
+ return;
3211
+ }
3212
+ this.__internal__.serial.queue.push({ bytes: n, action: t }), this.dispatch("internal:queue", {});
3213
+ }
3214
+ #w(e = 1) {
3215
+ this.__internal__.device_number = e, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e));
3216
+ }
3217
+ serialSetConnectionConstant(e = 1) {
3218
+ if (this.__internal__.bypassSerialBytesConnection) return this.__internal__.serial.bytes_connection;
3219
+ throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`);
3220
+ }
3221
+ serialMessage(e) {
3222
+ throw console.log(e), this.dispatch("serial:message", { code: e }), new Error("Method not implemented 'serialMessage'");
3223
+ }
3224
+ serialCorruptMessage(e) {
3225
+ throw console.log(e), this.dispatch("serial:corrupt-message", { code: e }), new Error("Method not implemented 'serialCorruptMessage'");
3226
+ }
3227
+ #v() {
3228
+ this.__internal__.last_error = {
3229
+ message: null,
3230
+ action: null,
3231
+ code: null,
3232
+ no_code: 0
3233
+ };
3234
+ }
3235
+ clearSerialQueue() {
3236
+ this.__internal__.serial.queue = [];
3237
+ }
3238
+ sumHex(e) {
3239
+ let t = 0;
3240
+ return e.forEach((n) => {
3241
+ t += parseInt(n, 16);
3242
+ }), t.toString(16);
3243
+ }
3244
+ toString() {
3245
+ return JSON.stringify({
3246
+ __class: this.typeDevice,
3247
+ device_number: this.deviceNumber,
3248
+ uuid: this.uuid,
3249
+ connected: this.isConnected,
3250
+ connection: this.__internal__.serial.bytes_connection
3251
+ });
3252
+ }
3253
+ softReload() {
3254
+ this.#v(), this.dispatch("serial:soft-reload", {});
3255
+ }
3256
+ async sendConnect() {
3257
+ if (!this.__internal__.serial.bytes_connection)
3258
+ throw new Error("No connection bytes defined");
3259
+ await this.appendToQueue(this.__internal__.serial.bytes_connection, "connect");
3260
+ }
3261
+ async sendCustomCode({ code: e = [] } = { code: [] }) {
3262
+ if (!e)
3263
+ throw new Error("No data to send");
3264
+ this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.validateBytes(e)), await this.appendToQueue(e, "custom");
3265
+ }
3266
+ stringToArrayHex(e) {
3267
+ return Array.from(e).map((t) => t.charCodeAt(0).toString(16));
3268
+ }
3269
+ stringToArrayBuffer(e, t = `
3270
+ `) {
3271
+ return this.parseStringToTextEncoder(e, t).buffer;
3272
+ }
3273
+ parseStringToTextEncoder(e = "", t = `
3274
+ `) {
3275
+ const n = new TextEncoder();
3276
+ return e += t, n.encode(e);
3277
+ }
3278
+ parseStringToBytes(e = "", t = `
3279
+ `) {
3280
+ const n = this.parseStringToTextEncoder(e, t);
3281
+ return Array.from(n).map((r) => r.toString(16));
3282
+ }
3283
+ parseUint8ToHex(e) {
3284
+ return Array.from(e).map((t) => t.toString(16).padStart(2, "0").toLowerCase());
3285
+ }
3286
+ parseHexToUint8(e) {
3287
+ return new Uint8Array(e.map((t) => parseInt(t, 16)));
3288
+ }
3289
+ stringArrayToUint8Array(e) {
3290
+ const t = [];
3291
+ return typeof e == "string" ? this.parseStringToTextEncoder(e).buffer : (e.forEach((n) => {
3292
+ const r = n.replace("0x", "");
3293
+ t.push(parseInt(r, 16));
3294
+ }), new Uint8Array(t));
3295
+ }
3296
+ parseUint8ArrayToString(e) {
3297
+ let t = new Uint8Array(0);
3298
+ e instanceof Uint8Array ? t = e : t = this.stringArrayToUint8Array(e), e = this.parseUint8ToHex(t);
3299
+ const n = e.map((r) => parseInt(r, 16));
3300
+ return this.__internal__.serial.response.replacer ? String.fromCharCode(...n).replace(this.__internal__.serial.response.replacer, "") : String.fromCharCode(...n);
3301
+ }
3302
+ hexToAscii(e) {
3303
+ const t = e.toString();
3304
+ let n = "";
3305
+ for (let r = 0; r < t.length; r += 2)
3306
+ n += String.fromCharCode(parseInt(t.substring(r, 2), 16));
3307
+ return n;
3308
+ }
3309
+ asciiToHex(e) {
3310
+ const t = [];
3311
+ for (let n = 0, r = e.length; n < r; n++) {
3312
+ const i = Number(e.charCodeAt(n)).toString(16);
3313
+ t.push(i);
3314
+ }
3315
+ return t.join("");
3316
+ }
3317
+ $checkAndDispatchConnection() {
3318
+ return this.isConnected;
3319
+ }
3320
+ }
3321
+ export {
3322
+ A,
3323
+ a,
3324
+ lt as u
3325
+ };