@nsshunt/stsrunnerframework 2.0.20 → 2.0.22

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.
package/dist/index.cjs CHANGED
@@ -6,7 +6,16 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
9
+ var __commonJSMin$1 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
10
+ var __exportAll = (all, no_symbols) => {
11
+ let target = {};
12
+ for (var name in all) __defProp(target, name, {
13
+ get: all[name],
14
+ enumerable: true
15
+ });
16
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
17
+ return target;
18
+ };
10
19
  var __copyProps = (to, from, except, desc) => {
11
20
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
21
  key = keys[i];
@@ -24,6 +33,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
33
  //#endregion
25
34
  let _nsshunt_stsutils = require("@nsshunt/stsutils");
26
35
  let _nsshunt_stsobservability = require("@nsshunt/stsobservability");
36
+ let fflate = require("fflate");
27
37
  //#region src/commonTypes.ts
28
38
  /**
29
39
  * Inter-Worker (IW) message commands.
@@ -1501,7 +1511,7 @@ var AbstractRunnerExecutionWorker = class {
1501
1511
  * - The broker itself does not interpret business meaning of unsolicited messages;
1502
1512
  * those are delegated to a caller-supplied callback
1503
1513
  */
1504
- var import_lodash_merge = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
1514
+ var import_lodash_merge = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin$1(((exports, module) => {
1505
1515
  /**
1506
1516
  * Lodash (Custom Build) <https://lodash.com/>
1507
1517
  * Build: `lodash modularize exports="npm" -o ./`
@@ -6584,11 +6594,3932 @@ var STSWorkerManager = class {
6584
6594
  };
6585
6595
  };
6586
6596
  //#endregion
6597
+ //#region node_modules/@nsshunt/stssocketioutils/dist/tiny-emitter-DB59cw42.js
6598
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
6599
+ var require_tiny_emitter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6600
+ function E() {}
6601
+ E.prototype = {
6602
+ on: function(name, callback, ctx) {
6603
+ var e = this.e || (this.e = {});
6604
+ (e[name] || (e[name] = [])).push({
6605
+ fn: callback,
6606
+ ctx
6607
+ });
6608
+ return this;
6609
+ },
6610
+ once: function(name, callback, ctx) {
6611
+ var self = this;
6612
+ function listener() {
6613
+ self.off(name, listener);
6614
+ callback.apply(ctx, arguments);
6615
+ }
6616
+ listener._ = callback;
6617
+ return this.on(name, listener, ctx);
6618
+ },
6619
+ emit: function(name) {
6620
+ var data = [].slice.call(arguments, 1);
6621
+ var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
6622
+ var i = 0;
6623
+ var len = evtArr.length;
6624
+ for (; i < len; i++) evtArr[i].fn.apply(evtArr[i].ctx, data);
6625
+ return this;
6626
+ },
6627
+ off: function(name, callback) {
6628
+ var e = this.e || (this.e = {});
6629
+ var evts = e[name];
6630
+ var liveEvents = [];
6631
+ if (evts && callback) {
6632
+ for (var i = 0, len = evts.length; i < len; i++) if (evts[i].fn !== callback && evts[i].fn._ !== callback) liveEvents.push(evts[i]);
6633
+ }
6634
+ liveEvents.length ? e[name] = liveEvents : delete e[name];
6635
+ return this;
6636
+ }
6637
+ };
6638
+ module.exports = E;
6639
+ module.exports.TinyEmitter = E;
6640
+ }));
6641
+ //#endregion
6642
+ //#region node_modules/engine.io-parser/build/esm/commons.js
6643
+ var PACKET_TYPES = Object.create(null);
6644
+ PACKET_TYPES["open"] = "0";
6645
+ PACKET_TYPES["close"] = "1";
6646
+ PACKET_TYPES["ping"] = "2";
6647
+ PACKET_TYPES["pong"] = "3";
6648
+ PACKET_TYPES["message"] = "4";
6649
+ PACKET_TYPES["upgrade"] = "5";
6650
+ PACKET_TYPES["noop"] = "6";
6651
+ var PACKET_TYPES_REVERSE = Object.create(null);
6652
+ Object.keys(PACKET_TYPES).forEach((key) => {
6653
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
6654
+ });
6655
+ var ERROR_PACKET = {
6656
+ type: "error",
6657
+ data: "parser error"
6658
+ };
6659
+ //#endregion
6660
+ //#region node_modules/engine.io-parser/build/esm/encodePacket.browser.js
6661
+ var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
6662
+ var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
6663
+ var isView$1 = (obj) => {
6664
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
6665
+ };
6666
+ var encodePacket = ({ type, data }, supportsBinary, callback) => {
6667
+ if (withNativeBlob$1 && data instanceof Blob) if (supportsBinary) return callback(data);
6668
+ else return encodeBlobAsBase64(data, callback);
6669
+ else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) if (supportsBinary) return callback(data);
6670
+ else return encodeBlobAsBase64(new Blob([data]), callback);
6671
+ return callback(PACKET_TYPES[type] + (data || ""));
6672
+ };
6673
+ var encodeBlobAsBase64 = (data, callback) => {
6674
+ const fileReader = new FileReader();
6675
+ fileReader.onload = function() {
6676
+ const content = fileReader.result.split(",")[1];
6677
+ callback("b" + (content || ""));
6678
+ };
6679
+ return fileReader.readAsDataURL(data);
6680
+ };
6681
+ function toArray(data) {
6682
+ if (data instanceof Uint8Array) return data;
6683
+ else if (data instanceof ArrayBuffer) return new Uint8Array(data);
6684
+ else return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
6685
+ }
6686
+ var TEXT_ENCODER;
6687
+ function encodePacketToBinary(packet, callback) {
6688
+ if (withNativeBlob$1 && packet.data instanceof Blob) return packet.data.arrayBuffer().then(toArray).then(callback);
6689
+ else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) return callback(toArray(packet.data));
6690
+ encodePacket(packet, false, (encoded) => {
6691
+ if (!TEXT_ENCODER) TEXT_ENCODER = new TextEncoder();
6692
+ callback(TEXT_ENCODER.encode(encoded));
6693
+ });
6694
+ }
6695
+ //#endregion
6696
+ //#region node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js
6697
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
6698
+ var lookup$1 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
6699
+ for (let i = 0; i < 64; i++) lookup$1[chars.charCodeAt(i)] = i;
6700
+ var decode$1 = (base64) => {
6701
+ let bufferLength = base64.length * .75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
6702
+ if (base64[base64.length - 1] === "=") {
6703
+ bufferLength--;
6704
+ if (base64[base64.length - 2] === "=") bufferLength--;
6705
+ }
6706
+ const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
6707
+ for (i = 0; i < len; i += 4) {
6708
+ encoded1 = lookup$1[base64.charCodeAt(i)];
6709
+ encoded2 = lookup$1[base64.charCodeAt(i + 1)];
6710
+ encoded3 = lookup$1[base64.charCodeAt(i + 2)];
6711
+ encoded4 = lookup$1[base64.charCodeAt(i + 3)];
6712
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
6713
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
6714
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
6715
+ }
6716
+ return arraybuffer;
6717
+ };
6718
+ //#endregion
6719
+ //#region node_modules/engine.io-parser/build/esm/decodePacket.browser.js
6720
+ var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
6721
+ var decodePacket = (encodedPacket, binaryType) => {
6722
+ if (typeof encodedPacket !== "string") return {
6723
+ type: "message",
6724
+ data: mapBinary(encodedPacket, binaryType)
6725
+ };
6726
+ const type = encodedPacket.charAt(0);
6727
+ if (type === "b") return {
6728
+ type: "message",
6729
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
6730
+ };
6731
+ if (!PACKET_TYPES_REVERSE[type]) return ERROR_PACKET;
6732
+ return encodedPacket.length > 1 ? {
6733
+ type: PACKET_TYPES_REVERSE[type],
6734
+ data: encodedPacket.substring(1)
6735
+ } : { type: PACKET_TYPES_REVERSE[type] };
6736
+ };
6737
+ var decodeBase64Packet = (data, binaryType) => {
6738
+ if (withNativeArrayBuffer$1) return mapBinary(decode$1(data), binaryType);
6739
+ else return {
6740
+ base64: true,
6741
+ data
6742
+ };
6743
+ };
6744
+ var mapBinary = (data, binaryType) => {
6745
+ switch (binaryType) {
6746
+ case "blob": if (data instanceof Blob) return data;
6747
+ else return new Blob([data]);
6748
+ default: if (data instanceof ArrayBuffer) return data;
6749
+ else return data.buffer;
6750
+ }
6751
+ };
6752
+ //#endregion
6753
+ //#region node_modules/engine.io-parser/build/esm/index.js
6754
+ var SEPARATOR = String.fromCharCode(30);
6755
+ var encodePayload = (packets, callback) => {
6756
+ const length = packets.length;
6757
+ const encodedPackets = new Array(length);
6758
+ let count = 0;
6759
+ packets.forEach((packet, i) => {
6760
+ encodePacket(packet, false, (encodedPacket) => {
6761
+ encodedPackets[i] = encodedPacket;
6762
+ if (++count === length) callback(encodedPackets.join(SEPARATOR));
6763
+ });
6764
+ });
6765
+ };
6766
+ var decodePayload = (encodedPayload, binaryType) => {
6767
+ const encodedPackets = encodedPayload.split(SEPARATOR);
6768
+ const packets = [];
6769
+ for (let i = 0; i < encodedPackets.length; i++) {
6770
+ const decodedPacket = decodePacket(encodedPackets[i], binaryType);
6771
+ packets.push(decodedPacket);
6772
+ if (decodedPacket.type === "error") break;
6773
+ }
6774
+ return packets;
6775
+ };
6776
+ function createPacketEncoderStream() {
6777
+ return new TransformStream({ transform(packet, controller) {
6778
+ encodePacketToBinary(packet, (encodedPacket) => {
6779
+ const payloadLength = encodedPacket.length;
6780
+ let header;
6781
+ if (payloadLength < 126) {
6782
+ header = new Uint8Array(1);
6783
+ new DataView(header.buffer).setUint8(0, payloadLength);
6784
+ } else if (payloadLength < 65536) {
6785
+ header = new Uint8Array(3);
6786
+ const view = new DataView(header.buffer);
6787
+ view.setUint8(0, 126);
6788
+ view.setUint16(1, payloadLength);
6789
+ } else {
6790
+ header = new Uint8Array(9);
6791
+ const view = new DataView(header.buffer);
6792
+ view.setUint8(0, 127);
6793
+ view.setBigUint64(1, BigInt(payloadLength));
6794
+ }
6795
+ if (packet.data && typeof packet.data !== "string") header[0] |= 128;
6796
+ controller.enqueue(header);
6797
+ controller.enqueue(encodedPacket);
6798
+ });
6799
+ } });
6800
+ }
6801
+ var TEXT_DECODER;
6802
+ function totalLength(chunks) {
6803
+ return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
6804
+ }
6805
+ function concatChunks(chunks, size) {
6806
+ if (chunks[0].length === size) return chunks.shift();
6807
+ const buffer = new Uint8Array(size);
6808
+ let j = 0;
6809
+ for (let i = 0; i < size; i++) {
6810
+ buffer[i] = chunks[0][j++];
6811
+ if (j === chunks[0].length) {
6812
+ chunks.shift();
6813
+ j = 0;
6814
+ }
6815
+ }
6816
+ if (chunks.length && j < chunks[0].length) chunks[0] = chunks[0].slice(j);
6817
+ return buffer;
6818
+ }
6819
+ function createPacketDecoderStream(maxPayload, binaryType) {
6820
+ if (!TEXT_DECODER) TEXT_DECODER = new TextDecoder();
6821
+ const chunks = [];
6822
+ let state = 0;
6823
+ let expectedLength = -1;
6824
+ let isBinary = false;
6825
+ return new TransformStream({ transform(chunk, controller) {
6826
+ chunks.push(chunk);
6827
+ while (true) {
6828
+ if (state === 0) {
6829
+ if (totalLength(chunks) < 1) break;
6830
+ const header = concatChunks(chunks, 1);
6831
+ isBinary = (header[0] & 128) === 128;
6832
+ expectedLength = header[0] & 127;
6833
+ if (expectedLength < 126) state = 3;
6834
+ else if (expectedLength === 126) state = 1;
6835
+ else state = 2;
6836
+ } else if (state === 1) {
6837
+ if (totalLength(chunks) < 2) break;
6838
+ const headerArray = concatChunks(chunks, 2);
6839
+ expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
6840
+ state = 3;
6841
+ } else if (state === 2) {
6842
+ if (totalLength(chunks) < 8) break;
6843
+ const headerArray = concatChunks(chunks, 8);
6844
+ const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
6845
+ const n = view.getUint32(0);
6846
+ if (n > Math.pow(2, 21) - 1) {
6847
+ controller.enqueue(ERROR_PACKET);
6848
+ break;
6849
+ }
6850
+ expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
6851
+ state = 3;
6852
+ } else {
6853
+ if (totalLength(chunks) < expectedLength) break;
6854
+ const data = concatChunks(chunks, expectedLength);
6855
+ controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
6856
+ state = 0;
6857
+ }
6858
+ if (expectedLength === 0 || expectedLength > maxPayload) {
6859
+ controller.enqueue(ERROR_PACKET);
6860
+ break;
6861
+ }
6862
+ }
6863
+ } });
6864
+ }
6865
+ //#endregion
6866
+ //#region node_modules/@socket.io/component-emitter/lib/esm/index.js
6867
+ /**
6868
+ * Initialize a new `Emitter`.
6869
+ *
6870
+ * @api public
6871
+ */
6872
+ function Emitter(obj) {
6873
+ if (obj) return mixin(obj);
6874
+ }
6875
+ /**
6876
+ * Mixin the emitter properties.
6877
+ *
6878
+ * @param {Object} obj
6879
+ * @return {Object}
6880
+ * @api private
6881
+ */
6882
+ function mixin(obj) {
6883
+ for (var key in Emitter.prototype) obj[key] = Emitter.prototype[key];
6884
+ return obj;
6885
+ }
6886
+ /**
6887
+ * Listen on the given `event` with `fn`.
6888
+ *
6889
+ * @param {String} event
6890
+ * @param {Function} fn
6891
+ * @return {Emitter}
6892
+ * @api public
6893
+ */
6894
+ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
6895
+ this._callbacks = this._callbacks || {};
6896
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
6897
+ return this;
6898
+ };
6899
+ /**
6900
+ * Adds an `event` listener that will be invoked a single
6901
+ * time then automatically removed.
6902
+ *
6903
+ * @param {String} event
6904
+ * @param {Function} fn
6905
+ * @return {Emitter}
6906
+ * @api public
6907
+ */
6908
+ Emitter.prototype.once = function(event, fn) {
6909
+ function on() {
6910
+ this.off(event, on);
6911
+ fn.apply(this, arguments);
6912
+ }
6913
+ on.fn = fn;
6914
+ this.on(event, on);
6915
+ return this;
6916
+ };
6917
+ /**
6918
+ * Remove the given callback for `event` or all
6919
+ * registered callbacks.
6920
+ *
6921
+ * @param {String} event
6922
+ * @param {Function} fn
6923
+ * @return {Emitter}
6924
+ * @api public
6925
+ */
6926
+ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
6927
+ this._callbacks = this._callbacks || {};
6928
+ if (0 == arguments.length) {
6929
+ this._callbacks = {};
6930
+ return this;
6931
+ }
6932
+ var callbacks = this._callbacks["$" + event];
6933
+ if (!callbacks) return this;
6934
+ if (1 == arguments.length) {
6935
+ delete this._callbacks["$" + event];
6936
+ return this;
6937
+ }
6938
+ var cb;
6939
+ for (var i = 0; i < callbacks.length; i++) {
6940
+ cb = callbacks[i];
6941
+ if (cb === fn || cb.fn === fn) {
6942
+ callbacks.splice(i, 1);
6943
+ break;
6944
+ }
6945
+ }
6946
+ if (callbacks.length === 0) delete this._callbacks["$" + event];
6947
+ return this;
6948
+ };
6949
+ /**
6950
+ * Emit `event` with the given args.
6951
+ *
6952
+ * @param {String} event
6953
+ * @param {Mixed} ...
6954
+ * @return {Emitter}
6955
+ */
6956
+ Emitter.prototype.emit = function(event) {
6957
+ this._callbacks = this._callbacks || {};
6958
+ var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
6959
+ for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i];
6960
+ if (callbacks) {
6961
+ callbacks = callbacks.slice(0);
6962
+ for (var i = 0, len = callbacks.length; i < len; ++i) callbacks[i].apply(this, args);
6963
+ }
6964
+ return this;
6965
+ };
6966
+ Emitter.prototype.emitReserved = Emitter.prototype.emit;
6967
+ /**
6968
+ * Return array of callbacks for `event`.
6969
+ *
6970
+ * @param {String} event
6971
+ * @return {Array}
6972
+ * @api public
6973
+ */
6974
+ Emitter.prototype.listeners = function(event) {
6975
+ this._callbacks = this._callbacks || {};
6976
+ return this._callbacks["$" + event] || [];
6977
+ };
6978
+ /**
6979
+ * Check if this emitter has `event` handlers.
6980
+ *
6981
+ * @param {String} event
6982
+ * @return {Boolean}
6983
+ * @api public
6984
+ */
6985
+ Emitter.prototype.hasListeners = function(event) {
6986
+ return !!this.listeners(event).length;
6987
+ };
6988
+ //#endregion
6989
+ //#region node_modules/engine.io-client/build/esm/globals.js
6990
+ var nextTick = (() => {
6991
+ if (typeof Promise === "function" && typeof Promise.resolve === "function") return (cb) => Promise.resolve().then(cb);
6992
+ else return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
6993
+ })();
6994
+ var globalThisShim = (() => {
6995
+ if (typeof self !== "undefined") return self;
6996
+ else if (typeof window !== "undefined") return window;
6997
+ else return Function("return this")();
6998
+ })();
6999
+ var defaultBinaryType = "arraybuffer";
7000
+ function createCookieJar() {}
7001
+ //#endregion
7002
+ //#region node_modules/engine.io-client/build/esm/util.js
7003
+ function pick(obj, ...attr) {
7004
+ return attr.reduce((acc, k) => {
7005
+ if (obj.hasOwnProperty(k)) acc[k] = obj[k];
7006
+ return acc;
7007
+ }, {});
7008
+ }
7009
+ var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
7010
+ var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
7011
+ function installTimerFunctions(obj, opts) {
7012
+ if (opts.useNativeTimers) {
7013
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
7014
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
7015
+ } else {
7016
+ obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
7017
+ obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
7018
+ }
7019
+ }
7020
+ var BASE64_OVERHEAD = 1.33;
7021
+ function byteLength(obj) {
7022
+ if (typeof obj === "string") return utf8Length(obj);
7023
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
7024
+ }
7025
+ function utf8Length(str) {
7026
+ let c = 0, length = 0;
7027
+ for (let i = 0, l = str.length; i < l; i++) {
7028
+ c = str.charCodeAt(i);
7029
+ if (c < 128) length += 1;
7030
+ else if (c < 2048) length += 2;
7031
+ else if (c < 55296 || c >= 57344) length += 3;
7032
+ else {
7033
+ i++;
7034
+ length += 4;
7035
+ }
7036
+ }
7037
+ return length;
7038
+ }
7039
+ /**
7040
+ * Generates a random 8-characters string.
7041
+ */
7042
+ function randomString() {
7043
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
7044
+ }
7045
+ //#endregion
7046
+ //#region node_modules/engine.io-client/build/esm/contrib/parseqs.js
7047
+ /**
7048
+ * Compiles a querystring
7049
+ * Returns string representation of the object
7050
+ *
7051
+ * @param {Object}
7052
+ * @api private
7053
+ */
7054
+ function encode(obj) {
7055
+ let str = "";
7056
+ for (let i in obj) if (obj.hasOwnProperty(i)) {
7057
+ if (str.length) str += "&";
7058
+ str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
7059
+ }
7060
+ return str;
7061
+ }
7062
+ /**
7063
+ * Parses a simple querystring into an object
7064
+ *
7065
+ * @param {String} qs
7066
+ * @api private
7067
+ */
7068
+ function decode(qs) {
7069
+ let qry = {};
7070
+ let pairs = qs.split("&");
7071
+ for (let i = 0, l = pairs.length; i < l; i++) {
7072
+ let pair = pairs[i].split("=");
7073
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
7074
+ }
7075
+ return qry;
7076
+ }
7077
+ //#endregion
7078
+ //#region node_modules/engine.io-client/build/esm/transport.js
7079
+ var TransportError = class extends Error {
7080
+ constructor(reason, description, context) {
7081
+ super(reason);
7082
+ this.description = description;
7083
+ this.context = context;
7084
+ this.type = "TransportError";
7085
+ }
7086
+ };
7087
+ var Transport = class extends Emitter {
7088
+ /**
7089
+ * Transport abstract constructor.
7090
+ *
7091
+ * @param {Object} opts - options
7092
+ * @protected
7093
+ */
7094
+ constructor(opts) {
7095
+ super();
7096
+ this.writable = false;
7097
+ installTimerFunctions(this, opts);
7098
+ this.opts = opts;
7099
+ this.query = opts.query;
7100
+ this.socket = opts.socket;
7101
+ this.supportsBinary = !opts.forceBase64;
7102
+ }
7103
+ /**
7104
+ * Emits an error.
7105
+ *
7106
+ * @param {String} reason
7107
+ * @param description
7108
+ * @param context - the error context
7109
+ * @return {Transport} for chaining
7110
+ * @protected
7111
+ */
7112
+ onError(reason, description, context) {
7113
+ super.emitReserved("error", new TransportError(reason, description, context));
7114
+ return this;
7115
+ }
7116
+ /**
7117
+ * Opens the transport.
7118
+ */
7119
+ open() {
7120
+ this.readyState = "opening";
7121
+ this.doOpen();
7122
+ return this;
7123
+ }
7124
+ /**
7125
+ * Closes the transport.
7126
+ */
7127
+ close() {
7128
+ if (this.readyState === "opening" || this.readyState === "open") {
7129
+ this.doClose();
7130
+ this.onClose();
7131
+ }
7132
+ return this;
7133
+ }
7134
+ /**
7135
+ * Sends multiple packets.
7136
+ *
7137
+ * @param {Array} packets
7138
+ */
7139
+ send(packets) {
7140
+ if (this.readyState === "open") this.write(packets);
7141
+ }
7142
+ /**
7143
+ * Called upon open
7144
+ *
7145
+ * @protected
7146
+ */
7147
+ onOpen() {
7148
+ this.readyState = "open";
7149
+ this.writable = true;
7150
+ super.emitReserved("open");
7151
+ }
7152
+ /**
7153
+ * Called with data.
7154
+ *
7155
+ * @param {String} data
7156
+ * @protected
7157
+ */
7158
+ onData(data) {
7159
+ const packet = decodePacket(data, this.socket.binaryType);
7160
+ this.onPacket(packet);
7161
+ }
7162
+ /**
7163
+ * Called with a decoded packet.
7164
+ *
7165
+ * @protected
7166
+ */
7167
+ onPacket(packet) {
7168
+ super.emitReserved("packet", packet);
7169
+ }
7170
+ /**
7171
+ * Called upon close.
7172
+ *
7173
+ * @protected
7174
+ */
7175
+ onClose(details) {
7176
+ this.readyState = "closed";
7177
+ super.emitReserved("close", details);
7178
+ }
7179
+ /**
7180
+ * Pauses the transport, in order not to lose packets during an upgrade.
7181
+ *
7182
+ * @param onPause
7183
+ */
7184
+ pause(onPause) {}
7185
+ createUri(schema, query = {}) {
7186
+ return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
7187
+ }
7188
+ _hostname() {
7189
+ const hostname = this.opts.hostname;
7190
+ return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
7191
+ }
7192
+ _port() {
7193
+ if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) return ":" + this.opts.port;
7194
+ else return "";
7195
+ }
7196
+ _query(query) {
7197
+ const encodedQuery = encode(query);
7198
+ return encodedQuery.length ? "?" + encodedQuery : "";
7199
+ }
7200
+ };
7201
+ //#endregion
7202
+ //#region node_modules/engine.io-client/build/esm/transports/polling.js
7203
+ var Polling = class extends Transport {
7204
+ constructor() {
7205
+ super(...arguments);
7206
+ this._polling = false;
7207
+ }
7208
+ get name() {
7209
+ return "polling";
7210
+ }
7211
+ /**
7212
+ * Opens the socket (triggers polling). We write a PING message to determine
7213
+ * when the transport is open.
7214
+ *
7215
+ * @protected
7216
+ */
7217
+ doOpen() {
7218
+ this._poll();
7219
+ }
7220
+ /**
7221
+ * Pauses polling.
7222
+ *
7223
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
7224
+ * @package
7225
+ */
7226
+ pause(onPause) {
7227
+ this.readyState = "pausing";
7228
+ const pause = () => {
7229
+ this.readyState = "paused";
7230
+ onPause();
7231
+ };
7232
+ if (this._polling || !this.writable) {
7233
+ let total = 0;
7234
+ if (this._polling) {
7235
+ total++;
7236
+ this.once("pollComplete", function() {
7237
+ --total || pause();
7238
+ });
7239
+ }
7240
+ if (!this.writable) {
7241
+ total++;
7242
+ this.once("drain", function() {
7243
+ --total || pause();
7244
+ });
7245
+ }
7246
+ } else pause();
7247
+ }
7248
+ /**
7249
+ * Starts polling cycle.
7250
+ *
7251
+ * @private
7252
+ */
7253
+ _poll() {
7254
+ this._polling = true;
7255
+ this.doPoll();
7256
+ this.emitReserved("poll");
7257
+ }
7258
+ /**
7259
+ * Overloads onData to detect payloads.
7260
+ *
7261
+ * @protected
7262
+ */
7263
+ onData(data) {
7264
+ const callback = (packet) => {
7265
+ if ("opening" === this.readyState && packet.type === "open") this.onOpen();
7266
+ if ("close" === packet.type) {
7267
+ this.onClose({ description: "transport closed by the server" });
7268
+ return false;
7269
+ }
7270
+ this.onPacket(packet);
7271
+ };
7272
+ decodePayload(data, this.socket.binaryType).forEach(callback);
7273
+ if ("closed" !== this.readyState) {
7274
+ this._polling = false;
7275
+ this.emitReserved("pollComplete");
7276
+ if ("open" === this.readyState) this._poll();
7277
+ }
7278
+ }
7279
+ /**
7280
+ * For polling, send a close packet.
7281
+ *
7282
+ * @protected
7283
+ */
7284
+ doClose() {
7285
+ const close = () => {
7286
+ this.write([{ type: "close" }]);
7287
+ };
7288
+ if ("open" === this.readyState) close();
7289
+ else this.once("open", close);
7290
+ }
7291
+ /**
7292
+ * Writes a packets payload.
7293
+ *
7294
+ * @param {Array} packets - data packets
7295
+ * @protected
7296
+ */
7297
+ write(packets) {
7298
+ this.writable = false;
7299
+ encodePayload(packets, (data) => {
7300
+ this.doWrite(data, () => {
7301
+ this.writable = true;
7302
+ this.emitReserved("drain");
7303
+ });
7304
+ });
7305
+ }
7306
+ /**
7307
+ * Generates uri for connection.
7308
+ *
7309
+ * @private
7310
+ */
7311
+ uri() {
7312
+ const schema = this.opts.secure ? "https" : "http";
7313
+ const query = this.query || {};
7314
+ if (false !== this.opts.timestampRequests) query[this.opts.timestampParam] = randomString();
7315
+ if (!this.supportsBinary && !query.sid) query.b64 = 1;
7316
+ return this.createUri(schema, query);
7317
+ }
7318
+ };
7319
+ //#endregion
7320
+ //#region node_modules/engine.io-client/build/esm/contrib/has-cors.js
7321
+ var value = false;
7322
+ try {
7323
+ value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
7324
+ } catch (err) {}
7325
+ var hasCORS = value;
7326
+ //#endregion
7327
+ //#region node_modules/engine.io-client/build/esm/transports/polling-xhr.js
7328
+ function empty() {}
7329
+ var BaseXHR = class extends Polling {
7330
+ /**
7331
+ * XHR Polling constructor.
7332
+ *
7333
+ * @param {Object} opts
7334
+ * @package
7335
+ */
7336
+ constructor(opts) {
7337
+ super(opts);
7338
+ if (typeof location !== "undefined") {
7339
+ const isSSL = "https:" === location.protocol;
7340
+ let port = location.port;
7341
+ if (!port) port = isSSL ? "443" : "80";
7342
+ this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
7343
+ }
7344
+ }
7345
+ /**
7346
+ * Sends data.
7347
+ *
7348
+ * @param {String} data to send.
7349
+ * @param {Function} called upon flush.
7350
+ * @private
7351
+ */
7352
+ doWrite(data, fn) {
7353
+ const req = this.request({
7354
+ method: "POST",
7355
+ data
7356
+ });
7357
+ req.on("success", fn);
7358
+ req.on("error", (xhrStatus, context) => {
7359
+ this.onError("xhr post error", xhrStatus, context);
7360
+ });
7361
+ }
7362
+ /**
7363
+ * Starts a poll cycle.
7364
+ *
7365
+ * @private
7366
+ */
7367
+ doPoll() {
7368
+ const req = this.request();
7369
+ req.on("data", this.onData.bind(this));
7370
+ req.on("error", (xhrStatus, context) => {
7371
+ this.onError("xhr poll error", xhrStatus, context);
7372
+ });
7373
+ this.pollXhr = req;
7374
+ }
7375
+ };
7376
+ var Request = class Request extends Emitter {
7377
+ /**
7378
+ * Request constructor
7379
+ *
7380
+ * @param {Object} options
7381
+ * @package
7382
+ */
7383
+ constructor(createRequest, uri, opts) {
7384
+ super();
7385
+ this.createRequest = createRequest;
7386
+ installTimerFunctions(this, opts);
7387
+ this._opts = opts;
7388
+ this._method = opts.method || "GET";
7389
+ this._uri = uri;
7390
+ this._data = void 0 !== opts.data ? opts.data : null;
7391
+ this._create();
7392
+ }
7393
+ /**
7394
+ * Creates the XHR object and sends the request.
7395
+ *
7396
+ * @private
7397
+ */
7398
+ _create() {
7399
+ var _a;
7400
+ const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
7401
+ opts.xdomain = !!this._opts.xd;
7402
+ const xhr = this._xhr = this.createRequest(opts);
7403
+ try {
7404
+ xhr.open(this._method, this._uri, true);
7405
+ try {
7406
+ if (this._opts.extraHeaders) {
7407
+ xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
7408
+ for (let i in this._opts.extraHeaders) if (this._opts.extraHeaders.hasOwnProperty(i)) xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
7409
+ }
7410
+ } catch (e) {}
7411
+ if ("POST" === this._method) try {
7412
+ xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
7413
+ } catch (e) {}
7414
+ try {
7415
+ xhr.setRequestHeader("Accept", "*/*");
7416
+ } catch (e) {}
7417
+ (_a = this._opts.cookieJar) === null || _a === void 0 || _a.addCookies(xhr);
7418
+ if ("withCredentials" in xhr) xhr.withCredentials = this._opts.withCredentials;
7419
+ if (this._opts.requestTimeout) xhr.timeout = this._opts.requestTimeout;
7420
+ xhr.onreadystatechange = () => {
7421
+ var _a;
7422
+ if (xhr.readyState === 3) (_a = this._opts.cookieJar) === null || _a === void 0 || _a.parseCookies(xhr.getResponseHeader("set-cookie"));
7423
+ if (4 !== xhr.readyState) return;
7424
+ if (200 === xhr.status || 1223 === xhr.status) this._onLoad();
7425
+ else this.setTimeoutFn(() => {
7426
+ this._onError(typeof xhr.status === "number" ? xhr.status : 0);
7427
+ }, 0);
7428
+ };
7429
+ xhr.send(this._data);
7430
+ } catch (e) {
7431
+ this.setTimeoutFn(() => {
7432
+ this._onError(e);
7433
+ }, 0);
7434
+ return;
7435
+ }
7436
+ if (typeof document !== "undefined") {
7437
+ this._index = Request.requestsCount++;
7438
+ Request.requests[this._index] = this;
7439
+ }
7440
+ }
7441
+ /**
7442
+ * Called upon error.
7443
+ *
7444
+ * @private
7445
+ */
7446
+ _onError(err) {
7447
+ this.emitReserved("error", err, this._xhr);
7448
+ this._cleanup(true);
7449
+ }
7450
+ /**
7451
+ * Cleans up house.
7452
+ *
7453
+ * @private
7454
+ */
7455
+ _cleanup(fromError) {
7456
+ if ("undefined" === typeof this._xhr || null === this._xhr) return;
7457
+ this._xhr.onreadystatechange = empty;
7458
+ if (fromError) try {
7459
+ this._xhr.abort();
7460
+ } catch (e) {}
7461
+ if (typeof document !== "undefined") delete Request.requests[this._index];
7462
+ this._xhr = null;
7463
+ }
7464
+ /**
7465
+ * Called upon load.
7466
+ *
7467
+ * @private
7468
+ */
7469
+ _onLoad() {
7470
+ const data = this._xhr.responseText;
7471
+ if (data !== null) {
7472
+ this.emitReserved("data", data);
7473
+ this.emitReserved("success");
7474
+ this._cleanup();
7475
+ }
7476
+ }
7477
+ /**
7478
+ * Aborts the request.
7479
+ *
7480
+ * @package
7481
+ */
7482
+ abort() {
7483
+ this._cleanup();
7484
+ }
7485
+ };
7486
+ Request.requestsCount = 0;
7487
+ Request.requests = {};
7488
+ /**
7489
+ * Aborts pending requests when unloading the window. This is needed to prevent
7490
+ * memory leaks (e.g. when using IE) and to ensure that no spurious error is
7491
+ * emitted.
7492
+ */
7493
+ if (typeof document !== "undefined") {
7494
+ if (typeof attachEvent === "function") attachEvent("onunload", unloadHandler);
7495
+ else if (typeof addEventListener === "function") {
7496
+ const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
7497
+ addEventListener(terminationEvent, unloadHandler, false);
7498
+ }
7499
+ }
7500
+ function unloadHandler() {
7501
+ for (let i in Request.requests) if (Request.requests.hasOwnProperty(i)) Request.requests[i].abort();
7502
+ }
7503
+ var hasXHR2 = (function() {
7504
+ const xhr = newRequest({ xdomain: false });
7505
+ return xhr && xhr.responseType !== null;
7506
+ })();
7507
+ /**
7508
+ * HTTP long-polling based on the built-in `XMLHttpRequest` object.
7509
+ *
7510
+ * Usage: browser
7511
+ *
7512
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
7513
+ */
7514
+ var XHR = class extends BaseXHR {
7515
+ constructor(opts) {
7516
+ super(opts);
7517
+ const forceBase64 = opts && opts.forceBase64;
7518
+ this.supportsBinary = hasXHR2 && !forceBase64;
7519
+ }
7520
+ request(opts = {}) {
7521
+ Object.assign(opts, { xd: this.xd }, this.opts);
7522
+ return new Request(newRequest, this.uri(), opts);
7523
+ }
7524
+ };
7525
+ function newRequest(opts) {
7526
+ const xdomain = opts.xdomain;
7527
+ try {
7528
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) return new XMLHttpRequest();
7529
+ } catch (e) {}
7530
+ if (!xdomain) try {
7531
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
7532
+ } catch (e) {}
7533
+ }
7534
+ //#endregion
7535
+ //#region node_modules/engine.io-client/build/esm/transports/websocket.js
7536
+ var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
7537
+ var BaseWS = class extends Transport {
7538
+ get name() {
7539
+ return "websocket";
7540
+ }
7541
+ doOpen() {
7542
+ const uri = this.uri();
7543
+ const protocols = this.opts.protocols;
7544
+ const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
7545
+ if (this.opts.extraHeaders) opts.headers = this.opts.extraHeaders;
7546
+ try {
7547
+ this.ws = this.createSocket(uri, protocols, opts);
7548
+ } catch (err) {
7549
+ return this.emitReserved("error", err);
7550
+ }
7551
+ this.ws.binaryType = this.socket.binaryType;
7552
+ this.addEventListeners();
7553
+ }
7554
+ /**
7555
+ * Adds event listeners to the socket
7556
+ *
7557
+ * @private
7558
+ */
7559
+ addEventListeners() {
7560
+ this.ws.onopen = () => {
7561
+ if (this.opts.autoUnref) this.ws._socket.unref();
7562
+ this.onOpen();
7563
+ };
7564
+ this.ws.onclose = (closeEvent) => this.onClose({
7565
+ description: "websocket connection closed",
7566
+ context: closeEvent
7567
+ });
7568
+ this.ws.onmessage = (ev) => this.onData(ev.data);
7569
+ this.ws.onerror = (e) => this.onError("websocket error", e);
7570
+ }
7571
+ write(packets) {
7572
+ this.writable = false;
7573
+ for (let i = 0; i < packets.length; i++) {
7574
+ const packet = packets[i];
7575
+ const lastPacket = i === packets.length - 1;
7576
+ encodePacket(packet, this.supportsBinary, (data) => {
7577
+ try {
7578
+ this.doWrite(packet, data);
7579
+ } catch (e) {}
7580
+ if (lastPacket) nextTick(() => {
7581
+ this.writable = true;
7582
+ this.emitReserved("drain");
7583
+ }, this.setTimeoutFn);
7584
+ });
7585
+ }
7586
+ }
7587
+ doClose() {
7588
+ if (typeof this.ws !== "undefined") {
7589
+ this.ws.onerror = () => {};
7590
+ this.ws.close();
7591
+ this.ws = null;
7592
+ }
7593
+ }
7594
+ /**
7595
+ * Generates uri for connection.
7596
+ *
7597
+ * @private
7598
+ */
7599
+ uri() {
7600
+ const schema = this.opts.secure ? "wss" : "ws";
7601
+ const query = this.query || {};
7602
+ if (this.opts.timestampRequests) query[this.opts.timestampParam] = randomString();
7603
+ if (!this.supportsBinary) query.b64 = 1;
7604
+ return this.createUri(schema, query);
7605
+ }
7606
+ };
7607
+ var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
7608
+ /**
7609
+ * WebSocket transport based on the built-in `WebSocket` object.
7610
+ *
7611
+ * Usage: browser, Node.js (since v21), Deno, Bun
7612
+ *
7613
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
7614
+ * @see https://caniuse.com/mdn-api_websocket
7615
+ * @see https://nodejs.org/api/globals.html#websocket
7616
+ */
7617
+ var WS = class extends BaseWS {
7618
+ createSocket(uri, protocols, opts) {
7619
+ return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
7620
+ }
7621
+ doWrite(_packet, data) {
7622
+ this.ws.send(data);
7623
+ }
7624
+ };
7625
+ //#endregion
7626
+ //#region node_modules/engine.io-client/build/esm/transports/webtransport.js
7627
+ /**
7628
+ * WebTransport transport based on the built-in `WebTransport` object.
7629
+ *
7630
+ * Usage: browser, Node.js (with the `@fails-components/webtransport` package)
7631
+ *
7632
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebTransport
7633
+ * @see https://caniuse.com/webtransport
7634
+ */
7635
+ var WT = class extends Transport {
7636
+ get name() {
7637
+ return "webtransport";
7638
+ }
7639
+ doOpen() {
7640
+ try {
7641
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
7642
+ } catch (err) {
7643
+ return this.emitReserved("error", err);
7644
+ }
7645
+ this._transport.closed.then(() => {
7646
+ this.onClose();
7647
+ }).catch((err) => {
7648
+ this.onError("webtransport error", err);
7649
+ });
7650
+ this._transport.ready.then(() => {
7651
+ this._transport.createBidirectionalStream().then((stream) => {
7652
+ const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
7653
+ const reader = stream.readable.pipeThrough(decoderStream).getReader();
7654
+ const encoderStream = createPacketEncoderStream();
7655
+ encoderStream.readable.pipeTo(stream.writable);
7656
+ this._writer = encoderStream.writable.getWriter();
7657
+ const read = () => {
7658
+ reader.read().then(({ done, value }) => {
7659
+ if (done) return;
7660
+ this.onPacket(value);
7661
+ read();
7662
+ }).catch((err) => {});
7663
+ };
7664
+ read();
7665
+ const packet = { type: "open" };
7666
+ if (this.query.sid) packet.data = `{"sid":"${this.query.sid}"}`;
7667
+ this._writer.write(packet).then(() => this.onOpen());
7668
+ });
7669
+ });
7670
+ }
7671
+ write(packets) {
7672
+ this.writable = false;
7673
+ for (let i = 0; i < packets.length; i++) {
7674
+ const packet = packets[i];
7675
+ const lastPacket = i === packets.length - 1;
7676
+ this._writer.write(packet).then(() => {
7677
+ if (lastPacket) nextTick(() => {
7678
+ this.writable = true;
7679
+ this.emitReserved("drain");
7680
+ }, this.setTimeoutFn);
7681
+ });
7682
+ }
7683
+ }
7684
+ doClose() {
7685
+ var _a;
7686
+ (_a = this._transport) === null || _a === void 0 || _a.close();
7687
+ }
7688
+ };
7689
+ //#endregion
7690
+ //#region node_modules/engine.io-client/build/esm/transports/index.js
7691
+ var transports = {
7692
+ websocket: WS,
7693
+ webtransport: WT,
7694
+ polling: XHR
7695
+ };
7696
+ //#endregion
7697
+ //#region node_modules/engine.io-client/build/esm/contrib/parseuri.js
7698
+ /**
7699
+ * Parses a URI
7700
+ *
7701
+ * Note: we could also have used the built-in URL object, but it isn't supported on all platforms.
7702
+ *
7703
+ * See:
7704
+ * - https://developer.mozilla.org/en-US/docs/Web/API/URL
7705
+ * - https://caniuse.com/url
7706
+ * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B
7707
+ *
7708
+ * History of the parse() method:
7709
+ * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c
7710
+ * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3
7711
+ * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242
7712
+ *
7713
+ * @author Steven Levithan <stevenlevithan.com> (MIT license)
7714
+ * @api private
7715
+ */
7716
+ var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
7717
+ var parts = [
7718
+ "source",
7719
+ "protocol",
7720
+ "authority",
7721
+ "userInfo",
7722
+ "user",
7723
+ "password",
7724
+ "host",
7725
+ "port",
7726
+ "relative",
7727
+ "path",
7728
+ "directory",
7729
+ "file",
7730
+ "query",
7731
+ "anchor"
7732
+ ];
7733
+ function parse(str) {
7734
+ if (str.length > 8e3) throw "URI too long";
7735
+ const src = str, b = str.indexOf("["), e = str.indexOf("]");
7736
+ if (b != -1 && e != -1) str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
7737
+ let m = re.exec(str || ""), uri = {}, i = 14;
7738
+ while (i--) uri[parts[i]] = m[i] || "";
7739
+ if (b != -1 && e != -1) {
7740
+ uri.source = src;
7741
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
7742
+ uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
7743
+ uri.ipv6uri = true;
7744
+ }
7745
+ uri.pathNames = pathNames(uri, uri["path"]);
7746
+ uri.queryKey = queryKey(uri, uri["query"]);
7747
+ return uri;
7748
+ }
7749
+ function pathNames(obj, path) {
7750
+ const names = path.replace(/\/{2,9}/g, "/").split("/");
7751
+ if (path.slice(0, 1) == "/" || path.length === 0) names.splice(0, 1);
7752
+ if (path.slice(-1) == "/") names.splice(names.length - 1, 1);
7753
+ return names;
7754
+ }
7755
+ function queryKey(uri, query) {
7756
+ const data = {};
7757
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
7758
+ if ($1) data[$1] = $2;
7759
+ });
7760
+ return data;
7761
+ }
7762
+ //#endregion
7763
+ //#region node_modules/engine.io-client/build/esm/socket.js
7764
+ var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
7765
+ var OFFLINE_EVENT_LISTENERS = [];
7766
+ if (withEventListeners) addEventListener("offline", () => {
7767
+ OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
7768
+ }, false);
7769
+ /**
7770
+ * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
7771
+ * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
7772
+ *
7773
+ * This class comes without upgrade mechanism, which means that it will keep the first low-level transport that
7774
+ * successfully establishes the connection.
7775
+ *
7776
+ * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
7777
+ *
7778
+ * @example
7779
+ * import { SocketWithoutUpgrade, WebSocket } from "engine.io-client";
7780
+ *
7781
+ * const socket = new SocketWithoutUpgrade({
7782
+ * transports: [WebSocket]
7783
+ * });
7784
+ *
7785
+ * socket.on("open", () => {
7786
+ * socket.send("hello");
7787
+ * });
7788
+ *
7789
+ * @see SocketWithUpgrade
7790
+ * @see Socket
7791
+ */
7792
+ var SocketWithoutUpgrade = class SocketWithoutUpgrade extends Emitter {
7793
+ /**
7794
+ * Socket constructor.
7795
+ *
7796
+ * @param {String|Object} uri - uri or options
7797
+ * @param {Object} opts - options
7798
+ */
7799
+ constructor(uri, opts) {
7800
+ super();
7801
+ this.binaryType = defaultBinaryType;
7802
+ this.writeBuffer = [];
7803
+ this._prevBufferLen = 0;
7804
+ this._pingInterval = -1;
7805
+ this._pingTimeout = -1;
7806
+ this._maxPayload = -1;
7807
+ /**
7808
+ * The expiration timestamp of the {@link _pingTimeoutTimer} object is tracked, in case the timer is throttled and the
7809
+ * callback is not fired on time. This can happen for example when a laptop is suspended or when a phone is locked.
7810
+ */
7811
+ this._pingTimeoutTime = Infinity;
7812
+ if (uri && "object" === typeof uri) {
7813
+ opts = uri;
7814
+ uri = null;
7815
+ }
7816
+ if (uri) {
7817
+ const parsedUri = parse(uri);
7818
+ opts.hostname = parsedUri.host;
7819
+ opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
7820
+ opts.port = parsedUri.port;
7821
+ if (parsedUri.query) opts.query = parsedUri.query;
7822
+ } else if (opts.host) opts.hostname = parse(opts.host).host;
7823
+ installTimerFunctions(this, opts);
7824
+ this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
7825
+ if (opts.hostname && !opts.port) opts.port = this.secure ? "443" : "80";
7826
+ this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
7827
+ this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
7828
+ this.transports = [];
7829
+ this._transportsByName = {};
7830
+ opts.transports.forEach((t) => {
7831
+ const transportName = t.prototype.name;
7832
+ this.transports.push(transportName);
7833
+ this._transportsByName[transportName] = t;
7834
+ });
7835
+ this.opts = Object.assign({
7836
+ path: "/engine.io",
7837
+ agent: false,
7838
+ withCredentials: false,
7839
+ upgrade: true,
7840
+ timestampParam: "t",
7841
+ rememberUpgrade: false,
7842
+ addTrailingSlash: true,
7843
+ rejectUnauthorized: true,
7844
+ perMessageDeflate: { threshold: 1024 },
7845
+ transportOptions: {},
7846
+ closeOnBeforeunload: false
7847
+ }, opts);
7848
+ this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
7849
+ if (typeof this.opts.query === "string") this.opts.query = decode(this.opts.query);
7850
+ if (withEventListeners) {
7851
+ if (this.opts.closeOnBeforeunload) {
7852
+ this._beforeunloadEventListener = () => {
7853
+ if (this.transport) {
7854
+ this.transport.removeAllListeners();
7855
+ this.transport.close();
7856
+ }
7857
+ };
7858
+ addEventListener("beforeunload", this._beforeunloadEventListener, false);
7859
+ }
7860
+ if (this.hostname !== "localhost") {
7861
+ this._offlineEventListener = () => {
7862
+ this._onClose("transport close", { description: "network connection lost" });
7863
+ };
7864
+ OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
7865
+ }
7866
+ }
7867
+ if (this.opts.withCredentials) this._cookieJar = /* @__PURE__ */ createCookieJar();
7868
+ this._open();
7869
+ }
7870
+ /**
7871
+ * Creates transport of the given type.
7872
+ *
7873
+ * @param {String} name - transport name
7874
+ * @return {Transport}
7875
+ * @private
7876
+ */
7877
+ createTransport(name) {
7878
+ const query = Object.assign({}, this.opts.query);
7879
+ query.EIO = 4;
7880
+ query.transport = name;
7881
+ if (this.id) query.sid = this.id;
7882
+ const opts = Object.assign({}, this.opts, {
7883
+ query,
7884
+ socket: this,
7885
+ hostname: this.hostname,
7886
+ secure: this.secure,
7887
+ port: this.port
7888
+ }, this.opts.transportOptions[name]);
7889
+ return new this._transportsByName[name](opts);
7890
+ }
7891
+ /**
7892
+ * Initializes transport to use and starts probe.
7893
+ *
7894
+ * @private
7895
+ */
7896
+ _open() {
7897
+ if (this.transports.length === 0) {
7898
+ this.setTimeoutFn(() => {
7899
+ this.emitReserved("error", "No transports available");
7900
+ }, 0);
7901
+ return;
7902
+ }
7903
+ const transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
7904
+ this.readyState = "opening";
7905
+ const transport = this.createTransport(transportName);
7906
+ transport.open();
7907
+ this.setTransport(transport);
7908
+ }
7909
+ /**
7910
+ * Sets the current transport. Disables the existing one (if any).
7911
+ *
7912
+ * @private
7913
+ */
7914
+ setTransport(transport) {
7915
+ if (this.transport) this.transport.removeAllListeners();
7916
+ this.transport = transport;
7917
+ 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));
7918
+ }
7919
+ /**
7920
+ * Called when connection is deemed open.
7921
+ *
7922
+ * @private
7923
+ */
7924
+ onOpen() {
7925
+ this.readyState = "open";
7926
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
7927
+ this.emitReserved("open");
7928
+ this.flush();
7929
+ }
7930
+ /**
7931
+ * Handles a packet.
7932
+ *
7933
+ * @private
7934
+ */
7935
+ _onPacket(packet) {
7936
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
7937
+ this.emitReserved("packet", packet);
7938
+ this.emitReserved("heartbeat");
7939
+ switch (packet.type) {
7940
+ case "open":
7941
+ this.onHandshake(JSON.parse(packet.data));
7942
+ break;
7943
+ case "ping":
7944
+ this._sendPacket("pong");
7945
+ this.emitReserved("ping");
7946
+ this.emitReserved("pong");
7947
+ this._resetPingTimeout();
7948
+ break;
7949
+ case "error":
7950
+ const err = /* @__PURE__ */ new Error("server error");
7951
+ err.code = packet.data;
7952
+ this._onError(err);
7953
+ break;
7954
+ case "message":
7955
+ this.emitReserved("data", packet.data);
7956
+ this.emitReserved("message", packet.data);
7957
+ break;
7958
+ }
7959
+ }
7960
+ }
7961
+ /**
7962
+ * Called upon handshake completion.
7963
+ *
7964
+ * @param {Object} data - handshake obj
7965
+ * @private
7966
+ */
7967
+ onHandshake(data) {
7968
+ this.emitReserved("handshake", data);
7969
+ this.id = data.sid;
7970
+ this.transport.query.sid = data.sid;
7971
+ this._pingInterval = data.pingInterval;
7972
+ this._pingTimeout = data.pingTimeout;
7973
+ this._maxPayload = data.maxPayload;
7974
+ this.onOpen();
7975
+ if ("closed" === this.readyState) return;
7976
+ this._resetPingTimeout();
7977
+ }
7978
+ /**
7979
+ * Sets and resets ping timeout timer based on server pings.
7980
+ *
7981
+ * @private
7982
+ */
7983
+ _resetPingTimeout() {
7984
+ this.clearTimeoutFn(this._pingTimeoutTimer);
7985
+ const delay = this._pingInterval + this._pingTimeout;
7986
+ this._pingTimeoutTime = Date.now() + delay;
7987
+ this._pingTimeoutTimer = this.setTimeoutFn(() => {
7988
+ this._onClose("ping timeout");
7989
+ }, delay);
7990
+ if (this.opts.autoUnref) this._pingTimeoutTimer.unref();
7991
+ }
7992
+ /**
7993
+ * Called on `drain` event
7994
+ *
7995
+ * @private
7996
+ */
7997
+ _onDrain() {
7998
+ this.writeBuffer.splice(0, this._prevBufferLen);
7999
+ this._prevBufferLen = 0;
8000
+ if (0 === this.writeBuffer.length) this.emitReserved("drain");
8001
+ else this.flush();
8002
+ }
8003
+ /**
8004
+ * Flush write buffers.
8005
+ *
8006
+ * @private
8007
+ */
8008
+ flush() {
8009
+ if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
8010
+ const packets = this._getWritablePackets();
8011
+ this.transport.send(packets);
8012
+ this._prevBufferLen = packets.length;
8013
+ this.emitReserved("flush");
8014
+ }
8015
+ }
8016
+ /**
8017
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
8018
+ * long-polling)
8019
+ *
8020
+ * @private
8021
+ */
8022
+ _getWritablePackets() {
8023
+ if (!(this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1)) return this.writeBuffer;
8024
+ let payloadSize = 1;
8025
+ for (let i = 0; i < this.writeBuffer.length; i++) {
8026
+ const data = this.writeBuffer[i].data;
8027
+ if (data) payloadSize += byteLength(data);
8028
+ if (i > 0 && payloadSize > this._maxPayload) return this.writeBuffer.slice(0, i);
8029
+ payloadSize += 2;
8030
+ }
8031
+ return this.writeBuffer;
8032
+ }
8033
+ /**
8034
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
8035
+ *
8036
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
8037
+ * `write()` method then the message would not be buffered by the Socket.IO client.
8038
+ *
8039
+ * @return {boolean}
8040
+ * @private
8041
+ */
8042
+ _hasPingExpired() {
8043
+ if (!this._pingTimeoutTime) return true;
8044
+ const hasExpired = Date.now() > this._pingTimeoutTime;
8045
+ if (hasExpired) {
8046
+ this._pingTimeoutTime = 0;
8047
+ nextTick(() => {
8048
+ this._onClose("ping timeout");
8049
+ }, this.setTimeoutFn);
8050
+ }
8051
+ return hasExpired;
8052
+ }
8053
+ /**
8054
+ * Sends a message.
8055
+ *
8056
+ * @param {String} msg - message.
8057
+ * @param {Object} options.
8058
+ * @param {Function} fn - callback function.
8059
+ * @return {Socket} for chaining.
8060
+ */
8061
+ write(msg, options, fn) {
8062
+ this._sendPacket("message", msg, options, fn);
8063
+ return this;
8064
+ }
8065
+ /**
8066
+ * Sends a message. Alias of {@link Socket#write}.
8067
+ *
8068
+ * @param {String} msg - message.
8069
+ * @param {Object} options.
8070
+ * @param {Function} fn - callback function.
8071
+ * @return {Socket} for chaining.
8072
+ */
8073
+ send(msg, options, fn) {
8074
+ this._sendPacket("message", msg, options, fn);
8075
+ return this;
8076
+ }
8077
+ /**
8078
+ * Sends a packet.
8079
+ *
8080
+ * @param {String} type: packet type.
8081
+ * @param {String} data.
8082
+ * @param {Object} options.
8083
+ * @param {Function} fn - callback function.
8084
+ * @private
8085
+ */
8086
+ _sendPacket(type, data, options, fn) {
8087
+ if ("function" === typeof data) {
8088
+ fn = data;
8089
+ data = void 0;
8090
+ }
8091
+ if ("function" === typeof options) {
8092
+ fn = options;
8093
+ options = null;
8094
+ }
8095
+ if ("closing" === this.readyState || "closed" === this.readyState) return;
8096
+ options = options || {};
8097
+ options.compress = false !== options.compress;
8098
+ const packet = {
8099
+ type,
8100
+ data,
8101
+ options
8102
+ };
8103
+ this.emitReserved("packetCreate", packet);
8104
+ this.writeBuffer.push(packet);
8105
+ if (fn) this.once("flush", fn);
8106
+ this.flush();
8107
+ }
8108
+ /**
8109
+ * Closes the connection.
8110
+ */
8111
+ close() {
8112
+ const close = () => {
8113
+ this._onClose("forced close");
8114
+ this.transport.close();
8115
+ };
8116
+ const cleanupAndClose = () => {
8117
+ this.off("upgrade", cleanupAndClose);
8118
+ this.off("upgradeError", cleanupAndClose);
8119
+ close();
8120
+ };
8121
+ const waitForUpgrade = () => {
8122
+ this.once("upgrade", cleanupAndClose);
8123
+ this.once("upgradeError", cleanupAndClose);
8124
+ };
8125
+ if ("opening" === this.readyState || "open" === this.readyState) {
8126
+ this.readyState = "closing";
8127
+ if (this.writeBuffer.length) this.once("drain", () => {
8128
+ if (this.upgrading) waitForUpgrade();
8129
+ else close();
8130
+ });
8131
+ else if (this.upgrading) waitForUpgrade();
8132
+ else close();
8133
+ }
8134
+ return this;
8135
+ }
8136
+ /**
8137
+ * Called upon transport error
8138
+ *
8139
+ * @private
8140
+ */
8141
+ _onError(err) {
8142
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
8143
+ if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
8144
+ this.transports.shift();
8145
+ return this._open();
8146
+ }
8147
+ this.emitReserved("error", err);
8148
+ this._onClose("transport error", err);
8149
+ }
8150
+ /**
8151
+ * Called upon transport close.
8152
+ *
8153
+ * @private
8154
+ */
8155
+ _onClose(reason, description) {
8156
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
8157
+ this.clearTimeoutFn(this._pingTimeoutTimer);
8158
+ this.transport.removeAllListeners("close");
8159
+ this.transport.close();
8160
+ this.transport.removeAllListeners();
8161
+ if (withEventListeners) {
8162
+ if (this._beforeunloadEventListener) removeEventListener("beforeunload", this._beforeunloadEventListener, false);
8163
+ if (this._offlineEventListener) {
8164
+ const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
8165
+ if (i !== -1) OFFLINE_EVENT_LISTENERS.splice(i, 1);
8166
+ }
8167
+ }
8168
+ this.readyState = "closed";
8169
+ this.id = null;
8170
+ this.emitReserved("close", reason, description);
8171
+ this.writeBuffer = [];
8172
+ this._prevBufferLen = 0;
8173
+ }
8174
+ }
8175
+ };
8176
+ SocketWithoutUpgrade.protocol = 4;
8177
+ /**
8178
+ * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
8179
+ * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
8180
+ *
8181
+ * This class comes with an upgrade mechanism, which means that once the connection is established with the first
8182
+ * low-level transport, it will try to upgrade to a better transport.
8183
+ *
8184
+ * In order to allow tree-shaking, there are no transports included, that's why the `transports` option is mandatory.
8185
+ *
8186
+ * @example
8187
+ * import { SocketWithUpgrade, WebSocket } from "engine.io-client";
8188
+ *
8189
+ * const socket = new SocketWithUpgrade({
8190
+ * transports: [WebSocket]
8191
+ * });
8192
+ *
8193
+ * socket.on("open", () => {
8194
+ * socket.send("hello");
8195
+ * });
8196
+ *
8197
+ * @see SocketWithoutUpgrade
8198
+ * @see Socket
8199
+ */
8200
+ var SocketWithUpgrade = class extends SocketWithoutUpgrade {
8201
+ constructor() {
8202
+ super(...arguments);
8203
+ this._upgrades = [];
8204
+ }
8205
+ onOpen() {
8206
+ super.onOpen();
8207
+ if ("open" === this.readyState && this.opts.upgrade) for (let i = 0; i < this._upgrades.length; i++) this._probe(this._upgrades[i]);
8208
+ }
8209
+ /**
8210
+ * Probes a transport.
8211
+ *
8212
+ * @param {String} name - transport name
8213
+ * @private
8214
+ */
8215
+ _probe(name) {
8216
+ let transport = this.createTransport(name);
8217
+ let failed = false;
8218
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
8219
+ const onTransportOpen = () => {
8220
+ if (failed) return;
8221
+ transport.send([{
8222
+ type: "ping",
8223
+ data: "probe"
8224
+ }]);
8225
+ transport.once("packet", (msg) => {
8226
+ if (failed) return;
8227
+ if ("pong" === msg.type && "probe" === msg.data) {
8228
+ this.upgrading = true;
8229
+ this.emitReserved("upgrading", transport);
8230
+ if (!transport) return;
8231
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
8232
+ this.transport.pause(() => {
8233
+ if (failed) return;
8234
+ if ("closed" === this.readyState) return;
8235
+ cleanup();
8236
+ this.setTransport(transport);
8237
+ transport.send([{ type: "upgrade" }]);
8238
+ this.emitReserved("upgrade", transport);
8239
+ transport = null;
8240
+ this.upgrading = false;
8241
+ this.flush();
8242
+ });
8243
+ } else {
8244
+ const err = /* @__PURE__ */ new Error("probe error");
8245
+ err.transport = transport.name;
8246
+ this.emitReserved("upgradeError", err);
8247
+ }
8248
+ });
8249
+ };
8250
+ function freezeTransport() {
8251
+ if (failed) return;
8252
+ failed = true;
8253
+ cleanup();
8254
+ transport.close();
8255
+ transport = null;
8256
+ }
8257
+ const onerror = (err) => {
8258
+ const error = /* @__PURE__ */ new Error("probe error: " + err);
8259
+ error.transport = transport.name;
8260
+ freezeTransport();
8261
+ this.emitReserved("upgradeError", error);
8262
+ };
8263
+ function onTransportClose() {
8264
+ onerror("transport closed");
8265
+ }
8266
+ function onclose() {
8267
+ onerror("socket closed");
8268
+ }
8269
+ function onupgrade(to) {
8270
+ if (transport && to.name !== transport.name) freezeTransport();
8271
+ }
8272
+ const cleanup = () => {
8273
+ transport.removeListener("open", onTransportOpen);
8274
+ transport.removeListener("error", onerror);
8275
+ transport.removeListener("close", onTransportClose);
8276
+ this.off("close", onclose);
8277
+ this.off("upgrading", onupgrade);
8278
+ };
8279
+ transport.once("open", onTransportOpen);
8280
+ transport.once("error", onerror);
8281
+ transport.once("close", onTransportClose);
8282
+ this.once("close", onclose);
8283
+ this.once("upgrading", onupgrade);
8284
+ if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") this.setTimeoutFn(() => {
8285
+ if (!failed) transport.open();
8286
+ }, 200);
8287
+ else transport.open();
8288
+ }
8289
+ onHandshake(data) {
8290
+ this._upgrades = this._filterUpgrades(data.upgrades);
8291
+ super.onHandshake(data);
8292
+ }
8293
+ /**
8294
+ * Filters upgrades, returning only those matching client transports.
8295
+ *
8296
+ * @param {Array} upgrades - server upgrades
8297
+ * @private
8298
+ */
8299
+ _filterUpgrades(upgrades) {
8300
+ const filteredUpgrades = [];
8301
+ for (let i = 0; i < upgrades.length; i++) if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
8302
+ return filteredUpgrades;
8303
+ }
8304
+ };
8305
+ /**
8306
+ * This class provides a WebSocket-like interface to connect to an Engine.IO server. The connection will be established
8307
+ * with one of the available low-level transports, like HTTP long-polling, WebSocket or WebTransport.
8308
+ *
8309
+ * This class comes with an upgrade mechanism, which means that once the connection is established with the first
8310
+ * low-level transport, it will try to upgrade to a better transport.
8311
+ *
8312
+ * @example
8313
+ * import { Socket } from "engine.io-client";
8314
+ *
8315
+ * const socket = new Socket();
8316
+ *
8317
+ * socket.on("open", () => {
8318
+ * socket.send("hello");
8319
+ * });
8320
+ *
8321
+ * @see SocketWithoutUpgrade
8322
+ * @see SocketWithUpgrade
8323
+ */
8324
+ var Socket$1 = class extends SocketWithUpgrade {
8325
+ constructor(uri, opts = {}) {
8326
+ const o = typeof uri === "object" ? uri : opts;
8327
+ if (!o.transports || o.transports && typeof o.transports[0] === "string") o.transports = (o.transports || [
8328
+ "polling",
8329
+ "websocket",
8330
+ "webtransport"
8331
+ ]).map((transportName) => transports[transportName]).filter((t) => !!t);
8332
+ super(uri, o);
8333
+ }
8334
+ };
8335
+ Socket$1.protocol;
8336
+ //#endregion
8337
+ //#region node_modules/socket.io-client/build/esm/url.js
8338
+ /**
8339
+ * URL parser.
8340
+ *
8341
+ * @param uri - url
8342
+ * @param path - the request path of the connection
8343
+ * @param loc - An object meant to mimic window.location.
8344
+ * Defaults to window.location.
8345
+ * @public
8346
+ */
8347
+ function url(uri, path = "", loc) {
8348
+ let obj = uri;
8349
+ loc = loc || typeof location !== "undefined" && location;
8350
+ if (null == uri) uri = loc.protocol + "//" + loc.host;
8351
+ if (typeof uri === "string") {
8352
+ if ("/" === uri.charAt(0)) if ("/" === uri.charAt(1)) uri = loc.protocol + uri;
8353
+ else uri = loc.host + uri;
8354
+ if (!/^(https?|wss?):\/\//.test(uri)) if ("undefined" !== typeof loc) uri = loc.protocol + "//" + uri;
8355
+ else uri = "https://" + uri;
8356
+ obj = parse(uri);
8357
+ }
8358
+ if (!obj.port) {
8359
+ if (/^(http|ws)$/.test(obj.protocol)) obj.port = "80";
8360
+ else if (/^(http|ws)s$/.test(obj.protocol)) obj.port = "443";
8361
+ }
8362
+ obj.path = obj.path || "/";
8363
+ const host = obj.host.indexOf(":") !== -1 ? "[" + obj.host + "]" : obj.host;
8364
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
8365
+ obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
8366
+ return obj;
8367
+ }
8368
+ //#endregion
8369
+ //#region node_modules/socket.io-parser/build/esm/is-binary.js
8370
+ var withNativeArrayBuffer = typeof ArrayBuffer === "function";
8371
+ var isView = (obj) => {
8372
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
8373
+ };
8374
+ var toString = Object.prototype.toString;
8375
+ var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
8376
+ var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
8377
+ /**
8378
+ * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
8379
+ *
8380
+ * @private
8381
+ */
8382
+ function isBinary(obj) {
8383
+ return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
8384
+ }
8385
+ function hasBinary(obj, toJSON) {
8386
+ if (!obj || typeof obj !== "object") return false;
8387
+ if (Array.isArray(obj)) {
8388
+ for (let i = 0, l = obj.length; i < l; i++) if (hasBinary(obj[i])) return true;
8389
+ return false;
8390
+ }
8391
+ if (isBinary(obj)) return true;
8392
+ if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) return hasBinary(obj.toJSON(), true);
8393
+ for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) return true;
8394
+ return false;
8395
+ }
8396
+ //#endregion
8397
+ //#region node_modules/socket.io-parser/build/esm/binary.js
8398
+ /**
8399
+ * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
8400
+ *
8401
+ * @param {Object} packet - socket.io event packet
8402
+ * @return {Object} with deconstructed packet and list of buffers
8403
+ * @public
8404
+ */
8405
+ function deconstructPacket(packet) {
8406
+ const buffers = [];
8407
+ const packetData = packet.data;
8408
+ const pack = packet;
8409
+ pack.data = _deconstructPacket(packetData, buffers);
8410
+ pack.attachments = buffers.length;
8411
+ return {
8412
+ packet: pack,
8413
+ buffers
8414
+ };
8415
+ }
8416
+ function _deconstructPacket(data, buffers) {
8417
+ if (!data) return data;
8418
+ if (isBinary(data)) {
8419
+ const placeholder = {
8420
+ _placeholder: true,
8421
+ num: buffers.length
8422
+ };
8423
+ buffers.push(data);
8424
+ return placeholder;
8425
+ } else if (Array.isArray(data)) {
8426
+ const newData = new Array(data.length);
8427
+ for (let i = 0; i < data.length; i++) newData[i] = _deconstructPacket(data[i], buffers);
8428
+ return newData;
8429
+ } else if (typeof data === "object" && !(data instanceof Date)) {
8430
+ const newData = {};
8431
+ for (const key in data) if (Object.prototype.hasOwnProperty.call(data, key)) newData[key] = _deconstructPacket(data[key], buffers);
8432
+ return newData;
8433
+ }
8434
+ return data;
8435
+ }
8436
+ /**
8437
+ * Reconstructs a binary packet from its placeholder packet and buffers
8438
+ *
8439
+ * @param {Object} packet - event packet with placeholders
8440
+ * @param {Array} buffers - binary buffers to put in placeholder positions
8441
+ * @return {Object} reconstructed packet
8442
+ * @public
8443
+ */
8444
+ function reconstructPacket(packet, buffers) {
8445
+ packet.data = _reconstructPacket(packet.data, buffers);
8446
+ delete packet.attachments;
8447
+ return packet;
8448
+ }
8449
+ function _reconstructPacket(data, buffers) {
8450
+ if (!data) return data;
8451
+ if (data && data._placeholder === true) if (typeof data.num === "number" && data.num >= 0 && data.num < buffers.length) return buffers[data.num];
8452
+ else throw new Error("illegal attachments");
8453
+ else if (Array.isArray(data)) for (let i = 0; i < data.length; i++) data[i] = _reconstructPacket(data[i], buffers);
8454
+ else if (typeof data === "object") {
8455
+ for (const key in data) if (Object.prototype.hasOwnProperty.call(data, key)) data[key] = _reconstructPacket(data[key], buffers);
8456
+ }
8457
+ return data;
8458
+ }
8459
+ //#endregion
8460
+ //#region node_modules/socket.io-parser/build/esm/index.js
8461
+ var esm_exports = /* @__PURE__ */ __exportAll({
8462
+ Decoder: () => Decoder,
8463
+ Encoder: () => Encoder,
8464
+ PacketType: () => PacketType,
8465
+ isPacketValid: () => isPacketValid,
8466
+ protocol: () => 5
8467
+ });
8468
+ /**
8469
+ * These strings must not be used as event names, as they have a special meaning.
8470
+ */
8471
+ var RESERVED_EVENTS$1 = [
8472
+ "connect",
8473
+ "connect_error",
8474
+ "disconnect",
8475
+ "disconnecting",
8476
+ "newListener",
8477
+ "removeListener"
8478
+ ];
8479
+ var PacketType;
8480
+ (function(PacketType) {
8481
+ PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
8482
+ PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
8483
+ PacketType[PacketType["EVENT"] = 2] = "EVENT";
8484
+ PacketType[PacketType["ACK"] = 3] = "ACK";
8485
+ PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
8486
+ PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
8487
+ PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
8488
+ })(PacketType || (PacketType = {}));
8489
+ /**
8490
+ * A socket.io Encoder instance
8491
+ */
8492
+ var Encoder = class {
8493
+ /**
8494
+ * Encoder constructor
8495
+ *
8496
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
8497
+ */
8498
+ constructor(replacer) {
8499
+ this.replacer = replacer;
8500
+ }
8501
+ /**
8502
+ * Encode a packet as a single string if non-binary, or as a
8503
+ * buffer sequence, depending on packet type.
8504
+ *
8505
+ * @param {Object} obj - packet object
8506
+ */
8507
+ encode(obj) {
8508
+ if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
8509
+ if (hasBinary(obj)) return this.encodeAsBinary({
8510
+ type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
8511
+ nsp: obj.nsp,
8512
+ data: obj.data,
8513
+ id: obj.id
8514
+ });
8515
+ }
8516
+ return [this.encodeAsString(obj)];
8517
+ }
8518
+ /**
8519
+ * Encode packet as string.
8520
+ */
8521
+ encodeAsString(obj) {
8522
+ let str = "" + obj.type;
8523
+ if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) str += obj.attachments + "-";
8524
+ if (obj.nsp && "/" !== obj.nsp) str += obj.nsp + ",";
8525
+ if (null != obj.id) str += obj.id;
8526
+ if (null != obj.data) str += JSON.stringify(obj.data, this.replacer);
8527
+ return str;
8528
+ }
8529
+ /**
8530
+ * Encode packet as 'buffer sequence' by removing blobs, and
8531
+ * deconstructing packet into object with placeholders and
8532
+ * a list of buffers.
8533
+ */
8534
+ encodeAsBinary(obj) {
8535
+ const deconstruction = deconstructPacket(obj);
8536
+ const pack = this.encodeAsString(deconstruction.packet);
8537
+ const buffers = deconstruction.buffers;
8538
+ buffers.unshift(pack);
8539
+ return buffers;
8540
+ }
8541
+ };
8542
+ /**
8543
+ * A socket.io Decoder instance
8544
+ *
8545
+ * @return {Object} decoder
8546
+ */
8547
+ var Decoder = class Decoder extends Emitter {
8548
+ /**
8549
+ * Decoder constructor
8550
+ */
8551
+ constructor(opts) {
8552
+ super();
8553
+ this.opts = Object.assign({
8554
+ reviver: void 0,
8555
+ maxAttachments: 10
8556
+ }, typeof opts === "function" ? { reviver: opts } : opts);
8557
+ }
8558
+ /**
8559
+ * Decodes an encoded packet string into packet JSON.
8560
+ *
8561
+ * @param {String} obj - encoded packet
8562
+ */
8563
+ add(obj) {
8564
+ let packet;
8565
+ if (typeof obj === "string") {
8566
+ if (this.reconstructor) throw new Error("got plaintext data when reconstructing a packet");
8567
+ packet = this.decodeString(obj);
8568
+ const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
8569
+ if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
8570
+ packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
8571
+ this.reconstructor = new BinaryReconstructor(packet);
8572
+ if (packet.attachments === 0) super.emitReserved("decoded", packet);
8573
+ } else super.emitReserved("decoded", packet);
8574
+ } else if (isBinary(obj) || obj.base64) if (!this.reconstructor) throw new Error("got binary data when not reconstructing a packet");
8575
+ else {
8576
+ packet = this.reconstructor.takeBinaryData(obj);
8577
+ if (packet) {
8578
+ this.reconstructor = null;
8579
+ super.emitReserved("decoded", packet);
8580
+ }
8581
+ }
8582
+ else throw new Error("Unknown type: " + obj);
8583
+ }
8584
+ /**
8585
+ * Decode a packet String (JSON data)
8586
+ *
8587
+ * @param {String} str
8588
+ * @return {Object} packet
8589
+ */
8590
+ decodeString(str) {
8591
+ let i = 0;
8592
+ const p = { type: Number(str.charAt(0)) };
8593
+ if (PacketType[p.type] === void 0) throw new Error("unknown packet type " + p.type);
8594
+ if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
8595
+ const start = i + 1;
8596
+ while (str.charAt(++i) !== "-" && i != str.length);
8597
+ const buf = str.substring(start, i);
8598
+ if (buf != Number(buf) || str.charAt(i) !== "-") throw new Error("Illegal attachments");
8599
+ const n = Number(buf);
8600
+ if (!isInteger(n) || n < 0) throw new Error("Illegal attachments");
8601
+ else if (n > this.opts.maxAttachments) throw new Error("too many attachments");
8602
+ p.attachments = n;
8603
+ }
8604
+ if ("/" === str.charAt(i + 1)) {
8605
+ const start = i + 1;
8606
+ while (++i) {
8607
+ if ("," === str.charAt(i)) break;
8608
+ if (i === str.length) break;
8609
+ }
8610
+ p.nsp = str.substring(start, i);
8611
+ } else p.nsp = "/";
8612
+ const next = str.charAt(i + 1);
8613
+ if ("" !== next && Number(next) == next) {
8614
+ const start = i + 1;
8615
+ while (++i) {
8616
+ const c = str.charAt(i);
8617
+ if (null == c || Number(c) != c) {
8618
+ --i;
8619
+ break;
8620
+ }
8621
+ if (i === str.length) break;
8622
+ }
8623
+ p.id = Number(str.substring(start, i + 1));
8624
+ }
8625
+ if (str.charAt(++i)) {
8626
+ const payload = this.tryParse(str.substr(i));
8627
+ if (Decoder.isPayloadValid(p.type, payload)) p.data = payload;
8628
+ else throw new Error("invalid payload");
8629
+ }
8630
+ return p;
8631
+ }
8632
+ tryParse(str) {
8633
+ try {
8634
+ return JSON.parse(str, this.opts.reviver);
8635
+ } catch (e) {
8636
+ return false;
8637
+ }
8638
+ }
8639
+ static isPayloadValid(type, payload) {
8640
+ switch (type) {
8641
+ case PacketType.CONNECT: return isObject(payload);
8642
+ case PacketType.DISCONNECT: return payload === void 0;
8643
+ case PacketType.CONNECT_ERROR: return typeof payload === "string" || isObject(payload);
8644
+ case PacketType.EVENT:
8645
+ case PacketType.BINARY_EVENT: return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
8646
+ case PacketType.ACK:
8647
+ case PacketType.BINARY_ACK: return Array.isArray(payload);
8648
+ }
8649
+ }
8650
+ /**
8651
+ * Deallocates a parser's resources
8652
+ */
8653
+ destroy() {
8654
+ if (this.reconstructor) {
8655
+ this.reconstructor.finishedReconstruction();
8656
+ this.reconstructor = null;
8657
+ }
8658
+ }
8659
+ };
8660
+ /**
8661
+ * A manager of a binary event's 'buffer sequence'. Should
8662
+ * be constructed whenever a packet of type BINARY_EVENT is
8663
+ * decoded.
8664
+ *
8665
+ * @param {Object} packet
8666
+ * @return {BinaryReconstructor} initialized reconstructor
8667
+ */
8668
+ var BinaryReconstructor = class {
8669
+ constructor(packet) {
8670
+ this.packet = packet;
8671
+ this.buffers = [];
8672
+ this.reconPack = packet;
8673
+ }
8674
+ /**
8675
+ * Method to be called when binary data received from connection
8676
+ * after a BINARY_EVENT packet.
8677
+ *
8678
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
8679
+ * @return {null | Object} returns null if more binary data is expected or
8680
+ * a reconstructed packet object if all buffers have been received.
8681
+ */
8682
+ takeBinaryData(binData) {
8683
+ this.buffers.push(binData);
8684
+ if (this.buffers.length === this.reconPack.attachments) {
8685
+ const packet = reconstructPacket(this.reconPack, this.buffers);
8686
+ this.finishedReconstruction();
8687
+ return packet;
8688
+ }
8689
+ return null;
8690
+ }
8691
+ /**
8692
+ * Cleans up binary packet reconstruction variables.
8693
+ */
8694
+ finishedReconstruction() {
8695
+ this.reconPack = null;
8696
+ this.buffers = [];
8697
+ }
8698
+ };
8699
+ function isNamespaceValid(nsp) {
8700
+ return typeof nsp === "string";
8701
+ }
8702
+ var isInteger = Number.isInteger || function(value) {
8703
+ return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
8704
+ };
8705
+ function isAckIdValid(id) {
8706
+ return id === void 0 || isInteger(id);
8707
+ }
8708
+ function isObject(value) {
8709
+ return Object.prototype.toString.call(value) === "[object Object]";
8710
+ }
8711
+ function isDataValid(type, payload) {
8712
+ switch (type) {
8713
+ case PacketType.CONNECT: return payload === void 0 || isObject(payload);
8714
+ case PacketType.DISCONNECT: return payload === void 0;
8715
+ case PacketType.EVENT: return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
8716
+ case PacketType.ACK: return Array.isArray(payload);
8717
+ case PacketType.CONNECT_ERROR: return typeof payload === "string" || isObject(payload);
8718
+ default: return false;
8719
+ }
8720
+ }
8721
+ function isPacketValid(packet) {
8722
+ return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
8723
+ }
8724
+ //#endregion
8725
+ //#region node_modules/socket.io-client/build/esm/on.js
8726
+ function on(obj, ev, fn) {
8727
+ obj.on(ev, fn);
8728
+ return function subDestroy() {
8729
+ obj.off(ev, fn);
8730
+ };
8731
+ }
8732
+ //#endregion
8733
+ //#region node_modules/socket.io-client/build/esm/socket.js
8734
+ /**
8735
+ * Internal events.
8736
+ * These events can't be emitted by the user.
8737
+ */
8738
+ var RESERVED_EVENTS = Object.freeze({
8739
+ connect: 1,
8740
+ connect_error: 1,
8741
+ disconnect: 1,
8742
+ disconnecting: 1,
8743
+ newListener: 1,
8744
+ removeListener: 1
8745
+ });
8746
+ /**
8747
+ * A Socket is the fundamental class for interacting with the server.
8748
+ *
8749
+ * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
8750
+ *
8751
+ * @example
8752
+ * const socket = io();
8753
+ *
8754
+ * socket.on("connect", () => {
8755
+ * console.log("connected");
8756
+ * });
8757
+ *
8758
+ * // send an event to the server
8759
+ * socket.emit("foo", "bar");
8760
+ *
8761
+ * socket.on("foobar", () => {
8762
+ * // an event was received from the server
8763
+ * });
8764
+ *
8765
+ * // upon disconnection
8766
+ * socket.on("disconnect", (reason) => {
8767
+ * console.log(`disconnected due to ${reason}`);
8768
+ * });
8769
+ */
8770
+ var Socket = class extends Emitter {
8771
+ /**
8772
+ * `Socket` constructor.
8773
+ */
8774
+ constructor(io, nsp, opts) {
8775
+ super();
8776
+ /**
8777
+ * Whether the socket is currently connected to the server.
8778
+ *
8779
+ * @example
8780
+ * const socket = io();
8781
+ *
8782
+ * socket.on("connect", () => {
8783
+ * console.log(socket.connected); // true
8784
+ * });
8785
+ *
8786
+ * socket.on("disconnect", () => {
8787
+ * console.log(socket.connected); // false
8788
+ * });
8789
+ */
8790
+ this.connected = false;
8791
+ /**
8792
+ * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will
8793
+ * be transmitted by the server.
8794
+ */
8795
+ this.recovered = false;
8796
+ /**
8797
+ * Buffer for packets received before the CONNECT packet
8798
+ */
8799
+ this.receiveBuffer = [];
8800
+ /**
8801
+ * Buffer for packets that will be sent once the socket is connected
8802
+ */
8803
+ this.sendBuffer = [];
8804
+ /**
8805
+ * The queue of packets to be sent with retry in case of failure.
8806
+ *
8807
+ * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order.
8808
+ * @private
8809
+ */
8810
+ this._queue = [];
8811
+ /**
8812
+ * A sequence to generate the ID of the {@link QueuedPacket}.
8813
+ * @private
8814
+ */
8815
+ this._queueSeq = 0;
8816
+ this.ids = 0;
8817
+ /**
8818
+ * A map containing acknowledgement handlers.
8819
+ *
8820
+ * The `withError` attribute is used to differentiate handlers that accept an error as first argument:
8821
+ *
8822
+ * - `socket.emit("test", (err, value) => { ... })` with `ackTimeout` option
8823
+ * - `socket.timeout(5000).emit("test", (err, value) => { ... })`
8824
+ * - `const value = await socket.emitWithAck("test")`
8825
+ *
8826
+ * From those that don't:
8827
+ *
8828
+ * - `socket.emit("test", (value) => { ... });`
8829
+ *
8830
+ * In the first case, the handlers will be called with an error when:
8831
+ *
8832
+ * - the timeout is reached
8833
+ * - the socket gets disconnected
8834
+ *
8835
+ * In the second case, the handlers will be simply discarded upon disconnection, since the client will never receive
8836
+ * an acknowledgement from the server.
8837
+ *
8838
+ * @private
8839
+ */
8840
+ this.acks = {};
8841
+ this.flags = {};
8842
+ this.io = io;
8843
+ this.nsp = nsp;
8844
+ if (opts && opts.auth) this.auth = opts.auth;
8845
+ this._opts = Object.assign({}, opts);
8846
+ if (this.io._autoConnect) this.open();
8847
+ }
8848
+ /**
8849
+ * Whether the socket is currently disconnected
8850
+ *
8851
+ * @example
8852
+ * const socket = io();
8853
+ *
8854
+ * socket.on("connect", () => {
8855
+ * console.log(socket.disconnected); // false
8856
+ * });
8857
+ *
8858
+ * socket.on("disconnect", () => {
8859
+ * console.log(socket.disconnected); // true
8860
+ * });
8861
+ */
8862
+ get disconnected() {
8863
+ return !this.connected;
8864
+ }
8865
+ /**
8866
+ * Subscribe to open, close and packet events
8867
+ *
8868
+ * @private
8869
+ */
8870
+ subEvents() {
8871
+ if (this.subs) return;
8872
+ const io = this.io;
8873
+ this.subs = [
8874
+ on(io, "open", this.onopen.bind(this)),
8875
+ on(io, "packet", this.onpacket.bind(this)),
8876
+ on(io, "error", this.onerror.bind(this)),
8877
+ on(io, "close", this.onclose.bind(this))
8878
+ ];
8879
+ }
8880
+ /**
8881
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
8882
+ *
8883
+ * @example
8884
+ * const socket = io();
8885
+ *
8886
+ * console.log(socket.active); // true
8887
+ *
8888
+ * socket.on("disconnect", (reason) => {
8889
+ * if (reason === "io server disconnect") {
8890
+ * // the disconnection was initiated by the server, you need to manually reconnect
8891
+ * console.log(socket.active); // false
8892
+ * }
8893
+ * // else the socket will automatically try to reconnect
8894
+ * console.log(socket.active); // true
8895
+ * });
8896
+ */
8897
+ get active() {
8898
+ return !!this.subs;
8899
+ }
8900
+ /**
8901
+ * "Opens" the socket.
8902
+ *
8903
+ * @example
8904
+ * const socket = io({
8905
+ * autoConnect: false
8906
+ * });
8907
+ *
8908
+ * socket.connect();
8909
+ */
8910
+ connect() {
8911
+ if (this.connected) return this;
8912
+ this.subEvents();
8913
+ if (!this.io["_reconnecting"]) this.io.open();
8914
+ if ("open" === this.io._readyState) this.onopen();
8915
+ return this;
8916
+ }
8917
+ /**
8918
+ * Alias for {@link connect()}.
8919
+ */
8920
+ open() {
8921
+ return this.connect();
8922
+ }
8923
+ /**
8924
+ * Sends a `message` event.
8925
+ *
8926
+ * This method mimics the WebSocket.send() method.
8927
+ *
8928
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
8929
+ *
8930
+ * @example
8931
+ * socket.send("hello");
8932
+ *
8933
+ * // this is equivalent to
8934
+ * socket.emit("message", "hello");
8935
+ *
8936
+ * @return self
8937
+ */
8938
+ send(...args) {
8939
+ args.unshift("message");
8940
+ this.emit.apply(this, args);
8941
+ return this;
8942
+ }
8943
+ /**
8944
+ * Override `emit`.
8945
+ * If the event is in `events`, it's emitted normally.
8946
+ *
8947
+ * @example
8948
+ * socket.emit("hello", "world");
8949
+ *
8950
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
8951
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
8952
+ *
8953
+ * // with an acknowledgement from the server
8954
+ * socket.emit("hello", "world", (val) => {
8955
+ * // ...
8956
+ * });
8957
+ *
8958
+ * @return self
8959
+ */
8960
+ emit(ev, ...args) {
8961
+ var _a, _b, _c;
8962
+ if (RESERVED_EVENTS.hasOwnProperty(ev)) throw new Error("\"" + ev.toString() + "\" is a reserved event name");
8963
+ args.unshift(ev);
8964
+ if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
8965
+ this._addToQueue(args);
8966
+ return this;
8967
+ }
8968
+ const packet = {
8969
+ type: PacketType.EVENT,
8970
+ data: args
8971
+ };
8972
+ packet.options = {};
8973
+ packet.options.compress = this.flags.compress !== false;
8974
+ if ("function" === typeof args[args.length - 1]) {
8975
+ const id = this.ids++;
8976
+ const ack = args.pop();
8977
+ this._registerAckCallback(id, ack);
8978
+ packet.id = id;
8979
+ }
8980
+ const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
8981
+ const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
8982
+ if (this.flags.volatile && !isTransportWritable) {} else if (isConnected) {
8983
+ this.notifyOutgoingListeners(packet);
8984
+ this.packet(packet);
8985
+ } else this.sendBuffer.push(packet);
8986
+ this.flags = {};
8987
+ return this;
8988
+ }
8989
+ /**
8990
+ * @private
8991
+ */
8992
+ _registerAckCallback(id, ack) {
8993
+ var _a;
8994
+ const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
8995
+ if (timeout === void 0) {
8996
+ this.acks[id] = ack;
8997
+ return;
8998
+ }
8999
+ const timer = this.io.setTimeoutFn(() => {
9000
+ delete this.acks[id];
9001
+ for (let i = 0; i < this.sendBuffer.length; i++) if (this.sendBuffer[i].id === id) this.sendBuffer.splice(i, 1);
9002
+ ack.call(this, /* @__PURE__ */ new Error("operation has timed out"));
9003
+ }, timeout);
9004
+ const fn = (...args) => {
9005
+ this.io.clearTimeoutFn(timer);
9006
+ ack.apply(this, args);
9007
+ };
9008
+ fn.withError = true;
9009
+ this.acks[id] = fn;
9010
+ }
9011
+ /**
9012
+ * Emits an event and waits for an acknowledgement
9013
+ *
9014
+ * @example
9015
+ * // without timeout
9016
+ * const response = await socket.emitWithAck("hello", "world");
9017
+ *
9018
+ * // with a specific timeout
9019
+ * try {
9020
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
9021
+ * } catch (err) {
9022
+ * // the server did not acknowledge the event in the given delay
9023
+ * }
9024
+ *
9025
+ * @return a Promise that will be fulfilled when the server acknowledges the event
9026
+ */
9027
+ emitWithAck(ev, ...args) {
9028
+ return new Promise((resolve, reject) => {
9029
+ const fn = (arg1, arg2) => {
9030
+ return arg1 ? reject(arg1) : resolve(arg2);
9031
+ };
9032
+ fn.withError = true;
9033
+ args.push(fn);
9034
+ this.emit(ev, ...args);
9035
+ });
9036
+ }
9037
+ /**
9038
+ * Add the packet to the queue.
9039
+ * @param args
9040
+ * @private
9041
+ */
9042
+ _addToQueue(args) {
9043
+ let ack;
9044
+ if (typeof args[args.length - 1] === "function") ack = args.pop();
9045
+ const packet = {
9046
+ id: this._queueSeq++,
9047
+ tryCount: 0,
9048
+ pending: false,
9049
+ args,
9050
+ flags: Object.assign({ fromQueue: true }, this.flags)
9051
+ };
9052
+ args.push((err, ...responseArgs) => {
9053
+ if (packet !== this._queue[0]) {}
9054
+ if (err !== null) {
9055
+ if (packet.tryCount > this._opts.retries) {
9056
+ this._queue.shift();
9057
+ if (ack) ack(err);
9058
+ }
9059
+ } else {
9060
+ this._queue.shift();
9061
+ if (ack) ack(null, ...responseArgs);
9062
+ }
9063
+ packet.pending = false;
9064
+ return this._drainQueue();
9065
+ });
9066
+ this._queue.push(packet);
9067
+ this._drainQueue();
9068
+ }
9069
+ /**
9070
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
9071
+ * @param force - whether to resend a packet that has not been acknowledged yet
9072
+ *
9073
+ * @private
9074
+ */
9075
+ _drainQueue(force = false) {
9076
+ if (!this.connected || this._queue.length === 0) return;
9077
+ const packet = this._queue[0];
9078
+ if (packet.pending && !force) return;
9079
+ packet.pending = true;
9080
+ packet.tryCount++;
9081
+ this.flags = packet.flags;
9082
+ this.emit.apply(this, packet.args);
9083
+ }
9084
+ /**
9085
+ * Sends a packet.
9086
+ *
9087
+ * @param packet
9088
+ * @private
9089
+ */
9090
+ packet(packet) {
9091
+ packet.nsp = this.nsp;
9092
+ this.io._packet(packet);
9093
+ }
9094
+ /**
9095
+ * Called upon engine `open`.
9096
+ *
9097
+ * @private
9098
+ */
9099
+ onopen() {
9100
+ if (typeof this.auth == "function") this.auth((data) => {
9101
+ this._sendConnectPacket(data);
9102
+ });
9103
+ else this._sendConnectPacket(this.auth);
9104
+ }
9105
+ /**
9106
+ * Sends a CONNECT packet to initiate the Socket.IO session.
9107
+ *
9108
+ * @param data
9109
+ * @private
9110
+ */
9111
+ _sendConnectPacket(data) {
9112
+ this.packet({
9113
+ type: PacketType.CONNECT,
9114
+ data: this._pid ? Object.assign({
9115
+ pid: this._pid,
9116
+ offset: this._lastOffset
9117
+ }, data) : data
9118
+ });
9119
+ }
9120
+ /**
9121
+ * Called upon engine or manager `error`.
9122
+ *
9123
+ * @param err
9124
+ * @private
9125
+ */
9126
+ onerror(err) {
9127
+ if (!this.connected) this.emitReserved("connect_error", err);
9128
+ }
9129
+ /**
9130
+ * Called upon engine `close`.
9131
+ *
9132
+ * @param reason
9133
+ * @param description
9134
+ * @private
9135
+ */
9136
+ onclose(reason, description) {
9137
+ this.connected = false;
9138
+ delete this.id;
9139
+ this.emitReserved("disconnect", reason, description);
9140
+ this._clearAcks();
9141
+ }
9142
+ /**
9143
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
9144
+ * the server.
9145
+ *
9146
+ * @private
9147
+ */
9148
+ _clearAcks() {
9149
+ Object.keys(this.acks).forEach((id) => {
9150
+ if (!this.sendBuffer.some((packet) => String(packet.id) === id)) {
9151
+ const ack = this.acks[id];
9152
+ delete this.acks[id];
9153
+ if (ack.withError) ack.call(this, /* @__PURE__ */ new Error("socket has been disconnected"));
9154
+ }
9155
+ });
9156
+ }
9157
+ /**
9158
+ * Called with socket packet.
9159
+ *
9160
+ * @param packet
9161
+ * @private
9162
+ */
9163
+ onpacket(packet) {
9164
+ if (!(packet.nsp === this.nsp)) return;
9165
+ switch (packet.type) {
9166
+ case PacketType.CONNECT:
9167
+ if (packet.data && packet.data.sid) this.onconnect(packet.data.sid, packet.data.pid);
9168
+ else this.emitReserved("connect_error", /* @__PURE__ */ 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/)"));
9169
+ break;
9170
+ case PacketType.EVENT:
9171
+ case PacketType.BINARY_EVENT:
9172
+ this.onevent(packet);
9173
+ break;
9174
+ case PacketType.ACK:
9175
+ case PacketType.BINARY_ACK:
9176
+ this.onack(packet);
9177
+ break;
9178
+ case PacketType.DISCONNECT:
9179
+ this.ondisconnect();
9180
+ break;
9181
+ case PacketType.CONNECT_ERROR:
9182
+ this.destroy();
9183
+ const err = new Error(packet.data.message);
9184
+ err.data = packet.data.data;
9185
+ this.emitReserved("connect_error", err);
9186
+ break;
9187
+ }
9188
+ }
9189
+ /**
9190
+ * Called upon a server event.
9191
+ *
9192
+ * @param packet
9193
+ * @private
9194
+ */
9195
+ onevent(packet) {
9196
+ const args = packet.data || [];
9197
+ if (null != packet.id) args.push(this.ack(packet.id));
9198
+ if (this.connected) this.emitEvent(args);
9199
+ else this.receiveBuffer.push(Object.freeze(args));
9200
+ }
9201
+ emitEvent(args) {
9202
+ if (this._anyListeners && this._anyListeners.length) {
9203
+ const listeners = this._anyListeners.slice();
9204
+ for (const listener of listeners) listener.apply(this, args);
9205
+ }
9206
+ super.emit.apply(this, args);
9207
+ if (this._pid && args.length && typeof args[args.length - 1] === "string") this._lastOffset = args[args.length - 1];
9208
+ }
9209
+ /**
9210
+ * Produces an ack callback to emit with an event.
9211
+ *
9212
+ * @private
9213
+ */
9214
+ ack(id) {
9215
+ const self = this;
9216
+ let sent = false;
9217
+ return function(...args) {
9218
+ if (sent) return;
9219
+ sent = true;
9220
+ self.packet({
9221
+ type: PacketType.ACK,
9222
+ id,
9223
+ data: args
9224
+ });
9225
+ };
9226
+ }
9227
+ /**
9228
+ * Called upon a server acknowledgement.
9229
+ *
9230
+ * @param packet
9231
+ * @private
9232
+ */
9233
+ onack(packet) {
9234
+ const ack = this.acks[packet.id];
9235
+ if (typeof ack !== "function") return;
9236
+ delete this.acks[packet.id];
9237
+ if (ack.withError) packet.data.unshift(null);
9238
+ ack.apply(this, packet.data);
9239
+ }
9240
+ /**
9241
+ * Called upon server connect.
9242
+ *
9243
+ * @private
9244
+ */
9245
+ onconnect(id, pid) {
9246
+ this.id = id;
9247
+ this.recovered = pid && this._pid === pid;
9248
+ this._pid = pid;
9249
+ this.connected = true;
9250
+ this.emitBuffered();
9251
+ this._drainQueue(true);
9252
+ this.emitReserved("connect");
9253
+ }
9254
+ /**
9255
+ * Emit buffered events (received and emitted).
9256
+ *
9257
+ * @private
9258
+ */
9259
+ emitBuffered() {
9260
+ this.receiveBuffer.forEach((args) => this.emitEvent(args));
9261
+ this.receiveBuffer = [];
9262
+ this.sendBuffer.forEach((packet) => {
9263
+ this.notifyOutgoingListeners(packet);
9264
+ this.packet(packet);
9265
+ });
9266
+ this.sendBuffer = [];
9267
+ }
9268
+ /**
9269
+ * Called upon server disconnect.
9270
+ *
9271
+ * @private
9272
+ */
9273
+ ondisconnect() {
9274
+ this.destroy();
9275
+ this.onclose("io server disconnect");
9276
+ }
9277
+ /**
9278
+ * Called upon forced client/server side disconnections,
9279
+ * this method ensures the manager stops tracking us and
9280
+ * that reconnections don't get triggered for this.
9281
+ *
9282
+ * @private
9283
+ */
9284
+ destroy() {
9285
+ if (this.subs) {
9286
+ this.subs.forEach((subDestroy) => subDestroy());
9287
+ this.subs = void 0;
9288
+ }
9289
+ this.io["_destroy"](this);
9290
+ }
9291
+ /**
9292
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
9293
+ *
9294
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
9295
+ *
9296
+ * @example
9297
+ * const socket = io();
9298
+ *
9299
+ * socket.on("disconnect", (reason) => {
9300
+ * // console.log(reason); prints "io client disconnect"
9301
+ * });
9302
+ *
9303
+ * socket.disconnect();
9304
+ *
9305
+ * @return self
9306
+ */
9307
+ disconnect() {
9308
+ if (this.connected) this.packet({ type: PacketType.DISCONNECT });
9309
+ this.destroy();
9310
+ if (this.connected) this.onclose("io client disconnect");
9311
+ return this;
9312
+ }
9313
+ /**
9314
+ * Alias for {@link disconnect()}.
9315
+ *
9316
+ * @return self
9317
+ */
9318
+ close() {
9319
+ return this.disconnect();
9320
+ }
9321
+ /**
9322
+ * Sets the compress flag.
9323
+ *
9324
+ * @example
9325
+ * socket.compress(false).emit("hello");
9326
+ *
9327
+ * @param compress - if `true`, compresses the sending data
9328
+ * @return self
9329
+ */
9330
+ compress(compress) {
9331
+ this.flags.compress = compress;
9332
+ return this;
9333
+ }
9334
+ /**
9335
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
9336
+ * ready to send messages.
9337
+ *
9338
+ * @example
9339
+ * socket.volatile.emit("hello"); // the server may or may not receive it
9340
+ *
9341
+ * @returns self
9342
+ */
9343
+ get volatile() {
9344
+ this.flags.volatile = true;
9345
+ return this;
9346
+ }
9347
+ /**
9348
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
9349
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
9350
+ *
9351
+ * @example
9352
+ * socket.timeout(5000).emit("my-event", (err) => {
9353
+ * if (err) {
9354
+ * // the server did not acknowledge the event in the given delay
9355
+ * }
9356
+ * });
9357
+ *
9358
+ * @returns self
9359
+ */
9360
+ timeout(timeout) {
9361
+ this.flags.timeout = timeout;
9362
+ return this;
9363
+ }
9364
+ /**
9365
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
9366
+ * callback.
9367
+ *
9368
+ * @example
9369
+ * socket.onAny((event, ...args) => {
9370
+ * console.log(`got ${event}`);
9371
+ * });
9372
+ *
9373
+ * @param listener
9374
+ */
9375
+ onAny(listener) {
9376
+ this._anyListeners = this._anyListeners || [];
9377
+ this._anyListeners.push(listener);
9378
+ return this;
9379
+ }
9380
+ /**
9381
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
9382
+ * callback. The listener is added to the beginning of the listeners array.
9383
+ *
9384
+ * @example
9385
+ * socket.prependAny((event, ...args) => {
9386
+ * console.log(`got event ${event}`);
9387
+ * });
9388
+ *
9389
+ * @param listener
9390
+ */
9391
+ prependAny(listener) {
9392
+ this._anyListeners = this._anyListeners || [];
9393
+ this._anyListeners.unshift(listener);
9394
+ return this;
9395
+ }
9396
+ /**
9397
+ * Removes the listener that will be fired when any event is emitted.
9398
+ *
9399
+ * @example
9400
+ * const catchAllListener = (event, ...args) => {
9401
+ * console.log(`got event ${event}`);
9402
+ * }
9403
+ *
9404
+ * socket.onAny(catchAllListener);
9405
+ *
9406
+ * // remove a specific listener
9407
+ * socket.offAny(catchAllListener);
9408
+ *
9409
+ * // or remove all listeners
9410
+ * socket.offAny();
9411
+ *
9412
+ * @param listener
9413
+ */
9414
+ offAny(listener) {
9415
+ if (!this._anyListeners) return this;
9416
+ if (listener) {
9417
+ const listeners = this._anyListeners;
9418
+ for (let i = 0; i < listeners.length; i++) if (listener === listeners[i]) {
9419
+ listeners.splice(i, 1);
9420
+ return this;
9421
+ }
9422
+ } else this._anyListeners = [];
9423
+ return this;
9424
+ }
9425
+ /**
9426
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
9427
+ * e.g. to remove listeners.
9428
+ */
9429
+ listenersAny() {
9430
+ return this._anyListeners || [];
9431
+ }
9432
+ /**
9433
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
9434
+ * callback.
9435
+ *
9436
+ * Note: acknowledgements sent to the server are not included.
9437
+ *
9438
+ * @example
9439
+ * socket.onAnyOutgoing((event, ...args) => {
9440
+ * console.log(`sent event ${event}`);
9441
+ * });
9442
+ *
9443
+ * @param listener
9444
+ */
9445
+ onAnyOutgoing(listener) {
9446
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
9447
+ this._anyOutgoingListeners.push(listener);
9448
+ return this;
9449
+ }
9450
+ /**
9451
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
9452
+ * callback. The listener is added to the beginning of the listeners array.
9453
+ *
9454
+ * Note: acknowledgements sent to the server are not included.
9455
+ *
9456
+ * @example
9457
+ * socket.prependAnyOutgoing((event, ...args) => {
9458
+ * console.log(`sent event ${event}`);
9459
+ * });
9460
+ *
9461
+ * @param listener
9462
+ */
9463
+ prependAnyOutgoing(listener) {
9464
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
9465
+ this._anyOutgoingListeners.unshift(listener);
9466
+ return this;
9467
+ }
9468
+ /**
9469
+ * Removes the listener that will be fired when any event is emitted.
9470
+ *
9471
+ * @example
9472
+ * const catchAllListener = (event, ...args) => {
9473
+ * console.log(`sent event ${event}`);
9474
+ * }
9475
+ *
9476
+ * socket.onAnyOutgoing(catchAllListener);
9477
+ *
9478
+ * // remove a specific listener
9479
+ * socket.offAnyOutgoing(catchAllListener);
9480
+ *
9481
+ * // or remove all listeners
9482
+ * socket.offAnyOutgoing();
9483
+ *
9484
+ * @param [listener] - the catch-all listener (optional)
9485
+ */
9486
+ offAnyOutgoing(listener) {
9487
+ if (!this._anyOutgoingListeners) return this;
9488
+ if (listener) {
9489
+ const listeners = this._anyOutgoingListeners;
9490
+ for (let i = 0; i < listeners.length; i++) if (listener === listeners[i]) {
9491
+ listeners.splice(i, 1);
9492
+ return this;
9493
+ }
9494
+ } else this._anyOutgoingListeners = [];
9495
+ return this;
9496
+ }
9497
+ /**
9498
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
9499
+ * e.g. to remove listeners.
9500
+ */
9501
+ listenersAnyOutgoing() {
9502
+ return this._anyOutgoingListeners || [];
9503
+ }
9504
+ /**
9505
+ * Notify the listeners for each packet sent
9506
+ *
9507
+ * @param packet
9508
+ *
9509
+ * @private
9510
+ */
9511
+ notifyOutgoingListeners(packet) {
9512
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
9513
+ const listeners = this._anyOutgoingListeners.slice();
9514
+ for (const listener of listeners) listener.apply(this, packet.data);
9515
+ }
9516
+ }
9517
+ };
9518
+ //#endregion
9519
+ //#region node_modules/socket.io-client/build/esm/contrib/backo2.js
9520
+ /**
9521
+ * Initialize backoff timer with `opts`.
9522
+ *
9523
+ * - `min` initial timeout in milliseconds [100]
9524
+ * - `max` max timeout [10000]
9525
+ * - `jitter` [0]
9526
+ * - `factor` [2]
9527
+ *
9528
+ * @param {Object} opts
9529
+ * @api public
9530
+ */
9531
+ function Backoff(opts) {
9532
+ opts = opts || {};
9533
+ this.ms = opts.min || 100;
9534
+ this.max = opts.max || 1e4;
9535
+ this.factor = opts.factor || 2;
9536
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
9537
+ this.attempts = 0;
9538
+ }
9539
+ /**
9540
+ * Return the backoff duration.
9541
+ *
9542
+ * @return {Number}
9543
+ * @api public
9544
+ */
9545
+ Backoff.prototype.duration = function() {
9546
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
9547
+ if (this.jitter) {
9548
+ var rand = Math.random();
9549
+ var deviation = Math.floor(rand * this.jitter * ms);
9550
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
9551
+ }
9552
+ return Math.min(ms, this.max) | 0;
9553
+ };
9554
+ /**
9555
+ * Reset the number of attempts.
9556
+ *
9557
+ * @api public
9558
+ */
9559
+ Backoff.prototype.reset = function() {
9560
+ this.attempts = 0;
9561
+ };
9562
+ /**
9563
+ * Set the minimum duration
9564
+ *
9565
+ * @api public
9566
+ */
9567
+ Backoff.prototype.setMin = function(min) {
9568
+ this.ms = min;
9569
+ };
9570
+ /**
9571
+ * Set the maximum duration
9572
+ *
9573
+ * @api public
9574
+ */
9575
+ Backoff.prototype.setMax = function(max) {
9576
+ this.max = max;
9577
+ };
9578
+ /**
9579
+ * Set the jitter
9580
+ *
9581
+ * @api public
9582
+ */
9583
+ Backoff.prototype.setJitter = function(jitter) {
9584
+ this.jitter = jitter;
9585
+ };
9586
+ //#endregion
9587
+ //#region node_modules/socket.io-client/build/esm/manager.js
9588
+ var Manager = class extends Emitter {
9589
+ constructor(uri, opts) {
9590
+ var _a;
9591
+ super();
9592
+ this.nsps = {};
9593
+ this.subs = [];
9594
+ if (uri && "object" === typeof uri) {
9595
+ opts = uri;
9596
+ uri = void 0;
9597
+ }
9598
+ opts = opts || {};
9599
+ opts.path = opts.path || "/socket.io";
9600
+ this.opts = opts;
9601
+ installTimerFunctions(this, opts);
9602
+ this.reconnection(opts.reconnection !== false);
9603
+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
9604
+ this.reconnectionDelay(opts.reconnectionDelay || 1e3);
9605
+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
9606
+ this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : .5);
9607
+ this.backoff = new Backoff({
9608
+ min: this.reconnectionDelay(),
9609
+ max: this.reconnectionDelayMax(),
9610
+ jitter: this.randomizationFactor()
9611
+ });
9612
+ this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
9613
+ this._readyState = "closed";
9614
+ this.uri = uri;
9615
+ const _parser = opts.parser || esm_exports;
9616
+ this.encoder = new _parser.Encoder();
9617
+ this.decoder = new _parser.Decoder();
9618
+ this._autoConnect = opts.autoConnect !== false;
9619
+ if (this._autoConnect) this.open();
9620
+ }
9621
+ reconnection(v) {
9622
+ if (!arguments.length) return this._reconnection;
9623
+ this._reconnection = !!v;
9624
+ if (!v) this.skipReconnect = true;
9625
+ return this;
9626
+ }
9627
+ reconnectionAttempts(v) {
9628
+ if (v === void 0) return this._reconnectionAttempts;
9629
+ this._reconnectionAttempts = v;
9630
+ return this;
9631
+ }
9632
+ reconnectionDelay(v) {
9633
+ var _a;
9634
+ if (v === void 0) return this._reconnectionDelay;
9635
+ this._reconnectionDelay = v;
9636
+ (_a = this.backoff) === null || _a === void 0 || _a.setMin(v);
9637
+ return this;
9638
+ }
9639
+ randomizationFactor(v) {
9640
+ var _a;
9641
+ if (v === void 0) return this._randomizationFactor;
9642
+ this._randomizationFactor = v;
9643
+ (_a = this.backoff) === null || _a === void 0 || _a.setJitter(v);
9644
+ return this;
9645
+ }
9646
+ reconnectionDelayMax(v) {
9647
+ var _a;
9648
+ if (v === void 0) return this._reconnectionDelayMax;
9649
+ this._reconnectionDelayMax = v;
9650
+ (_a = this.backoff) === null || _a === void 0 || _a.setMax(v);
9651
+ return this;
9652
+ }
9653
+ timeout(v) {
9654
+ if (!arguments.length) return this._timeout;
9655
+ this._timeout = v;
9656
+ return this;
9657
+ }
9658
+ /**
9659
+ * Starts trying to reconnect if reconnection is enabled and we have not
9660
+ * started reconnecting yet
9661
+ *
9662
+ * @private
9663
+ */
9664
+ maybeReconnectOnOpen() {
9665
+ if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) this.reconnect();
9666
+ }
9667
+ /**
9668
+ * Sets the current transport `socket`.
9669
+ *
9670
+ * @param {Function} fn - optional, callback
9671
+ * @return self
9672
+ * @public
9673
+ */
9674
+ open(fn) {
9675
+ if (~this._readyState.indexOf("open")) return this;
9676
+ this.engine = new Socket$1(this.uri, this.opts);
9677
+ const socket = this.engine;
9678
+ const self = this;
9679
+ this._readyState = "opening";
9680
+ this.skipReconnect = false;
9681
+ const openSubDestroy = on(socket, "open", function() {
9682
+ self.onopen();
9683
+ fn && fn();
9684
+ });
9685
+ const onError = (err) => {
9686
+ this.cleanup();
9687
+ this._readyState = "closed";
9688
+ this.emitReserved("error", err);
9689
+ if (fn) fn(err);
9690
+ else this.maybeReconnectOnOpen();
9691
+ };
9692
+ const errorSub = on(socket, "error", onError);
9693
+ if (false !== this._timeout) {
9694
+ const timeout = this._timeout;
9695
+ const timer = this.setTimeoutFn(() => {
9696
+ openSubDestroy();
9697
+ onError(/* @__PURE__ */ new Error("timeout"));
9698
+ socket.close();
9699
+ }, timeout);
9700
+ if (this.opts.autoUnref) timer.unref();
9701
+ this.subs.push(() => {
9702
+ this.clearTimeoutFn(timer);
9703
+ });
9704
+ }
9705
+ this.subs.push(openSubDestroy);
9706
+ this.subs.push(errorSub);
9707
+ return this;
9708
+ }
9709
+ /**
9710
+ * Alias for open()
9711
+ *
9712
+ * @return self
9713
+ * @public
9714
+ */
9715
+ connect(fn) {
9716
+ return this.open(fn);
9717
+ }
9718
+ /**
9719
+ * Called upon transport open.
9720
+ *
9721
+ * @private
9722
+ */
9723
+ onopen() {
9724
+ this.cleanup();
9725
+ this._readyState = "open";
9726
+ this.emitReserved("open");
9727
+ const socket = this.engine;
9728
+ this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this)));
9729
+ }
9730
+ /**
9731
+ * Called upon a ping.
9732
+ *
9733
+ * @private
9734
+ */
9735
+ onping() {
9736
+ this.emitReserved("ping");
9737
+ }
9738
+ /**
9739
+ * Called with data.
9740
+ *
9741
+ * @private
9742
+ */
9743
+ ondata(data) {
9744
+ try {
9745
+ this.decoder.add(data);
9746
+ } catch (e) {
9747
+ this.onclose("parse error", e);
9748
+ }
9749
+ }
9750
+ /**
9751
+ * Called when parser fully decodes a packet.
9752
+ *
9753
+ * @private
9754
+ */
9755
+ ondecoded(packet) {
9756
+ nextTick(() => {
9757
+ this.emitReserved("packet", packet);
9758
+ }, this.setTimeoutFn);
9759
+ }
9760
+ /**
9761
+ * Called upon socket error.
9762
+ *
9763
+ * @private
9764
+ */
9765
+ onerror(err) {
9766
+ this.emitReserved("error", err);
9767
+ }
9768
+ /**
9769
+ * Creates a new socket for the given `nsp`.
9770
+ *
9771
+ * @return {Socket}
9772
+ * @public
9773
+ */
9774
+ socket(nsp, opts) {
9775
+ let socket = this.nsps[nsp];
9776
+ if (!socket) {
9777
+ socket = new Socket(this, nsp, opts);
9778
+ this.nsps[nsp] = socket;
9779
+ } else if (this._autoConnect && !socket.active) socket.connect();
9780
+ return socket;
9781
+ }
9782
+ /**
9783
+ * Called upon a socket close.
9784
+ *
9785
+ * @param socket
9786
+ * @private
9787
+ */
9788
+ _destroy(socket) {
9789
+ const nsps = Object.keys(this.nsps);
9790
+ for (const nsp of nsps) if (this.nsps[nsp].active) return;
9791
+ this._close();
9792
+ }
9793
+ /**
9794
+ * Writes a packet.
9795
+ *
9796
+ * @param packet
9797
+ * @private
9798
+ */
9799
+ _packet(packet) {
9800
+ const encodedPackets = this.encoder.encode(packet);
9801
+ for (let i = 0; i < encodedPackets.length; i++) this.engine.write(encodedPackets[i], packet.options);
9802
+ }
9803
+ /**
9804
+ * Clean up transport subscriptions and packet buffer.
9805
+ *
9806
+ * @private
9807
+ */
9808
+ cleanup() {
9809
+ this.subs.forEach((subDestroy) => subDestroy());
9810
+ this.subs.length = 0;
9811
+ this.decoder.destroy();
9812
+ }
9813
+ /**
9814
+ * Close the current socket.
9815
+ *
9816
+ * @private
9817
+ */
9818
+ _close() {
9819
+ this.skipReconnect = true;
9820
+ this._reconnecting = false;
9821
+ this.onclose("forced close");
9822
+ }
9823
+ /**
9824
+ * Alias for close()
9825
+ *
9826
+ * @private
9827
+ */
9828
+ disconnect() {
9829
+ return this._close();
9830
+ }
9831
+ /**
9832
+ * Called when:
9833
+ *
9834
+ * - the low-level engine is closed
9835
+ * - the parser encountered a badly formatted packet
9836
+ * - all sockets are disconnected
9837
+ *
9838
+ * @private
9839
+ */
9840
+ onclose(reason, description) {
9841
+ var _a;
9842
+ this.cleanup();
9843
+ (_a = this.engine) === null || _a === void 0 || _a.close();
9844
+ this.backoff.reset();
9845
+ this._readyState = "closed";
9846
+ this.emitReserved("close", reason, description);
9847
+ if (this._reconnection && !this.skipReconnect) this.reconnect();
9848
+ }
9849
+ /**
9850
+ * Attempt a reconnection.
9851
+ *
9852
+ * @private
9853
+ */
9854
+ reconnect() {
9855
+ if (this._reconnecting || this.skipReconnect) return this;
9856
+ const self = this;
9857
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
9858
+ this.backoff.reset();
9859
+ this.emitReserved("reconnect_failed");
9860
+ this._reconnecting = false;
9861
+ } else {
9862
+ const delay = this.backoff.duration();
9863
+ this._reconnecting = true;
9864
+ const timer = this.setTimeoutFn(() => {
9865
+ if (self.skipReconnect) return;
9866
+ this.emitReserved("reconnect_attempt", self.backoff.attempts);
9867
+ if (self.skipReconnect) return;
9868
+ self.open((err) => {
9869
+ if (err) {
9870
+ self._reconnecting = false;
9871
+ self.reconnect();
9872
+ this.emitReserved("reconnect_error", err);
9873
+ } else self.onreconnect();
9874
+ });
9875
+ }, delay);
9876
+ if (this.opts.autoUnref) timer.unref();
9877
+ this.subs.push(() => {
9878
+ this.clearTimeoutFn(timer);
9879
+ });
9880
+ }
9881
+ }
9882
+ /**
9883
+ * Called upon successful reconnect.
9884
+ *
9885
+ * @private
9886
+ */
9887
+ onreconnect() {
9888
+ const attempt = this.backoff.attempts;
9889
+ this._reconnecting = false;
9890
+ this.backoff.reset();
9891
+ this.emitReserved("reconnect", attempt);
9892
+ }
9893
+ };
9894
+ //#endregion
9895
+ //#region node_modules/socket.io-client/build/esm/index.js
9896
+ /**
9897
+ * Managers cache.
9898
+ */
9899
+ var cache = {};
9900
+ function lookup(uri, opts) {
9901
+ if (typeof uri === "object") {
9902
+ opts = uri;
9903
+ uri = void 0;
9904
+ }
9905
+ opts = opts || {};
9906
+ const parsed = url(uri, opts.path || "/socket.io");
9907
+ const source = parsed.source;
9908
+ const id = parsed.id;
9909
+ const path = parsed.path;
9910
+ const sameNamespace = cache[id] && path in cache[id]["nsps"];
9911
+ const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
9912
+ let io;
9913
+ if (newConnection) io = new Manager(source, opts);
9914
+ else {
9915
+ if (!cache[id]) cache[id] = new Manager(source, opts);
9916
+ io = cache[id];
9917
+ }
9918
+ if (parsed.query && !opts.query) opts.query = parsed.queryKey;
9919
+ return io.socket(parsed.path, opts);
9920
+ }
9921
+ Object.assign(lookup, {
9922
+ Manager,
9923
+ Socket,
9924
+ io: lookup,
9925
+ connect: lookup
9926
+ });
9927
+ //#endregion
9928
+ //#region node_modules/@nsshunt/stssocketioutils/dist/index.mjs
9929
+ var import_tiny_emitter = require_tiny_emitter();
9930
+ var SocketIoClient = class extends import_tiny_emitter.TinyEmitter {
9931
+ #agentManager;
9932
+ #logger;
9933
+ #name;
9934
+ #address;
9935
+ #socketIoCustomPath;
9936
+ #authToken;
9937
+ #socket;
9938
+ #reconnectTimeout = 2e3;
9939
+ constructor(name) {
9940
+ super();
9941
+ this.#name = name;
9942
+ }
9943
+ get logPrefix() {
9944
+ return `SocketIoClient[${this.#name}]:`;
9945
+ }
9946
+ LogDebugMessage(message) {
9947
+ if (this.#logger) this.#logger.debug(`${this.logPrefix}${message}`);
9948
+ }
9949
+ LogErrorMessage(message) {
9950
+ if (this.#logger) this.#logger.error(`${this.logPrefix}${message}`);
9951
+ }
9952
+ LogWarningMessage(message) {
9953
+ if (this.#logger) this.#logger.warn(`${this.logPrefix}${message}`);
9954
+ }
9955
+ get name() {
9956
+ return this.#name;
9957
+ }
9958
+ get reconnectTimeout() {
9959
+ return this.#reconnectTimeout;
9960
+ }
9961
+ get agentManager() {
9962
+ return this.#agentManager;
9963
+ }
9964
+ get logger() {
9965
+ return this.#logger;
9966
+ }
9967
+ get address() {
9968
+ return this.#address;
9969
+ }
9970
+ get authToken() {
9971
+ return this.#authToken;
9972
+ }
9973
+ get socketIoCustomPath() {
9974
+ return this.#socketIoCustomPath;
9975
+ }
9976
+ get socket() {
9977
+ return this.#socket;
9978
+ }
9979
+ WithAddress(address) {
9980
+ this.#address = address;
9981
+ return this;
9982
+ }
9983
+ WithAuthToken(authToken) {
9984
+ this.#authToken = authToken;
9985
+ return this;
9986
+ }
9987
+ WithSocketIoCustomPath(socketIoCustomPath) {
9988
+ this.#socketIoCustomPath = socketIoCustomPath;
9989
+ return this;
9990
+ }
9991
+ WithLogger(logger) {
9992
+ this.#logger = logger;
9993
+ return this;
9994
+ }
9995
+ WithAgentManager(agentManager) {
9996
+ this.#agentManager = agentManager;
9997
+ return this;
9998
+ }
9999
+ WithReconnectTimeout(reconnectTimeout) {
10000
+ this.#reconnectTimeout = reconnectTimeout;
10001
+ return this;
10002
+ }
10003
+ SetupSocket() {
10004
+ if (!this.#address) throw new Error(`SocketIoClientHelper:SetupSocket(): Error: [address not provided]`);
10005
+ this.#EstablishSocketConnect();
10006
+ return this;
10007
+ }
10008
+ EngineError(error) {}
10009
+ EngineReconnectError(error) {}
10010
+ EngineConnectError(error) {}
10011
+ EngineReconnect(attempt) {}
10012
+ #EstablishSocketConnect() {
10013
+ if (this.#socket !== void 0) {
10014
+ if (this.#socket.connected === true) this.#socket.disconnect();
10015
+ this.#socket = void 0;
10016
+ if (_nsshunt_stsutils.isNode) setTimeout(() => this.#EstablishSocketConnect(), this.#reconnectTimeout).unref();
10017
+ else setTimeout(() => this.#EstablishSocketConnect(), this.#reconnectTimeout);
10018
+ return;
10019
+ }
10020
+ let socketOptions;
10021
+ if (_nsshunt_stsutils.isNode) {
10022
+ socketOptions = { transports: ["websocket"] };
10023
+ if (this.#agentManager) {
10024
+ if (!this.#address) throw new Error(`SocketIoClient:SetupSocket(): Error: [address not provided when using agentManager]`);
10025
+ socketOptions.agent = this.#agentManager.GetAgent(this.#address);
10026
+ }
10027
+ } else socketOptions = { transports: ["websocket"] };
10028
+ if (this.#authToken) socketOptions.auth = (cb) => {
10029
+ cb({ token: this.#authToken });
10030
+ };
10031
+ if (this.#socketIoCustomPath && this.#socketIoCustomPath.localeCompare("") !== 0) socketOptions.path = this.#socketIoCustomPath;
10032
+ this.#socket = lookup(this.#address, socketOptions);
10033
+ this.#socket.io.on("error", (err) => {
10034
+ this.LogErrorMessage(`socketDetail.socket.io.on('error'): [${err}] Address: [${this.#address}]`);
10035
+ this.EngineError(err);
10036
+ });
10037
+ this.#socket.io.on("reconnect_error", (err) => {
10038
+ this.LogErrorMessage(`socketDetail.socket.io.on('reconnect_error'): [${err}] Address: [${this.#address}]`);
10039
+ this.EngineReconnectError(err);
10040
+ });
10041
+ this.#socket.on("connect_error", (err) => {
10042
+ this.LogErrorMessage(`socketDetail.socket.on('connect_error'): [${err}] Address: [${this.#address}]`);
10043
+ this.EngineConnectError(err);
10044
+ });
10045
+ this.#socket.io.on("reconnect", (attempt) => {
10046
+ this.LogErrorMessage(`socketDetail.socket.io.on('reconnect'): Number: [${attempt}] Address: [${this.#address}]`);
10047
+ this.EngineReconnect(attempt);
10048
+ });
10049
+ this.#socket.on("connect", () => {
10050
+ if (this.#socket) {
10051
+ this.LogDebugMessage(`Socket: [${this.#socket.id}]: connected, Address: [${this.#address}]`);
10052
+ setTimeout(() => {
10053
+ this.SocketConnect(this.#socket);
10054
+ }, 0);
10055
+ this.SetupSocketEvents(this.#socket);
10056
+ } else {
10057
+ const errorMessage = "Could not get socket object from socket.io, Address: [${socketDetail.address}]";
10058
+ this.LogErrorMessage(errorMessage);
10059
+ this.SocketConnectError(new Error(errorMessage));
10060
+ }
10061
+ });
10062
+ this.#socket.on("disconnect", (reason) => {
10063
+ this.LogDebugMessage("socket disconnect: " + reason);
10064
+ this.SocketDisconnect(reason);
10065
+ switch (reason) {
10066
+ case "io server disconnect":
10067
+ this.LogDebugMessage("The server disconnected using disconnectSockets, i.e. normal safe shutdown from explicit disconnection by the server.");
10068
+ this.LogDebugMessage("The connection will be re-established when the server becomes available.");
10069
+ this.#socket = void 0;
10070
+ if (_nsshunt_stsutils.isNode) {
10071
+ if (this.#agentManager) this.#agentManager.ResetAgent();
10072
+ setTimeout(() => this.#EstablishSocketConnect(), this.#reconnectTimeout).unref();
10073
+ } else setTimeout(() => this.#EstablishSocketConnect(), this.#reconnectTimeout);
10074
+ break;
10075
+ case "io client disconnect":
10076
+ this.LogDebugMessage("The client disconnected using disconnectSockets, i.e. normal safe disconnection from explicit disconnection by the client.");
10077
+ this.LogDebugMessage("The connection will not be re-established automatically.");
10078
+ break;
10079
+ case "transport close":
10080
+ case "ping timeout":
10081
+ case "transport error":
10082
+ this.LogDebugMessage(`Server unexpectedly disconnected. Reason: [${reason}]`);
10083
+ this.LogDebugMessage("The connection will be re-established when the server becomes available.");
10084
+ if (this.#socket) this.#socket.disconnect();
10085
+ this.#socket = void 0;
10086
+ if (_nsshunt_stsutils.isNode) {
10087
+ if (this.#agentManager) this.#agentManager?.ResetAgent();
10088
+ setTimeout(() => this.#EstablishSocketConnect(), this.#reconnectTimeout).unref();
10089
+ } else setTimeout(() => this.#EstablishSocketConnect(), this.#reconnectTimeout);
10090
+ break;
10091
+ }
10092
+ });
10093
+ }
10094
+ };
10095
+ //#endregion
10096
+ //#region src/wsevents.ts
10097
+ var IEventReturnValueBaseType = /* @__PURE__ */ function(IEventReturnValueBaseType) {
10098
+ IEventReturnValueBaseType["serviceDetails"] = "serviceDetails";
10099
+ IEventReturnValueBaseType["workers"] = "workers";
10100
+ IEventReturnValueBaseType["archiveList"] = "archiveList";
10101
+ IEventReturnValueBaseType["runner"] = "runner";
10102
+ IEventReturnValueBaseType["worker"] = "worker";
10103
+ IEventReturnValueBaseType["executeWorkerActionResult"] = "executeWorkerActionResult";
10104
+ IEventReturnValueBaseType["executeRunnerActionResult"] = "executeRunnerActionResult";
10105
+ return IEventReturnValueBaseType;
10106
+ }({});
10107
+ var IEventRequestCommand = /* @__PURE__ */ function(IEventRequestCommand) {
10108
+ IEventRequestCommand["AddRunner"] = "AddRunner";
10109
+ IEventRequestCommand["AddRunnerToWorker"] = "AddRunnerToWorker";
10110
+ IEventRequestCommand["AddWorker"] = "AddWorker";
10111
+ IEventRequestCommand["GetService"] = "GetService";
10112
+ IEventRequestCommand["GetWorkers"] = "GetWorkers";
10113
+ IEventRequestCommand["GetWorkersSmall"] = "GetWorkersSmall";
10114
+ IEventRequestCommand["GetArchiveList"] = "GetArchiveList";
10115
+ IEventRequestCommand["StartWorkers"] = "StartWorkers";
10116
+ IEventRequestCommand["StopWorkers"] = "StopWorkers";
10117
+ IEventRequestCommand["PauseWorkers"] = "PauseWorkers";
10118
+ IEventRequestCommand["ResumeWorkers"] = "ResumeWorkers";
10119
+ IEventRequestCommand["ExecuteWorkers"] = "ExecuteWorkers";
10120
+ IEventRequestCommand["ResetWorkers"] = "ResetWorkers";
10121
+ IEventRequestCommand["TerminateWorkers"] = "TerminateWorkers";
10122
+ IEventRequestCommand["UpdateWorkers"] = "UpdateWorkers";
10123
+ IEventRequestCommand["StartRunners"] = "StartRunners";
10124
+ IEventRequestCommand["StopRunners"] = "StopRunners";
10125
+ IEventRequestCommand["PauseRunners"] = "PauseRunners";
10126
+ IEventRequestCommand["ResumeRunners"] = "ResumeRunners";
10127
+ IEventRequestCommand["ExecuteRunners"] = "ExecuteRunners";
10128
+ IEventRequestCommand["ResetRunners"] = "ResetRunners";
10129
+ IEventRequestCommand["TerminateRunners"] = "TerminateRunners";
10130
+ IEventRequestCommand["UpdateRunners"] = "UpdateRunners";
10131
+ return IEventRequestCommand;
10132
+ }({});
10133
+ //#endregion
10134
+ //#region src/workerManagerProxy.ts
10135
+ var WorkerManagerProxy = class extends SocketIoClient {
10136
+ _options;
10137
+ _id = globalThis.crypto.randomUUID();
10138
+ _clientName = "";
10139
+ _wm;
10140
+ #debug = (message) => this._options.logger.debug(message);
10141
+ #error = (error) => this._options.logger.error(error);
10142
+ #info = (message) => this._options.logger.info(message);
10143
+ constructor(options) {
10144
+ super(options.name);
10145
+ this._options = options;
10146
+ this._clientName = options.name;
10147
+ this._wm = this._options.CreateSTSWorkerManager();
10148
+ this.#info(chalk.yellow(`Worker Manager ID: [${this._wm.id}]`));
10149
+ this._Start();
10150
+ }
10151
+ get workerManager() {
10152
+ return this._wm;
10153
+ }
10154
+ get id() {
10155
+ return this._id;
10156
+ }
10157
+ SocketConnectError(error) {}
10158
+ SocketDisconnect(reason) {}
10159
+ SocketConnect(socket) {
10160
+ this._OnSocketConnected(socket, this.name, []);
10161
+ }
10162
+ SocketError(error) {
10163
+ this.#error(`${this.name}: SetupClientSideSocket call back: [${error}]`);
10164
+ }
10165
+ SetupSocketEvents(socket) {
10166
+ this._RegisterSocketEvents(socket, this.name);
10167
+ }
10168
+ _GetKeyPayloadData = (eventRequestCommand, eventReturnValueBaseType) => {
10169
+ return {
10170
+ id: this._id,
10171
+ workerManagerId: this._wm.id,
10172
+ name: this._options.name,
10173
+ eventRequestCommand,
10174
+ type: eventReturnValueBaseType
10175
+ };
10176
+ };
10177
+ _LogPayloadEventRetVal = (retVal) => {
10178
+ return retVal;
10179
+ };
10180
+ _Start = async () => {
10181
+ this._EmitEvent("Starting", {});
10182
+ this.WithAddress(this._options.ststccendpoint).WithLogger(_nsshunt_stsutils.defaultLogger).WithSocketIoCustomPath("");
10183
+ if (this._options.agentManager) this.WithAgentManager(this._options.agentManager);
10184
+ this.#info(chalk.yellow(`STS Test Runner Service Instance.`));
10185
+ this.#info(chalk.yellow(`This service instance emulates instances of the ststestrunnernode service.`));
10186
+ this.#info(chalk.yellow(`Service Instance ID: [${this._id}]`));
10187
+ this.#info(chalk.yellow(`Service Instance Name: [${this._options.name}]`));
10188
+ this.#info(chalk.yellow(`Options: [${JSON.stringify(this._options)}]`));
10189
+ this.SetupSocket();
10190
+ const start = async () => {
10191
+ for (let i = 0; i < this._options.workers; i++) await this._AddWorker({
10192
+ tags: [""],
10193
+ userData: {},
10194
+ mocked: false,
10195
+ hostName: "host01",
10196
+ agentId: "agent01",
10197
+ userAgent: globalThis.crypto.randomUUID(),
10198
+ logLevel: 4
10199
+ });
10200
+ this._EmitEvent("Started", {});
10201
+ };
10202
+ await start();
10203
+ };
10204
+ Stop = async () => {
10205
+ this._EmitEvent("Stopping ...", {});
10206
+ this.#debug(chalk.magenta(`Stop(): Stopping Service.`));
10207
+ await this._wm.TerminateWorkers([]);
10208
+ this.#debug(`Stop(): Workers terminated`);
10209
+ if (this.socket) {
10210
+ this.#debug(`Stop(): Going to disconnect socket ...`);
10211
+ this.socket.disconnect();
10212
+ this.#debug(`Stop(): Socket disconnected.`);
10213
+ }
10214
+ this.#debug(`Stop(): Sleeping (500ms) ...`);
10215
+ await (0, _nsshunt_stsutils.Sleep)(500);
10216
+ this.#debug(chalk.magenta(`Stop(): Service Stopped.`));
10217
+ this._EmitEvent("Stopped", {});
10218
+ };
10219
+ _GetService = async () => {
10220
+ const raw = this._EmitEvent("GetService", this._LogPayloadEventRetVal({
10221
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetService, IEventReturnValueBaseType.serviceDetails),
10222
+ serviceDetails: await this._options.GetServiceDetails()
10223
+ }));
10224
+ raw.serviceDetails = (0, fflate.gzipSync)((0, fflate.strToU8)(JSON.stringify(raw.serviceDetails)));
10225
+ return raw;
10226
+ };
10227
+ _GetServiceNoZip = async () => {
10228
+ return this._EmitEvent("GetService", this._LogPayloadEventRetVal({
10229
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetService, IEventReturnValueBaseType.serviceDetails),
10230
+ serviceDetails: await this._options.GetServiceDetails()
10231
+ }));
10232
+ };
10233
+ _EmitStateChange = (runnerEx) => {
10234
+ this.#debug(chalk.rgb(10, 50, 200)(`_EmitStateChange(): ==>> Runner State Change: [${runnerEx.workerId}] RunnerId: [${runnerEx.id}] State: [${runnerEx.state}]`));
10235
+ const stateChangeRetVal = {
10236
+ eventRequestCommand: "StateChange",
10237
+ type: IEventReturnValueBaseType.runner,
10238
+ workerManagerId: this._wm.id,
10239
+ id: this._id,
10240
+ name: this._options.name,
10241
+ runner: runnerEx.toRunner()
10242
+ };
10243
+ this._EmitEvent(`StateChange`, stateChangeRetVal);
10244
+ this.socket?.emit("StateChange", stateChangeRetVal);
10245
+ };
10246
+ _EmitTelemetry = (runnerEx) => {
10247
+ this.#debug(chalk.rgb(10, 50, 200)(`_EmitTelemetry(): ==>> Runner State Change: [${runnerEx.workerId}] RunnerId: [${runnerEx.id}] State: [${runnerEx.state}]`));
10248
+ const telemetryRetVal = {
10249
+ eventRequestCommand: "StateChange",
10250
+ type: IEventReturnValueBaseType.runner,
10251
+ workerManagerId: this._wm.id,
10252
+ id: this._id,
10253
+ name: this._options.name,
10254
+ runner: runnerEx.toRunner()
10255
+ };
10256
+ this._EmitEvent(`Telemetry`, telemetryRetVal);
10257
+ this.socket?.emit("Telemetry", telemetryRetVal);
10258
+ };
10259
+ _SetupRunnerEventHandlers = (runnerEx) => {
10260
+ runnerEx.on("StateChange", this._EmitStateChange);
10261
+ runnerEx.on("Telemetry", this._EmitTelemetry);
10262
+ };
10263
+ _OnSocketConnected = (socket, clientName, joinRooms) => {
10264
+ this.#debug(chalk.green(`${this._id} ${clientName}: --> connected`));
10265
+ this._EmitEvent("SocketConnected", {
10266
+ id: this._id,
10267
+ clientName,
10268
+ joinRooms: [
10269
+ ...joinRooms,
10270
+ "ststrnservices",
10271
+ this._id
10272
+ ]
10273
+ });
10274
+ if (joinRooms.length > 0) socket.emit("__STSjoinRoom", joinRooms);
10275
+ socket.emit("__STSjoinRoom", ["ststrnservices"]).emit("__STSjoinRoom", [this._id]);
10276
+ };
10277
+ _AddWorker = async (options) => {
10278
+ const workerEx = await this._wm.AddWorker(options);
10279
+ if (workerEx) return this._EmitEvent("AddWorker", this._LogPayloadEventRetVal({
10280
+ ...this._GetKeyPayloadData(IEventRequestCommand.AddWorker, IEventReturnValueBaseType.worker),
10281
+ worker: workerEx.toWorker()
10282
+ }));
10283
+ else return this._EmitEvent("AddWorker", this._LogPayloadEventRetVal({
10284
+ ...this._GetKeyPayloadData(IEventRequestCommand.AddWorker, IEventReturnValueBaseType.worker),
10285
+ worker: {}
10286
+ }));
10287
+ };
10288
+ _GetArchiveList = async (runnerSearchFilters) => {
10289
+ const raw = this._EmitEvent("GetArchiveList", this._LogPayloadEventRetVal({
10290
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetArchiveList, IEventReturnValueBaseType.archiveList),
10291
+ archiveList: await this._wm.GetArchiveList(runnerSearchFilters)
10292
+ }));
10293
+ raw.archiveList = (0, fflate.gzipSync)((0, fflate.strToU8)(JSON.stringify(raw.archiveList)));
10294
+ return raw;
10295
+ };
10296
+ _GetArchiveListNoZip = async (runnerSearchFilters) => {
10297
+ return this._EmitEvent("GetArchiveList", this._LogPayloadEventRetVal({
10298
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetArchiveList, IEventReturnValueBaseType.archiveList),
10299
+ archiveList: await this._wm.GetArchiveList(runnerSearchFilters)
10300
+ }));
10301
+ };
10302
+ _GetWorkers = async () => {
10303
+ const raw = this._EmitEvent("GetWorkers", this._LogPayloadEventRetVal({
10304
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetWorkers, IEventReturnValueBaseType.workers),
10305
+ workers: await this._wm.GetWorkers()
10306
+ }));
10307
+ raw.workers = (0, fflate.gzipSync)((0, fflate.strToU8)(JSON.stringify(raw.workers)));
10308
+ return raw;
10309
+ };
10310
+ _GetWorkersNoZip = async () => {
10311
+ return this._EmitEvent("GetWorkers", this._LogPayloadEventRetVal({
10312
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetWorkers, IEventReturnValueBaseType.workers),
10313
+ workers: await this._wm.GetWorkers()
10314
+ }));
10315
+ };
10316
+ _GetWorkersSmall = async (states) => {
10317
+ const raw = this._EmitEvent("GetWorkersSmall", this._LogPayloadEventRetVal({
10318
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetWorkersSmall, IEventReturnValueBaseType.workers),
10319
+ workerCores: await this._wm.GetWorkersCore(states)
10320
+ }));
10321
+ raw.workers = (0, fflate.gzipSync)((0, fflate.strToU8)(JSON.stringify(raw.workers)));
10322
+ return raw;
10323
+ };
10324
+ _GetWorkersSmallNoZip = async (states) => {
10325
+ return this._EmitEvent("GetWorkersSmall", this._LogPayloadEventRetVal({
10326
+ ...this._GetKeyPayloadData(IEventRequestCommand.GetWorkersSmall, IEventReturnValueBaseType.workers),
10327
+ workerCores: await this._wm.GetWorkersCore(states)
10328
+ }));
10329
+ };
10330
+ _StartWorkers = async (workerIds) => {
10331
+ return this._EmitEvent("StartWorkers", this._LogPayloadEventRetVal({
10332
+ ...this._GetKeyPayloadData(IEventRequestCommand.StartWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10333
+ executeWorkerActionResult: await this._wm.StartWorkers(workerIds)
10334
+ }));
10335
+ };
10336
+ _StopWorkers = async (workerIds) => {
10337
+ return this._EmitEvent("StopWorkers", this._LogPayloadEventRetVal({
10338
+ ...this._GetKeyPayloadData(IEventRequestCommand.StopWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10339
+ executeWorkerActionResult: await this._wm.StopWorkers(workerIds)
10340
+ }));
10341
+ };
10342
+ _PauseWorkers = async (workerIds) => {
10343
+ return this._EmitEvent("PauseWorkers", this._LogPayloadEventRetVal({
10344
+ ...this._GetKeyPayloadData(IEventRequestCommand.PauseWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10345
+ executeWorkerActionResult: await this._wm.PauseWorkers(workerIds)
10346
+ }));
10347
+ };
10348
+ _ResumeWorkers = async (workerIds) => {
10349
+ return this._EmitEvent("ResumeWorkers", this._LogPayloadEventRetVal({
10350
+ ...this._GetKeyPayloadData(IEventRequestCommand.ResumeWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10351
+ executeWorkerActionResult: await this._wm.ResumeWorkers(workerIds)
10352
+ }));
10353
+ };
10354
+ _ExecuteWorkers = async (workerIds) => {
10355
+ return this._EmitEvent("ExecuteWorkers", this._LogPayloadEventRetVal({
10356
+ ...this._GetKeyPayloadData(IEventRequestCommand.ExecuteWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10357
+ executeWorkerActionResult: await this._wm.ExecuteWorkers(workerIds)
10358
+ }));
10359
+ };
10360
+ _ResetWorkers = async (workerIds) => {
10361
+ return this._EmitEvent("ResetWorkers", this._LogPayloadEventRetVal({
10362
+ ...this._GetKeyPayloadData(IEventRequestCommand.ResetWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10363
+ executeWorkerActionResult: await this._wm.ResetWorkers(workerIds)
10364
+ }));
10365
+ };
10366
+ _TerminateWorkers = async (workerIds) => {
10367
+ return this._EmitEvent("TerminateWorkers", this._LogPayloadEventRetVal({
10368
+ ...this._GetKeyPayloadData(IEventRequestCommand.TerminateWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10369
+ executeWorkerActionResult: await this._wm.TerminateWorkers(workerIds)
10370
+ }));
10371
+ };
10372
+ _UpdateWorkers = async (workerIds, options) => {
10373
+ return this._EmitEvent("UpdateWorkers", this._LogPayloadEventRetVal({
10374
+ ...this._GetKeyPayloadData(IEventRequestCommand.UpdateWorkers, IEventReturnValueBaseType.executeWorkerActionResult),
10375
+ executeWorkerActionResult: await this._wm.UpdateWorkers(workerIds, options)
10376
+ }));
10377
+ };
10378
+ _StopRunners = async (workerId, runnerIds) => {
10379
+ return this._EmitEvent("StopRunners", this._LogPayloadEventRetVal({
10380
+ ...this._GetKeyPayloadData(IEventRequestCommand.StopRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10381
+ executeRunnerActionResult: await this._wm.StopRunners(workerId, runnerIds)
10382
+ }));
10383
+ };
10384
+ _StartRunners = async (workerId, runnerIds) => {
10385
+ return this._EmitEvent("StartRunners", this._LogPayloadEventRetVal({
10386
+ ...this._GetKeyPayloadData(IEventRequestCommand.StartRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10387
+ executeRunnerActionResult: await this._wm.StartRunners(workerId, runnerIds)
10388
+ }));
10389
+ };
10390
+ _PauseRunners = async (workerId, runnerIds) => {
10391
+ return this._EmitEvent("PauseRunners", this._LogPayloadEventRetVal({
10392
+ ...this._GetKeyPayloadData(IEventRequestCommand.PauseRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10393
+ executeRunnerActionResult: await this._wm.PauseRunners(workerId, runnerIds)
10394
+ }));
10395
+ };
10396
+ _ResumeRunners = async (workerId, runnerIds) => {
10397
+ return this._EmitEvent("ResumeRunners", this._LogPayloadEventRetVal({
10398
+ ...this._GetKeyPayloadData(IEventRequestCommand.ResumeRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10399
+ executeRunnerActionResult: await this._wm.ResumeRunners(workerId, runnerIds)
10400
+ }));
10401
+ };
10402
+ _ExecuteRunners = async (workerId, runnerIds) => {
10403
+ return this._EmitEvent("ExecuteRunners", this._LogPayloadEventRetVal({
10404
+ ...this._GetKeyPayloadData(IEventRequestCommand.ExecuteRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10405
+ executeRunnerActionResult: await this._wm.ExecuteRunners(workerId, runnerIds)
10406
+ }));
10407
+ };
10408
+ _ResetRunners = async (workerId, runnerIds) => {
10409
+ return this._EmitEvent("ResetRunners", this._LogPayloadEventRetVal({
10410
+ ...this._GetKeyPayloadData(IEventRequestCommand.ResetRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10411
+ executeRunnerActionResult: await this._wm.ResetRunners(workerId, runnerIds)
10412
+ }));
10413
+ };
10414
+ _TerminateRunners = async (workerId, runnerIds) => {
10415
+ return this._EmitEvent("TerminateRunners", this._LogPayloadEventRetVal({
10416
+ ...this._GetKeyPayloadData(IEventRequestCommand.TerminateRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10417
+ executeRunnerActionResult: await this._wm.TerminateRunners(workerId, runnerIds)
10418
+ }));
10419
+ };
10420
+ _UpdateRunners = async (workerId, runnerIds, options) => {
10421
+ return this._EmitEvent("UpdateRunners", this._LogPayloadEventRetVal({
10422
+ ...this._GetKeyPayloadData(IEventRequestCommand.UpdateRunners, IEventReturnValueBaseType.executeRunnerActionResult),
10423
+ executeRunnerActionResult: await this._wm.UpdateRunners(workerId, runnerIds, options)
10424
+ }));
10425
+ };
10426
+ _AddRunner = async (options) => {
10427
+ this.#debug(chalk.yellow(`${this._id} ${this._clientName}: --> AddRunner: [${JSON.stringify(options)}]`));
10428
+ const runnerEx = await this._wm.AddRunner(options);
10429
+ let runner = {};
10430
+ if (runnerEx) {
10431
+ this._SetupRunnerEventHandlers(runnerEx);
10432
+ this.#debug(chalk.yellow(`${this._clientName}: AddRunner: WorkerId: [${runnerEx.workerId}] RunnerId: [${runnerEx.id}]`));
10433
+ runner = runnerEx.toRunner();
10434
+ }
10435
+ return this._EmitEvent(IEventRequestCommand.AddRunner, this._LogPayloadEventRetVal({
10436
+ ...this._GetKeyPayloadData(IEventRequestCommand.AddRunner, IEventReturnValueBaseType.runner),
10437
+ runner
10438
+ }));
10439
+ };
10440
+ _AddRunnerToWorkerByWorkerId = async (workerId, options) => {
10441
+ this.#debug(chalk.yellow(`${this._id} ${this._clientName}: --> AddRunner: [${JSON.stringify(options)}]`));
10442
+ const runnerEx = await this._wm.AddRunnerToWorkerByWorkerId(workerId, options);
10443
+ let runner = {};
10444
+ if (runnerEx) {
10445
+ this._SetupRunnerEventHandlers(runnerEx);
10446
+ this.#debug(chalk.yellow(`${this._clientName}: AddRunnerToWorker: WorkerId: [${runnerEx.workerId}] RunnerId: [${runnerEx.id}]`));
10447
+ runner = runnerEx.toRunner();
10448
+ }
10449
+ return this._EmitEvent(IEventRequestCommand.AddRunnerToWorker, this._LogPayloadEventRetVal({
10450
+ ...this._GetKeyPayloadData(IEventRequestCommand.AddRunnerToWorker, IEventReturnValueBaseType.runner),
10451
+ runner
10452
+ }));
10453
+ };
10454
+ _RegisterSocketEvents = (socket, clientName) => {
10455
+ `${this._id}${clientName}`;
10456
+ const handlers = this._GetSocketEventHandlers(socket, clientName);
10457
+ for (const [event, handler] of Object.entries(handlers)) {
10458
+ const wrappedHandler = async (...args) => {
10459
+ return handler(...args);
10460
+ };
10461
+ socket.on(event, wrappedHandler);
10462
+ }
10463
+ };
10464
+ _EmitEvent = (eventName, data) => {
10465
+ this.emit(eventName, data);
10466
+ return data;
10467
+ };
10468
+ _GetSocketEventHandlers = (socket, clientName) => {
10469
+ const logPrefix = `${this._id} ${clientName}:`;
10470
+ return {
10471
+ "disconnect": (reason) => {
10472
+ this._EmitEvent("disconnect", reason);
10473
+ this.#error(`#disconnect(): [${reason}]`);
10474
+ },
10475
+ "connect_error": (error) => {
10476
+ this._EmitEvent("connect_error", error);
10477
+ if (!socket.active) this.#error(error.message);
10478
+ },
10479
+ "error": (error) => {
10480
+ this._EmitEvent("error", error);
10481
+ this.#error(`#GetSocketEventHandlers(): [${error}]`);
10482
+ },
10483
+ "__STSdisconnect": (reason) => {
10484
+ this._EmitEvent("__STSdisconnect", reason);
10485
+ this.#debug(chalk.magenta(`${logPrefix}: [${socket.id}] [${reason}]`));
10486
+ this.Stop();
10487
+ },
10488
+ "GetService": async (cb) => cb(await this._GetService()),
10489
+ "GetWorkers": async (cb) => cb(await this._GetWorkers()),
10490
+ "GetWorkersSmall": async (states, cb) => cb(await this._GetWorkersSmall(states)),
10491
+ "GetArchiveList": async (runnerSearchFilters, cb) => cb(await this._GetArchiveList(runnerSearchFilters)),
10492
+ "AddRunner": async (options, cb) => cb(await this._AddRunner(options)),
10493
+ "AddRunnerToWorkerByWorkerId": async (workerId, options, cb) => cb(await this._AddRunnerToWorkerByWorkerId(workerId, options)),
10494
+ "AddWorker": async (options, cb) => cb(await this._AddWorker(options)),
10495
+ "StartWorkers": async (workerIds, cb) => cb(await this._StartWorkers(workerIds)),
10496
+ "StopWorkers": async (workerIds, cb) => cb(await this._StopWorkers(workerIds)),
10497
+ "PauseWorkers": async (workerIds, cb) => cb(await this._PauseWorkers(workerIds)),
10498
+ "ResumeWorkers": async (workerIds, cb) => cb(await this._ResumeWorkers(workerIds)),
10499
+ "ExecuteWorkers": async (workerIds, cb) => cb(await this._ExecuteWorkers(workerIds)),
10500
+ "ResetWorkers": async (workerIds, cb) => cb(await this._ResetWorkers(workerIds)),
10501
+ "TerminateWorkers": async (workerIds, cb) => cb(await this._TerminateWorkers(workerIds)),
10502
+ "UpdateWorkers": async (workerIds, options, cb) => cb(await this._UpdateWorkers(workerIds, options)),
10503
+ "StartRunners": async (workerId, runnerIds, cb) => cb(await this._StartRunners(workerId, runnerIds)),
10504
+ "StopRunners": async (workerId, runnerIds, cb) => cb(await this._StopRunners(workerId, runnerIds)),
10505
+ "PauseRunners": async (workerId, runnerIds, cb) => cb(await this._PauseRunners(workerId, runnerIds)),
10506
+ "ResumeRunners": async (workerId, runnerIds, cb) => cb(await this._ResumeRunners(workerId, runnerIds)),
10507
+ "ExecuteRunners": async (workerId, runnerIds, cb) => cb(await this._ExecuteRunners(workerId, runnerIds)),
10508
+ "ResetRunners": async (workerId, runnerIds, cb) => cb(await this._ResetRunners(workerId, runnerIds)),
10509
+ "TerminateRunners": async (workerId, runnerIds, cb) => cb(await this._TerminateRunners(workerId, runnerIds)),
10510
+ "UpdateRunners": async (workerId, runnerIds, options, cb) => cb(await this._UpdateRunners(workerId, runnerIds, options))
10511
+ };
10512
+ };
10513
+ };
10514
+ //#endregion
6587
10515
  exports.AbstractRunnerExecutionWorker = AbstractRunnerExecutionWorker;
10516
+ exports.IEventRequestCommand = IEventRequestCommand;
10517
+ exports.IEventReturnValueBaseType = IEventReturnValueBaseType;
6588
10518
  exports.IRunnerState = IRunnerState;
6589
10519
  exports.IWorkerState = IWorkerState;
6590
10520
  exports.PublishMessageCommandsTestRunner = PublishMessageCommandsTestRunner;
6591
10521
  exports.STSWorkerManager = STSWorkerManager;
10522
+ exports.WorkerManagerProxy = WorkerManagerProxy;
6592
10523
  exports.eIWMessageCommands = eIWMessageCommands;
6593
10524
 
6594
10525
  //# sourceMappingURL=index.cjs.map