@xapp/chat-widget 1.40.4 → 1.41.1

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.es.js CHANGED
@@ -45,7 +45,7 @@ function useConnectionInfo(env) {
45
45
  return useServerConfig(env, nonce);
46
46
  }
47
47
 
48
- /*! *****************************************************************************
48
+ /******************************************************************************
49
49
  Copyright (c) Microsoft Corporation.
50
50
 
51
51
  Permission to use, copy, modify, and/or distribute this software for any
@@ -3036,8 +3036,10 @@ function getConfigurableMessages() {
3036
3036
  function getConfigurableMessagesConfig(messages) {
3037
3037
  var items = messages.items;
3038
3038
  var config = [{ retry: 0, delay: 5, text: "" }];
3039
- for (var i = 0; i < items.length; i++) {
3040
- config.push({ retry: i + 1, delay: items[i].delay, text: items[i].text });
3039
+ if (Array.isArray(items) && items.length > 0) {
3040
+ for (var i = 0; i < items.length; i++) {
3041
+ config.push({ retry: i + 1, delay: items[i].delay, text: items[i].text });
3042
+ }
3041
3043
  }
3042
3044
  return config;
3043
3045
  }
@@ -3508,246 +3510,203 @@ var StentorLocalChat = /** @class */ (function () {
3508
3510
  return StentorLocalChat;
3509
3511
  }());
3510
3512
 
3511
- /**
3512
- * Parses an URI
3513
- *
3514
- * @author Steven Levithan <stevenlevithan.com> (MIT license)
3515
- * @api private
3516
- */
3517
-
3518
- var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
3519
-
3520
- var parts = [
3521
- 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
3522
- ];
3523
-
3524
- var parseuri = function parseuri(str) {
3525
- var src = str,
3526
- b = str.indexOf('['),
3527
- e = str.indexOf(']');
3513
+ const PACKET_TYPES = Object.create(null); // no Map = no polyfill
3514
+ PACKET_TYPES["open"] = "0";
3515
+ PACKET_TYPES["close"] = "1";
3516
+ PACKET_TYPES["ping"] = "2";
3517
+ PACKET_TYPES["pong"] = "3";
3518
+ PACKET_TYPES["message"] = "4";
3519
+ PACKET_TYPES["upgrade"] = "5";
3520
+ PACKET_TYPES["noop"] = "6";
3521
+ const PACKET_TYPES_REVERSE = Object.create(null);
3522
+ Object.keys(PACKET_TYPES).forEach(key => {
3523
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
3524
+ });
3525
+ const ERROR_PACKET = { type: "error", data: "parser error" };
3528
3526
 
3529
- if (b != -1 && e != -1) {
3530
- str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
3527
+ const withNativeBlob$1 = typeof Blob === "function" ||
3528
+ (typeof Blob !== "undefined" &&
3529
+ Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
3530
+ const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
3531
+ // ArrayBuffer.isView method is not defined in IE10
3532
+ const isView$1 = obj => {
3533
+ return typeof ArrayBuffer.isView === "function"
3534
+ ? ArrayBuffer.isView(obj)
3535
+ : obj && obj.buffer instanceof ArrayBuffer;
3536
+ };
3537
+ const encodePacket = ({ type, data }, supportsBinary, callback) => {
3538
+ if (withNativeBlob$1 && data instanceof Blob) {
3539
+ if (supportsBinary) {
3540
+ return callback(data);
3541
+ }
3542
+ else {
3543
+ return encodeBlobAsBase64(data, callback);
3544
+ }
3531
3545
  }
3532
-
3533
- var m = re.exec(str || ''),
3534
- uri = {},
3535
- i = 14;
3536
-
3537
- while (i--) {
3538
- uri[parts[i]] = m[i] || '';
3546
+ else if (withNativeArrayBuffer$2 &&
3547
+ (data instanceof ArrayBuffer || isView$1(data))) {
3548
+ if (supportsBinary) {
3549
+ return callback(data);
3550
+ }
3551
+ else {
3552
+ return encodeBlobAsBase64(new Blob([data]), callback);
3553
+ }
3539
3554
  }
3555
+ // plain string
3556
+ return callback(PACKET_TYPES[type] + (data || ""));
3557
+ };
3558
+ const encodeBlobAsBase64 = (data, callback) => {
3559
+ const fileReader = new FileReader();
3560
+ fileReader.onload = function () {
3561
+ const content = fileReader.result.split(",")[1];
3562
+ callback("b" + content);
3563
+ };
3564
+ return fileReader.readAsDataURL(data);
3565
+ };
3540
3566
 
3541
- if (b != -1 && e != -1) {
3542
- uri.source = src;
3543
- uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
3544
- uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
3545
- uri.ipv6uri = true;
3567
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3568
+ // Use a lookup table to find the index.
3569
+ const lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
3570
+ for (let i = 0; i < chars.length; i++) {
3571
+ lookup$1[chars.charCodeAt(i)] = i;
3572
+ }
3573
+ const decode$1 = (base64) => {
3574
+ let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
3575
+ if (base64[base64.length - 1] === '=') {
3576
+ bufferLength--;
3577
+ if (base64[base64.length - 2] === '=') {
3578
+ bufferLength--;
3579
+ }
3546
3580
  }
3547
-
3548
- uri.pathNames = pathNames(uri, uri['path']);
3549
- uri.queryKey = queryKey(uri, uri['query']);
3550
-
3551
- return uri;
3581
+ const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
3582
+ for (i = 0; i < len; i += 4) {
3583
+ encoded1 = lookup$1[base64.charCodeAt(i)];
3584
+ encoded2 = lookup$1[base64.charCodeAt(i + 1)];
3585
+ encoded3 = lookup$1[base64.charCodeAt(i + 2)];
3586
+ encoded4 = lookup$1[base64.charCodeAt(i + 3)];
3587
+ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
3588
+ bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
3589
+ bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
3590
+ }
3591
+ return arraybuffer;
3552
3592
  };
3553
3593
 
3554
- function pathNames(obj, path) {
3555
- var regx = /\/{2,9}/g,
3556
- names = path.replace(regx, "/").split("/");
3557
-
3558
- if (path.substr(0, 1) == '/' || path.length === 0) {
3559
- names.splice(0, 1);
3594
+ const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
3595
+ const decodePacket = (encodedPacket, binaryType) => {
3596
+ if (typeof encodedPacket !== "string") {
3597
+ return {
3598
+ type: "message",
3599
+ data: mapBinary(encodedPacket, binaryType)
3600
+ };
3560
3601
  }
3561
- if (path.substr(path.length - 1, 1) == '/') {
3562
- names.splice(names.length - 1, 1);
3602
+ const type = encodedPacket.charAt(0);
3603
+ if (type === "b") {
3604
+ return {
3605
+ type: "message",
3606
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
3607
+ };
3563
3608
  }
3564
-
3565
- return names;
3566
- }
3567
-
3568
- function queryKey(uri, query) {
3569
- var data = {};
3570
-
3571
- query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
3572
- if ($1) {
3573
- data[$1] = $2;
3609
+ const packetType = PACKET_TYPES_REVERSE[type];
3610
+ if (!packetType) {
3611
+ return ERROR_PACKET;
3612
+ }
3613
+ return encodedPacket.length > 1
3614
+ ? {
3615
+ type: PACKET_TYPES_REVERSE[type],
3616
+ data: encodedPacket.substring(1)
3574
3617
  }
3618
+ : {
3619
+ type: PACKET_TYPES_REVERSE[type]
3620
+ };
3621
+ };
3622
+ const decodeBase64Packet = (data, binaryType) => {
3623
+ if (withNativeArrayBuffer$1) {
3624
+ const decoded = decode$1(data);
3625
+ return mapBinary(decoded, binaryType);
3626
+ }
3627
+ else {
3628
+ return { base64: true, data }; // fallback for old browsers
3629
+ }
3630
+ };
3631
+ const mapBinary = (data, binaryType) => {
3632
+ switch (binaryType) {
3633
+ case "blob":
3634
+ return data instanceof ArrayBuffer ? new Blob([data]) : data;
3635
+ case "arraybuffer":
3636
+ default:
3637
+ return data; // assuming the data is already an ArrayBuffer
3638
+ }
3639
+ };
3640
+
3641
+ const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
3642
+ const encodePayload = (packets, callback) => {
3643
+ // some packets may be added to the array while encoding, so the initial length must be saved
3644
+ const length = packets.length;
3645
+ const encodedPackets = new Array(length);
3646
+ let count = 0;
3647
+ packets.forEach((packet, i) => {
3648
+ // force base64 encoding for binary packets
3649
+ encodePacket(packet, false, encodedPacket => {
3650
+ encodedPackets[i] = encodedPacket;
3651
+ if (++count === length) {
3652
+ callback(encodedPackets.join(SEPARATOR));
3653
+ }
3654
+ });
3575
3655
  });
3656
+ };
3657
+ const decodePayload = (encodedPayload, binaryType) => {
3658
+ const encodedPackets = encodedPayload.split(SEPARATOR);
3659
+ const packets = [];
3660
+ for (let i = 0; i < encodedPackets.length; i++) {
3661
+ const decodedPacket = decodePacket(encodedPackets[i], binaryType);
3662
+ packets.push(decodedPacket);
3663
+ if (decodedPacket.type === "error") {
3664
+ break;
3665
+ }
3666
+ }
3667
+ return packets;
3668
+ };
3669
+ const protocol$1 = 4;
3576
3670
 
3577
- return data;
3578
- }
3671
+ /**
3672
+ * Expose `Emitter`.
3673
+ */
3674
+
3675
+ var Emitter_1 = Emitter;
3579
3676
 
3580
3677
  /**
3581
- * URL parser.
3678
+ * Initialize a new `Emitter`.
3582
3679
  *
3583
- * @param uri - url
3584
- * @param path - the request path of the connection
3585
- * @param loc - An object meant to mimic window.location.
3586
- * Defaults to window.location.
3587
- * @public
3680
+ * @api public
3588
3681
  */
3589
- function url(uri, path = "", loc) {
3590
- let obj = uri;
3591
- // default to window.location
3592
- loc = loc || (typeof location !== "undefined" && location);
3593
- if (null == uri)
3594
- uri = loc.protocol + "//" + loc.host;
3595
- // relative path support
3596
- if (typeof uri === "string") {
3597
- if ("/" === uri.charAt(0)) {
3598
- if ("/" === uri.charAt(1)) {
3599
- uri = loc.protocol + uri;
3600
- }
3601
- else {
3602
- uri = loc.host + uri;
3603
- }
3604
- }
3605
- if (!/^(https?|wss?):\/\//.test(uri)) {
3606
- if ("undefined" !== typeof loc) {
3607
- uri = loc.protocol + "//" + uri;
3608
- }
3609
- else {
3610
- uri = "https://" + uri;
3611
- }
3612
- }
3613
- // parse
3614
- obj = parseuri(uri);
3615
- }
3616
- // make sure we treat `localhost:80` and `localhost` equally
3617
- if (!obj.port) {
3618
- if (/^(http|ws)$/.test(obj.protocol)) {
3619
- obj.port = "80";
3620
- }
3621
- else if (/^(http|ws)s$/.test(obj.protocol)) {
3622
- obj.port = "443";
3623
- }
3624
- }
3625
- obj.path = obj.path || "/";
3626
- const ipv6 = obj.host.indexOf(":") !== -1;
3627
- const host = ipv6 ? "[" + obj.host + "]" : obj.host;
3628
- // define unique id
3629
- obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
3630
- // define href
3631
- obj.href =
3632
- obj.protocol +
3633
- "://" +
3634
- host +
3635
- (loc && loc.port === obj.port ? "" : ":" + obj.port);
3636
- return obj;
3637
- }
3638
3682
 
3639
- var hasCors = {exports: {}};
3683
+ function Emitter(obj) {
3684
+ if (obj) return mixin(obj);
3685
+ }
3640
3686
 
3641
3687
  /**
3642
- * Module exports.
3643
- *
3644
- * Logic borrowed from Modernizr:
3688
+ * Mixin the emitter properties.
3645
3689
  *
3646
- * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
3690
+ * @param {Object} obj
3691
+ * @return {Object}
3692
+ * @api private
3647
3693
  */
3648
3694
 
3649
- try {
3650
- hasCors.exports = typeof XMLHttpRequest !== 'undefined' &&
3651
- 'withCredentials' in new XMLHttpRequest();
3652
- } catch (err) {
3653
- // if XMLHttp support is disabled in IE then it will throw
3654
- // when trying to create
3655
- hasCors.exports = false;
3695
+ function mixin(obj) {
3696
+ for (var key in Emitter.prototype) {
3697
+ obj[key] = Emitter.prototype[key];
3698
+ }
3699
+ return obj;
3656
3700
  }
3657
3701
 
3658
- var hasCORS = hasCors.exports;
3659
-
3660
- var globalThis$1 = (() => {
3661
- if (typeof self !== "undefined") {
3662
- return self;
3663
- }
3664
- else if (typeof window !== "undefined") {
3665
- return window;
3666
- }
3667
- else {
3668
- return Function("return this")();
3669
- }
3670
- })();
3671
-
3672
- // browser shim for xmlhttprequest module
3673
- function XMLHttpRequest$1 (opts) {
3674
- const xdomain = opts.xdomain;
3675
- // XMLHttpRequest can be disabled on IE
3676
- try {
3677
- if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
3678
- return new XMLHttpRequest();
3679
- }
3680
- }
3681
- catch (e) { }
3682
- if (!xdomain) {
3683
- try {
3684
- return new globalThis$1[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
3685
- }
3686
- catch (e) { }
3687
- }
3688
- }
3689
-
3690
- function pick(obj, ...attr) {
3691
- return attr.reduce((acc, k) => {
3692
- if (obj.hasOwnProperty(k)) {
3693
- acc[k] = obj[k];
3694
- }
3695
- return acc;
3696
- }, {});
3697
- }
3698
- // Keep a reference to the real timeout functions so they can be used when overridden
3699
- const NATIVE_SET_TIMEOUT = setTimeout;
3700
- const NATIVE_CLEAR_TIMEOUT = clearTimeout;
3701
- function installTimerFunctions(obj, opts) {
3702
- if (opts.useNativeTimers) {
3703
- obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis$1);
3704
- obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis$1);
3705
- }
3706
- else {
3707
- obj.setTimeoutFn = setTimeout.bind(globalThis$1);
3708
- obj.clearTimeoutFn = clearTimeout.bind(globalThis$1);
3709
- }
3710
- }
3711
-
3712
- /**
3713
- * Expose `Emitter`.
3714
- */
3715
-
3716
- var Emitter_1 = Emitter;
3717
-
3718
- /**
3719
- * Initialize a new `Emitter`.
3720
- *
3721
- * @api public
3722
- */
3723
-
3724
- function Emitter(obj) {
3725
- if (obj) return mixin(obj);
3726
- }
3727
-
3728
- /**
3729
- * Mixin the emitter properties.
3730
- *
3731
- * @param {Object} obj
3732
- * @return {Object}
3733
- * @api private
3734
- */
3735
-
3736
- function mixin(obj) {
3737
- for (var key in Emitter.prototype) {
3738
- obj[key] = Emitter.prototype[key];
3739
- }
3740
- return obj;
3741
- }
3742
-
3743
- /**
3744
- * Listen on the given `event` with `fn`.
3745
- *
3746
- * @param {String} event
3747
- * @param {Function} fn
3748
- * @return {Emitter}
3749
- * @api public
3750
- */
3702
+ /**
3703
+ * Listen on the given `event` with `fn`.
3704
+ *
3705
+ * @param {String} event
3706
+ * @param {Function} fn
3707
+ * @return {Emitter}
3708
+ * @api public
3709
+ */
3751
3710
 
3752
3711
  Emitter.prototype.on =
3753
3712
  Emitter.prototype.addEventListener = function(event, fn){
@@ -3885,201 +3844,78 @@ Emitter.prototype.hasListeners = function(event){
3885
3844
  return !! this.listeners(event).length;
3886
3845
  };
3887
3846
 
3888
- const PACKET_TYPES = Object.create(null); // no Map = no polyfill
3889
- PACKET_TYPES["open"] = "0";
3890
- PACKET_TYPES["close"] = "1";
3891
- PACKET_TYPES["ping"] = "2";
3892
- PACKET_TYPES["pong"] = "3";
3893
- PACKET_TYPES["message"] = "4";
3894
- PACKET_TYPES["upgrade"] = "5";
3895
- PACKET_TYPES["noop"] = "6";
3896
- const PACKET_TYPES_REVERSE = Object.create(null);
3897
- Object.keys(PACKET_TYPES).forEach(key => {
3898
- PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
3899
- });
3900
- const ERROR_PACKET = { type: "error", data: "parser error" };
3901
-
3902
- const withNativeBlob$1 = typeof Blob === "function" ||
3903
- (typeof Blob !== "undefined" &&
3904
- Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
3905
- const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
3906
- // ArrayBuffer.isView method is not defined in IE10
3907
- const isView$1 = obj => {
3908
- return typeof ArrayBuffer.isView === "function"
3909
- ? ArrayBuffer.isView(obj)
3910
- : obj && obj.buffer instanceof ArrayBuffer;
3911
- };
3912
- const encodePacket = ({ type, data }, supportsBinary, callback) => {
3913
- if (withNativeBlob$1 && data instanceof Blob) {
3914
- if (supportsBinary) {
3915
- return callback(data);
3916
- }
3917
- else {
3918
- return encodeBlobAsBase64(data, callback);
3919
- }
3847
+ const globalThisShim = (() => {
3848
+ if (typeof self !== "undefined") {
3849
+ return self;
3920
3850
  }
3921
- else if (withNativeArrayBuffer$2 &&
3922
- (data instanceof ArrayBuffer || isView$1(data))) {
3923
- if (supportsBinary) {
3924
- return callback(data);
3925
- }
3926
- else {
3927
- return encodeBlobAsBase64(new Blob([data]), callback);
3928
- }
3851
+ else if (typeof window !== "undefined") {
3852
+ return window;
3929
3853
  }
3930
- // plain string
3931
- return callback(PACKET_TYPES[type] + (data || ""));
3932
- };
3933
- const encodeBlobAsBase64 = (data, callback) => {
3934
- const fileReader = new FileReader();
3935
- fileReader.onload = function () {
3936
- const content = fileReader.result.split(",")[1];
3937
- callback("b" + content);
3938
- };
3939
- return fileReader.readAsDataURL(data);
3940
- };
3941
-
3942
- var base64Arraybuffer_umd = {exports: {}};
3854
+ else {
3855
+ return Function("return this")();
3856
+ }
3857
+ })();
3943
3858
 
3944
- /*
3945
- * base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
3946
- * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
3947
- * Released under MIT License
3948
- */
3949
-
3950
- (function (module, exports) {
3951
- (function (global, factory) {
3952
- factory(exports) ;
3953
- }(commonjsGlobal, (function (exports) {
3954
- var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
3955
- // Use a lookup table to find the index.
3956
- var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
3957
- for (var i = 0; i < chars.length; i++) {
3958
- lookup[chars.charCodeAt(i)] = i;
3959
- }
3960
- var encode = function (arraybuffer) {
3961
- var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
3962
- for (i = 0; i < len; i += 3) {
3963
- base64 += chars[bytes[i] >> 2];
3964
- base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
3965
- base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
3966
- base64 += chars[bytes[i + 2] & 63];
3859
+ function pick(obj, ...attr) {
3860
+ return attr.reduce((acc, k) => {
3861
+ if (obj.hasOwnProperty(k)) {
3862
+ acc[k] = obj[k];
3967
3863
  }
3968
- if (len % 3 === 2) {
3969
- base64 = base64.substring(0, base64.length - 1) + '=';
3864
+ return acc;
3865
+ }, {});
3866
+ }
3867
+ // Keep a reference to the real timeout functions so they can be used when overridden
3868
+ const NATIVE_SET_TIMEOUT = setTimeout;
3869
+ const NATIVE_CLEAR_TIMEOUT = clearTimeout;
3870
+ function installTimerFunctions(obj, opts) {
3871
+ if (opts.useNativeTimers) {
3872
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
3873
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
3874
+ }
3875
+ else {
3876
+ obj.setTimeoutFn = setTimeout.bind(globalThisShim);
3877
+ obj.clearTimeoutFn = clearTimeout.bind(globalThisShim);
3878
+ }
3879
+ }
3880
+ // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
3881
+ const BASE64_OVERHEAD = 1.33;
3882
+ // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
3883
+ function byteLength(obj) {
3884
+ if (typeof obj === "string") {
3885
+ return utf8Length(obj);
3886
+ }
3887
+ // arraybuffer or blob
3888
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
3889
+ }
3890
+ function utf8Length(str) {
3891
+ let c = 0, length = 0;
3892
+ for (let i = 0, l = str.length; i < l; i++) {
3893
+ c = str.charCodeAt(i);
3894
+ if (c < 0x80) {
3895
+ length += 1;
3970
3896
  }
3971
- else if (len % 3 === 1) {
3972
- base64 = base64.substring(0, base64.length - 2) + '==';
3897
+ else if (c < 0x800) {
3898
+ length += 2;
3973
3899
  }
3974
- return base64;
3975
- };
3976
- var decode = function (base64) {
3977
- var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
3978
- if (base64[base64.length - 1] === '=') {
3979
- bufferLength--;
3980
- if (base64[base64.length - 2] === '=') {
3981
- bufferLength--;
3982
- }
3900
+ else if (c < 0xd800 || c >= 0xe000) {
3901
+ length += 3;
3983
3902
  }
3984
- var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
3985
- for (i = 0; i < len; i += 4) {
3986
- encoded1 = lookup[base64.charCodeAt(i)];
3987
- encoded2 = lookup[base64.charCodeAt(i + 1)];
3988
- encoded3 = lookup[base64.charCodeAt(i + 2)];
3989
- encoded4 = lookup[base64.charCodeAt(i + 3)];
3990
- bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
3991
- bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
3992
- bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
3903
+ else {
3904
+ i++;
3905
+ length += 4;
3993
3906
  }
3994
- return arraybuffer;
3995
- };
3996
-
3997
- exports.decode = decode;
3998
- exports.encode = encode;
3999
-
4000
- Object.defineProperty(exports, '__esModule', { value: true });
4001
-
4002
- })));
4003
-
4004
- }(base64Arraybuffer_umd, base64Arraybuffer_umd.exports));
4005
-
4006
- const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
4007
- const decodePacket = (encodedPacket, binaryType) => {
4008
- if (typeof encodedPacket !== "string") {
4009
- return {
4010
- type: "message",
4011
- data: mapBinary(encodedPacket, binaryType)
4012
- };
4013
- }
4014
- const type = encodedPacket.charAt(0);
4015
- if (type === "b") {
4016
- return {
4017
- type: "message",
4018
- data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
4019
- };
4020
3907
  }
4021
- const packetType = PACKET_TYPES_REVERSE[type];
4022
- if (!packetType) {
4023
- return ERROR_PACKET;
4024
- }
4025
- return encodedPacket.length > 1
4026
- ? {
4027
- type: PACKET_TYPES_REVERSE[type],
4028
- data: encodedPacket.substring(1)
4029
- }
4030
- : {
4031
- type: PACKET_TYPES_REVERSE[type]
4032
- };
4033
- };
4034
- const decodeBase64Packet = (data, binaryType) => {
4035
- if (withNativeArrayBuffer$1) {
4036
- const decoded = base64Arraybuffer_umd.exports.decode(data);
4037
- return mapBinary(decoded, binaryType);
4038
- }
4039
- else {
4040
- return { base64: true, data }; // fallback for old browsers
4041
- }
4042
- };
4043
- const mapBinary = (data, binaryType) => {
4044
- switch (binaryType) {
4045
- case "blob":
4046
- return data instanceof ArrayBuffer ? new Blob([data]) : data;
4047
- case "arraybuffer":
4048
- default:
4049
- return data; // assuming the data is already an ArrayBuffer
4050
- }
4051
- };
3908
+ return length;
3909
+ }
4052
3910
 
4053
- const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
4054
- const encodePayload = (packets, callback) => {
4055
- // some packets may be added to the array while encoding, so the initial length must be saved
4056
- const length = packets.length;
4057
- const encodedPackets = new Array(length);
4058
- let count = 0;
4059
- packets.forEach((packet, i) => {
4060
- // force base64 encoding for binary packets
4061
- encodePacket(packet, false, encodedPacket => {
4062
- encodedPackets[i] = encodedPacket;
4063
- if (++count === length) {
4064
- callback(encodedPackets.join(SEPARATOR));
4065
- }
4066
- });
4067
- });
4068
- };
4069
- const decodePayload = (encodedPayload, binaryType) => {
4070
- const encodedPackets = encodedPayload.split(SEPARATOR);
4071
- const packets = [];
4072
- for (let i = 0; i < encodedPackets.length; i++) {
4073
- const decodedPacket = decodePacket(encodedPackets[i], binaryType);
4074
- packets.push(decodedPacket);
4075
- if (decodedPacket.type === "error") {
4076
- break;
4077
- }
3911
+ class TransportError extends Error {
3912
+ constructor(reason, description, context) {
3913
+ super(reason);
3914
+ this.description = description;
3915
+ this.context = context;
3916
+ this.type = "TransportError";
4078
3917
  }
4079
- return packets;
4080
- };
4081
- const protocol$1 = 4;
4082
-
3918
+ }
4083
3919
  class Transport extends Emitter_1 {
4084
3920
  /**
4085
3921
  * Transport abstract constructor.
@@ -4099,17 +3935,14 @@ class Transport extends Emitter_1 {
4099
3935
  /**
4100
3936
  * Emits an error.
4101
3937
  *
4102
- * @param {String} str
3938
+ * @param {String} reason
3939
+ * @param description
3940
+ * @param context - the error context
4103
3941
  * @return {Transport} for chaining
4104
3942
  * @api protected
4105
3943
  */
4106
- onError(msg, desc) {
4107
- const err = new Error(msg);
4108
- // @ts-ignore
4109
- err.type = "TransportError";
4110
- // @ts-ignore
4111
- err.description = desc;
4112
- super.emit("error", err);
3944
+ onError(reason, description, context) {
3945
+ super.emitReserved("error", new TransportError(reason, description, context));
4113
3946
  return this;
4114
3947
  }
4115
3948
  /**
@@ -4155,7 +3988,7 @@ class Transport extends Emitter_1 {
4155
3988
  onOpen() {
4156
3989
  this.readyState = "open";
4157
3990
  this.writable = true;
4158
- super.emit("open");
3991
+ super.emitReserved("open");
4159
3992
  }
4160
3993
  /**
4161
3994
  * Called with data.
@@ -4173,26 +4006,22 @@ class Transport extends Emitter_1 {
4173
4006
  * @api protected
4174
4007
  */
4175
4008
  onPacket(packet) {
4176
- super.emit("packet", packet);
4009
+ super.emitReserved("packet", packet);
4177
4010
  }
4178
4011
  /**
4179
4012
  * Called upon close.
4180
4013
  *
4181
4014
  * @api protected
4182
4015
  */
4183
- onClose() {
4016
+ onClose(details) {
4184
4017
  this.readyState = "closed";
4185
- super.emit("close");
4018
+ super.emitReserved("close", details);
4186
4019
  }
4187
4020
  }
4188
4021
 
4189
- var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
4190
- , length = 64
4191
- , map = {}
4192
- , seed = 0
4193
- , i = 0
4194
- , prev;
4195
-
4022
+ // imported from https://github.com/unshiftio/yeast
4023
+ const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), length = 64, map = {};
4024
+ let seed = 0, i = 0, prev;
4196
4025
  /**
4197
4026
  * Return a string representing the specified number.
4198
4027
  *
@@ -4200,34 +4029,14 @@ var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_
4200
4029
  * @returns {String} The string representation of the number.
4201
4030
  * @api public
4202
4031
  */
4203
- function encode(num) {
4204
- var encoded = '';
4205
-
4206
- do {
4207
- encoded = alphabet[num % length] + encoded;
4208
- num = Math.floor(num / length);
4209
- } while (num > 0);
4210
-
4211
- return encoded;
4212
- }
4213
-
4214
- /**
4215
- * Return the integer value specified by the given string.
4216
- *
4217
- * @param {String} str The string to convert.
4218
- * @returns {Number} The integer value represented by the string.
4219
- * @api public
4220
- */
4221
- function decode(str) {
4222
- var decoded = 0;
4223
-
4224
- for (i = 0; i < str.length; i++) {
4225
- decoded = decoded * length + map[str.charAt(i)];
4226
- }
4227
-
4228
- return decoded;
4032
+ function encode$1(num) {
4033
+ let encoded = '';
4034
+ do {
4035
+ encoded = alphabet[num % length] + encoded;
4036
+ num = Math.floor(num / length);
4037
+ } while (num > 0);
4038
+ return encoded;
4229
4039
  }
4230
-
4231
4040
  /**
4232
4041
  * Yeast: A tiny growing id generator.
4233
4042
  *
@@ -4235,26 +4044,18 @@ function decode(str) {
4235
4044
  * @api public
4236
4045
  */
4237
4046
  function yeast() {
4238
- var now = encode(+new Date());
4239
-
4240
- if (now !== prev) return seed = 0, prev = now;
4241
- return now +'.'+ encode(seed++);
4047
+ const now = encode$1(+new Date());
4048
+ if (now !== prev)
4049
+ return seed = 0, prev = now;
4050
+ return now + '.' + encode$1(seed++);
4242
4051
  }
4243
-
4244
4052
  //
4245
4053
  // Map each character to its index.
4246
4054
  //
4247
- for (; i < length; i++) map[alphabet[i]] = i;
4248
-
4249
- //
4250
- // Expose the `yeast`, `encode` and `decode` functions.
4251
- //
4252
- yeast.encode = encode;
4253
- yeast.decode = decode;
4254
- var yeast_1 = yeast;
4255
-
4256
- var parseqs = {};
4055
+ for (; i < length; i++)
4056
+ map[alphabet[i]] = i;
4257
4057
 
4058
+ // imported from https://github.com/galkn/querystring
4258
4059
  /**
4259
4060
  * Compiles a querystring
4260
4061
  * Returns string representation of the object
@@ -4262,41 +4063,98 @@ var parseqs = {};
4262
4063
  * @param {Object}
4263
4064
  * @api private
4264
4065
  */
4265
-
4266
- parseqs.encode = function (obj) {
4267
- var str = '';
4268
-
4269
- for (var i in obj) {
4270
- if (obj.hasOwnProperty(i)) {
4271
- if (str.length) str += '&';
4272
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
4066
+ function encode(obj) {
4067
+ let str = '';
4068
+ for (let i in obj) {
4069
+ if (obj.hasOwnProperty(i)) {
4070
+ if (str.length)
4071
+ str += '&';
4072
+ str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
4073
+ }
4273
4074
  }
4274
- }
4275
-
4276
- return str;
4277
- };
4278
-
4075
+ return str;
4076
+ }
4279
4077
  /**
4280
4078
  * Parses a simple querystring into an object
4281
4079
  *
4282
4080
  * @param {String} qs
4283
4081
  * @api private
4284
4082
  */
4083
+ function decode(qs) {
4084
+ let qry = {};
4085
+ let pairs = qs.split('&');
4086
+ for (let i = 0, l = pairs.length; i < l; i++) {
4087
+ let pair = pairs[i].split('=');
4088
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
4089
+ }
4090
+ return qry;
4091
+ }
4285
4092
 
4286
- parseqs.decode = function(qs){
4287
- var qry = {};
4288
- var pairs = qs.split('&');
4289
- for (var i = 0, l = pairs.length; i < l; i++) {
4290
- var pair = pairs[i].split('=');
4291
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
4292
- }
4293
- return qry;
4294
- };
4093
+ // imported from https://github.com/component/has-cors
4094
+ let value = false;
4095
+ try {
4096
+ value = typeof XMLHttpRequest !== 'undefined' &&
4097
+ 'withCredentials' in new XMLHttpRequest();
4098
+ }
4099
+ catch (err) {
4100
+ // if XMLHttp support is disabled in IE then it will throw
4101
+ // when trying to create
4102
+ }
4103
+ const hasCORS = value;
4295
4104
 
4105
+ // browser shim for xmlhttprequest module
4106
+ function XHR(opts) {
4107
+ const xdomain = opts.xdomain;
4108
+ // XMLHttpRequest can be disabled on IE
4109
+ try {
4110
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
4111
+ return new XMLHttpRequest();
4112
+ }
4113
+ }
4114
+ catch (e) { }
4115
+ if (!xdomain) {
4116
+ try {
4117
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
4118
+ }
4119
+ catch (e) { }
4120
+ }
4121
+ }
4122
+
4123
+ function empty$2() { }
4124
+ const hasXHR2 = (function () {
4125
+ const xhr = new XHR({
4126
+ xdomain: false
4127
+ });
4128
+ return null != xhr.responseType;
4129
+ })();
4296
4130
  class Polling extends Transport {
4297
- constructor() {
4298
- super(...arguments);
4131
+ /**
4132
+ * XHR Polling constructor.
4133
+ *
4134
+ * @param {Object} opts
4135
+ * @api public
4136
+ */
4137
+ constructor(opts) {
4138
+ super(opts);
4299
4139
  this.polling = false;
4140
+ if (typeof location !== "undefined") {
4141
+ const isSSL = "https:" === location.protocol;
4142
+ let port = location.port;
4143
+ // some user agents have empty `location.port`
4144
+ if (!port) {
4145
+ port = isSSL ? "443" : "80";
4146
+ }
4147
+ this.xd =
4148
+ (typeof location !== "undefined" &&
4149
+ opts.hostname !== location.hostname) ||
4150
+ port !== opts.port;
4151
+ this.xs = opts.secure !== isSSL;
4152
+ }
4153
+ /**
4154
+ * XHR supports binary
4155
+ */
4156
+ const forceBase64 = opts && opts.forceBase64;
4157
+ this.supportsBinary = hasXHR2 && !forceBase64;
4300
4158
  }
4301
4159
  /**
4302
4160
  * Transport name.
@@ -4352,7 +4210,7 @@ class Polling extends Transport {
4352
4210
  poll() {
4353
4211
  this.polling = true;
4354
4212
  this.doPoll();
4355
- this.emit("poll");
4213
+ this.emitReserved("poll");
4356
4214
  }
4357
4215
  /**
4358
4216
  * Overloads onData to detect payloads.
@@ -4367,7 +4225,7 @@ class Polling extends Transport {
4367
4225
  }
4368
4226
  // if its a close packet, we close the ongoing requests
4369
4227
  if ("close" === packet.type) {
4370
- this.onClose();
4228
+ this.onClose({ description: "transport closed by the server" });
4371
4229
  return false;
4372
4230
  }
4373
4231
  // otherwise bypass onData and handle the message
@@ -4379,7 +4237,7 @@ class Polling extends Transport {
4379
4237
  if ("closed" !== this.readyState) {
4380
4238
  // if we got data we're not polling
4381
4239
  this.polling = false;
4382
- this.emit("pollComplete");
4240
+ this.emitReserved("pollComplete");
4383
4241
  if ("open" === this.readyState) {
4384
4242
  this.poll();
4385
4243
  }
@@ -4415,7 +4273,7 @@ class Polling extends Transport {
4415
4273
  encodePayload(packets, data => {
4416
4274
  this.doWrite(data, () => {
4417
4275
  this.writable = true;
4418
- this.emit("drain");
4276
+ this.emitReserved("drain");
4419
4277
  });
4420
4278
  });
4421
4279
  }
@@ -4430,7 +4288,7 @@ class Polling extends Transport {
4430
4288
  let port = "";
4431
4289
  // cache busting is forced
4432
4290
  if (false !== this.opts.timestampRequests) {
4433
- query[this.opts.timestampParam] = yeast_1();
4291
+ query[this.opts.timestampParam] = yeast();
4434
4292
  }
4435
4293
  if (!this.supportsBinary && !query.sid) {
4436
4294
  query.b64 = 1;
@@ -4441,7 +4299,7 @@ class Polling extends Transport {
4441
4299
  ("http" === schema && Number(this.opts.port) !== 80))) {
4442
4300
  port = ":" + this.opts.port;
4443
4301
  }
4444
- const encodedQuery = parseqs.encode(query);
4302
+ const encodedQuery = encode(query);
4445
4303
  const ipv6 = this.opts.hostname.indexOf(":") !== -1;
4446
4304
  return (schema +
4447
4305
  "://" +
@@ -4450,47 +4308,6 @@ class Polling extends Transport {
4450
4308
  this.opts.path +
4451
4309
  (encodedQuery.length ? "?" + encodedQuery : ""));
4452
4310
  }
4453
- }
4454
-
4455
- /* global attachEvent */
4456
- /**
4457
- * Empty function
4458
- */
4459
- function empty$2() { }
4460
- const hasXHR2 = (function () {
4461
- const xhr = new XMLHttpRequest$1({
4462
- xdomain: false
4463
- });
4464
- return null != xhr.responseType;
4465
- })();
4466
- class XHR extends Polling {
4467
- /**
4468
- * XHR Polling constructor.
4469
- *
4470
- * @param {Object} opts
4471
- * @api public
4472
- */
4473
- constructor(opts) {
4474
- super(opts);
4475
- if (typeof location !== "undefined") {
4476
- const isSSL = "https:" === location.protocol;
4477
- let port = location.port;
4478
- // some user agents have empty `location.port`
4479
- if (!port) {
4480
- port = isSSL ? "443" : "80";
4481
- }
4482
- this.xd =
4483
- (typeof location !== "undefined" &&
4484
- opts.hostname !== location.hostname) ||
4485
- port !== opts.port;
4486
- this.xs = opts.secure !== isSSL;
4487
- }
4488
- /**
4489
- * XHR supports binary
4490
- */
4491
- const forceBase64 = opts && opts.forceBase64;
4492
- this.supportsBinary = hasXHR2 && !forceBase64;
4493
- }
4494
4311
  /**
4495
4312
  * Creates a request.
4496
4313
  *
@@ -4514,8 +4331,8 @@ class XHR extends Polling {
4514
4331
  data: data
4515
4332
  });
4516
4333
  req.on("success", fn);
4517
- req.on("error", err => {
4518
- this.onError("xhr post error", err);
4334
+ req.on("error", (xhrStatus, context) => {
4335
+ this.onError("xhr post error", xhrStatus, context);
4519
4336
  });
4520
4337
  }
4521
4338
  /**
@@ -4526,8 +4343,8 @@ class XHR extends Polling {
4526
4343
  doPoll() {
4527
4344
  const req = this.request();
4528
4345
  req.on("data", this.onData.bind(this));
4529
- req.on("error", err => {
4530
- this.onError("xhr poll error", err);
4346
+ req.on("error", (xhrStatus, context) => {
4347
+ this.onError("xhr poll error", xhrStatus, context);
4531
4348
  });
4532
4349
  this.pollXhr = req;
4533
4350
  }
@@ -4558,7 +4375,7 @@ class Request extends Emitter_1 {
4558
4375
  const opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
4559
4376
  opts.xdomain = !!this.opts.xd;
4560
4377
  opts.xscheme = !!this.opts.xs;
4561
- const xhr = (this.xhr = new XMLHttpRequest$1(opts));
4378
+ const xhr = (this.xhr = new XHR(opts));
4562
4379
  try {
4563
4380
  xhr.open(this.method, this.uri, this.async);
4564
4381
  try {
@@ -4612,30 +4429,12 @@ class Request extends Emitter_1 {
4612
4429
  this.setTimeoutFn(() => {
4613
4430
  this.onError(e);
4614
4431
  }, 0);
4615
- return;
4616
- }
4617
- if (typeof document !== "undefined") {
4618
- this.index = Request.requestsCount++;
4619
- Request.requests[this.index] = this;
4620
- }
4621
- }
4622
- /**
4623
- * Called upon successful response.
4624
- *
4625
- * @api private
4626
- */
4627
- onSuccess() {
4628
- this.emit("success");
4629
- this.cleanup();
4630
- }
4631
- /**
4632
- * Called if we have data.
4633
- *
4634
- * @api private
4635
- */
4636
- onData(data) {
4637
- this.emit("data", data);
4638
- this.onSuccess();
4432
+ return;
4433
+ }
4434
+ if (typeof document !== "undefined") {
4435
+ this.index = Request.requestsCount++;
4436
+ Request.requests[this.index] = this;
4437
+ }
4639
4438
  }
4640
4439
  /**
4641
4440
  * Called upon error.
@@ -4643,7 +4442,7 @@ class Request extends Emitter_1 {
4643
4442
  * @api private
4644
4443
  */
4645
4444
  onError(err) {
4646
- this.emit("error", err);
4445
+ this.emitReserved("error", err, this.xhr);
4647
4446
  this.cleanup(true);
4648
4447
  }
4649
4448
  /**
@@ -4675,7 +4474,9 @@ class Request extends Emitter_1 {
4675
4474
  onLoad() {
4676
4475
  const data = this.xhr.responseText;
4677
4476
  if (data !== null) {
4678
- this.onData(data);
4477
+ this.emitReserved("data", data);
4478
+ this.emitReserved("success");
4479
+ this.cleanup();
4679
4480
  }
4680
4481
  }
4681
4482
  /**
@@ -4701,7 +4502,7 @@ if (typeof document !== "undefined") {
4701
4502
  attachEvent("onunload", unloadHandler);
4702
4503
  }
4703
4504
  else if (typeof addEventListener === "function") {
4704
- const terminationEvent = "onpagehide" in globalThis$1 ? "pagehide" : "unload";
4505
+ const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
4705
4506
  addEventListener(terminationEvent, unloadHandler, false);
4706
4507
  }
4707
4508
  }
@@ -4722,7 +4523,7 @@ const nextTick = (() => {
4722
4523
  return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
4723
4524
  }
4724
4525
  })();
4725
- const WebSocket = globalThis$1.WebSocket || globalThis$1.MozWebSocket;
4526
+ const WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
4726
4527
  const usingBrowserWebSocket = true;
4727
4528
  const defaultBinaryType = "arraybuffer";
4728
4529
 
@@ -4777,7 +4578,7 @@ class WS extends Transport {
4777
4578
  : new WebSocket(uri, protocols, opts);
4778
4579
  }
4779
4580
  catch (err) {
4780
- return this.emit("error", err);
4581
+ return this.emitReserved("error", err);
4781
4582
  }
4782
4583
  this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
4783
4584
  this.addEventListeners();
@@ -4794,7 +4595,10 @@ class WS extends Transport {
4794
4595
  }
4795
4596
  this.onOpen();
4796
4597
  };
4797
- this.ws.onclose = this.onClose.bind(this);
4598
+ this.ws.onclose = closeEvent => this.onClose({
4599
+ description: "websocket connection closed",
4600
+ context: closeEvent
4601
+ });
4798
4602
  this.ws.onmessage = ev => this.onData(ev.data);
4799
4603
  this.ws.onerror = e => this.onError("websocket error", e);
4800
4604
  }
@@ -4830,7 +4634,7 @@ class WS extends Transport {
4830
4634
  // defer to next tick to allow Socket to clear writeBuffer
4831
4635
  nextTick(() => {
4832
4636
  this.writable = true;
4833
- this.emit("drain");
4637
+ this.emitReserved("drain");
4834
4638
  }, this.setTimeoutFn);
4835
4639
  }
4836
4640
  });
@@ -4864,13 +4668,13 @@ class WS extends Transport {
4864
4668
  }
4865
4669
  // append timestamp to URI
4866
4670
  if (this.opts.timestampRequests) {
4867
- query[this.opts.timestampParam] = yeast_1();
4671
+ query[this.opts.timestampParam] = yeast();
4868
4672
  }
4869
4673
  // communicate binary support capabilities
4870
4674
  if (!this.supportsBinary) {
4871
4675
  query.b64 = 1;
4872
4676
  }
4873
- const encodedQuery = parseqs.encode(query);
4677
+ const encodedQuery = encode(query);
4874
4678
  const ipv6 = this.opts.hostname.indexOf(":") !== -1;
4875
4679
  return (schema +
4876
4680
  "://" +
@@ -4886,16 +4690,65 @@ class WS extends Transport {
4886
4690
  * @api public
4887
4691
  */
4888
4692
  check() {
4889
- return (!!WebSocket &&
4890
- !("__initialize" in WebSocket && this.name === WS.prototype.name));
4693
+ return !!WebSocket;
4891
4694
  }
4892
4695
  }
4893
4696
 
4894
4697
  const transports = {
4895
4698
  websocket: WS,
4896
- polling: XHR
4699
+ polling: Polling
4897
4700
  };
4898
4701
 
4702
+ // imported from https://github.com/galkn/parseuri
4703
+ /**
4704
+ * Parses an URI
4705
+ *
4706
+ * @author Steven Levithan <stevenlevithan.com> (MIT license)
4707
+ * @api private
4708
+ */
4709
+ const re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
4710
+ const parts = [
4711
+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
4712
+ ];
4713
+ function parse$2(str) {
4714
+ const src = str, b = str.indexOf('['), e = str.indexOf(']');
4715
+ if (b != -1 && e != -1) {
4716
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
4717
+ }
4718
+ let m = re.exec(str || ''), uri = {}, i = 14;
4719
+ while (i--) {
4720
+ uri[parts[i]] = m[i] || '';
4721
+ }
4722
+ if (b != -1 && e != -1) {
4723
+ uri.source = src;
4724
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
4725
+ uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
4726
+ uri.ipv6uri = true;
4727
+ }
4728
+ uri.pathNames = pathNames(uri, uri['path']);
4729
+ uri.queryKey = queryKey(uri, uri['query']);
4730
+ return uri;
4731
+ }
4732
+ function pathNames(obj, path) {
4733
+ const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
4734
+ if (path.substr(0, 1) == '/' || path.length === 0) {
4735
+ names.splice(0, 1);
4736
+ }
4737
+ if (path.substr(path.length - 1, 1) == '/') {
4738
+ names.splice(names.length - 1, 1);
4739
+ }
4740
+ return names;
4741
+ }
4742
+ function queryKey(uri, query) {
4743
+ const data = {};
4744
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
4745
+ if ($1) {
4746
+ data[$1] = $2;
4747
+ }
4748
+ });
4749
+ return data;
4750
+ }
4751
+
4899
4752
  class Socket$1 extends Emitter_1 {
4900
4753
  /**
4901
4754
  * Socket constructor.
@@ -4911,7 +4764,7 @@ class Socket$1 extends Emitter_1 {
4911
4764
  uri = null;
4912
4765
  }
4913
4766
  if (uri) {
4914
- uri = parseuri(uri);
4767
+ uri = parse$2(uri);
4915
4768
  opts.hostname = uri.host;
4916
4769
  opts.secure = uri.protocol === "https" || uri.protocol === "wss";
4917
4770
  opts.port = uri.port;
@@ -4919,7 +4772,7 @@ class Socket$1 extends Emitter_1 {
4919
4772
  opts.query = uri.query;
4920
4773
  }
4921
4774
  else if (opts.host) {
4922
- opts.hostname = parseuri(opts.host).host;
4775
+ opts.hostname = parse$2(opts.host).host;
4923
4776
  }
4924
4777
  installTimerFunctions(this, opts);
4925
4778
  this.secure =
@@ -4960,7 +4813,7 @@ class Socket$1 extends Emitter_1 {
4960
4813
  }, opts);
4961
4814
  this.opts.path = this.opts.path.replace(/\/$/, "") + "/";
4962
4815
  if (typeof this.opts.query === "string") {
4963
- this.opts.query = parseqs.decode(this.opts.query);
4816
+ this.opts.query = decode(this.opts.query);
4964
4817
  }
4965
4818
  // set on handshake
4966
4819
  this.id = null;
@@ -4984,7 +4837,9 @@ class Socket$1 extends Emitter_1 {
4984
4837
  }
4985
4838
  if (this.hostname !== "localhost") {
4986
4839
  this.offlineEventListener = () => {
4987
- this.onClose("transport close");
4840
+ this.onClose("transport close", {
4841
+ description: "network connection lost"
4842
+ });
4988
4843
  };
4989
4844
  addEventListener("offline", this.offlineEventListener, false);
4990
4845
  }
@@ -4999,7 +4854,7 @@ class Socket$1 extends Emitter_1 {
4999
4854
  * @api private
5000
4855
  */
5001
4856
  createTransport(name) {
5002
- const query = clone(this.opts.query);
4857
+ const query = Object.assign({}, this.opts.query);
5003
4858
  // append engine.io protocol identifier
5004
4859
  query.EIO = protocol$1;
5005
4860
  // transport name
@@ -5067,9 +4922,7 @@ class Socket$1 extends Emitter_1 {
5067
4922
  .on("drain", this.onDrain.bind(this))
5068
4923
  .on("packet", this.onPacket.bind(this))
5069
4924
  .on("error", this.onError.bind(this))
5070
- .on("close", () => {
5071
- this.onClose("transport close");
5072
- });
4925
+ .on("close", reason => this.onClose("transport close", reason));
5073
4926
  }
5074
4927
  /**
5075
4928
  * Probes a transport.
@@ -5231,6 +5084,7 @@ class Socket$1 extends Emitter_1 {
5231
5084
  this.upgrades = this.filterUpgrades(data.upgrades);
5232
5085
  this.pingInterval = data.pingInterval;
5233
5086
  this.pingTimeout = data.pingTimeout;
5087
+ this.maxPayload = data.maxPayload;
5234
5088
  this.onOpen();
5235
5089
  // In case open handler closes socket
5236
5090
  if ("closed" === this.readyState)
@@ -5279,13 +5133,40 @@ class Socket$1 extends Emitter_1 {
5279
5133
  this.transport.writable &&
5280
5134
  !this.upgrading &&
5281
5135
  this.writeBuffer.length) {
5282
- this.transport.send(this.writeBuffer);
5136
+ const packets = this.getWritablePackets();
5137
+ this.transport.send(packets);
5283
5138
  // keep track of current length of writeBuffer
5284
5139
  // splice writeBuffer and callbackBuffer on `drain`
5285
- this.prevBufferLen = this.writeBuffer.length;
5140
+ this.prevBufferLen = packets.length;
5286
5141
  this.emitReserved("flush");
5287
5142
  }
5288
5143
  }
5144
+ /**
5145
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
5146
+ * long-polling)
5147
+ *
5148
+ * @private
5149
+ */
5150
+ getWritablePackets() {
5151
+ const shouldCheckPayloadSize = this.maxPayload &&
5152
+ this.transport.name === "polling" &&
5153
+ this.writeBuffer.length > 1;
5154
+ if (!shouldCheckPayloadSize) {
5155
+ return this.writeBuffer;
5156
+ }
5157
+ let payloadSize = 1; // first packet type
5158
+ for (let i = 0; i < this.writeBuffer.length; i++) {
5159
+ const data = this.writeBuffer[i].data;
5160
+ if (data) {
5161
+ payloadSize += byteLength(data);
5162
+ }
5163
+ if (i > 0 && payloadSize > this.maxPayload) {
5164
+ return this.writeBuffer.slice(0, i);
5165
+ }
5166
+ payloadSize += 2; // separator + packet type
5167
+ }
5168
+ return this.writeBuffer;
5169
+ }
5289
5170
  /**
5290
5171
  * Sends a message.
5291
5172
  *
@@ -5393,7 +5274,7 @@ class Socket$1 extends Emitter_1 {
5393
5274
  *
5394
5275
  * @api private
5395
5276
  */
5396
- onClose(reason, desc) {
5277
+ onClose(reason, description) {
5397
5278
  if ("opening" === this.readyState ||
5398
5279
  "open" === this.readyState ||
5399
5280
  "closing" === this.readyState) {
@@ -5413,7 +5294,7 @@ class Socket$1 extends Emitter_1 {
5413
5294
  // clear session id
5414
5295
  this.id = null;
5415
5296
  // emit close event
5416
- this.emitReserved("close", reason, desc);
5297
+ this.emitReserved("close", reason, description);
5417
5298
  // clean buffers after, so users can still
5418
5299
  // grab the buffers on `close` event
5419
5300
  this.writeBuffer = [];
@@ -5439,18 +5320,68 @@ class Socket$1 extends Emitter_1 {
5439
5320
  }
5440
5321
  }
5441
5322
  Socket$1.protocol = protocol$1;
5442
- function clone(obj) {
5443
- const o = {};
5444
- for (let i in obj) {
5445
- if (obj.hasOwnProperty(i)) {
5446
- o[i] = obj[i];
5323
+
5324
+ Socket$1.protocol;
5325
+
5326
+ /**
5327
+ * URL parser.
5328
+ *
5329
+ * @param uri - url
5330
+ * @param path - the request path of the connection
5331
+ * @param loc - An object meant to mimic window.location.
5332
+ * Defaults to window.location.
5333
+ * @public
5334
+ */
5335
+ function url(uri, path = "", loc) {
5336
+ let obj = uri;
5337
+ // default to window.location
5338
+ loc = loc || (typeof location !== "undefined" && location);
5339
+ if (null == uri)
5340
+ uri = loc.protocol + "//" + loc.host;
5341
+ // relative path support
5342
+ if (typeof uri === "string") {
5343
+ if ("/" === uri.charAt(0)) {
5344
+ if ("/" === uri.charAt(1)) {
5345
+ uri = loc.protocol + uri;
5346
+ }
5347
+ else {
5348
+ uri = loc.host + uri;
5349
+ }
5350
+ }
5351
+ if (!/^(https?|wss?):\/\//.test(uri)) {
5352
+ if ("undefined" !== typeof loc) {
5353
+ uri = loc.protocol + "//" + uri;
5354
+ }
5355
+ else {
5356
+ uri = "https://" + uri;
5357
+ }
5358
+ }
5359
+ // parse
5360
+ obj = parse$2(uri);
5361
+ }
5362
+ // make sure we treat `localhost:80` and `localhost` equally
5363
+ if (!obj.port) {
5364
+ if (/^(http|ws)$/.test(obj.protocol)) {
5365
+ obj.port = "80";
5366
+ }
5367
+ else if (/^(http|ws)s$/.test(obj.protocol)) {
5368
+ obj.port = "443";
5447
5369
  }
5448
5370
  }
5449
- return o;
5371
+ obj.path = obj.path || "/";
5372
+ const ipv6 = obj.host.indexOf(":") !== -1;
5373
+ const host = ipv6 ? "[" + obj.host + "]" : obj.host;
5374
+ // define unique id
5375
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
5376
+ // define href
5377
+ obj.href =
5378
+ obj.protocol +
5379
+ "://" +
5380
+ host +
5381
+ (loc && loc.port === obj.port ? "" : ":" + obj.port);
5382
+ return obj;
5450
5383
  }
5451
5384
 
5452
- Socket$1.protocol;
5453
-
5454
5385
  const withNativeArrayBuffer = typeof ArrayBuffer === "function";
5455
5386
  const isView = (obj) => {
5456
5387
  return typeof ArrayBuffer.isView === "function"
@@ -5597,6 +5528,14 @@ var PacketType;
5597
5528
  * A socket.io Encoder instance
5598
5529
  */
5599
5530
  class Encoder {
5531
+ /**
5532
+ * Encoder constructor
5533
+ *
5534
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
5535
+ */
5536
+ constructor(replacer) {
5537
+ this.replacer = replacer;
5538
+ }
5600
5539
  /**
5601
5540
  * Encode a packet as a single string if non-binary, or as a
5602
5541
  * buffer sequence, depending on packet type.
@@ -5637,7 +5576,7 @@ class Encoder {
5637
5576
  }
5638
5577
  // json data
5639
5578
  if (null != obj.data) {
5640
- str += JSON.stringify(obj.data);
5579
+ str += JSON.stringify(obj.data, this.replacer);
5641
5580
  }
5642
5581
  return str;
5643
5582
  }
@@ -5660,8 +5599,14 @@ class Encoder {
5660
5599
  * @return {Object} decoder
5661
5600
  */
5662
5601
  class Decoder extends Emitter_1 {
5663
- constructor() {
5602
+ /**
5603
+ * Decoder constructor
5604
+ *
5605
+ * @param {function} reviver - custom reviver to pass down to JSON.stringify
5606
+ */
5607
+ constructor(reviver) {
5664
5608
  super();
5609
+ this.reviver = reviver;
5665
5610
  }
5666
5611
  /**
5667
5612
  * Decodes an encoded packet string into packet JSON.
@@ -5762,7 +5707,7 @@ class Decoder extends Emitter_1 {
5762
5707
  }
5763
5708
  // look up json data
5764
5709
  if (str.charAt(++i)) {
5765
- const payload = tryParse(str.substr(i));
5710
+ const payload = this.tryParse(str.substr(i));
5766
5711
  if (Decoder.isPayloadValid(p.type, payload)) {
5767
5712
  p.data = payload;
5768
5713
  }
@@ -5772,6 +5717,14 @@ class Decoder extends Emitter_1 {
5772
5717
  }
5773
5718
  return p;
5774
5719
  }
5720
+ tryParse(str) {
5721
+ try {
5722
+ return JSON.parse(str, this.reviver);
5723
+ }
5724
+ catch (e) {
5725
+ return false;
5726
+ }
5727
+ }
5775
5728
  static isPayloadValid(type, payload) {
5776
5729
  switch (type) {
5777
5730
  case PacketType.CONNECT:
@@ -5797,14 +5750,6 @@ class Decoder extends Emitter_1 {
5797
5750
  }
5798
5751
  }
5799
5752
  }
5800
- function tryParse(str) {
5801
- try {
5802
- return JSON.parse(str);
5803
- }
5804
- catch (e) {
5805
- return false;
5806
- }
5807
- }
5808
5753
  /**
5809
5754
  * A manager of a binary event's 'buffer sequence'. Should
5810
5755
  * be constructed whenever a packet of type BINARY_EVENT is
@@ -5883,7 +5828,6 @@ class Socket extends Emitter_1 {
5883
5828
  constructor(io, nsp, opts) {
5884
5829
  super();
5885
5830
  this.connected = false;
5886
- this.disconnected = true;
5887
5831
  this.receiveBuffer = [];
5888
5832
  this.sendBuffer = [];
5889
5833
  this.ids = 0;
@@ -5897,6 +5841,12 @@ class Socket extends Emitter_1 {
5897
5841
  if (this.io._autoConnect)
5898
5842
  this.open();
5899
5843
  }
5844
+ /**
5845
+ * Whether the socket is currently disconnected
5846
+ */
5847
+ get disconnected() {
5848
+ return !this.connected;
5849
+ }
5900
5850
  /**
5901
5851
  * Subscribe to open, close and packet events
5902
5852
  *
@@ -5982,6 +5932,7 @@ class Socket extends Emitter_1 {
5982
5932
  const discardPacket = this.flags.volatile && (!isTransportWritable || !this.connected);
5983
5933
  if (discardPacket) ;
5984
5934
  else if (this.connected) {
5935
+ this.notifyOutgoingListeners(packet);
5985
5936
  this.packet(packet);
5986
5937
  }
5987
5938
  else {
@@ -6055,13 +6006,13 @@ class Socket extends Emitter_1 {
6055
6006
  * Called upon engine `close`.
6056
6007
  *
6057
6008
  * @param reason
6009
+ * @param description
6058
6010
  * @private
6059
6011
  */
6060
- onclose(reason) {
6012
+ onclose(reason, description) {
6061
6013
  this.connected = false;
6062
- this.disconnected = true;
6063
6014
  delete this.id;
6064
- this.emitReserved("disconnect", reason);
6015
+ this.emitReserved("disconnect", reason, description);
6065
6016
  }
6066
6017
  /**
6067
6018
  * Called with socket packet.
@@ -6084,14 +6035,10 @@ class Socket extends Emitter_1 {
6084
6035
  }
6085
6036
  break;
6086
6037
  case PacketType.EVENT:
6087
- this.onevent(packet);
6088
- break;
6089
6038
  case PacketType.BINARY_EVENT:
6090
6039
  this.onevent(packet);
6091
6040
  break;
6092
6041
  case PacketType.ACK:
6093
- this.onack(packet);
6094
- break;
6095
6042
  case PacketType.BINARY_ACK:
6096
6043
  this.onack(packet);
6097
6044
  break;
@@ -6175,7 +6122,6 @@ class Socket extends Emitter_1 {
6175
6122
  onconnect(id) {
6176
6123
  this.id = id;
6177
6124
  this.connected = true;
6178
- this.disconnected = false;
6179
6125
  this.emitBuffered();
6180
6126
  this.emitReserved("connect");
6181
6127
  }
@@ -6187,7 +6133,10 @@ class Socket extends Emitter_1 {
6187
6133
  emitBuffered() {
6188
6134
  this.receiveBuffer.forEach((args) => this.emitEvent(args));
6189
6135
  this.receiveBuffer = [];
6190
- this.sendBuffer.forEach((packet) => this.packet(packet));
6136
+ this.sendBuffer.forEach((packet) => {
6137
+ this.notifyOutgoingListeners(packet);
6138
+ this.packet(packet);
6139
+ });
6191
6140
  this.sendBuffer = [];
6192
6141
  }
6193
6142
  /**
@@ -6339,14 +6288,112 @@ class Socket extends Emitter_1 {
6339
6288
  listenersAny() {
6340
6289
  return this._anyListeners || [];
6341
6290
  }
6291
+ /**
6292
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
6293
+ * callback.
6294
+ *
6295
+ * @param listener
6296
+ *
6297
+ * <pre><code>
6298
+ *
6299
+ * socket.onAnyOutgoing((event, ...args) => {
6300
+ * console.log(event);
6301
+ * });
6302
+ *
6303
+ * </pre></code>
6304
+ *
6305
+ * @public
6306
+ */
6307
+ onAnyOutgoing(listener) {
6308
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
6309
+ this._anyOutgoingListeners.push(listener);
6310
+ return this;
6311
+ }
6312
+ /**
6313
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
6314
+ * callback. The listener is added to the beginning of the listeners array.
6315
+ *
6316
+ * @param listener
6317
+ *
6318
+ * <pre><code>
6319
+ *
6320
+ * socket.prependAnyOutgoing((event, ...args) => {
6321
+ * console.log(event);
6322
+ * });
6323
+ *
6324
+ * </pre></code>
6325
+ *
6326
+ * @public
6327
+ */
6328
+ prependAnyOutgoing(listener) {
6329
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
6330
+ this._anyOutgoingListeners.unshift(listener);
6331
+ return this;
6332
+ }
6333
+ /**
6334
+ * Removes the listener that will be fired when any event is emitted.
6335
+ *
6336
+ * @param listener
6337
+ *
6338
+ * <pre><code>
6339
+ *
6340
+ * const handler = (event, ...args) => {
6341
+ * console.log(event);
6342
+ * }
6343
+ *
6344
+ * socket.onAnyOutgoing(handler);
6345
+ *
6346
+ * // then later
6347
+ * socket.offAnyOutgoing(handler);
6348
+ *
6349
+ * </pre></code>
6350
+ *
6351
+ * @public
6352
+ */
6353
+ offAnyOutgoing(listener) {
6354
+ if (!this._anyOutgoingListeners) {
6355
+ return this;
6356
+ }
6357
+ if (listener) {
6358
+ const listeners = this._anyOutgoingListeners;
6359
+ for (let i = 0; i < listeners.length; i++) {
6360
+ if (listener === listeners[i]) {
6361
+ listeners.splice(i, 1);
6362
+ return this;
6363
+ }
6364
+ }
6365
+ }
6366
+ else {
6367
+ this._anyOutgoingListeners = [];
6368
+ }
6369
+ return this;
6370
+ }
6371
+ /**
6372
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
6373
+ * e.g. to remove listeners.
6374
+ *
6375
+ * @public
6376
+ */
6377
+ listenersAnyOutgoing() {
6378
+ return this._anyOutgoingListeners || [];
6379
+ }
6380
+ /**
6381
+ * Notify the listeners for each packet sent
6382
+ *
6383
+ * @param packet
6384
+ *
6385
+ * @private
6386
+ */
6387
+ notifyOutgoingListeners(packet) {
6388
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
6389
+ const listeners = this._anyOutgoingListeners.slice();
6390
+ for (const listener of listeners) {
6391
+ listener.apply(this, packet.data);
6392
+ }
6393
+ }
6394
+ }
6342
6395
  }
6343
6396
 
6344
- /**
6345
- * Expose `Backoff`.
6346
- */
6347
-
6348
- var backo2 = Backoff;
6349
-
6350
6397
  /**
6351
6398
  * Initialize backoff timer with `opts`.
6352
6399
  *
@@ -6358,71 +6405,60 @@ var backo2 = Backoff;
6358
6405
  * @param {Object} opts
6359
6406
  * @api public
6360
6407
  */
6361
-
6362
6408
  function Backoff(opts) {
6363
- opts = opts || {};
6364
- this.ms = opts.min || 100;
6365
- this.max = opts.max || 10000;
6366
- this.factor = opts.factor || 2;
6367
- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
6368
- this.attempts = 0;
6409
+ opts = opts || {};
6410
+ this.ms = opts.min || 100;
6411
+ this.max = opts.max || 10000;
6412
+ this.factor = opts.factor || 2;
6413
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
6414
+ this.attempts = 0;
6369
6415
  }
6370
-
6371
6416
  /**
6372
6417
  * Return the backoff duration.
6373
6418
  *
6374
6419
  * @return {Number}
6375
6420
  * @api public
6376
6421
  */
6377
-
6378
- Backoff.prototype.duration = function(){
6379
- var ms = this.ms * Math.pow(this.factor, this.attempts++);
6380
- if (this.jitter) {
6381
- var rand = Math.random();
6382
- var deviation = Math.floor(rand * this.jitter * ms);
6383
- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
6384
- }
6385
- return Math.min(ms, this.max) | 0;
6422
+ Backoff.prototype.duration = function () {
6423
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
6424
+ if (this.jitter) {
6425
+ var rand = Math.random();
6426
+ var deviation = Math.floor(rand * this.jitter * ms);
6427
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
6428
+ }
6429
+ return Math.min(ms, this.max) | 0;
6386
6430
  };
6387
-
6388
6431
  /**
6389
6432
  * Reset the number of attempts.
6390
6433
  *
6391
6434
  * @api public
6392
6435
  */
6393
-
6394
- Backoff.prototype.reset = function(){
6395
- this.attempts = 0;
6436
+ Backoff.prototype.reset = function () {
6437
+ this.attempts = 0;
6396
6438
  };
6397
-
6398
6439
  /**
6399
6440
  * Set the minimum duration
6400
6441
  *
6401
6442
  * @api public
6402
6443
  */
6403
-
6404
- Backoff.prototype.setMin = function(min){
6405
- this.ms = min;
6444
+ Backoff.prototype.setMin = function (min) {
6445
+ this.ms = min;
6406
6446
  };
6407
-
6408
6447
  /**
6409
6448
  * Set the maximum duration
6410
6449
  *
6411
6450
  * @api public
6412
6451
  */
6413
-
6414
- Backoff.prototype.setMax = function(max){
6415
- this.max = max;
6452
+ Backoff.prototype.setMax = function (max) {
6453
+ this.max = max;
6416
6454
  };
6417
-
6418
6455
  /**
6419
6456
  * Set the jitter
6420
6457
  *
6421
6458
  * @api public
6422
6459
  */
6423
-
6424
- Backoff.prototype.setJitter = function(jitter){
6425
- this.jitter = jitter;
6460
+ Backoff.prototype.setJitter = function (jitter) {
6461
+ this.jitter = jitter;
6426
6462
  };
6427
6463
 
6428
6464
  class Manager extends Emitter_1 {
@@ -6444,7 +6480,7 @@ class Manager extends Emitter_1 {
6444
6480
  this.reconnectionDelay(opts.reconnectionDelay || 1000);
6445
6481
  this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
6446
6482
  this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
6447
- this.backoff = new backo2({
6483
+ this.backoff = new Backoff({
6448
6484
  min: this.reconnectionDelay(),
6449
6485
  max: this.reconnectionDelayMax(),
6450
6486
  jitter: this.randomizationFactor(),
@@ -6705,11 +6741,11 @@ class Manager extends Emitter_1 {
6705
6741
  *
6706
6742
  * @private
6707
6743
  */
6708
- onclose(reason) {
6744
+ onclose(reason, description) {
6709
6745
  this.cleanup();
6710
6746
  this.backoff.reset();
6711
6747
  this._readyState = "closed";
6712
- this.emitReserved("close", reason);
6748
+ this.emitReserved("close", reason, description);
6713
6749
  if (this._reconnection && !this.skipReconnect) {
6714
6750
  this.reconnect();
6715
6751
  }
@@ -7637,6 +7673,35 @@ var ChatMessage = function (props) {
7637
7673
  React$1.createElement("div", { className: "chat-msg-container ".concat(getClassName(props.message)) }, renderByType())));
7638
7674
  };
7639
7675
 
7676
+ /**
7677
+ * value must be like "60m", "2h" etc.
7678
+ */
7679
+ function convertToSeconds(value) {
7680
+ var unit = value === null || value === void 0 ? void 0 : value.slice(-1);
7681
+ var number = parseFloat(value === null || value === void 0 ? void 0 : value.slice(0, -1));
7682
+ switch (unit) {
7683
+ case "d": {
7684
+ return number * 24 * 60 * 60;
7685
+ }
7686
+ case "h": {
7687
+ return number * 60 * 60;
7688
+ }
7689
+ case "m": {
7690
+ return number * 60;
7691
+ }
7692
+ case "s": {
7693
+ return number;
7694
+ }
7695
+ default: {
7696
+ return number;
7697
+ }
7698
+ }
7699
+ }
7700
+
7701
+ function checkSessionExpiration(duration, lastMessageTimestamp, lastTimestamp) {
7702
+ return lastTimestamp - lastMessageTimestamp > convertToSeconds(duration);
7703
+ }
7704
+
7640
7705
  function useExternalScript(url) {
7641
7706
  useEffect(function () {
7642
7707
  if (!url) {
@@ -30816,7 +30881,13 @@ var ChatWidget = function (props) {
30816
30881
  set$1("visible", newVisible);
30817
30882
  }, [staticMode]);
30818
30883
  useEffect(function () {
30819
- // For reopen widget after move on same window
30884
+ var _a;
30885
+ if (checkSessionExpiration(chatState === null || chatState === void 0 ? void 0 : chatState.sessionExpiration, (_a = chatState === null || chatState === void 0 ? void 0 : chatState.chats[chatState.chats.length - 1]) === null || _a === void 0 ? void 0 : _a.timestamp, chatState === null || chatState === void 0 ? void 0 : chatState.lastTimestamp)) {
30886
+ innerDispatch(reset());
30887
+ }
30888
+ }, []);
30889
+ useEffect(function () {
30890
+ // For reopen widget after move on same windowyar
30820
30891
  if (get("opened")) {
30821
30892
  setVisible(true);
30822
30893
  }
@@ -30986,7 +31057,7 @@ function createDefaultState(state) {
30986
31057
  connectionStatus: "offline",
30987
31058
  token: null,
30988
31059
  greetingRequested: false
30989
- }, accountStatus: "offline", departments: {}, visitor: DEFAULT_VISITOR, agents: {}, chats: [], lastTimestamp: 0, lastRatingRequestTimestamp: 0, hasRating: false, isChatting: false, queuePosition: 0, failureMsg: null, visitorId: visitorFingerprint(), chips: [] }, state);
31060
+ }, accountStatus: "offline", departments: {}, visitor: DEFAULT_VISITOR, agents: {}, chats: [], lastTimestamp: 0, lastRatingRequestTimestamp: 0, hasRating: false, isChatting: false, queuePosition: 0, failureMsg: null, visitorId: visitorFingerprint(), chips: [], sessionExpiration: "24h" }, state);
30990
31061
  }
30991
31062
  var DEFAULT_STATE = createDefaultState();
30992
31063
 
@@ -31183,7 +31254,7 @@ function createChatStore(config, dataStorage) {
31183
31254
  if (dataStorage === void 0) { dataStorage = localStorage; }
31184
31255
  var connection = config.connection;
31185
31256
  var storage = new BrowserStateStorage(dataStorage, "xappchat.".concat(connection.serverUrl, ".").concat(connection.accountKey));
31186
- var defaultState = createDefaultState({ accessToken: config.accessToken, userId: config.userId, attributes: config.attributes });
31257
+ var defaultState = createDefaultState({ accessToken: config.accessToken, userId: config.userId, attributes: config.attributes, sessionExpiration: config.sessionExpiration });
31187
31258
  var chatReducer = persistStateReducer(storage, defaultState, storeHandler);
31188
31259
  var middlewares = [
31189
31260
  thunk
@@ -31193,19 +31264,20 @@ function createChatStore(config, dataStorage) {
31193
31264
  }
31194
31265
 
31195
31266
  var ChatWidgetContainer = function (props) {
31196
- var _a, _b, _c, _d;
31267
+ var _a, _b, _c, _d, _e;
31197
31268
  var messageMiddleware = useStandardMiddleware();
31198
31269
  var connection = useServerConfig(props.config);
31199
31270
  var chatStore = useMemo(function () {
31200
- var _a, _b, _c;
31271
+ var _a, _b, _c, _d;
31201
31272
  return createChatStore({
31202
31273
  connection: connection,
31203
31274
  userId: (_a = props.config) === null || _a === void 0 ? void 0 : _a.userId,
31204
31275
  accessToken: (_b = props.config) === null || _b === void 0 ? void 0 : _b.accessToken,
31205
31276
  attributes: (_c = props.config) === null || _c === void 0 ? void 0 : _c.attributes,
31277
+ sessionExpiration: (_d = props.config) === null || _d === void 0 ? void 0 : _d.sessionExpiration
31206
31278
  });
31207
- }, [connection, (_a = props.config) === null || _a === void 0 ? void 0 : _a.userId, (_b = props.config) === null || _b === void 0 ? void 0 : _b.accessToken, (_c = props.config) === null || _c === void 0 ? void 0 : _c.attributes]);
31208
- if ((_d = props.config) === null || _d === void 0 ? void 0 : _d.disabled) {
31279
+ }, [connection, (_a = props.config) === null || _a === void 0 ? void 0 : _a.userId, (_b = props.config) === null || _b === void 0 ? void 0 : _b.accessToken, (_c = props.config) === null || _c === void 0 ? void 0 : _c.attributes, (_d = props.config) === null || _d === void 0 ? void 0 : _d.sessionExpiration]);
31280
+ if ((_e = props.config) === null || _e === void 0 ? void 0 : _e.disabled) {
31209
31281
  return React$1.createElement(React$1.Fragment, null);
31210
31282
  }
31211
31283
  var widgetProps = __assign(__assign({}, props), { messageMiddleware: messageMiddleware });