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