room-kit 1.0.1 → 1.0.5

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,3988 @@
1
+ "use strict";
2
+ (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __export = (target, all) => {
5
+ for (var name in all)
6
+ __defProp(target, name, { get: all[name], enumerable: true });
7
+ };
8
+
9
+ // node_modules/engine.io-parser/build/esm/commons.js
10
+ var PACKET_TYPES = /* @__PURE__ */ Object.create(null);
11
+ PACKET_TYPES["open"] = "0";
12
+ PACKET_TYPES["close"] = "1";
13
+ PACKET_TYPES["ping"] = "2";
14
+ PACKET_TYPES["pong"] = "3";
15
+ PACKET_TYPES["message"] = "4";
16
+ PACKET_TYPES["upgrade"] = "5";
17
+ PACKET_TYPES["noop"] = "6";
18
+ var PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
19
+ Object.keys(PACKET_TYPES).forEach((key) => {
20
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
21
+ });
22
+ var ERROR_PACKET = { type: "error", data: "parser error" };
23
+
24
+ // node_modules/engine.io-parser/build/esm/encodePacket.browser.js
25
+ var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
26
+ var withNativeArrayBuffer = typeof ArrayBuffer === "function";
27
+ var isView = (obj) => {
28
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
29
+ };
30
+ var encodePacket = ({ type, data }, supportsBinary, callback) => {
31
+ if (withNativeBlob && data instanceof Blob) {
32
+ if (supportsBinary) {
33
+ return callback(data);
34
+ } else {
35
+ return encodeBlobAsBase64(data, callback);
36
+ }
37
+ } else if (withNativeArrayBuffer && (data instanceof ArrayBuffer || isView(data))) {
38
+ if (supportsBinary) {
39
+ return callback(data);
40
+ } else {
41
+ return encodeBlobAsBase64(new Blob([data]), callback);
42
+ }
43
+ }
44
+ return callback(PACKET_TYPES[type] + (data || ""));
45
+ };
46
+ var encodeBlobAsBase64 = (data, callback) => {
47
+ const fileReader = new FileReader();
48
+ fileReader.onload = function() {
49
+ const content = fileReader.result.split(",")[1];
50
+ callback("b" + (content || ""));
51
+ };
52
+ return fileReader.readAsDataURL(data);
53
+ };
54
+ function toArray(data) {
55
+ if (data instanceof Uint8Array) {
56
+ return data;
57
+ } else if (data instanceof ArrayBuffer) {
58
+ return new Uint8Array(data);
59
+ } else {
60
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
61
+ }
62
+ }
63
+ var TEXT_ENCODER;
64
+ function encodePacketToBinary(packet, callback) {
65
+ if (withNativeBlob && packet.data instanceof Blob) {
66
+ return packet.data.arrayBuffer().then(toArray).then(callback);
67
+ } else if (withNativeArrayBuffer && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
68
+ return callback(toArray(packet.data));
69
+ }
70
+ encodePacket(packet, false, (encoded) => {
71
+ if (!TEXT_ENCODER) {
72
+ TEXT_ENCODER = new TextEncoder();
73
+ }
74
+ callback(TEXT_ENCODER.encode(encoded));
75
+ });
76
+ }
77
+
78
+ // node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js
79
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
80
+ var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
81
+ for (let i = 0; i < chars.length; i++) {
82
+ lookup[chars.charCodeAt(i)] = i;
83
+ }
84
+ var decode = (base64) => {
85
+ let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
86
+ if (base64[base64.length - 1] === "=") {
87
+ bufferLength--;
88
+ if (base64[base64.length - 2] === "=") {
89
+ bufferLength--;
90
+ }
91
+ }
92
+ const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
93
+ for (i = 0; i < len; i += 4) {
94
+ encoded1 = lookup[base64.charCodeAt(i)];
95
+ encoded2 = lookup[base64.charCodeAt(i + 1)];
96
+ encoded3 = lookup[base64.charCodeAt(i + 2)];
97
+ encoded4 = lookup[base64.charCodeAt(i + 3)];
98
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
99
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
100
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
101
+ }
102
+ return arraybuffer;
103
+ };
104
+
105
+ // node_modules/engine.io-parser/build/esm/decodePacket.browser.js
106
+ var withNativeArrayBuffer2 = typeof ArrayBuffer === "function";
107
+ var decodePacket = (encodedPacket, binaryType) => {
108
+ if (typeof encodedPacket !== "string") {
109
+ return {
110
+ type: "message",
111
+ data: mapBinary(encodedPacket, binaryType)
112
+ };
113
+ }
114
+ const type = encodedPacket.charAt(0);
115
+ if (type === "b") {
116
+ return {
117
+ type: "message",
118
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
119
+ };
120
+ }
121
+ const packetType = PACKET_TYPES_REVERSE[type];
122
+ if (!packetType) {
123
+ return ERROR_PACKET;
124
+ }
125
+ return encodedPacket.length > 1 ? {
126
+ type: PACKET_TYPES_REVERSE[type],
127
+ data: encodedPacket.substring(1)
128
+ } : {
129
+ type: PACKET_TYPES_REVERSE[type]
130
+ };
131
+ };
132
+ var decodeBase64Packet = (data, binaryType) => {
133
+ if (withNativeArrayBuffer2) {
134
+ const decoded = decode(data);
135
+ return mapBinary(decoded, binaryType);
136
+ } else {
137
+ return { base64: true, data };
138
+ }
139
+ };
140
+ var mapBinary = (data, binaryType) => {
141
+ switch (binaryType) {
142
+ case "blob":
143
+ if (data instanceof Blob) {
144
+ return data;
145
+ } else {
146
+ return new Blob([data]);
147
+ }
148
+ case "arraybuffer":
149
+ default:
150
+ if (data instanceof ArrayBuffer) {
151
+ return data;
152
+ } else {
153
+ return data.buffer;
154
+ }
155
+ }
156
+ };
157
+
158
+ // node_modules/engine.io-parser/build/esm/index.js
159
+ var SEPARATOR = String.fromCharCode(30);
160
+ var encodePayload = (packets, callback) => {
161
+ const length = packets.length;
162
+ const encodedPackets = new Array(length);
163
+ let count = 0;
164
+ packets.forEach((packet, i) => {
165
+ encodePacket(packet, false, (encodedPacket) => {
166
+ encodedPackets[i] = encodedPacket;
167
+ if (++count === length) {
168
+ callback(encodedPackets.join(SEPARATOR));
169
+ }
170
+ });
171
+ });
172
+ };
173
+ var decodePayload = (encodedPayload, binaryType) => {
174
+ const encodedPackets = encodedPayload.split(SEPARATOR);
175
+ const packets = [];
176
+ for (let i = 0; i < encodedPackets.length; i++) {
177
+ const decodedPacket = decodePacket(encodedPackets[i], binaryType);
178
+ packets.push(decodedPacket);
179
+ if (decodedPacket.type === "error") {
180
+ break;
181
+ }
182
+ }
183
+ return packets;
184
+ };
185
+ function createPacketEncoderStream() {
186
+ return new TransformStream({
187
+ transform(packet, controller) {
188
+ encodePacketToBinary(packet, (encodedPacket) => {
189
+ const payloadLength = encodedPacket.length;
190
+ let header;
191
+ if (payloadLength < 126) {
192
+ header = new Uint8Array(1);
193
+ new DataView(header.buffer).setUint8(0, payloadLength);
194
+ } else if (payloadLength < 65536) {
195
+ header = new Uint8Array(3);
196
+ const view = new DataView(header.buffer);
197
+ view.setUint8(0, 126);
198
+ view.setUint16(1, payloadLength);
199
+ } else {
200
+ header = new Uint8Array(9);
201
+ const view = new DataView(header.buffer);
202
+ view.setUint8(0, 127);
203
+ view.setBigUint64(1, BigInt(payloadLength));
204
+ }
205
+ if (packet.data && typeof packet.data !== "string") {
206
+ header[0] |= 128;
207
+ }
208
+ controller.enqueue(header);
209
+ controller.enqueue(encodedPacket);
210
+ });
211
+ }
212
+ });
213
+ }
214
+ var TEXT_DECODER;
215
+ function totalLength(chunks) {
216
+ return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
217
+ }
218
+ function concatChunks(chunks, size) {
219
+ if (chunks[0].length === size) {
220
+ return chunks.shift();
221
+ }
222
+ const buffer = new Uint8Array(size);
223
+ let j = 0;
224
+ for (let i = 0; i < size; i++) {
225
+ buffer[i] = chunks[0][j++];
226
+ if (j === chunks[0].length) {
227
+ chunks.shift();
228
+ j = 0;
229
+ }
230
+ }
231
+ if (chunks.length && j < chunks[0].length) {
232
+ chunks[0] = chunks[0].slice(j);
233
+ }
234
+ return buffer;
235
+ }
236
+ function createPacketDecoderStream(maxPayload, binaryType) {
237
+ if (!TEXT_DECODER) {
238
+ TEXT_DECODER = new TextDecoder();
239
+ }
240
+ const chunks = [];
241
+ let state = 0;
242
+ let expectedLength = -1;
243
+ let isBinary2 = false;
244
+ return new TransformStream({
245
+ transform(chunk, controller) {
246
+ chunks.push(chunk);
247
+ while (true) {
248
+ if (state === 0) {
249
+ if (totalLength(chunks) < 1) {
250
+ break;
251
+ }
252
+ const header = concatChunks(chunks, 1);
253
+ isBinary2 = (header[0] & 128) === 128;
254
+ expectedLength = header[0] & 127;
255
+ if (expectedLength < 126) {
256
+ state = 3;
257
+ } else if (expectedLength === 126) {
258
+ state = 1;
259
+ } else {
260
+ state = 2;
261
+ }
262
+ } else if (state === 1) {
263
+ if (totalLength(chunks) < 2) {
264
+ break;
265
+ }
266
+ const headerArray = concatChunks(chunks, 2);
267
+ expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
268
+ state = 3;
269
+ } else if (state === 2) {
270
+ if (totalLength(chunks) < 8) {
271
+ break;
272
+ }
273
+ const headerArray = concatChunks(chunks, 8);
274
+ const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
275
+ const n = view.getUint32(0);
276
+ if (n > Math.pow(2, 53 - 32) - 1) {
277
+ controller.enqueue(ERROR_PACKET);
278
+ break;
279
+ }
280
+ expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
281
+ state = 3;
282
+ } else {
283
+ if (totalLength(chunks) < expectedLength) {
284
+ break;
285
+ }
286
+ const data = concatChunks(chunks, expectedLength);
287
+ controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
288
+ state = 0;
289
+ }
290
+ if (expectedLength === 0 || expectedLength > maxPayload) {
291
+ controller.enqueue(ERROR_PACKET);
292
+ break;
293
+ }
294
+ }
295
+ }
296
+ });
297
+ }
298
+ var protocol = 4;
299
+
300
+ // node_modules/@socket.io/component-emitter/lib/esm/index.js
301
+ function Emitter(obj) {
302
+ if (obj) return mixin(obj);
303
+ }
304
+ function mixin(obj) {
305
+ for (var key in Emitter.prototype) {
306
+ obj[key] = Emitter.prototype[key];
307
+ }
308
+ return obj;
309
+ }
310
+ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
311
+ this._callbacks = this._callbacks || {};
312
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
313
+ return this;
314
+ };
315
+ Emitter.prototype.once = function(event, fn) {
316
+ function on2() {
317
+ this.off(event, on2);
318
+ fn.apply(this, arguments);
319
+ }
320
+ on2.fn = fn;
321
+ this.on(event, on2);
322
+ return this;
323
+ };
324
+ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
325
+ this._callbacks = this._callbacks || {};
326
+ if (0 == arguments.length) {
327
+ this._callbacks = {};
328
+ return this;
329
+ }
330
+ var callbacks = this._callbacks["$" + event];
331
+ if (!callbacks) return this;
332
+ if (1 == arguments.length) {
333
+ delete this._callbacks["$" + event];
334
+ return this;
335
+ }
336
+ var cb;
337
+ for (var i = 0; i < callbacks.length; i++) {
338
+ cb = callbacks[i];
339
+ if (cb === fn || cb.fn === fn) {
340
+ callbacks.splice(i, 1);
341
+ break;
342
+ }
343
+ }
344
+ if (callbacks.length === 0) {
345
+ delete this._callbacks["$" + event];
346
+ }
347
+ return this;
348
+ };
349
+ Emitter.prototype.emit = function(event) {
350
+ this._callbacks = this._callbacks || {};
351
+ var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
352
+ for (var i = 1; i < arguments.length; i++) {
353
+ args[i - 1] = arguments[i];
354
+ }
355
+ if (callbacks) {
356
+ callbacks = callbacks.slice(0);
357
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
358
+ callbacks[i].apply(this, args);
359
+ }
360
+ }
361
+ return this;
362
+ };
363
+ Emitter.prototype.emitReserved = Emitter.prototype.emit;
364
+ Emitter.prototype.listeners = function(event) {
365
+ this._callbacks = this._callbacks || {};
366
+ return this._callbacks["$" + event] || [];
367
+ };
368
+ Emitter.prototype.hasListeners = function(event) {
369
+ return !!this.listeners(event).length;
370
+ };
371
+
372
+ // node_modules/engine.io-client/build/esm/globals.js
373
+ var nextTick = (() => {
374
+ const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
375
+ if (isPromiseAvailable) {
376
+ return (cb) => Promise.resolve().then(cb);
377
+ } else {
378
+ return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
379
+ }
380
+ })();
381
+ var globalThisShim = (() => {
382
+ if (typeof self !== "undefined") {
383
+ return self;
384
+ } else if (typeof window !== "undefined") {
385
+ return window;
386
+ } else {
387
+ return Function("return this")();
388
+ }
389
+ })();
390
+ var defaultBinaryType = "arraybuffer";
391
+ function createCookieJar() {
392
+ }
393
+
394
+ // node_modules/engine.io-client/build/esm/util.js
395
+ function pick(obj, ...attr) {
396
+ return attr.reduce((acc, k) => {
397
+ if (obj.hasOwnProperty(k)) {
398
+ acc[k] = obj[k];
399
+ }
400
+ return acc;
401
+ }, {});
402
+ }
403
+ var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
404
+ var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
405
+ function installTimerFunctions(obj, opts) {
406
+ if (opts.useNativeTimers) {
407
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
408
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
409
+ } else {
410
+ obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
411
+ obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
412
+ }
413
+ }
414
+ var BASE64_OVERHEAD = 1.33;
415
+ function byteLength(obj) {
416
+ if (typeof obj === "string") {
417
+ return utf8Length(obj);
418
+ }
419
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
420
+ }
421
+ function utf8Length(str) {
422
+ let c = 0, length = 0;
423
+ for (let i = 0, l = str.length; i < l; i++) {
424
+ c = str.charCodeAt(i);
425
+ if (c < 128) {
426
+ length += 1;
427
+ } else if (c < 2048) {
428
+ length += 2;
429
+ } else if (c < 55296 || c >= 57344) {
430
+ length += 3;
431
+ } else {
432
+ i++;
433
+ length += 4;
434
+ }
435
+ }
436
+ return length;
437
+ }
438
+ function randomString() {
439
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
440
+ }
441
+
442
+ // node_modules/engine.io-client/build/esm/contrib/parseqs.js
443
+ function encode(obj) {
444
+ let str = "";
445
+ for (let i in obj) {
446
+ if (obj.hasOwnProperty(i)) {
447
+ if (str.length)
448
+ str += "&";
449
+ str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
450
+ }
451
+ }
452
+ return str;
453
+ }
454
+ function decode2(qs) {
455
+ let qry = {};
456
+ let pairs = qs.split("&");
457
+ for (let i = 0, l = pairs.length; i < l; i++) {
458
+ let pair = pairs[i].split("=");
459
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
460
+ }
461
+ return qry;
462
+ }
463
+
464
+ // node_modules/engine.io-client/build/esm/transport.js
465
+ var TransportError = class extends Error {
466
+ constructor(reason, description, context) {
467
+ super(reason);
468
+ this.description = description;
469
+ this.context = context;
470
+ this.type = "TransportError";
471
+ }
472
+ };
473
+ var Transport = class extends Emitter {
474
+ /**
475
+ * Transport abstract constructor.
476
+ *
477
+ * @param {Object} opts - options
478
+ * @protected
479
+ */
480
+ constructor(opts) {
481
+ super();
482
+ this.writable = false;
483
+ installTimerFunctions(this, opts);
484
+ this.opts = opts;
485
+ this.query = opts.query;
486
+ this.socket = opts.socket;
487
+ this.supportsBinary = !opts.forceBase64;
488
+ }
489
+ /**
490
+ * Emits an error.
491
+ *
492
+ * @param {String} reason
493
+ * @param description
494
+ * @param context - the error context
495
+ * @return {Transport} for chaining
496
+ * @protected
497
+ */
498
+ onError(reason, description, context) {
499
+ super.emitReserved("error", new TransportError(reason, description, context));
500
+ return this;
501
+ }
502
+ /**
503
+ * Opens the transport.
504
+ */
505
+ open() {
506
+ this.readyState = "opening";
507
+ this.doOpen();
508
+ return this;
509
+ }
510
+ /**
511
+ * Closes the transport.
512
+ */
513
+ close() {
514
+ if (this.readyState === "opening" || this.readyState === "open") {
515
+ this.doClose();
516
+ this.onClose();
517
+ }
518
+ return this;
519
+ }
520
+ /**
521
+ * Sends multiple packets.
522
+ *
523
+ * @param {Array} packets
524
+ */
525
+ send(packets) {
526
+ if (this.readyState === "open") {
527
+ this.write(packets);
528
+ } else {
529
+ }
530
+ }
531
+ /**
532
+ * Called upon open
533
+ *
534
+ * @protected
535
+ */
536
+ onOpen() {
537
+ this.readyState = "open";
538
+ this.writable = true;
539
+ super.emitReserved("open");
540
+ }
541
+ /**
542
+ * Called with data.
543
+ *
544
+ * @param {String} data
545
+ * @protected
546
+ */
547
+ onData(data) {
548
+ const packet = decodePacket(data, this.socket.binaryType);
549
+ this.onPacket(packet);
550
+ }
551
+ /**
552
+ * Called with a decoded packet.
553
+ *
554
+ * @protected
555
+ */
556
+ onPacket(packet) {
557
+ super.emitReserved("packet", packet);
558
+ }
559
+ /**
560
+ * Called upon close.
561
+ *
562
+ * @protected
563
+ */
564
+ onClose(details) {
565
+ this.readyState = "closed";
566
+ super.emitReserved("close", details);
567
+ }
568
+ /**
569
+ * Pauses the transport, in order not to lose packets during an upgrade.
570
+ *
571
+ * @param onPause
572
+ */
573
+ pause(onPause) {
574
+ }
575
+ createUri(schema, query = {}) {
576
+ return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
577
+ }
578
+ _hostname() {
579
+ const hostname = this.opts.hostname;
580
+ return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
581
+ }
582
+ _port() {
583
+ if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
584
+ return ":" + this.opts.port;
585
+ } else {
586
+ return "";
587
+ }
588
+ }
589
+ _query(query) {
590
+ const encodedQuery = encode(query);
591
+ return encodedQuery.length ? "?" + encodedQuery : "";
592
+ }
593
+ };
594
+
595
+ // node_modules/engine.io-client/build/esm/transports/polling.js
596
+ var Polling = class extends Transport {
597
+ constructor() {
598
+ super(...arguments);
599
+ this._polling = false;
600
+ }
601
+ get name() {
602
+ return "polling";
603
+ }
604
+ /**
605
+ * Opens the socket (triggers polling). We write a PING message to determine
606
+ * when the transport is open.
607
+ *
608
+ * @protected
609
+ */
610
+ doOpen() {
611
+ this._poll();
612
+ }
613
+ /**
614
+ * Pauses polling.
615
+ *
616
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
617
+ * @package
618
+ */
619
+ pause(onPause) {
620
+ this.readyState = "pausing";
621
+ const pause = () => {
622
+ this.readyState = "paused";
623
+ onPause();
624
+ };
625
+ if (this._polling || !this.writable) {
626
+ let total = 0;
627
+ if (this._polling) {
628
+ total++;
629
+ this.once("pollComplete", function() {
630
+ --total || pause();
631
+ });
632
+ }
633
+ if (!this.writable) {
634
+ total++;
635
+ this.once("drain", function() {
636
+ --total || pause();
637
+ });
638
+ }
639
+ } else {
640
+ pause();
641
+ }
642
+ }
643
+ /**
644
+ * Starts polling cycle.
645
+ *
646
+ * @private
647
+ */
648
+ _poll() {
649
+ this._polling = true;
650
+ this.doPoll();
651
+ this.emitReserved("poll");
652
+ }
653
+ /**
654
+ * Overloads onData to detect payloads.
655
+ *
656
+ * @protected
657
+ */
658
+ onData(data) {
659
+ const callback = (packet) => {
660
+ if ("opening" === this.readyState && packet.type === "open") {
661
+ this.onOpen();
662
+ }
663
+ if ("close" === packet.type) {
664
+ this.onClose({ description: "transport closed by the server" });
665
+ return false;
666
+ }
667
+ this.onPacket(packet);
668
+ };
669
+ decodePayload(data, this.socket.binaryType).forEach(callback);
670
+ if ("closed" !== this.readyState) {
671
+ this._polling = false;
672
+ this.emitReserved("pollComplete");
673
+ if ("open" === this.readyState) {
674
+ this._poll();
675
+ } else {
676
+ }
677
+ }
678
+ }
679
+ /**
680
+ * For polling, send a close packet.
681
+ *
682
+ * @protected
683
+ */
684
+ doClose() {
685
+ const close = () => {
686
+ this.write([{ type: "close" }]);
687
+ };
688
+ if ("open" === this.readyState) {
689
+ close();
690
+ } else {
691
+ this.once("open", close);
692
+ }
693
+ }
694
+ /**
695
+ * Writes a packets payload.
696
+ *
697
+ * @param {Array} packets - data packets
698
+ * @protected
699
+ */
700
+ write(packets) {
701
+ this.writable = false;
702
+ encodePayload(packets, (data) => {
703
+ this.doWrite(data, () => {
704
+ this.writable = true;
705
+ this.emitReserved("drain");
706
+ });
707
+ });
708
+ }
709
+ /**
710
+ * Generates uri for connection.
711
+ *
712
+ * @private
713
+ */
714
+ uri() {
715
+ const schema = this.opts.secure ? "https" : "http";
716
+ const query = this.query || {};
717
+ if (false !== this.opts.timestampRequests) {
718
+ query[this.opts.timestampParam] = randomString();
719
+ }
720
+ if (!this.supportsBinary && !query.sid) {
721
+ query.b64 = 1;
722
+ }
723
+ return this.createUri(schema, query);
724
+ }
725
+ };
726
+
727
+ // node_modules/engine.io-client/build/esm/contrib/has-cors.js
728
+ var value = false;
729
+ try {
730
+ value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
731
+ } catch (err) {
732
+ }
733
+ var hasCORS = value;
734
+
735
+ // node_modules/engine.io-client/build/esm/transports/polling-xhr.js
736
+ function empty() {
737
+ }
738
+ var BaseXHR = class extends Polling {
739
+ /**
740
+ * XHR Polling constructor.
741
+ *
742
+ * @param {Object} opts
743
+ * @package
744
+ */
745
+ constructor(opts) {
746
+ super(opts);
747
+ if (typeof location !== "undefined") {
748
+ const isSSL = "https:" === location.protocol;
749
+ let port = location.port;
750
+ if (!port) {
751
+ port = isSSL ? "443" : "80";
752
+ }
753
+ this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
754
+ }
755
+ }
756
+ /**
757
+ * Sends data.
758
+ *
759
+ * @param {String} data to send.
760
+ * @param {Function} called upon flush.
761
+ * @private
762
+ */
763
+ doWrite(data, fn) {
764
+ const req = this.request({
765
+ method: "POST",
766
+ data
767
+ });
768
+ req.on("success", fn);
769
+ req.on("error", (xhrStatus, context) => {
770
+ this.onError("xhr post error", xhrStatus, context);
771
+ });
772
+ }
773
+ /**
774
+ * Starts a poll cycle.
775
+ *
776
+ * @private
777
+ */
778
+ doPoll() {
779
+ const req = this.request();
780
+ req.on("data", this.onData.bind(this));
781
+ req.on("error", (xhrStatus, context) => {
782
+ this.onError("xhr poll error", xhrStatus, context);
783
+ });
784
+ this.pollXhr = req;
785
+ }
786
+ };
787
+ var Request = class _Request extends Emitter {
788
+ /**
789
+ * Request constructor
790
+ *
791
+ * @param {Object} options
792
+ * @package
793
+ */
794
+ constructor(createRequest, uri, opts) {
795
+ super();
796
+ this.createRequest = createRequest;
797
+ installTimerFunctions(this, opts);
798
+ this._opts = opts;
799
+ this._method = opts.method || "GET";
800
+ this._uri = uri;
801
+ this._data = void 0 !== opts.data ? opts.data : null;
802
+ this._create();
803
+ }
804
+ /**
805
+ * Creates the XHR object and sends the request.
806
+ *
807
+ * @private
808
+ */
809
+ _create() {
810
+ var _a;
811
+ const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
812
+ opts.xdomain = !!this._opts.xd;
813
+ const xhr = this._xhr = this.createRequest(opts);
814
+ try {
815
+ xhr.open(this._method, this._uri, true);
816
+ try {
817
+ if (this._opts.extraHeaders) {
818
+ xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
819
+ for (let i in this._opts.extraHeaders) {
820
+ if (this._opts.extraHeaders.hasOwnProperty(i)) {
821
+ xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
822
+ }
823
+ }
824
+ }
825
+ } catch (e) {
826
+ }
827
+ if ("POST" === this._method) {
828
+ try {
829
+ xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
830
+ } catch (e) {
831
+ }
832
+ }
833
+ try {
834
+ xhr.setRequestHeader("Accept", "*/*");
835
+ } catch (e) {
836
+ }
837
+ (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
838
+ if ("withCredentials" in xhr) {
839
+ xhr.withCredentials = this._opts.withCredentials;
840
+ }
841
+ if (this._opts.requestTimeout) {
842
+ xhr.timeout = this._opts.requestTimeout;
843
+ }
844
+ xhr.onreadystatechange = () => {
845
+ var _a2;
846
+ if (xhr.readyState === 3) {
847
+ (_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.parseCookies(
848
+ // @ts-ignore
849
+ xhr.getResponseHeader("set-cookie")
850
+ );
851
+ }
852
+ if (4 !== xhr.readyState)
853
+ return;
854
+ if (200 === xhr.status || 1223 === xhr.status) {
855
+ this._onLoad();
856
+ } else {
857
+ this.setTimeoutFn(() => {
858
+ this._onError(typeof xhr.status === "number" ? xhr.status : 0);
859
+ }, 0);
860
+ }
861
+ };
862
+ xhr.send(this._data);
863
+ } catch (e) {
864
+ this.setTimeoutFn(() => {
865
+ this._onError(e);
866
+ }, 0);
867
+ return;
868
+ }
869
+ if (typeof document !== "undefined") {
870
+ this._index = _Request.requestsCount++;
871
+ _Request.requests[this._index] = this;
872
+ }
873
+ }
874
+ /**
875
+ * Called upon error.
876
+ *
877
+ * @private
878
+ */
879
+ _onError(err) {
880
+ this.emitReserved("error", err, this._xhr);
881
+ this._cleanup(true);
882
+ }
883
+ /**
884
+ * Cleans up house.
885
+ *
886
+ * @private
887
+ */
888
+ _cleanup(fromError) {
889
+ if ("undefined" === typeof this._xhr || null === this._xhr) {
890
+ return;
891
+ }
892
+ this._xhr.onreadystatechange = empty;
893
+ if (fromError) {
894
+ try {
895
+ this._xhr.abort();
896
+ } catch (e) {
897
+ }
898
+ }
899
+ if (typeof document !== "undefined") {
900
+ delete _Request.requests[this._index];
901
+ }
902
+ this._xhr = null;
903
+ }
904
+ /**
905
+ * Called upon load.
906
+ *
907
+ * @private
908
+ */
909
+ _onLoad() {
910
+ const data = this._xhr.responseText;
911
+ if (data !== null) {
912
+ this.emitReserved("data", data);
913
+ this.emitReserved("success");
914
+ this._cleanup();
915
+ }
916
+ }
917
+ /**
918
+ * Aborts the request.
919
+ *
920
+ * @package
921
+ */
922
+ abort() {
923
+ this._cleanup();
924
+ }
925
+ };
926
+ Request.requestsCount = 0;
927
+ Request.requests = {};
928
+ if (typeof document !== "undefined") {
929
+ if (typeof attachEvent === "function") {
930
+ attachEvent("onunload", unloadHandler);
931
+ } else if (typeof addEventListener === "function") {
932
+ const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
933
+ addEventListener(terminationEvent, unloadHandler, false);
934
+ }
935
+ }
936
+ function unloadHandler() {
937
+ for (let i in Request.requests) {
938
+ if (Request.requests.hasOwnProperty(i)) {
939
+ Request.requests[i].abort();
940
+ }
941
+ }
942
+ }
943
+ var hasXHR2 = (function() {
944
+ const xhr = newRequest({
945
+ xdomain: false
946
+ });
947
+ return xhr && xhr.responseType !== null;
948
+ })();
949
+ var XHR = class extends BaseXHR {
950
+ constructor(opts) {
951
+ super(opts);
952
+ const forceBase64 = opts && opts.forceBase64;
953
+ this.supportsBinary = hasXHR2 && !forceBase64;
954
+ }
955
+ request(opts = {}) {
956
+ Object.assign(opts, { xd: this.xd }, this.opts);
957
+ return new Request(newRequest, this.uri(), opts);
958
+ }
959
+ };
960
+ function newRequest(opts) {
961
+ const xdomain = opts.xdomain;
962
+ try {
963
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
964
+ return new XMLHttpRequest();
965
+ }
966
+ } catch (e) {
967
+ }
968
+ if (!xdomain) {
969
+ try {
970
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
971
+ } catch (e) {
972
+ }
973
+ }
974
+ }
975
+
976
+ // node_modules/engine.io-client/build/esm/transports/websocket.js
977
+ var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
978
+ var BaseWS = class extends Transport {
979
+ get name() {
980
+ return "websocket";
981
+ }
982
+ doOpen() {
983
+ const uri = this.uri();
984
+ const protocols = this.opts.protocols;
985
+ const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
986
+ if (this.opts.extraHeaders) {
987
+ opts.headers = this.opts.extraHeaders;
988
+ }
989
+ try {
990
+ this.ws = this.createSocket(uri, protocols, opts);
991
+ } catch (err) {
992
+ return this.emitReserved("error", err);
993
+ }
994
+ this.ws.binaryType = this.socket.binaryType;
995
+ this.addEventListeners();
996
+ }
997
+ /**
998
+ * Adds event listeners to the socket
999
+ *
1000
+ * @private
1001
+ */
1002
+ addEventListeners() {
1003
+ this.ws.onopen = () => {
1004
+ if (this.opts.autoUnref) {
1005
+ this.ws._socket.unref();
1006
+ }
1007
+ this.onOpen();
1008
+ };
1009
+ this.ws.onclose = (closeEvent) => this.onClose({
1010
+ description: "websocket connection closed",
1011
+ context: closeEvent
1012
+ });
1013
+ this.ws.onmessage = (ev) => this.onData(ev.data);
1014
+ this.ws.onerror = (e) => this.onError("websocket error", e);
1015
+ }
1016
+ write(packets) {
1017
+ this.writable = false;
1018
+ for (let i = 0; i < packets.length; i++) {
1019
+ const packet = packets[i];
1020
+ const lastPacket = i === packets.length - 1;
1021
+ encodePacket(packet, this.supportsBinary, (data) => {
1022
+ try {
1023
+ this.doWrite(packet, data);
1024
+ } catch (e) {
1025
+ }
1026
+ if (lastPacket) {
1027
+ nextTick(() => {
1028
+ this.writable = true;
1029
+ this.emitReserved("drain");
1030
+ }, this.setTimeoutFn);
1031
+ }
1032
+ });
1033
+ }
1034
+ }
1035
+ doClose() {
1036
+ if (typeof this.ws !== "undefined") {
1037
+ this.ws.onerror = () => {
1038
+ };
1039
+ this.ws.close();
1040
+ this.ws = null;
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Generates uri for connection.
1045
+ *
1046
+ * @private
1047
+ */
1048
+ uri() {
1049
+ const schema = this.opts.secure ? "wss" : "ws";
1050
+ const query = this.query || {};
1051
+ if (this.opts.timestampRequests) {
1052
+ query[this.opts.timestampParam] = randomString();
1053
+ }
1054
+ if (!this.supportsBinary) {
1055
+ query.b64 = 1;
1056
+ }
1057
+ return this.createUri(schema, query);
1058
+ }
1059
+ };
1060
+ var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
1061
+ var WS = class extends BaseWS {
1062
+ createSocket(uri, protocols, opts) {
1063
+ return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
1064
+ }
1065
+ doWrite(_packet, data) {
1066
+ this.ws.send(data);
1067
+ }
1068
+ };
1069
+
1070
+ // node_modules/engine.io-client/build/esm/transports/webtransport.js
1071
+ var WT = class extends Transport {
1072
+ get name() {
1073
+ return "webtransport";
1074
+ }
1075
+ doOpen() {
1076
+ try {
1077
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
1078
+ } catch (err) {
1079
+ return this.emitReserved("error", err);
1080
+ }
1081
+ this._transport.closed.then(() => {
1082
+ this.onClose();
1083
+ }).catch((err) => {
1084
+ this.onError("webtransport error", err);
1085
+ });
1086
+ this._transport.ready.then(() => {
1087
+ this._transport.createBidirectionalStream().then((stream) => {
1088
+ const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
1089
+ const reader = stream.readable.pipeThrough(decoderStream).getReader();
1090
+ const encoderStream = createPacketEncoderStream();
1091
+ encoderStream.readable.pipeTo(stream.writable);
1092
+ this._writer = encoderStream.writable.getWriter();
1093
+ const read = () => {
1094
+ reader.read().then(({ done, value: value2 }) => {
1095
+ if (done) {
1096
+ return;
1097
+ }
1098
+ this.onPacket(value2);
1099
+ read();
1100
+ }).catch((err) => {
1101
+ });
1102
+ };
1103
+ read();
1104
+ const packet = { type: "open" };
1105
+ if (this.query.sid) {
1106
+ packet.data = `{"sid":"${this.query.sid}"}`;
1107
+ }
1108
+ this._writer.write(packet).then(() => this.onOpen());
1109
+ });
1110
+ });
1111
+ }
1112
+ write(packets) {
1113
+ this.writable = false;
1114
+ for (let i = 0; i < packets.length; i++) {
1115
+ const packet = packets[i];
1116
+ const lastPacket = i === packets.length - 1;
1117
+ this._writer.write(packet).then(() => {
1118
+ if (lastPacket) {
1119
+ nextTick(() => {
1120
+ this.writable = true;
1121
+ this.emitReserved("drain");
1122
+ }, this.setTimeoutFn);
1123
+ }
1124
+ });
1125
+ }
1126
+ }
1127
+ doClose() {
1128
+ var _a;
1129
+ (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
1130
+ }
1131
+ };
1132
+
1133
+ // node_modules/engine.io-client/build/esm/transports/index.js
1134
+ var transports = {
1135
+ websocket: WS,
1136
+ webtransport: WT,
1137
+ polling: XHR
1138
+ };
1139
+
1140
+ // node_modules/engine.io-client/build/esm/contrib/parseuri.js
1141
+ var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
1142
+ var parts = [
1143
+ "source",
1144
+ "protocol",
1145
+ "authority",
1146
+ "userInfo",
1147
+ "user",
1148
+ "password",
1149
+ "host",
1150
+ "port",
1151
+ "relative",
1152
+ "path",
1153
+ "directory",
1154
+ "file",
1155
+ "query",
1156
+ "anchor"
1157
+ ];
1158
+ function parse(str) {
1159
+ if (str.length > 8e3) {
1160
+ throw "URI too long";
1161
+ }
1162
+ const src = str, b = str.indexOf("["), e = str.indexOf("]");
1163
+ if (b != -1 && e != -1) {
1164
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
1165
+ }
1166
+ let m = re.exec(str || ""), uri = {}, i = 14;
1167
+ while (i--) {
1168
+ uri[parts[i]] = m[i] || "";
1169
+ }
1170
+ if (b != -1 && e != -1) {
1171
+ uri.source = src;
1172
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
1173
+ uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
1174
+ uri.ipv6uri = true;
1175
+ }
1176
+ uri.pathNames = pathNames(uri, uri["path"]);
1177
+ uri.queryKey = queryKey(uri, uri["query"]);
1178
+ return uri;
1179
+ }
1180
+ function pathNames(obj, path) {
1181
+ const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
1182
+ if (path.slice(0, 1) == "/" || path.length === 0) {
1183
+ names.splice(0, 1);
1184
+ }
1185
+ if (path.slice(-1) == "/") {
1186
+ names.splice(names.length - 1, 1);
1187
+ }
1188
+ return names;
1189
+ }
1190
+ function queryKey(uri, query) {
1191
+ const data = {};
1192
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
1193
+ if ($1) {
1194
+ data[$1] = $2;
1195
+ }
1196
+ });
1197
+ return data;
1198
+ }
1199
+
1200
+ // node_modules/engine.io-client/build/esm/socket.js
1201
+ var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
1202
+ var OFFLINE_EVENT_LISTENERS = [];
1203
+ if (withEventListeners) {
1204
+ addEventListener("offline", () => {
1205
+ OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
1206
+ }, false);
1207
+ }
1208
+ var SocketWithoutUpgrade = class _SocketWithoutUpgrade extends Emitter {
1209
+ /**
1210
+ * Socket constructor.
1211
+ *
1212
+ * @param {String|Object} uri - uri or options
1213
+ * @param {Object} opts - options
1214
+ */
1215
+ constructor(uri, opts) {
1216
+ super();
1217
+ this.binaryType = defaultBinaryType;
1218
+ this.writeBuffer = [];
1219
+ this._prevBufferLen = 0;
1220
+ this._pingInterval = -1;
1221
+ this._pingTimeout = -1;
1222
+ this._maxPayload = -1;
1223
+ this._pingTimeoutTime = Infinity;
1224
+ if (uri && "object" === typeof uri) {
1225
+ opts = uri;
1226
+ uri = null;
1227
+ }
1228
+ if (uri) {
1229
+ const parsedUri = parse(uri);
1230
+ opts.hostname = parsedUri.host;
1231
+ opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
1232
+ opts.port = parsedUri.port;
1233
+ if (parsedUri.query)
1234
+ opts.query = parsedUri.query;
1235
+ } else if (opts.host) {
1236
+ opts.hostname = parse(opts.host).host;
1237
+ }
1238
+ installTimerFunctions(this, opts);
1239
+ this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
1240
+ if (opts.hostname && !opts.port) {
1241
+ opts.port = this.secure ? "443" : "80";
1242
+ }
1243
+ this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
1244
+ this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
1245
+ this.transports = [];
1246
+ this._transportsByName = {};
1247
+ opts.transports.forEach((t) => {
1248
+ const transportName = t.prototype.name;
1249
+ this.transports.push(transportName);
1250
+ this._transportsByName[transportName] = t;
1251
+ });
1252
+ this.opts = Object.assign({
1253
+ path: "/engine.io",
1254
+ agent: false,
1255
+ withCredentials: false,
1256
+ upgrade: true,
1257
+ timestampParam: "t",
1258
+ rememberUpgrade: false,
1259
+ addTrailingSlash: true,
1260
+ rejectUnauthorized: true,
1261
+ perMessageDeflate: {
1262
+ threshold: 1024
1263
+ },
1264
+ transportOptions: {},
1265
+ closeOnBeforeunload: false
1266
+ }, opts);
1267
+ this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
1268
+ if (typeof this.opts.query === "string") {
1269
+ this.opts.query = decode2(this.opts.query);
1270
+ }
1271
+ if (withEventListeners) {
1272
+ if (this.opts.closeOnBeforeunload) {
1273
+ this._beforeunloadEventListener = () => {
1274
+ if (this.transport) {
1275
+ this.transport.removeAllListeners();
1276
+ this.transport.close();
1277
+ }
1278
+ };
1279
+ addEventListener("beforeunload", this._beforeunloadEventListener, false);
1280
+ }
1281
+ if (this.hostname !== "localhost") {
1282
+ this._offlineEventListener = () => {
1283
+ this._onClose("transport close", {
1284
+ description: "network connection lost"
1285
+ });
1286
+ };
1287
+ OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
1288
+ }
1289
+ }
1290
+ if (this.opts.withCredentials) {
1291
+ this._cookieJar = createCookieJar();
1292
+ }
1293
+ this._open();
1294
+ }
1295
+ /**
1296
+ * Creates transport of the given type.
1297
+ *
1298
+ * @param {String} name - transport name
1299
+ * @return {Transport}
1300
+ * @private
1301
+ */
1302
+ createTransport(name) {
1303
+ const query = Object.assign({}, this.opts.query);
1304
+ query.EIO = protocol;
1305
+ query.transport = name;
1306
+ if (this.id)
1307
+ query.sid = this.id;
1308
+ const opts = Object.assign({}, this.opts, {
1309
+ query,
1310
+ socket: this,
1311
+ hostname: this.hostname,
1312
+ secure: this.secure,
1313
+ port: this.port
1314
+ }, this.opts.transportOptions[name]);
1315
+ return new this._transportsByName[name](opts);
1316
+ }
1317
+ /**
1318
+ * Initializes transport to use and starts probe.
1319
+ *
1320
+ * @private
1321
+ */
1322
+ _open() {
1323
+ if (this.transports.length === 0) {
1324
+ this.setTimeoutFn(() => {
1325
+ this.emitReserved("error", "No transports available");
1326
+ }, 0);
1327
+ return;
1328
+ }
1329
+ const transportName = this.opts.rememberUpgrade && _SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
1330
+ this.readyState = "opening";
1331
+ const transport = this.createTransport(transportName);
1332
+ transport.open();
1333
+ this.setTransport(transport);
1334
+ }
1335
+ /**
1336
+ * Sets the current transport. Disables the existing one (if any).
1337
+ *
1338
+ * @private
1339
+ */
1340
+ setTransport(transport) {
1341
+ if (this.transport) {
1342
+ this.transport.removeAllListeners();
1343
+ }
1344
+ this.transport = transport;
1345
+ transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
1346
+ }
1347
+ /**
1348
+ * Called when connection is deemed open.
1349
+ *
1350
+ * @private
1351
+ */
1352
+ onOpen() {
1353
+ this.readyState = "open";
1354
+ _SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
1355
+ this.emitReserved("open");
1356
+ this.flush();
1357
+ }
1358
+ /**
1359
+ * Handles a packet.
1360
+ *
1361
+ * @private
1362
+ */
1363
+ _onPacket(packet) {
1364
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
1365
+ this.emitReserved("packet", packet);
1366
+ this.emitReserved("heartbeat");
1367
+ switch (packet.type) {
1368
+ case "open":
1369
+ this.onHandshake(JSON.parse(packet.data));
1370
+ break;
1371
+ case "ping":
1372
+ this._sendPacket("pong");
1373
+ this.emitReserved("ping");
1374
+ this.emitReserved("pong");
1375
+ this._resetPingTimeout();
1376
+ break;
1377
+ case "error":
1378
+ const err = new Error("server error");
1379
+ err.code = packet.data;
1380
+ this._onError(err);
1381
+ break;
1382
+ case "message":
1383
+ this.emitReserved("data", packet.data);
1384
+ this.emitReserved("message", packet.data);
1385
+ break;
1386
+ }
1387
+ } else {
1388
+ }
1389
+ }
1390
+ /**
1391
+ * Called upon handshake completion.
1392
+ *
1393
+ * @param {Object} data - handshake obj
1394
+ * @private
1395
+ */
1396
+ onHandshake(data) {
1397
+ this.emitReserved("handshake", data);
1398
+ this.id = data.sid;
1399
+ this.transport.query.sid = data.sid;
1400
+ this._pingInterval = data.pingInterval;
1401
+ this._pingTimeout = data.pingTimeout;
1402
+ this._maxPayload = data.maxPayload;
1403
+ this.onOpen();
1404
+ if ("closed" === this.readyState)
1405
+ return;
1406
+ this._resetPingTimeout();
1407
+ }
1408
+ /**
1409
+ * Sets and resets ping timeout timer based on server pings.
1410
+ *
1411
+ * @private
1412
+ */
1413
+ _resetPingTimeout() {
1414
+ this.clearTimeoutFn(this._pingTimeoutTimer);
1415
+ const delay = this._pingInterval + this._pingTimeout;
1416
+ this._pingTimeoutTime = Date.now() + delay;
1417
+ this._pingTimeoutTimer = this.setTimeoutFn(() => {
1418
+ this._onClose("ping timeout");
1419
+ }, delay);
1420
+ if (this.opts.autoUnref) {
1421
+ this._pingTimeoutTimer.unref();
1422
+ }
1423
+ }
1424
+ /**
1425
+ * Called on `drain` event
1426
+ *
1427
+ * @private
1428
+ */
1429
+ _onDrain() {
1430
+ this.writeBuffer.splice(0, this._prevBufferLen);
1431
+ this._prevBufferLen = 0;
1432
+ if (0 === this.writeBuffer.length) {
1433
+ this.emitReserved("drain");
1434
+ } else {
1435
+ this.flush();
1436
+ }
1437
+ }
1438
+ /**
1439
+ * Flush write buffers.
1440
+ *
1441
+ * @private
1442
+ */
1443
+ flush() {
1444
+ if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
1445
+ const packets = this._getWritablePackets();
1446
+ this.transport.send(packets);
1447
+ this._prevBufferLen = packets.length;
1448
+ this.emitReserved("flush");
1449
+ }
1450
+ }
1451
+ /**
1452
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
1453
+ * long-polling)
1454
+ *
1455
+ * @private
1456
+ */
1457
+ _getWritablePackets() {
1458
+ const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
1459
+ if (!shouldCheckPayloadSize) {
1460
+ return this.writeBuffer;
1461
+ }
1462
+ let payloadSize = 1;
1463
+ for (let i = 0; i < this.writeBuffer.length; i++) {
1464
+ const data = this.writeBuffer[i].data;
1465
+ if (data) {
1466
+ payloadSize += byteLength(data);
1467
+ }
1468
+ if (i > 0 && payloadSize > this._maxPayload) {
1469
+ return this.writeBuffer.slice(0, i);
1470
+ }
1471
+ payloadSize += 2;
1472
+ }
1473
+ return this.writeBuffer;
1474
+ }
1475
+ /**
1476
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
1477
+ *
1478
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
1479
+ * `write()` method then the message would not be buffered by the Socket.IO client.
1480
+ *
1481
+ * @return {boolean}
1482
+ * @private
1483
+ */
1484
+ /* private */
1485
+ _hasPingExpired() {
1486
+ if (!this._pingTimeoutTime)
1487
+ return true;
1488
+ const hasExpired = Date.now() > this._pingTimeoutTime;
1489
+ if (hasExpired) {
1490
+ this._pingTimeoutTime = 0;
1491
+ nextTick(() => {
1492
+ this._onClose("ping timeout");
1493
+ }, this.setTimeoutFn);
1494
+ }
1495
+ return hasExpired;
1496
+ }
1497
+ /**
1498
+ * Sends a message.
1499
+ *
1500
+ * @param {String} msg - message.
1501
+ * @param {Object} options.
1502
+ * @param {Function} fn - callback function.
1503
+ * @return {Socket} for chaining.
1504
+ */
1505
+ write(msg, options, fn) {
1506
+ this._sendPacket("message", msg, options, fn);
1507
+ return this;
1508
+ }
1509
+ /**
1510
+ * Sends a message. Alias of {@link Socket#write}.
1511
+ *
1512
+ * @param {String} msg - message.
1513
+ * @param {Object} options.
1514
+ * @param {Function} fn - callback function.
1515
+ * @return {Socket} for chaining.
1516
+ */
1517
+ send(msg, options, fn) {
1518
+ this._sendPacket("message", msg, options, fn);
1519
+ return this;
1520
+ }
1521
+ /**
1522
+ * Sends a packet.
1523
+ *
1524
+ * @param {String} type: packet type.
1525
+ * @param {String} data.
1526
+ * @param {Object} options.
1527
+ * @param {Function} fn - callback function.
1528
+ * @private
1529
+ */
1530
+ _sendPacket(type, data, options, fn) {
1531
+ if ("function" === typeof data) {
1532
+ fn = data;
1533
+ data = void 0;
1534
+ }
1535
+ if ("function" === typeof options) {
1536
+ fn = options;
1537
+ options = null;
1538
+ }
1539
+ if ("closing" === this.readyState || "closed" === this.readyState) {
1540
+ return;
1541
+ }
1542
+ options = options || {};
1543
+ options.compress = false !== options.compress;
1544
+ const packet = {
1545
+ type,
1546
+ data,
1547
+ options
1548
+ };
1549
+ this.emitReserved("packetCreate", packet);
1550
+ this.writeBuffer.push(packet);
1551
+ if (fn)
1552
+ this.once("flush", fn);
1553
+ this.flush();
1554
+ }
1555
+ /**
1556
+ * Closes the connection.
1557
+ */
1558
+ close() {
1559
+ const close = () => {
1560
+ this._onClose("forced close");
1561
+ this.transport.close();
1562
+ };
1563
+ const cleanupAndClose = () => {
1564
+ this.off("upgrade", cleanupAndClose);
1565
+ this.off("upgradeError", cleanupAndClose);
1566
+ close();
1567
+ };
1568
+ const waitForUpgrade = () => {
1569
+ this.once("upgrade", cleanupAndClose);
1570
+ this.once("upgradeError", cleanupAndClose);
1571
+ };
1572
+ if ("opening" === this.readyState || "open" === this.readyState) {
1573
+ this.readyState = "closing";
1574
+ if (this.writeBuffer.length) {
1575
+ this.once("drain", () => {
1576
+ if (this.upgrading) {
1577
+ waitForUpgrade();
1578
+ } else {
1579
+ close();
1580
+ }
1581
+ });
1582
+ } else if (this.upgrading) {
1583
+ waitForUpgrade();
1584
+ } else {
1585
+ close();
1586
+ }
1587
+ }
1588
+ return this;
1589
+ }
1590
+ /**
1591
+ * Called upon transport error
1592
+ *
1593
+ * @private
1594
+ */
1595
+ _onError(err) {
1596
+ _SocketWithoutUpgrade.priorWebsocketSuccess = false;
1597
+ if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
1598
+ this.transports.shift();
1599
+ return this._open();
1600
+ }
1601
+ this.emitReserved("error", err);
1602
+ this._onClose("transport error", err);
1603
+ }
1604
+ /**
1605
+ * Called upon transport close.
1606
+ *
1607
+ * @private
1608
+ */
1609
+ _onClose(reason, description) {
1610
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
1611
+ this.clearTimeoutFn(this._pingTimeoutTimer);
1612
+ this.transport.removeAllListeners("close");
1613
+ this.transport.close();
1614
+ this.transport.removeAllListeners();
1615
+ if (withEventListeners) {
1616
+ if (this._beforeunloadEventListener) {
1617
+ removeEventListener("beforeunload", this._beforeunloadEventListener, false);
1618
+ }
1619
+ if (this._offlineEventListener) {
1620
+ const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
1621
+ if (i !== -1) {
1622
+ OFFLINE_EVENT_LISTENERS.splice(i, 1);
1623
+ }
1624
+ }
1625
+ }
1626
+ this.readyState = "closed";
1627
+ this.id = null;
1628
+ this.emitReserved("close", reason, description);
1629
+ this.writeBuffer = [];
1630
+ this._prevBufferLen = 0;
1631
+ }
1632
+ }
1633
+ };
1634
+ SocketWithoutUpgrade.protocol = protocol;
1635
+ var SocketWithUpgrade = class extends SocketWithoutUpgrade {
1636
+ constructor() {
1637
+ super(...arguments);
1638
+ this._upgrades = [];
1639
+ }
1640
+ onOpen() {
1641
+ super.onOpen();
1642
+ if ("open" === this.readyState && this.opts.upgrade) {
1643
+ for (let i = 0; i < this._upgrades.length; i++) {
1644
+ this._probe(this._upgrades[i]);
1645
+ }
1646
+ }
1647
+ }
1648
+ /**
1649
+ * Probes a transport.
1650
+ *
1651
+ * @param {String} name - transport name
1652
+ * @private
1653
+ */
1654
+ _probe(name) {
1655
+ let transport = this.createTransport(name);
1656
+ let failed = false;
1657
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
1658
+ const onTransportOpen = () => {
1659
+ if (failed)
1660
+ return;
1661
+ transport.send([{ type: "ping", data: "probe" }]);
1662
+ transport.once("packet", (msg) => {
1663
+ if (failed)
1664
+ return;
1665
+ if ("pong" === msg.type && "probe" === msg.data) {
1666
+ this.upgrading = true;
1667
+ this.emitReserved("upgrading", transport);
1668
+ if (!transport)
1669
+ return;
1670
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
1671
+ this.transport.pause(() => {
1672
+ if (failed)
1673
+ return;
1674
+ if ("closed" === this.readyState)
1675
+ return;
1676
+ cleanup();
1677
+ this.setTransport(transport);
1678
+ transport.send([{ type: "upgrade" }]);
1679
+ this.emitReserved("upgrade", transport);
1680
+ transport = null;
1681
+ this.upgrading = false;
1682
+ this.flush();
1683
+ });
1684
+ } else {
1685
+ const err = new Error("probe error");
1686
+ err.transport = transport.name;
1687
+ this.emitReserved("upgradeError", err);
1688
+ }
1689
+ });
1690
+ };
1691
+ function freezeTransport() {
1692
+ if (failed)
1693
+ return;
1694
+ failed = true;
1695
+ cleanup();
1696
+ transport.close();
1697
+ transport = null;
1698
+ }
1699
+ const onerror = (err) => {
1700
+ const error = new Error("probe error: " + err);
1701
+ error.transport = transport.name;
1702
+ freezeTransport();
1703
+ this.emitReserved("upgradeError", error);
1704
+ };
1705
+ function onTransportClose() {
1706
+ onerror("transport closed");
1707
+ }
1708
+ function onclose() {
1709
+ onerror("socket closed");
1710
+ }
1711
+ function onupgrade(to) {
1712
+ if (transport && to.name !== transport.name) {
1713
+ freezeTransport();
1714
+ }
1715
+ }
1716
+ const cleanup = () => {
1717
+ transport.removeListener("open", onTransportOpen);
1718
+ transport.removeListener("error", onerror);
1719
+ transport.removeListener("close", onTransportClose);
1720
+ this.off("close", onclose);
1721
+ this.off("upgrading", onupgrade);
1722
+ };
1723
+ transport.once("open", onTransportOpen);
1724
+ transport.once("error", onerror);
1725
+ transport.once("close", onTransportClose);
1726
+ this.once("close", onclose);
1727
+ this.once("upgrading", onupgrade);
1728
+ if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
1729
+ this.setTimeoutFn(() => {
1730
+ if (!failed) {
1731
+ transport.open();
1732
+ }
1733
+ }, 200);
1734
+ } else {
1735
+ transport.open();
1736
+ }
1737
+ }
1738
+ onHandshake(data) {
1739
+ this._upgrades = this._filterUpgrades(data.upgrades);
1740
+ super.onHandshake(data);
1741
+ }
1742
+ /**
1743
+ * Filters upgrades, returning only those matching client transports.
1744
+ *
1745
+ * @param {Array} upgrades - server upgrades
1746
+ * @private
1747
+ */
1748
+ _filterUpgrades(upgrades) {
1749
+ const filteredUpgrades = [];
1750
+ for (let i = 0; i < upgrades.length; i++) {
1751
+ if (~this.transports.indexOf(upgrades[i]))
1752
+ filteredUpgrades.push(upgrades[i]);
1753
+ }
1754
+ return filteredUpgrades;
1755
+ }
1756
+ };
1757
+ var Socket = class extends SocketWithUpgrade {
1758
+ constructor(uri, opts = {}) {
1759
+ const o = typeof uri === "object" ? uri : opts;
1760
+ if (!o.transports || o.transports && typeof o.transports[0] === "string") {
1761
+ o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t) => !!t);
1762
+ }
1763
+ super(uri, o);
1764
+ }
1765
+ };
1766
+
1767
+ // node_modules/engine.io-client/build/esm/index.js
1768
+ var protocol2 = Socket.protocol;
1769
+
1770
+ // node_modules/socket.io-client/build/esm/url.js
1771
+ function url(uri, path = "", loc) {
1772
+ let obj = uri;
1773
+ loc = loc || typeof location !== "undefined" && location;
1774
+ if (null == uri)
1775
+ uri = loc.protocol + "//" + loc.host;
1776
+ if (typeof uri === "string") {
1777
+ if ("/" === uri.charAt(0)) {
1778
+ if ("/" === uri.charAt(1)) {
1779
+ uri = loc.protocol + uri;
1780
+ } else {
1781
+ uri = loc.host + uri;
1782
+ }
1783
+ }
1784
+ if (!/^(https?|wss?):\/\//.test(uri)) {
1785
+ if ("undefined" !== typeof loc) {
1786
+ uri = loc.protocol + "//" + uri;
1787
+ } else {
1788
+ uri = "https://" + uri;
1789
+ }
1790
+ }
1791
+ obj = parse(uri);
1792
+ }
1793
+ if (!obj.port) {
1794
+ if (/^(http|ws)$/.test(obj.protocol)) {
1795
+ obj.port = "80";
1796
+ } else if (/^(http|ws)s$/.test(obj.protocol)) {
1797
+ obj.port = "443";
1798
+ }
1799
+ }
1800
+ obj.path = obj.path || "/";
1801
+ const ipv6 = obj.host.indexOf(":") !== -1;
1802
+ const host = ipv6 ? "[" + obj.host + "]" : obj.host;
1803
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
1804
+ obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
1805
+ return obj;
1806
+ }
1807
+
1808
+ // node_modules/socket.io-parser/build/esm/index.js
1809
+ var esm_exports = {};
1810
+ __export(esm_exports, {
1811
+ Decoder: () => Decoder,
1812
+ Encoder: () => Encoder,
1813
+ PacketType: () => PacketType,
1814
+ isPacketValid: () => isPacketValid,
1815
+ protocol: () => protocol3
1816
+ });
1817
+
1818
+ // node_modules/socket.io-parser/build/esm/is-binary.js
1819
+ var withNativeArrayBuffer3 = typeof ArrayBuffer === "function";
1820
+ var isView2 = (obj) => {
1821
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
1822
+ };
1823
+ var toString = Object.prototype.toString;
1824
+ var withNativeBlob2 = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
1825
+ var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
1826
+ function isBinary(obj) {
1827
+ return withNativeArrayBuffer3 && (obj instanceof ArrayBuffer || isView2(obj)) || withNativeBlob2 && obj instanceof Blob || withNativeFile && obj instanceof File;
1828
+ }
1829
+ function hasBinary(obj, toJSON) {
1830
+ if (!obj || typeof obj !== "object") {
1831
+ return false;
1832
+ }
1833
+ if (Array.isArray(obj)) {
1834
+ for (let i = 0, l = obj.length; i < l; i++) {
1835
+ if (hasBinary(obj[i])) {
1836
+ return true;
1837
+ }
1838
+ }
1839
+ return false;
1840
+ }
1841
+ if (isBinary(obj)) {
1842
+ return true;
1843
+ }
1844
+ if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
1845
+ return hasBinary(obj.toJSON(), true);
1846
+ }
1847
+ for (const key in obj) {
1848
+ if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
1849
+ return true;
1850
+ }
1851
+ }
1852
+ return false;
1853
+ }
1854
+
1855
+ // node_modules/socket.io-parser/build/esm/binary.js
1856
+ function deconstructPacket(packet) {
1857
+ const buffers = [];
1858
+ const packetData = packet.data;
1859
+ const pack = packet;
1860
+ pack.data = _deconstructPacket(packetData, buffers);
1861
+ pack.attachments = buffers.length;
1862
+ return { packet: pack, buffers };
1863
+ }
1864
+ function _deconstructPacket(data, buffers) {
1865
+ if (!data)
1866
+ return data;
1867
+ if (isBinary(data)) {
1868
+ const placeholder = { _placeholder: true, num: buffers.length };
1869
+ buffers.push(data);
1870
+ return placeholder;
1871
+ } else if (Array.isArray(data)) {
1872
+ const newData = new Array(data.length);
1873
+ for (let i = 0; i < data.length; i++) {
1874
+ newData[i] = _deconstructPacket(data[i], buffers);
1875
+ }
1876
+ return newData;
1877
+ } else if (typeof data === "object" && !(data instanceof Date)) {
1878
+ const newData = {};
1879
+ for (const key in data) {
1880
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
1881
+ newData[key] = _deconstructPacket(data[key], buffers);
1882
+ }
1883
+ }
1884
+ return newData;
1885
+ }
1886
+ return data;
1887
+ }
1888
+ function reconstructPacket(packet, buffers) {
1889
+ packet.data = _reconstructPacket(packet.data, buffers);
1890
+ delete packet.attachments;
1891
+ return packet;
1892
+ }
1893
+ function _reconstructPacket(data, buffers) {
1894
+ if (!data)
1895
+ return data;
1896
+ if (data && data._placeholder === true) {
1897
+ const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
1898
+ if (isIndexValid) {
1899
+ return buffers[data.num];
1900
+ } else {
1901
+ throw new Error("illegal attachments");
1902
+ }
1903
+ } else if (Array.isArray(data)) {
1904
+ for (let i = 0; i < data.length; i++) {
1905
+ data[i] = _reconstructPacket(data[i], buffers);
1906
+ }
1907
+ } else if (typeof data === "object") {
1908
+ for (const key in data) {
1909
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
1910
+ data[key] = _reconstructPacket(data[key], buffers);
1911
+ }
1912
+ }
1913
+ }
1914
+ return data;
1915
+ }
1916
+
1917
+ // node_modules/socket.io-parser/build/esm/index.js
1918
+ var RESERVED_EVENTS = [
1919
+ "connect",
1920
+ // used on the client side
1921
+ "connect_error",
1922
+ // used on the client side
1923
+ "disconnect",
1924
+ // used on both sides
1925
+ "disconnecting",
1926
+ // used on the server side
1927
+ "newListener",
1928
+ // used by the Node.js EventEmitter
1929
+ "removeListener"
1930
+ // used by the Node.js EventEmitter
1931
+ ];
1932
+ var protocol3 = 5;
1933
+ var PacketType;
1934
+ (function(PacketType2) {
1935
+ PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
1936
+ PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
1937
+ PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
1938
+ PacketType2[PacketType2["ACK"] = 3] = "ACK";
1939
+ PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
1940
+ PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
1941
+ PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_ACK";
1942
+ })(PacketType || (PacketType = {}));
1943
+ var Encoder = class {
1944
+ /**
1945
+ * Encoder constructor
1946
+ *
1947
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
1948
+ */
1949
+ constructor(replacer) {
1950
+ this.replacer = replacer;
1951
+ }
1952
+ /**
1953
+ * Encode a packet as a single string if non-binary, or as a
1954
+ * buffer sequence, depending on packet type.
1955
+ *
1956
+ * @param {Object} obj - packet object
1957
+ */
1958
+ encode(obj) {
1959
+ if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
1960
+ if (hasBinary(obj)) {
1961
+ return this.encodeAsBinary({
1962
+ type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
1963
+ nsp: obj.nsp,
1964
+ data: obj.data,
1965
+ id: obj.id
1966
+ });
1967
+ }
1968
+ }
1969
+ return [this.encodeAsString(obj)];
1970
+ }
1971
+ /**
1972
+ * Encode packet as string.
1973
+ */
1974
+ encodeAsString(obj) {
1975
+ let str = "" + obj.type;
1976
+ if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
1977
+ str += obj.attachments + "-";
1978
+ }
1979
+ if (obj.nsp && "/" !== obj.nsp) {
1980
+ str += obj.nsp + ",";
1981
+ }
1982
+ if (null != obj.id) {
1983
+ str += obj.id;
1984
+ }
1985
+ if (null != obj.data) {
1986
+ str += JSON.stringify(obj.data, this.replacer);
1987
+ }
1988
+ return str;
1989
+ }
1990
+ /**
1991
+ * Encode packet as 'buffer sequence' by removing blobs, and
1992
+ * deconstructing packet into object with placeholders and
1993
+ * a list of buffers.
1994
+ */
1995
+ encodeAsBinary(obj) {
1996
+ const deconstruction = deconstructPacket(obj);
1997
+ const pack = this.encodeAsString(deconstruction.packet);
1998
+ const buffers = deconstruction.buffers;
1999
+ buffers.unshift(pack);
2000
+ return buffers;
2001
+ }
2002
+ };
2003
+ var Decoder = class _Decoder extends Emitter {
2004
+ /**
2005
+ * Decoder constructor
2006
+ */
2007
+ constructor(opts) {
2008
+ super();
2009
+ this.opts = Object.assign({
2010
+ reviver: void 0,
2011
+ maxAttachments: 10
2012
+ }, typeof opts === "function" ? { reviver: opts } : opts);
2013
+ }
2014
+ /**
2015
+ * Decodes an encoded packet string into packet JSON.
2016
+ *
2017
+ * @param {String} obj - encoded packet
2018
+ */
2019
+ add(obj) {
2020
+ let packet;
2021
+ if (typeof obj === "string") {
2022
+ if (this.reconstructor) {
2023
+ throw new Error("got plaintext data when reconstructing a packet");
2024
+ }
2025
+ packet = this.decodeString(obj);
2026
+ const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
2027
+ if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
2028
+ packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
2029
+ this.reconstructor = new BinaryReconstructor(packet);
2030
+ if (packet.attachments === 0) {
2031
+ super.emitReserved("decoded", packet);
2032
+ }
2033
+ } else {
2034
+ super.emitReserved("decoded", packet);
2035
+ }
2036
+ } else if (isBinary(obj) || obj.base64) {
2037
+ if (!this.reconstructor) {
2038
+ throw new Error("got binary data when not reconstructing a packet");
2039
+ } else {
2040
+ packet = this.reconstructor.takeBinaryData(obj);
2041
+ if (packet) {
2042
+ this.reconstructor = null;
2043
+ super.emitReserved("decoded", packet);
2044
+ }
2045
+ }
2046
+ } else {
2047
+ throw new Error("Unknown type: " + obj);
2048
+ }
2049
+ }
2050
+ /**
2051
+ * Decode a packet String (JSON data)
2052
+ *
2053
+ * @param {String} str
2054
+ * @return {Object} packet
2055
+ */
2056
+ decodeString(str) {
2057
+ let i = 0;
2058
+ const p = {
2059
+ type: Number(str.charAt(0))
2060
+ };
2061
+ if (PacketType[p.type] === void 0) {
2062
+ throw new Error("unknown packet type " + p.type);
2063
+ }
2064
+ if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
2065
+ const start = i + 1;
2066
+ while (str.charAt(++i) !== "-" && i != str.length) {
2067
+ }
2068
+ const buf = str.substring(start, i);
2069
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
2070
+ throw new Error("Illegal attachments");
2071
+ }
2072
+ const n = Number(buf);
2073
+ if (!isInteger(n) || n < 0) {
2074
+ throw new Error("Illegal attachments");
2075
+ } else if (n > this.opts.maxAttachments) {
2076
+ throw new Error("too many attachments");
2077
+ }
2078
+ p.attachments = n;
2079
+ }
2080
+ if ("/" === str.charAt(i + 1)) {
2081
+ const start = i + 1;
2082
+ while (++i) {
2083
+ const c = str.charAt(i);
2084
+ if ("," === c)
2085
+ break;
2086
+ if (i === str.length)
2087
+ break;
2088
+ }
2089
+ p.nsp = str.substring(start, i);
2090
+ } else {
2091
+ p.nsp = "/";
2092
+ }
2093
+ const next = str.charAt(i + 1);
2094
+ if ("" !== next && Number(next) == next) {
2095
+ const start = i + 1;
2096
+ while (++i) {
2097
+ const c = str.charAt(i);
2098
+ if (null == c || Number(c) != c) {
2099
+ --i;
2100
+ break;
2101
+ }
2102
+ if (i === str.length)
2103
+ break;
2104
+ }
2105
+ p.id = Number(str.substring(start, i + 1));
2106
+ }
2107
+ if (str.charAt(++i)) {
2108
+ const payload = this.tryParse(str.substr(i));
2109
+ if (_Decoder.isPayloadValid(p.type, payload)) {
2110
+ p.data = payload;
2111
+ } else {
2112
+ throw new Error("invalid payload");
2113
+ }
2114
+ }
2115
+ return p;
2116
+ }
2117
+ tryParse(str) {
2118
+ try {
2119
+ return JSON.parse(str, this.opts.reviver);
2120
+ } catch (e) {
2121
+ return false;
2122
+ }
2123
+ }
2124
+ static isPayloadValid(type, payload) {
2125
+ switch (type) {
2126
+ case PacketType.CONNECT:
2127
+ return isObject(payload);
2128
+ case PacketType.DISCONNECT:
2129
+ return payload === void 0;
2130
+ case PacketType.CONNECT_ERROR:
2131
+ return typeof payload === "string" || isObject(payload);
2132
+ case PacketType.EVENT:
2133
+ case PacketType.BINARY_EVENT:
2134
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2135
+ case PacketType.ACK:
2136
+ case PacketType.BINARY_ACK:
2137
+ return Array.isArray(payload);
2138
+ }
2139
+ }
2140
+ /**
2141
+ * Deallocates a parser's resources
2142
+ */
2143
+ destroy() {
2144
+ if (this.reconstructor) {
2145
+ this.reconstructor.finishedReconstruction();
2146
+ this.reconstructor = null;
2147
+ }
2148
+ }
2149
+ };
2150
+ var BinaryReconstructor = class {
2151
+ constructor(packet) {
2152
+ this.packet = packet;
2153
+ this.buffers = [];
2154
+ this.reconPack = packet;
2155
+ }
2156
+ /**
2157
+ * Method to be called when binary data received from connection
2158
+ * after a BINARY_EVENT packet.
2159
+ *
2160
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
2161
+ * @return {null | Object} returns null if more binary data is expected or
2162
+ * a reconstructed packet object if all buffers have been received.
2163
+ */
2164
+ takeBinaryData(binData) {
2165
+ this.buffers.push(binData);
2166
+ if (this.buffers.length === this.reconPack.attachments) {
2167
+ const packet = reconstructPacket(this.reconPack, this.buffers);
2168
+ this.finishedReconstruction();
2169
+ return packet;
2170
+ }
2171
+ return null;
2172
+ }
2173
+ /**
2174
+ * Cleans up binary packet reconstruction variables.
2175
+ */
2176
+ finishedReconstruction() {
2177
+ this.reconPack = null;
2178
+ this.buffers = [];
2179
+ }
2180
+ };
2181
+ function isNamespaceValid(nsp) {
2182
+ return typeof nsp === "string";
2183
+ }
2184
+ var isInteger = Number.isInteger || function(value2) {
2185
+ return typeof value2 === "number" && isFinite(value2) && Math.floor(value2) === value2;
2186
+ };
2187
+ function isAckIdValid(id) {
2188
+ return id === void 0 || isInteger(id);
2189
+ }
2190
+ function isObject(value2) {
2191
+ return Object.prototype.toString.call(value2) === "[object Object]";
2192
+ }
2193
+ function isDataValid(type, payload) {
2194
+ switch (type) {
2195
+ case PacketType.CONNECT:
2196
+ return payload === void 0 || isObject(payload);
2197
+ case PacketType.DISCONNECT:
2198
+ return payload === void 0;
2199
+ case PacketType.EVENT:
2200
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2201
+ case PacketType.ACK:
2202
+ return Array.isArray(payload);
2203
+ case PacketType.CONNECT_ERROR:
2204
+ return typeof payload === "string" || isObject(payload);
2205
+ default:
2206
+ return false;
2207
+ }
2208
+ }
2209
+ function isPacketValid(packet) {
2210
+ return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
2211
+ }
2212
+
2213
+ // node_modules/socket.io-client/build/esm/on.js
2214
+ function on(obj, ev, fn) {
2215
+ obj.on(ev, fn);
2216
+ return function subDestroy() {
2217
+ obj.off(ev, fn);
2218
+ };
2219
+ }
2220
+
2221
+ // node_modules/socket.io-client/build/esm/socket.js
2222
+ var RESERVED_EVENTS2 = Object.freeze({
2223
+ connect: 1,
2224
+ connect_error: 1,
2225
+ disconnect: 1,
2226
+ disconnecting: 1,
2227
+ // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
2228
+ newListener: 1,
2229
+ removeListener: 1
2230
+ });
2231
+ var Socket2 = class extends Emitter {
2232
+ /**
2233
+ * `Socket` constructor.
2234
+ */
2235
+ constructor(io, nsp, opts) {
2236
+ super();
2237
+ this.connected = false;
2238
+ this.recovered = false;
2239
+ this.receiveBuffer = [];
2240
+ this.sendBuffer = [];
2241
+ this._queue = [];
2242
+ this._queueSeq = 0;
2243
+ this.ids = 0;
2244
+ this.acks = {};
2245
+ this.flags = {};
2246
+ this.io = io;
2247
+ this.nsp = nsp;
2248
+ if (opts && opts.auth) {
2249
+ this.auth = opts.auth;
2250
+ }
2251
+ this._opts = Object.assign({}, opts);
2252
+ if (this.io._autoConnect)
2253
+ this.open();
2254
+ }
2255
+ /**
2256
+ * Whether the socket is currently disconnected
2257
+ *
2258
+ * @example
2259
+ * const socket = io();
2260
+ *
2261
+ * socket.on("connect", () => {
2262
+ * console.log(socket.disconnected); // false
2263
+ * });
2264
+ *
2265
+ * socket.on("disconnect", () => {
2266
+ * console.log(socket.disconnected); // true
2267
+ * });
2268
+ */
2269
+ get disconnected() {
2270
+ return !this.connected;
2271
+ }
2272
+ /**
2273
+ * Subscribe to open, close and packet events
2274
+ *
2275
+ * @private
2276
+ */
2277
+ subEvents() {
2278
+ if (this.subs)
2279
+ return;
2280
+ const io = this.io;
2281
+ this.subs = [
2282
+ on(io, "open", this.onopen.bind(this)),
2283
+ on(io, "packet", this.onpacket.bind(this)),
2284
+ on(io, "error", this.onerror.bind(this)),
2285
+ on(io, "close", this.onclose.bind(this))
2286
+ ];
2287
+ }
2288
+ /**
2289
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
2290
+ *
2291
+ * @example
2292
+ * const socket = io();
2293
+ *
2294
+ * console.log(socket.active); // true
2295
+ *
2296
+ * socket.on("disconnect", (reason) => {
2297
+ * if (reason === "io server disconnect") {
2298
+ * // the disconnection was initiated by the server, you need to manually reconnect
2299
+ * console.log(socket.active); // false
2300
+ * }
2301
+ * // else the socket will automatically try to reconnect
2302
+ * console.log(socket.active); // true
2303
+ * });
2304
+ */
2305
+ get active() {
2306
+ return !!this.subs;
2307
+ }
2308
+ /**
2309
+ * "Opens" the socket.
2310
+ *
2311
+ * @example
2312
+ * const socket = io({
2313
+ * autoConnect: false
2314
+ * });
2315
+ *
2316
+ * socket.connect();
2317
+ */
2318
+ connect() {
2319
+ if (this.connected)
2320
+ return this;
2321
+ this.subEvents();
2322
+ if (!this.io["_reconnecting"])
2323
+ this.io.open();
2324
+ if ("open" === this.io._readyState)
2325
+ this.onopen();
2326
+ return this;
2327
+ }
2328
+ /**
2329
+ * Alias for {@link connect()}.
2330
+ */
2331
+ open() {
2332
+ return this.connect();
2333
+ }
2334
+ /**
2335
+ * Sends a `message` event.
2336
+ *
2337
+ * This method mimics the WebSocket.send() method.
2338
+ *
2339
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
2340
+ *
2341
+ * @example
2342
+ * socket.send("hello");
2343
+ *
2344
+ * // this is equivalent to
2345
+ * socket.emit("message", "hello");
2346
+ *
2347
+ * @return self
2348
+ */
2349
+ send(...args) {
2350
+ args.unshift("message");
2351
+ this.emit.apply(this, args);
2352
+ return this;
2353
+ }
2354
+ /**
2355
+ * Override `emit`.
2356
+ * If the event is in `events`, it's emitted normally.
2357
+ *
2358
+ * @example
2359
+ * socket.emit("hello", "world");
2360
+ *
2361
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
2362
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
2363
+ *
2364
+ * // with an acknowledgement from the server
2365
+ * socket.emit("hello", "world", (val) => {
2366
+ * // ...
2367
+ * });
2368
+ *
2369
+ * @return self
2370
+ */
2371
+ emit(ev, ...args) {
2372
+ var _a, _b, _c;
2373
+ if (RESERVED_EVENTS2.hasOwnProperty(ev)) {
2374
+ throw new Error('"' + ev.toString() + '" is a reserved event name');
2375
+ }
2376
+ args.unshift(ev);
2377
+ if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
2378
+ this._addToQueue(args);
2379
+ return this;
2380
+ }
2381
+ const packet = {
2382
+ type: PacketType.EVENT,
2383
+ data: args
2384
+ };
2385
+ packet.options = {};
2386
+ packet.options.compress = this.flags.compress !== false;
2387
+ if ("function" === typeof args[args.length - 1]) {
2388
+ const id = this.ids++;
2389
+ const ack = args.pop();
2390
+ this._registerAckCallback(id, ack);
2391
+ packet.id = id;
2392
+ }
2393
+ const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
2394
+ const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
2395
+ const discardPacket = this.flags.volatile && !isTransportWritable;
2396
+ if (discardPacket) {
2397
+ } else if (isConnected) {
2398
+ this.notifyOutgoingListeners(packet);
2399
+ this.packet(packet);
2400
+ } else {
2401
+ this.sendBuffer.push(packet);
2402
+ }
2403
+ this.flags = {};
2404
+ return this;
2405
+ }
2406
+ /**
2407
+ * @private
2408
+ */
2409
+ _registerAckCallback(id, ack) {
2410
+ var _a;
2411
+ const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
2412
+ if (timeout === void 0) {
2413
+ this.acks[id] = ack;
2414
+ return;
2415
+ }
2416
+ const timer = this.io.setTimeoutFn(() => {
2417
+ delete this.acks[id];
2418
+ for (let i = 0; i < this.sendBuffer.length; i++) {
2419
+ if (this.sendBuffer[i].id === id) {
2420
+ this.sendBuffer.splice(i, 1);
2421
+ }
2422
+ }
2423
+ ack.call(this, new Error("operation has timed out"));
2424
+ }, timeout);
2425
+ const fn = (...args) => {
2426
+ this.io.clearTimeoutFn(timer);
2427
+ ack.apply(this, args);
2428
+ };
2429
+ fn.withError = true;
2430
+ this.acks[id] = fn;
2431
+ }
2432
+ /**
2433
+ * Emits an event and waits for an acknowledgement
2434
+ *
2435
+ * @example
2436
+ * // without timeout
2437
+ * const response = await socket.emitWithAck("hello", "world");
2438
+ *
2439
+ * // with a specific timeout
2440
+ * try {
2441
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
2442
+ * } catch (err) {
2443
+ * // the server did not acknowledge the event in the given delay
2444
+ * }
2445
+ *
2446
+ * @return a Promise that will be fulfilled when the server acknowledges the event
2447
+ */
2448
+ emitWithAck(ev, ...args) {
2449
+ return new Promise((resolve, reject) => {
2450
+ const fn = (arg1, arg2) => {
2451
+ return arg1 ? reject(arg1) : resolve(arg2);
2452
+ };
2453
+ fn.withError = true;
2454
+ args.push(fn);
2455
+ this.emit(ev, ...args);
2456
+ });
2457
+ }
2458
+ /**
2459
+ * Add the packet to the queue.
2460
+ * @param args
2461
+ * @private
2462
+ */
2463
+ _addToQueue(args) {
2464
+ let ack;
2465
+ if (typeof args[args.length - 1] === "function") {
2466
+ ack = args.pop();
2467
+ }
2468
+ const packet = {
2469
+ id: this._queueSeq++,
2470
+ tryCount: 0,
2471
+ pending: false,
2472
+ args,
2473
+ flags: Object.assign({ fromQueue: true }, this.flags)
2474
+ };
2475
+ args.push((err, ...responseArgs) => {
2476
+ if (packet !== this._queue[0]) {
2477
+ }
2478
+ const hasError = err !== null;
2479
+ if (hasError) {
2480
+ if (packet.tryCount > this._opts.retries) {
2481
+ this._queue.shift();
2482
+ if (ack) {
2483
+ ack(err);
2484
+ }
2485
+ }
2486
+ } else {
2487
+ this._queue.shift();
2488
+ if (ack) {
2489
+ ack(null, ...responseArgs);
2490
+ }
2491
+ }
2492
+ packet.pending = false;
2493
+ return this._drainQueue();
2494
+ });
2495
+ this._queue.push(packet);
2496
+ this._drainQueue();
2497
+ }
2498
+ /**
2499
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
2500
+ * @param force - whether to resend a packet that has not been acknowledged yet
2501
+ *
2502
+ * @private
2503
+ */
2504
+ _drainQueue(force = false) {
2505
+ if (!this.connected || this._queue.length === 0) {
2506
+ return;
2507
+ }
2508
+ const packet = this._queue[0];
2509
+ if (packet.pending && !force) {
2510
+ return;
2511
+ }
2512
+ packet.pending = true;
2513
+ packet.tryCount++;
2514
+ this.flags = packet.flags;
2515
+ this.emit.apply(this, packet.args);
2516
+ }
2517
+ /**
2518
+ * Sends a packet.
2519
+ *
2520
+ * @param packet
2521
+ * @private
2522
+ */
2523
+ packet(packet) {
2524
+ packet.nsp = this.nsp;
2525
+ this.io._packet(packet);
2526
+ }
2527
+ /**
2528
+ * Called upon engine `open`.
2529
+ *
2530
+ * @private
2531
+ */
2532
+ onopen() {
2533
+ if (typeof this.auth == "function") {
2534
+ this.auth((data) => {
2535
+ this._sendConnectPacket(data);
2536
+ });
2537
+ } else {
2538
+ this._sendConnectPacket(this.auth);
2539
+ }
2540
+ }
2541
+ /**
2542
+ * Sends a CONNECT packet to initiate the Socket.IO session.
2543
+ *
2544
+ * @param data
2545
+ * @private
2546
+ */
2547
+ _sendConnectPacket(data) {
2548
+ this.packet({
2549
+ type: PacketType.CONNECT,
2550
+ data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
2551
+ });
2552
+ }
2553
+ /**
2554
+ * Called upon engine or manager `error`.
2555
+ *
2556
+ * @param err
2557
+ * @private
2558
+ */
2559
+ onerror(err) {
2560
+ if (!this.connected) {
2561
+ this.emitReserved("connect_error", err);
2562
+ }
2563
+ }
2564
+ /**
2565
+ * Called upon engine `close`.
2566
+ *
2567
+ * @param reason
2568
+ * @param description
2569
+ * @private
2570
+ */
2571
+ onclose(reason, description) {
2572
+ this.connected = false;
2573
+ delete this.id;
2574
+ this.emitReserved("disconnect", reason, description);
2575
+ this._clearAcks();
2576
+ }
2577
+ /**
2578
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
2579
+ * the server.
2580
+ *
2581
+ * @private
2582
+ */
2583
+ _clearAcks() {
2584
+ Object.keys(this.acks).forEach((id) => {
2585
+ const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
2586
+ if (!isBuffered) {
2587
+ const ack = this.acks[id];
2588
+ delete this.acks[id];
2589
+ if (ack.withError) {
2590
+ ack.call(this, new Error("socket has been disconnected"));
2591
+ }
2592
+ }
2593
+ });
2594
+ }
2595
+ /**
2596
+ * Called with socket packet.
2597
+ *
2598
+ * @param packet
2599
+ * @private
2600
+ */
2601
+ onpacket(packet) {
2602
+ const sameNamespace = packet.nsp === this.nsp;
2603
+ if (!sameNamespace)
2604
+ return;
2605
+ switch (packet.type) {
2606
+ case PacketType.CONNECT:
2607
+ if (packet.data && packet.data.sid) {
2608
+ this.onconnect(packet.data.sid, packet.data.pid);
2609
+ } else {
2610
+ 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/)"));
2611
+ }
2612
+ break;
2613
+ case PacketType.EVENT:
2614
+ case PacketType.BINARY_EVENT:
2615
+ this.onevent(packet);
2616
+ break;
2617
+ case PacketType.ACK:
2618
+ case PacketType.BINARY_ACK:
2619
+ this.onack(packet);
2620
+ break;
2621
+ case PacketType.DISCONNECT:
2622
+ this.ondisconnect();
2623
+ break;
2624
+ case PacketType.CONNECT_ERROR:
2625
+ this.destroy();
2626
+ const err = new Error(packet.data.message);
2627
+ err.data = packet.data.data;
2628
+ this.emitReserved("connect_error", err);
2629
+ break;
2630
+ }
2631
+ }
2632
+ /**
2633
+ * Called upon a server event.
2634
+ *
2635
+ * @param packet
2636
+ * @private
2637
+ */
2638
+ onevent(packet) {
2639
+ const args = packet.data || [];
2640
+ if (null != packet.id) {
2641
+ args.push(this.ack(packet.id));
2642
+ }
2643
+ if (this.connected) {
2644
+ this.emitEvent(args);
2645
+ } else {
2646
+ this.receiveBuffer.push(Object.freeze(args));
2647
+ }
2648
+ }
2649
+ emitEvent(args) {
2650
+ if (this._anyListeners && this._anyListeners.length) {
2651
+ const listeners = this._anyListeners.slice();
2652
+ for (const listener of listeners) {
2653
+ listener.apply(this, args);
2654
+ }
2655
+ }
2656
+ super.emit.apply(this, args);
2657
+ if (this._pid && args.length && typeof args[args.length - 1] === "string") {
2658
+ this._lastOffset = args[args.length - 1];
2659
+ }
2660
+ }
2661
+ /**
2662
+ * Produces an ack callback to emit with an event.
2663
+ *
2664
+ * @private
2665
+ */
2666
+ ack(id) {
2667
+ const self2 = this;
2668
+ let sent = false;
2669
+ return function(...args) {
2670
+ if (sent)
2671
+ return;
2672
+ sent = true;
2673
+ self2.packet({
2674
+ type: PacketType.ACK,
2675
+ id,
2676
+ data: args
2677
+ });
2678
+ };
2679
+ }
2680
+ /**
2681
+ * Called upon a server acknowledgement.
2682
+ *
2683
+ * @param packet
2684
+ * @private
2685
+ */
2686
+ onack(packet) {
2687
+ const ack = this.acks[packet.id];
2688
+ if (typeof ack !== "function") {
2689
+ return;
2690
+ }
2691
+ delete this.acks[packet.id];
2692
+ if (ack.withError) {
2693
+ packet.data.unshift(null);
2694
+ }
2695
+ ack.apply(this, packet.data);
2696
+ }
2697
+ /**
2698
+ * Called upon server connect.
2699
+ *
2700
+ * @private
2701
+ */
2702
+ onconnect(id, pid) {
2703
+ this.id = id;
2704
+ this.recovered = pid && this._pid === pid;
2705
+ this._pid = pid;
2706
+ this.connected = true;
2707
+ this.emitBuffered();
2708
+ this._drainQueue(true);
2709
+ this.emitReserved("connect");
2710
+ }
2711
+ /**
2712
+ * Emit buffered events (received and emitted).
2713
+ *
2714
+ * @private
2715
+ */
2716
+ emitBuffered() {
2717
+ this.receiveBuffer.forEach((args) => this.emitEvent(args));
2718
+ this.receiveBuffer = [];
2719
+ this.sendBuffer.forEach((packet) => {
2720
+ this.notifyOutgoingListeners(packet);
2721
+ this.packet(packet);
2722
+ });
2723
+ this.sendBuffer = [];
2724
+ }
2725
+ /**
2726
+ * Called upon server disconnect.
2727
+ *
2728
+ * @private
2729
+ */
2730
+ ondisconnect() {
2731
+ this.destroy();
2732
+ this.onclose("io server disconnect");
2733
+ }
2734
+ /**
2735
+ * Called upon forced client/server side disconnections,
2736
+ * this method ensures the manager stops tracking us and
2737
+ * that reconnections don't get triggered for this.
2738
+ *
2739
+ * @private
2740
+ */
2741
+ destroy() {
2742
+ if (this.subs) {
2743
+ this.subs.forEach((subDestroy) => subDestroy());
2744
+ this.subs = void 0;
2745
+ }
2746
+ this.io["_destroy"](this);
2747
+ }
2748
+ /**
2749
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
2750
+ *
2751
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
2752
+ *
2753
+ * @example
2754
+ * const socket = io();
2755
+ *
2756
+ * socket.on("disconnect", (reason) => {
2757
+ * // console.log(reason); prints "io client disconnect"
2758
+ * });
2759
+ *
2760
+ * socket.disconnect();
2761
+ *
2762
+ * @return self
2763
+ */
2764
+ disconnect() {
2765
+ if (this.connected) {
2766
+ this.packet({ type: PacketType.DISCONNECT });
2767
+ }
2768
+ this.destroy();
2769
+ if (this.connected) {
2770
+ this.onclose("io client disconnect");
2771
+ }
2772
+ return this;
2773
+ }
2774
+ /**
2775
+ * Alias for {@link disconnect()}.
2776
+ *
2777
+ * @return self
2778
+ */
2779
+ close() {
2780
+ return this.disconnect();
2781
+ }
2782
+ /**
2783
+ * Sets the compress flag.
2784
+ *
2785
+ * @example
2786
+ * socket.compress(false).emit("hello");
2787
+ *
2788
+ * @param compress - if `true`, compresses the sending data
2789
+ * @return self
2790
+ */
2791
+ compress(compress) {
2792
+ this.flags.compress = compress;
2793
+ return this;
2794
+ }
2795
+ /**
2796
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
2797
+ * ready to send messages.
2798
+ *
2799
+ * @example
2800
+ * socket.volatile.emit("hello"); // the server may or may not receive it
2801
+ *
2802
+ * @returns self
2803
+ */
2804
+ get volatile() {
2805
+ this.flags.volatile = true;
2806
+ return this;
2807
+ }
2808
+ /**
2809
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
2810
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
2811
+ *
2812
+ * @example
2813
+ * socket.timeout(5000).emit("my-event", (err) => {
2814
+ * if (err) {
2815
+ * // the server did not acknowledge the event in the given delay
2816
+ * }
2817
+ * });
2818
+ *
2819
+ * @returns self
2820
+ */
2821
+ timeout(timeout) {
2822
+ this.flags.timeout = timeout;
2823
+ return this;
2824
+ }
2825
+ /**
2826
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2827
+ * callback.
2828
+ *
2829
+ * @example
2830
+ * socket.onAny((event, ...args) => {
2831
+ * console.log(`got ${event}`);
2832
+ * });
2833
+ *
2834
+ * @param listener
2835
+ */
2836
+ onAny(listener) {
2837
+ this._anyListeners = this._anyListeners || [];
2838
+ this._anyListeners.push(listener);
2839
+ return this;
2840
+ }
2841
+ /**
2842
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2843
+ * callback. The listener is added to the beginning of the listeners array.
2844
+ *
2845
+ * @example
2846
+ * socket.prependAny((event, ...args) => {
2847
+ * console.log(`got event ${event}`);
2848
+ * });
2849
+ *
2850
+ * @param listener
2851
+ */
2852
+ prependAny(listener) {
2853
+ this._anyListeners = this._anyListeners || [];
2854
+ this._anyListeners.unshift(listener);
2855
+ return this;
2856
+ }
2857
+ /**
2858
+ * Removes the listener that will be fired when any event is emitted.
2859
+ *
2860
+ * @example
2861
+ * const catchAllListener = (event, ...args) => {
2862
+ * console.log(`got event ${event}`);
2863
+ * }
2864
+ *
2865
+ * socket.onAny(catchAllListener);
2866
+ *
2867
+ * // remove a specific listener
2868
+ * socket.offAny(catchAllListener);
2869
+ *
2870
+ * // or remove all listeners
2871
+ * socket.offAny();
2872
+ *
2873
+ * @param listener
2874
+ */
2875
+ offAny(listener) {
2876
+ if (!this._anyListeners) {
2877
+ return this;
2878
+ }
2879
+ if (listener) {
2880
+ const listeners = this._anyListeners;
2881
+ for (let i = 0; i < listeners.length; i++) {
2882
+ if (listener === listeners[i]) {
2883
+ listeners.splice(i, 1);
2884
+ return this;
2885
+ }
2886
+ }
2887
+ } else {
2888
+ this._anyListeners = [];
2889
+ }
2890
+ return this;
2891
+ }
2892
+ /**
2893
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
2894
+ * e.g. to remove listeners.
2895
+ */
2896
+ listenersAny() {
2897
+ return this._anyListeners || [];
2898
+ }
2899
+ /**
2900
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2901
+ * callback.
2902
+ *
2903
+ * Note: acknowledgements sent to the server are not included.
2904
+ *
2905
+ * @example
2906
+ * socket.onAnyOutgoing((event, ...args) => {
2907
+ * console.log(`sent event ${event}`);
2908
+ * });
2909
+ *
2910
+ * @param listener
2911
+ */
2912
+ onAnyOutgoing(listener) {
2913
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
2914
+ this._anyOutgoingListeners.push(listener);
2915
+ return this;
2916
+ }
2917
+ /**
2918
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
2919
+ * callback. The listener is added to the beginning of the listeners array.
2920
+ *
2921
+ * Note: acknowledgements sent to the server are not included.
2922
+ *
2923
+ * @example
2924
+ * socket.prependAnyOutgoing((event, ...args) => {
2925
+ * console.log(`sent event ${event}`);
2926
+ * });
2927
+ *
2928
+ * @param listener
2929
+ */
2930
+ prependAnyOutgoing(listener) {
2931
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
2932
+ this._anyOutgoingListeners.unshift(listener);
2933
+ return this;
2934
+ }
2935
+ /**
2936
+ * Removes the listener that will be fired when any event is emitted.
2937
+ *
2938
+ * @example
2939
+ * const catchAllListener = (event, ...args) => {
2940
+ * console.log(`sent event ${event}`);
2941
+ * }
2942
+ *
2943
+ * socket.onAnyOutgoing(catchAllListener);
2944
+ *
2945
+ * // remove a specific listener
2946
+ * socket.offAnyOutgoing(catchAllListener);
2947
+ *
2948
+ * // or remove all listeners
2949
+ * socket.offAnyOutgoing();
2950
+ *
2951
+ * @param [listener] - the catch-all listener (optional)
2952
+ */
2953
+ offAnyOutgoing(listener) {
2954
+ if (!this._anyOutgoingListeners) {
2955
+ return this;
2956
+ }
2957
+ if (listener) {
2958
+ const listeners = this._anyOutgoingListeners;
2959
+ for (let i = 0; i < listeners.length; i++) {
2960
+ if (listener === listeners[i]) {
2961
+ listeners.splice(i, 1);
2962
+ return this;
2963
+ }
2964
+ }
2965
+ } else {
2966
+ this._anyOutgoingListeners = [];
2967
+ }
2968
+ return this;
2969
+ }
2970
+ /**
2971
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
2972
+ * e.g. to remove listeners.
2973
+ */
2974
+ listenersAnyOutgoing() {
2975
+ return this._anyOutgoingListeners || [];
2976
+ }
2977
+ /**
2978
+ * Notify the listeners for each packet sent
2979
+ *
2980
+ * @param packet
2981
+ *
2982
+ * @private
2983
+ */
2984
+ notifyOutgoingListeners(packet) {
2985
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
2986
+ const listeners = this._anyOutgoingListeners.slice();
2987
+ for (const listener of listeners) {
2988
+ listener.apply(this, packet.data);
2989
+ }
2990
+ }
2991
+ }
2992
+ };
2993
+
2994
+ // node_modules/socket.io-client/build/esm/contrib/backo2.js
2995
+ function Backoff(opts) {
2996
+ opts = opts || {};
2997
+ this.ms = opts.min || 100;
2998
+ this.max = opts.max || 1e4;
2999
+ this.factor = opts.factor || 2;
3000
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
3001
+ this.attempts = 0;
3002
+ }
3003
+ Backoff.prototype.duration = function() {
3004
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
3005
+ if (this.jitter) {
3006
+ var rand = Math.random();
3007
+ var deviation = Math.floor(rand * this.jitter * ms);
3008
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
3009
+ }
3010
+ return Math.min(ms, this.max) | 0;
3011
+ };
3012
+ Backoff.prototype.reset = function() {
3013
+ this.attempts = 0;
3014
+ };
3015
+ Backoff.prototype.setMin = function(min) {
3016
+ this.ms = min;
3017
+ };
3018
+ Backoff.prototype.setMax = function(max) {
3019
+ this.max = max;
3020
+ };
3021
+ Backoff.prototype.setJitter = function(jitter) {
3022
+ this.jitter = jitter;
3023
+ };
3024
+
3025
+ // node_modules/socket.io-client/build/esm/manager.js
3026
+ var Manager = class extends Emitter {
3027
+ constructor(uri, opts) {
3028
+ var _a;
3029
+ super();
3030
+ this.nsps = {};
3031
+ this.subs = [];
3032
+ if (uri && "object" === typeof uri) {
3033
+ opts = uri;
3034
+ uri = void 0;
3035
+ }
3036
+ opts = opts || {};
3037
+ opts.path = opts.path || "/socket.io";
3038
+ this.opts = opts;
3039
+ installTimerFunctions(this, opts);
3040
+ this.reconnection(opts.reconnection !== false);
3041
+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
3042
+ this.reconnectionDelay(opts.reconnectionDelay || 1e3);
3043
+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
3044
+ this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
3045
+ this.backoff = new Backoff({
3046
+ min: this.reconnectionDelay(),
3047
+ max: this.reconnectionDelayMax(),
3048
+ jitter: this.randomizationFactor()
3049
+ });
3050
+ this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
3051
+ this._readyState = "closed";
3052
+ this.uri = uri;
3053
+ const _parser = opts.parser || esm_exports;
3054
+ this.encoder = new _parser.Encoder();
3055
+ this.decoder = new _parser.Decoder();
3056
+ this._autoConnect = opts.autoConnect !== false;
3057
+ if (this._autoConnect)
3058
+ this.open();
3059
+ }
3060
+ reconnection(v) {
3061
+ if (!arguments.length)
3062
+ return this._reconnection;
3063
+ this._reconnection = !!v;
3064
+ if (!v) {
3065
+ this.skipReconnect = true;
3066
+ }
3067
+ return this;
3068
+ }
3069
+ reconnectionAttempts(v) {
3070
+ if (v === void 0)
3071
+ return this._reconnectionAttempts;
3072
+ this._reconnectionAttempts = v;
3073
+ return this;
3074
+ }
3075
+ reconnectionDelay(v) {
3076
+ var _a;
3077
+ if (v === void 0)
3078
+ return this._reconnectionDelay;
3079
+ this._reconnectionDelay = v;
3080
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
3081
+ return this;
3082
+ }
3083
+ randomizationFactor(v) {
3084
+ var _a;
3085
+ if (v === void 0)
3086
+ return this._randomizationFactor;
3087
+ this._randomizationFactor = v;
3088
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
3089
+ return this;
3090
+ }
3091
+ reconnectionDelayMax(v) {
3092
+ var _a;
3093
+ if (v === void 0)
3094
+ return this._reconnectionDelayMax;
3095
+ this._reconnectionDelayMax = v;
3096
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
3097
+ return this;
3098
+ }
3099
+ timeout(v) {
3100
+ if (!arguments.length)
3101
+ return this._timeout;
3102
+ this._timeout = v;
3103
+ return this;
3104
+ }
3105
+ /**
3106
+ * Starts trying to reconnect if reconnection is enabled and we have not
3107
+ * started reconnecting yet
3108
+ *
3109
+ * @private
3110
+ */
3111
+ maybeReconnectOnOpen() {
3112
+ if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
3113
+ this.reconnect();
3114
+ }
3115
+ }
3116
+ /**
3117
+ * Sets the current transport `socket`.
3118
+ *
3119
+ * @param {Function} fn - optional, callback
3120
+ * @return self
3121
+ * @public
3122
+ */
3123
+ open(fn) {
3124
+ if (~this._readyState.indexOf("open"))
3125
+ return this;
3126
+ this.engine = new Socket(this.uri, this.opts);
3127
+ const socket2 = this.engine;
3128
+ const self2 = this;
3129
+ this._readyState = "opening";
3130
+ this.skipReconnect = false;
3131
+ const openSubDestroy = on(socket2, "open", function() {
3132
+ self2.onopen();
3133
+ fn && fn();
3134
+ });
3135
+ const onError = (err) => {
3136
+ this.cleanup();
3137
+ this._readyState = "closed";
3138
+ this.emitReserved("error", err);
3139
+ if (fn) {
3140
+ fn(err);
3141
+ } else {
3142
+ this.maybeReconnectOnOpen();
3143
+ }
3144
+ };
3145
+ const errorSub = on(socket2, "error", onError);
3146
+ if (false !== this._timeout) {
3147
+ const timeout = this._timeout;
3148
+ const timer = this.setTimeoutFn(() => {
3149
+ openSubDestroy();
3150
+ onError(new Error("timeout"));
3151
+ socket2.close();
3152
+ }, timeout);
3153
+ if (this.opts.autoUnref) {
3154
+ timer.unref();
3155
+ }
3156
+ this.subs.push(() => {
3157
+ this.clearTimeoutFn(timer);
3158
+ });
3159
+ }
3160
+ this.subs.push(openSubDestroy);
3161
+ this.subs.push(errorSub);
3162
+ return this;
3163
+ }
3164
+ /**
3165
+ * Alias for open()
3166
+ *
3167
+ * @return self
3168
+ * @public
3169
+ */
3170
+ connect(fn) {
3171
+ return this.open(fn);
3172
+ }
3173
+ /**
3174
+ * Called upon transport open.
3175
+ *
3176
+ * @private
3177
+ */
3178
+ onopen() {
3179
+ this.cleanup();
3180
+ this._readyState = "open";
3181
+ this.emitReserved("open");
3182
+ const socket2 = this.engine;
3183
+ this.subs.push(
3184
+ on(socket2, "ping", this.onping.bind(this)),
3185
+ on(socket2, "data", this.ondata.bind(this)),
3186
+ on(socket2, "error", this.onerror.bind(this)),
3187
+ on(socket2, "close", this.onclose.bind(this)),
3188
+ // @ts-ignore
3189
+ on(this.decoder, "decoded", this.ondecoded.bind(this))
3190
+ );
3191
+ }
3192
+ /**
3193
+ * Called upon a ping.
3194
+ *
3195
+ * @private
3196
+ */
3197
+ onping() {
3198
+ this.emitReserved("ping");
3199
+ }
3200
+ /**
3201
+ * Called with data.
3202
+ *
3203
+ * @private
3204
+ */
3205
+ ondata(data) {
3206
+ try {
3207
+ this.decoder.add(data);
3208
+ } catch (e) {
3209
+ this.onclose("parse error", e);
3210
+ }
3211
+ }
3212
+ /**
3213
+ * Called when parser fully decodes a packet.
3214
+ *
3215
+ * @private
3216
+ */
3217
+ ondecoded(packet) {
3218
+ nextTick(() => {
3219
+ this.emitReserved("packet", packet);
3220
+ }, this.setTimeoutFn);
3221
+ }
3222
+ /**
3223
+ * Called upon socket error.
3224
+ *
3225
+ * @private
3226
+ */
3227
+ onerror(err) {
3228
+ this.emitReserved("error", err);
3229
+ }
3230
+ /**
3231
+ * Creates a new socket for the given `nsp`.
3232
+ *
3233
+ * @return {Socket}
3234
+ * @public
3235
+ */
3236
+ socket(nsp, opts) {
3237
+ let socket2 = this.nsps[nsp];
3238
+ if (!socket2) {
3239
+ socket2 = new Socket2(this, nsp, opts);
3240
+ this.nsps[nsp] = socket2;
3241
+ } else if (this._autoConnect && !socket2.active) {
3242
+ socket2.connect();
3243
+ }
3244
+ return socket2;
3245
+ }
3246
+ /**
3247
+ * Called upon a socket close.
3248
+ *
3249
+ * @param socket
3250
+ * @private
3251
+ */
3252
+ _destroy(socket2) {
3253
+ const nsps = Object.keys(this.nsps);
3254
+ for (const nsp of nsps) {
3255
+ const socket3 = this.nsps[nsp];
3256
+ if (socket3.active) {
3257
+ return;
3258
+ }
3259
+ }
3260
+ this._close();
3261
+ }
3262
+ /**
3263
+ * Writes a packet.
3264
+ *
3265
+ * @param packet
3266
+ * @private
3267
+ */
3268
+ _packet(packet) {
3269
+ const encodedPackets = this.encoder.encode(packet);
3270
+ for (let i = 0; i < encodedPackets.length; i++) {
3271
+ this.engine.write(encodedPackets[i], packet.options);
3272
+ }
3273
+ }
3274
+ /**
3275
+ * Clean up transport subscriptions and packet buffer.
3276
+ *
3277
+ * @private
3278
+ */
3279
+ cleanup() {
3280
+ this.subs.forEach((subDestroy) => subDestroy());
3281
+ this.subs.length = 0;
3282
+ this.decoder.destroy();
3283
+ }
3284
+ /**
3285
+ * Close the current socket.
3286
+ *
3287
+ * @private
3288
+ */
3289
+ _close() {
3290
+ this.skipReconnect = true;
3291
+ this._reconnecting = false;
3292
+ this.onclose("forced close");
3293
+ }
3294
+ /**
3295
+ * Alias for close()
3296
+ *
3297
+ * @private
3298
+ */
3299
+ disconnect() {
3300
+ return this._close();
3301
+ }
3302
+ /**
3303
+ * Called when:
3304
+ *
3305
+ * - the low-level engine is closed
3306
+ * - the parser encountered a badly formatted packet
3307
+ * - all sockets are disconnected
3308
+ *
3309
+ * @private
3310
+ */
3311
+ onclose(reason, description) {
3312
+ var _a;
3313
+ this.cleanup();
3314
+ (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
3315
+ this.backoff.reset();
3316
+ this._readyState = "closed";
3317
+ this.emitReserved("close", reason, description);
3318
+ if (this._reconnection && !this.skipReconnect) {
3319
+ this.reconnect();
3320
+ }
3321
+ }
3322
+ /**
3323
+ * Attempt a reconnection.
3324
+ *
3325
+ * @private
3326
+ */
3327
+ reconnect() {
3328
+ if (this._reconnecting || this.skipReconnect)
3329
+ return this;
3330
+ const self2 = this;
3331
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
3332
+ this.backoff.reset();
3333
+ this.emitReserved("reconnect_failed");
3334
+ this._reconnecting = false;
3335
+ } else {
3336
+ const delay = this.backoff.duration();
3337
+ this._reconnecting = true;
3338
+ const timer = this.setTimeoutFn(() => {
3339
+ if (self2.skipReconnect)
3340
+ return;
3341
+ this.emitReserved("reconnect_attempt", self2.backoff.attempts);
3342
+ if (self2.skipReconnect)
3343
+ return;
3344
+ self2.open((err) => {
3345
+ if (err) {
3346
+ self2._reconnecting = false;
3347
+ self2.reconnect();
3348
+ this.emitReserved("reconnect_error", err);
3349
+ } else {
3350
+ self2.onreconnect();
3351
+ }
3352
+ });
3353
+ }, delay);
3354
+ if (this.opts.autoUnref) {
3355
+ timer.unref();
3356
+ }
3357
+ this.subs.push(() => {
3358
+ this.clearTimeoutFn(timer);
3359
+ });
3360
+ }
3361
+ }
3362
+ /**
3363
+ * Called upon successful reconnect.
3364
+ *
3365
+ * @private
3366
+ */
3367
+ onreconnect() {
3368
+ const attempt = this.backoff.attempts;
3369
+ this._reconnecting = false;
3370
+ this.backoff.reset();
3371
+ this.emitReserved("reconnect", attempt);
3372
+ }
3373
+ };
3374
+
3375
+ // node_modules/socket.io-client/build/esm/index.js
3376
+ var cache = {};
3377
+ function lookup2(uri, opts) {
3378
+ if (typeof uri === "object") {
3379
+ opts = uri;
3380
+ uri = void 0;
3381
+ }
3382
+ opts = opts || {};
3383
+ const parsed = url(uri, opts.path || "/socket.io");
3384
+ const source = parsed.source;
3385
+ const id = parsed.id;
3386
+ const path = parsed.path;
3387
+ const sameNamespace = cache[id] && path in cache[id]["nsps"];
3388
+ const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
3389
+ let io;
3390
+ if (newConnection) {
3391
+ io = new Manager(source, opts);
3392
+ } else {
3393
+ if (!cache[id]) {
3394
+ cache[id] = new Manager(source, opts);
3395
+ }
3396
+ io = cache[id];
3397
+ }
3398
+ if (parsed.query && !opts.query) {
3399
+ opts.query = parsed.queryKey;
3400
+ }
3401
+ return io.socket(parsed.path, opts);
3402
+ }
3403
+ Object.assign(lookup2, {
3404
+ Manager,
3405
+ Socket: Socket2,
3406
+ io: lookup2,
3407
+ connect: lookup2
3408
+ });
3409
+
3410
+ // ../src/client.ts
3411
+ var JOIN_EVENT = "room-kit:join";
3412
+ var LEAVE_EVENT = "room-kit:leave";
3413
+ var RPC_EVENT = "room-kit:rpc";
3414
+ var CLIENT_EVENT = "room-kit:client-event";
3415
+ var SERVER_EVENT = "room-kit:server-event";
3416
+ var PRESENCE_EVENT = "room-kit:presence";
3417
+ var PRESENCE_QUERY_EVENT = "room-kit:presence-query";
3418
+ var DEFAULT_ACK_TIMEOUT_MS = 3e4;
3419
+ var clientRegistries = /* @__PURE__ */ new WeakMap();
3420
+ function createRoomClient(socket2, room) {
3421
+ return {
3422
+ name: room.name,
3423
+ get connection() {
3424
+ const registry = getClientRegistry(socket2);
3425
+ return {
3426
+ get current() {
3427
+ return registry.connectionState;
3428
+ },
3429
+ onChange(handler) {
3430
+ registry.connectionListeners.add(handler);
3431
+ return () => {
3432
+ registry.connectionListeners.delete(handler);
3433
+ };
3434
+ }
3435
+ };
3436
+ },
3437
+ join(payload) {
3438
+ const registry = getClientRegistry(socket2);
3439
+ return emitAck(socket2, JOIN_EVENT, {
3440
+ roomType: room.name,
3441
+ payload
3442
+ }).then((value2) => {
3443
+ const state = {
3444
+ name: room.name,
3445
+ roomId: value2.roomId,
3446
+ memberId: value2.memberId,
3447
+ roomProfile: value2.roomProfile,
3448
+ presenceCurrent: value2.presence,
3449
+ joinRequest: payload,
3450
+ eventListeners: /* @__PURE__ */ new Map(),
3451
+ presenceListeners: /* @__PURE__ */ new Set()
3452
+ };
3453
+ registry.joinedRooms.set(makeJoinedRoomKey(room.name, value2.roomId), state);
3454
+ return createJoinedRoom(socket2, state);
3455
+ });
3456
+ }
3457
+ };
3458
+ }
3459
+ function createJoinedRoom(socket2, state) {
3460
+ const rpc = new Proxy({}, {
3461
+ get(_target, key) {
3462
+ if (typeof key !== "string") {
3463
+ return void 0;
3464
+ }
3465
+ return (...args) => {
3466
+ return emitAck(socket2, RPC_EVENT, {
3467
+ roomType: state.name,
3468
+ roomId: state.roomId,
3469
+ name: key,
3470
+ args
3471
+ });
3472
+ };
3473
+ }
3474
+ });
3475
+ const emit = new Proxy({}, {
3476
+ get(_target, key) {
3477
+ if (typeof key !== "string") {
3478
+ return void 0;
3479
+ }
3480
+ return (payload) => {
3481
+ return emitAck(socket2, CLIENT_EVENT, {
3482
+ roomType: state.name,
3483
+ roomId: state.roomId,
3484
+ name: key,
3485
+ payload
3486
+ });
3487
+ };
3488
+ }
3489
+ });
3490
+ const on2 = new Proxy({}, {
3491
+ get(_target, key) {
3492
+ if (typeof key !== "string") {
3493
+ return void 0;
3494
+ }
3495
+ return (handler) => {
3496
+ return registerEventListener(state, key, handler);
3497
+ };
3498
+ }
3499
+ });
3500
+ const listen = (options) => {
3501
+ const cleanups = [];
3502
+ if (options.events) {
3503
+ for (const [key, handler] of Object.entries(options.events)) {
3504
+ if (typeof handler !== "function") {
3505
+ continue;
3506
+ }
3507
+ cleanups.push(registerEventListener(state, key, handler));
3508
+ }
3509
+ }
3510
+ if ("presence" in options && options.presence?.onChange) {
3511
+ cleanups.push(registerPresenceListener(state, options.presence.onChange));
3512
+ }
3513
+ let cleaned = false;
3514
+ return () => {
3515
+ if (cleaned) {
3516
+ return;
3517
+ }
3518
+ cleaned = true;
3519
+ for (const cleanup of cleanups) {
3520
+ cleanup();
3521
+ }
3522
+ };
3523
+ };
3524
+ const base = {
3525
+ name: state.name,
3526
+ roomId: state.roomId,
3527
+ memberId: state.memberId,
3528
+ roomProfile: state.roomProfile,
3529
+ rpc,
3530
+ emit,
3531
+ on: on2,
3532
+ listen,
3533
+ async leave() {
3534
+ await emitAck(socket2, LEAVE_EVENT, {
3535
+ roomType: state.name,
3536
+ roomId: state.roomId
3537
+ });
3538
+ const registry = getClientRegistry(socket2);
3539
+ registry.joinedRooms.delete(makeJoinedRoomKey(state.name, state.roomId));
3540
+ }
3541
+ };
3542
+ return new Proxy(base, {
3543
+ get(target, key, receiver) {
3544
+ if (key === "presence") {
3545
+ return {
3546
+ get current() {
3547
+ return state.presenceCurrent;
3548
+ },
3549
+ onChange(handler) {
3550
+ return registerPresenceListener(state, handler);
3551
+ },
3552
+ count() {
3553
+ return emitAck(socket2, PRESENCE_QUERY_EVENT, {
3554
+ roomType: state.name,
3555
+ roomId: state.roomId,
3556
+ kind: "count"
3557
+ });
3558
+ },
3559
+ list(query = {}) {
3560
+ return emitAck(socket2, PRESENCE_QUERY_EVENT, {
3561
+ roomType: state.name,
3562
+ roomId: state.roomId,
3563
+ kind: "list",
3564
+ ...query
3565
+ });
3566
+ }
3567
+ };
3568
+ }
3569
+ return Reflect.get(target, key, receiver);
3570
+ }
3571
+ });
3572
+ }
3573
+ function registerEventListener(state, key, handler) {
3574
+ const handlers = state.eventListeners.get(key) ?? /* @__PURE__ */ new Set();
3575
+ handlers.add(handler);
3576
+ state.eventListeners.set(key, handlers);
3577
+ return () => {
3578
+ handlers.delete(handler);
3579
+ if (handlers.size === 0) {
3580
+ state.eventListeners.delete(key);
3581
+ }
3582
+ };
3583
+ }
3584
+ function registerPresenceListener(state, handler) {
3585
+ state.presenceListeners.add(handler);
3586
+ return () => {
3587
+ state.presenceListeners.delete(handler);
3588
+ };
3589
+ }
3590
+ function getClientRegistry(socket2) {
3591
+ const existing = clientRegistries.get(socket2);
3592
+ if (existing) {
3593
+ return existing;
3594
+ }
3595
+ const created = {
3596
+ serverHandlerInstalled: false,
3597
+ presenceHandlerInstalled: false,
3598
+ reconnectHandlerInstalled: false,
3599
+ disconnectHandlerInstalled: false,
3600
+ connectErrorHandlerInstalled: false,
3601
+ reconnectAttemptHandlerInstalled: false,
3602
+ reconnectErrorHandlerInstalled: false,
3603
+ reconnectFailedHandlerInstalled: false,
3604
+ hasConnectedOnce: false,
3605
+ connectionState: "connecting",
3606
+ connectionListeners: /* @__PURE__ */ new Set(),
3607
+ joinedRooms: /* @__PURE__ */ new Map()
3608
+ };
3609
+ installClientHandlers(socket2, created);
3610
+ clientRegistries.set(socket2, created);
3611
+ return created;
3612
+ }
3613
+ function installClientHandlers(socket2, registry) {
3614
+ if (!registry.serverHandlerInstalled) {
3615
+ const onServerEvent = (frame) => {
3616
+ if (!frame || typeof frame !== "object" || typeof frame.roomType !== "string" || typeof frame.roomId !== "string" || typeof frame.name !== "string" || !frame.meta || typeof frame.meta !== "object" || typeof frame.meta.sentAt !== "string") {
3617
+ return;
3618
+ }
3619
+ const state = registry.joinedRooms.get(makeJoinedRoomKey(frame.roomType, frame.roomId));
3620
+ if (!state) {
3621
+ return;
3622
+ }
3623
+ const handlers = state.eventListeners.get(frame.name);
3624
+ if (!handlers || handlers.size === 0) {
3625
+ return;
3626
+ }
3627
+ const meta = {
3628
+ ...frame.meta,
3629
+ sentAt: new Date(frame.meta.sentAt)
3630
+ };
3631
+ for (const handler of handlers) {
3632
+ try {
3633
+ handler(frame.payload, meta);
3634
+ } catch {
3635
+ }
3636
+ }
3637
+ };
3638
+ socket2.on(SERVER_EVENT, onServerEvent);
3639
+ registry.serverHandlerInstalled = true;
3640
+ }
3641
+ if (!registry.presenceHandlerInstalled) {
3642
+ const onPresence = (frame) => {
3643
+ if (!frame || typeof frame !== "object" || typeof frame.roomType !== "string" || typeof frame.roomId !== "string") {
3644
+ return;
3645
+ }
3646
+ const state = registry.joinedRooms.get(makeJoinedRoomKey(frame.roomType, frame.roomId));
3647
+ if (!state) {
3648
+ return;
3649
+ }
3650
+ state.presenceCurrent = frame.presence;
3651
+ if (state.presenceCurrent === void 0) {
3652
+ return;
3653
+ }
3654
+ for (const handler of state.presenceListeners) {
3655
+ try {
3656
+ handler(state.presenceCurrent);
3657
+ } catch {
3658
+ }
3659
+ }
3660
+ };
3661
+ socket2.on(PRESENCE_EVENT, onPresence);
3662
+ registry.presenceHandlerInstalled = true;
3663
+ }
3664
+ if (!registry.reconnectHandlerInstalled) {
3665
+ const onConnect = () => {
3666
+ registry.hasConnectedOnce = true;
3667
+ setConnectionState(registry, "connected");
3668
+ void replayJoinedRooms(socket2, registry);
3669
+ };
3670
+ socket2.on("connect", onConnect);
3671
+ registry.reconnectHandlerInstalled = true;
3672
+ }
3673
+ if (!registry.disconnectHandlerInstalled) {
3674
+ const onDisconnect = () => {
3675
+ setConnectionState(registry, "disconnected");
3676
+ };
3677
+ socket2.on("disconnect", onDisconnect);
3678
+ registry.disconnectHandlerInstalled = true;
3679
+ }
3680
+ if (!registry.connectErrorHandlerInstalled) {
3681
+ const onConnectError = () => {
3682
+ setConnectionState(registry, registry.hasConnectedOnce ? "reconnecting" : "connecting");
3683
+ };
3684
+ socket2.on("connect_error", onConnectError);
3685
+ registry.connectErrorHandlerInstalled = true;
3686
+ }
3687
+ if (!registry.reconnectAttemptHandlerInstalled) {
3688
+ const onReconnectAttempt = () => {
3689
+ setConnectionState(registry, "reconnecting");
3690
+ };
3691
+ socket2.on("reconnect_attempt", onReconnectAttempt);
3692
+ registry.reconnectAttemptHandlerInstalled = true;
3693
+ }
3694
+ if (!registry.reconnectFailedHandlerInstalled) {
3695
+ const onReconnectFailed = () => {
3696
+ setConnectionState(registry, "disconnected");
3697
+ };
3698
+ socket2.on("reconnect_failed", onReconnectFailed);
3699
+ registry.reconnectFailedHandlerInstalled = true;
3700
+ }
3701
+ if (!registry.reconnectErrorHandlerInstalled) {
3702
+ const onReconnectError = () => {
3703
+ setConnectionState(registry, "reconnecting");
3704
+ };
3705
+ socket2.on("reconnect_error", onReconnectError);
3706
+ registry.reconnectErrorHandlerInstalled = true;
3707
+ }
3708
+ }
3709
+ async function replayJoinedRooms(socket2, registry) {
3710
+ for (const [key, state] of Array.from(registry.joinedRooms.entries())) {
3711
+ try {
3712
+ const value2 = await emitAck(socket2, JOIN_EVENT, {
3713
+ roomType: state.name,
3714
+ payload: state.joinRequest
3715
+ });
3716
+ state.roomId = value2.roomId;
3717
+ state.memberId = value2.memberId;
3718
+ state.roomProfile = value2.roomProfile;
3719
+ state.presenceCurrent = value2.presence;
3720
+ const newKey = makeJoinedRoomKey(state.name, value2.roomId);
3721
+ if (newKey !== key) {
3722
+ registry.joinedRooms.delete(key);
3723
+ }
3724
+ registry.joinedRooms.set(newKey, state);
3725
+ } catch {
3726
+ registry.joinedRooms.delete(key);
3727
+ }
3728
+ }
3729
+ }
3730
+ function makeJoinedRoomKey(name, roomId) {
3731
+ return `${name}:${roomId}`;
3732
+ }
3733
+ function emitAck(socket2, eventName, payload) {
3734
+ return new Promise((resolve, reject) => {
3735
+ const timer = setTimeout(() => {
3736
+ reject(new Error(`Acknowledgement timeout for '${eventName}'`));
3737
+ }, DEFAULT_ACK_TIMEOUT_MS);
3738
+ socket2.emit(eventName, payload, (result) => {
3739
+ clearTimeout(timer);
3740
+ if (!result || typeof result !== "object") {
3741
+ reject(new Error("Invalid acknowledgement payload"));
3742
+ return;
3743
+ }
3744
+ if (result.ok) {
3745
+ resolve(result.value);
3746
+ return;
3747
+ }
3748
+ reject(new Error(result.error));
3749
+ });
3750
+ });
3751
+ }
3752
+ function setConnectionState(registry, next) {
3753
+ if (registry.connectionState === next) {
3754
+ return;
3755
+ }
3756
+ registry.connectionState = next;
3757
+ for (const listener of registry.connectionListeners) {
3758
+ try {
3759
+ listener(next);
3760
+ } catch {
3761
+ }
3762
+ }
3763
+ }
3764
+
3765
+ // ../src/room.ts
3766
+ function defineRoomType(options) {
3767
+ return {
3768
+ kind: "room",
3769
+ name: options.name,
3770
+ presence: options.presence ?? "list"
3771
+ };
3772
+ }
3773
+
3774
+ // common.ts
3775
+ var chatRoomType = defineRoomType({ name: "example-chat", presence: "list" });
3776
+
3777
+ // public/app.ts
3778
+ var socket = lookup2();
3779
+ var chatClient = createRoomClient(socket, chatRoomType);
3780
+ var joinPanel = document.getElementById("join-panel");
3781
+ var workspace = document.getElementById("workspace");
3782
+ var joinForm = document.getElementById("join-form");
3783
+ var messageForm = document.getElementById("message-form");
3784
+ var leaveButton = document.getElementById("leave-button");
3785
+ var presencePrevButton = document.getElementById("presence-prev");
3786
+ var presenceNextButton = document.getElementById("presence-next");
3787
+ var status = document.getElementById("status");
3788
+ var roomTitle = document.getElementById("room-title");
3789
+ var roomSubtitle = document.getElementById("room-subtitle");
3790
+ var messages = document.getElementById("messages");
3791
+ var presenceList = document.getElementById("presence-list");
3792
+ var presenceCount = document.getElementById("presence-count");
3793
+ var presencePage = document.getElementById("presence-page");
3794
+ var nameInput = document.getElementById("name-input");
3795
+ var roomInput = document.getElementById("room-input");
3796
+ var keyInput = document.getElementById("key-input");
3797
+ var messageInput = document.getElementById("message-input");
3798
+ var joinedRoom = null;
3799
+ var stopRoomListeners = null;
3800
+ var presenceOffset = 0;
3801
+ var presencePageSize = 4;
3802
+ function setStatus(message) {
3803
+ status.textContent = message;
3804
+ }
3805
+ function setWorkspaceVisible(visible) {
3806
+ workspace.classList.toggle("hidden", !visible);
3807
+ joinPanel.classList.toggle("hidden", visible);
3808
+ }
3809
+ function clearMessages() {
3810
+ messages.innerHTML = "";
3811
+ }
3812
+ function renderMessage(message) {
3813
+ const item = document.createElement("article");
3814
+ item.className = "message";
3815
+ item.innerHTML = `
3816
+ <div class="message-header">
3817
+ <span class="message-name">${escapeHtml(message.name)}</span>
3818
+ <span class="message-time">${formatTime(message.sentAt)}</span>
3819
+ </div>
3820
+ <div class="message-text">${escapeHtml(message.text)}</div>
3821
+ `;
3822
+ messages.appendChild(item);
3823
+ messages.scrollTop = messages.scrollHeight;
3824
+ }
3825
+ function renderSystemNotice(text, sentAt) {
3826
+ const item = document.createElement("article");
3827
+ item.className = "message";
3828
+ item.innerHTML = `
3829
+ <div class="message-header">
3830
+ <span class="message-name">System</span>
3831
+ <span class="message-time">${formatTime(sentAt)}</span>
3832
+ </div>
3833
+ <div class="message-text">${escapeHtml(text)}</div>
3834
+ `;
3835
+ messages.appendChild(item);
3836
+ messages.scrollTop = messages.scrollHeight;
3837
+ }
3838
+ function renderHistory(history) {
3839
+ clearMessages();
3840
+ for (const message of history) {
3841
+ renderMessage(message);
3842
+ }
3843
+ }
3844
+ async function refreshPresence() {
3845
+ if (!joinedRoom) {
3846
+ return;
3847
+ }
3848
+ const [count, page] = await Promise.all([
3849
+ joinedRoom.presence.count(),
3850
+ joinedRoom.presence.list({ offset: presenceOffset, limit: presencePageSize })
3851
+ ]);
3852
+ presenceCount.textContent = `${count} online`;
3853
+ presencePage.textContent = page.members.length === 0 ? `Showing 0 of ${count} members.` : `Showing ${page.offset + 1}-${page.offset + page.members.length} of ${count} members.`;
3854
+ presenceList.innerHTML = "";
3855
+ if (page.members.length === 0) {
3856
+ const empty2 = document.createElement("li");
3857
+ empty2.className = "presence-empty";
3858
+ empty2.textContent = "Nobody is here yet.";
3859
+ presenceList.appendChild(empty2);
3860
+ return;
3861
+ }
3862
+ for (const entry of page.members) {
3863
+ const item = document.createElement("li");
3864
+ item.className = "presence-item";
3865
+ item.innerHTML = `
3866
+ <span>${escapeHtml(entry.memberProfile.userName)}</span>
3867
+ <span class="presence-pill" aria-hidden="true"></span>
3868
+ `;
3869
+ presenceList.appendChild(item);
3870
+ }
3871
+ }
3872
+ function formatTime(value2) {
3873
+ const date = new Date(value2);
3874
+ return Number.isNaN(date.getTime()) ? "" : new Intl.DateTimeFormat(void 0, {
3875
+ hour: "2-digit",
3876
+ minute: "2-digit"
3877
+ }).format(date);
3878
+ }
3879
+ function escapeHtml(value2) {
3880
+ return String(value2).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
3881
+ }
3882
+ async function connectRoom() {
3883
+ const payload = {
3884
+ roomId: roomInput.value.trim().toLowerCase(),
3885
+ roomKey: keyInput.value,
3886
+ userName: nameInput.value
3887
+ };
3888
+ setStatus("Joining room...");
3889
+ try {
3890
+ presenceOffset = 0;
3891
+ joinedRoom = await chatClient.join(payload);
3892
+ renderHistory(joinedRoom.roomProfile.history);
3893
+ stopRoomListeners = joinedRoom.listen({
3894
+ events: {
3895
+ message: (message) => {
3896
+ renderMessage(message);
3897
+ },
3898
+ systemNotice: (notice) => {
3899
+ renderSystemNotice(notice.text, notice.sentAt);
3900
+ }
3901
+ },
3902
+ presence: {
3903
+ onChange: () => {
3904
+ void refreshPresence();
3905
+ }
3906
+ }
3907
+ });
3908
+ await refreshPresence();
3909
+ roomTitle.textContent = joinedRoom.roomId;
3910
+ roomSubtitle.textContent = `Signed in as ${payload.userName}. The room stays private behind the shared key.`;
3911
+ setWorkspaceVisible(true);
3912
+ setStatus(`Connected to ${joinedRoom.roomId}.`);
3913
+ messageInput.focus();
3914
+ } catch (error) {
3915
+ joinedRoom = null;
3916
+ setStatus(error instanceof Error ? error.message : String(error));
3917
+ }
3918
+ }
3919
+ async function leaveRoom() {
3920
+ if (!joinedRoom) {
3921
+ return;
3922
+ }
3923
+ const roomId = joinedRoom.roomId;
3924
+ try {
3925
+ await joinedRoom.leave();
3926
+ } finally {
3927
+ stopRoomListeners?.();
3928
+ stopRoomListeners = null;
3929
+ joinedRoom = null;
3930
+ setWorkspaceVisible(false);
3931
+ joinForm.reset();
3932
+ clearMessages();
3933
+ presenceList.innerHTML = "";
3934
+ presenceCount.textContent = "0 online";
3935
+ presencePage.textContent = "Showing 0 members.";
3936
+ roomTitle.textContent = "-";
3937
+ roomSubtitle.textContent = "-";
3938
+ setStatus(`Left ${roomId}.`);
3939
+ }
3940
+ }
3941
+ joinForm.addEventListener("submit", async (event) => {
3942
+ event.preventDefault();
3943
+ await connectRoom();
3944
+ });
3945
+ messageForm.addEventListener("submit", async (event) => {
3946
+ event.preventDefault();
3947
+ if (!joinedRoom) {
3948
+ setStatus("Join a room before sending messages.");
3949
+ return;
3950
+ }
3951
+ const text = messageInput.value.trim();
3952
+ if (!text) {
3953
+ return;
3954
+ }
3955
+ try {
3956
+ await joinedRoom.rpc.sendMessage({ text });
3957
+ messageInput.value = "";
3958
+ } catch (error) {
3959
+ setStatus(error instanceof Error ? error.message : String(error));
3960
+ }
3961
+ });
3962
+ leaveButton.addEventListener("click", async () => {
3963
+ await leaveRoom();
3964
+ });
3965
+ presencePrevButton.addEventListener("click", async () => {
3966
+ if (!joinedRoom || presenceOffset === 0) {
3967
+ return;
3968
+ }
3969
+ presenceOffset = Math.max(0, presenceOffset - presencePageSize);
3970
+ await refreshPresence();
3971
+ });
3972
+ presenceNextButton.addEventListener("click", async () => {
3973
+ if (!joinedRoom) {
3974
+ return;
3975
+ }
3976
+ presenceOffset += presencePageSize;
3977
+ await refreshPresence();
3978
+ });
3979
+ socket.on("connect", () => {
3980
+ setStatus("Connected. Join a room to start chatting.");
3981
+ });
3982
+ socket.on("disconnect", () => {
3983
+ setStatus("Disconnected from the server.");
3984
+ });
3985
+ setWorkspaceVisible(false);
3986
+ setStatus("Connecting to server...");
3987
+ presencePage.textContent = "Showing 0 members.";
3988
+ })();