diff --git a/.pubnub.yml b/.pubnub.yml index 6f6b2b734..dad178d21 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,10 @@ --- changelog: + - date: 2024-11-18 + version: v8.3.1 + changes: + - type: bug + text: "Fix issue because of which presence events not delivered to the `Subscription` and `SubscriptionSet` objects (only global listeners)." - date: 2024-11-14 version: v8.3.0 changes: @@ -1067,7 +1072,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '8.3.0' +version: '8.3.1' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -1083,7 +1088,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v8.3.0.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v8.3.1.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1754,7 +1759,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v8.3.0/pubnub.8.3.0.js + location: https://github.com/pubnub/javascript/releases/download/v8.3.1/pubnub.8.3.1.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index b2656bc3e..24a5ef0f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## v8.3.1 +November 18 2024 + +#### Fixed +- Fix issue because of which presence events not delivered to the `Subscription` and `SubscriptionSet` objects (only global listeners). + ## v8.3.0 November 14 2024 diff --git a/README.md b/README.md index 031c6e8d0..ec506a28c 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ Watch [Getting Started with PubNub JS SDK](https://app.dashcam.io/replay/64ee0d2 npm install pubnub ``` * or download one of our builds from our CDN: - * https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.0.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.0.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.1.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.1.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index c4b461527..94fd00418 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -3948,7 +3948,7 @@ return base.PubNubFile; }, get version() { - return '8.3.0'; + return '8.3.1'; }, getVersion() { return this.version; diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index c12894583..fcef699a5 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var o={encode:function(e){var t,n=new ArrayBuffer(256),o=new DataView(n),a=0;function c(e){for(var s=n.byteLength,r=a+e;s>2,u=0;u>6),r.push(128|63&o)):o<55296?(r.push(224|o>>12),r.push(128|o>>6&63),r.push(128|63&o)):(o=(1023&o)<<10,o|=1023&t.charCodeAt(++n),o+=65536,r.push(240|o>>18),r.push(128|o>>12&63),r.push(128|o>>6&63),r.push(128|63&o))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function f(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,m=l(),b=m>>5,v=31&m;if(7===b)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,o=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==o)return o*n;return t.setUint32(0,r<<16|i<<13|o<<13),t.getFloat32(0)}();case 26:return c(o.getFloat32(a),4);case 27:return c(o.getFloat64(a),8)}if((d=g(v))<0&&(b<2||6=0;)S+=d,w.push(u(d));var k=new Uint8Array(S),E=0;for(r=0;r=0;)f(O,d);else f(O,d);return String.fromCharCode.apply(null,O);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),r=0;r{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}a.supportsBlob="undefined"!=typeof Blob,a.supportsFile="undefined"!=typeof File,a.supportsBuffer=!1,a.supportsStream=!1,a.supportsString=!0,a.supportsArrayBuffer=!0,a.supportsEncryptFile=!0,a.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function o(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=a,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,o=r-i;let a,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[a]+s[c]+s[u]+s[l];return 1==i?(h=n[o],a=(252&h)>>2,c=(3&h)<<4,t+=s[a]+s[c]+"=="):2==i&&(h=n[o]<<8|n[o+1],a=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[a]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){return s=Object.assign({message:e},{}),null!==(n=s.statusCode)&&void 0!==n||(s.statusCode=0),Object.assign(Object.assign({},s),{statusCode:s.statusCode,category:h.PNValidationErrorCategory,error:!0});var s,n}var g,y,f,m,b,v=v||function(e){var t={},s=t.lib={},n=function(){},r=s.Base={extend:function(e){n.prototype=this;var t=new n;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},i=s.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||a).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new i.init(s,t/2)}},c=o.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new i.init(s,t)}},u=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=s.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,o=this.blockSize,a=r/(4*o);if(t=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=a(e.pow(c,.5))),o[u]=a(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],a=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],y=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((y<<15|y>>>17)^(y<<13|y>>>19)^y>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+o[d]+p[d],y=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=a+g|0,a=i,i=r,r=n,n=g+y|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+a|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),y=(g=v).enc.Utf8,g.algo.HMAC=g.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=y.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),o=r.words,a=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,o=0;4>o&&r+.75*o>>6*(3-o)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(o|a)<<24-r%4*8,r++}return m.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,o){return((e=e+(t&s|~t&n)+r+o)<>>32-i)+t}function s(e,t,s,n,r,i,o){return((e=e+(t&n|s&~n)+r+o)<>>32-i)+t}function n(e,t,s,n,r,i,o){return((e=e+(t^s^n)+r+o)<>>32-i)+t}function r(e,t,s,n,r,i,o){return((e=e+(s^(t|~n))+r+o)<>>32-i)+t}for(var i=v,o=(c=i.lib).WordArray,a=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var o=0;16>o;o++){var a=e[c=i+o];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}o=this._hash.words;var c=e[i+0],l=(a=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],y=e[i+7],f=e[i+8],m=e[i+9],b=e[i+10],v=e[i+11],w=e[i+12],S=e[i+13],k=e[i+14],E=e[i+15],O=t(O=o[0],P=o[1],N=o[2],C=o[3],c,7,u[0]),C=t(C,O,P,N,a,12,u[1]),N=t(N,C,O,P,l,17,u[2]),P=t(P,N,C,O,h,22,u[3]);O=t(O,P,N,C,d,7,u[4]),C=t(C,O,P,N,p,12,u[5]),N=t(N,C,O,P,g,17,u[6]),P=t(P,N,C,O,y,22,u[7]),O=t(O,P,N,C,f,7,u[8]),C=t(C,O,P,N,m,12,u[9]),N=t(N,C,O,P,b,17,u[10]),P=t(P,N,C,O,v,22,u[11]),O=t(O,P,N,C,w,7,u[12]),C=t(C,O,P,N,S,12,u[13]),N=t(N,C,O,P,k,17,u[14]),O=s(O,P=t(P,N,C,O,E,22,u[15]),N,C,a,5,u[16]),C=s(C,O,P,N,g,9,u[17]),N=s(N,C,O,P,v,14,u[18]),P=s(P,N,C,O,c,20,u[19]),O=s(O,P,N,C,p,5,u[20]),C=s(C,O,P,N,b,9,u[21]),N=s(N,C,O,P,E,14,u[22]),P=s(P,N,C,O,d,20,u[23]),O=s(O,P,N,C,m,5,u[24]),C=s(C,O,P,N,k,9,u[25]),N=s(N,C,O,P,h,14,u[26]),P=s(P,N,C,O,f,20,u[27]),O=s(O,P,N,C,S,5,u[28]),C=s(C,O,P,N,l,9,u[29]),N=s(N,C,O,P,y,14,u[30]),O=n(O,P=s(P,N,C,O,w,20,u[31]),N,C,p,4,u[32]),C=n(C,O,P,N,f,11,u[33]),N=n(N,C,O,P,v,16,u[34]),P=n(P,N,C,O,k,23,u[35]),O=n(O,P,N,C,a,4,u[36]),C=n(C,O,P,N,d,11,u[37]),N=n(N,C,O,P,y,16,u[38]),P=n(P,N,C,O,b,23,u[39]),O=n(O,P,N,C,S,4,u[40]),C=n(C,O,P,N,c,11,u[41]),N=n(N,C,O,P,h,16,u[42]),P=n(P,N,C,O,g,23,u[43]),O=n(O,P,N,C,m,4,u[44]),C=n(C,O,P,N,w,11,u[45]),N=n(N,C,O,P,E,16,u[46]),O=r(O,P=n(P,N,C,O,l,23,u[47]),N,C,c,6,u[48]),C=r(C,O,P,N,y,10,u[49]),N=r(N,C,O,P,k,15,u[50]),P=r(P,N,C,O,p,21,u[51]),O=r(O,P,N,C,w,6,u[52]),C=r(C,O,P,N,h,10,u[53]),N=r(N,C,O,P,b,15,u[54]),P=r(P,N,C,O,a,21,u[55]),O=r(O,P,N,C,f,6,u[56]),C=r(C,O,P,N,E,10,u[57]),N=r(N,C,O,P,g,15,u[58]),P=r(P,N,C,O,S,21,u[59]),O=r(O,P,N,C,d,6,u[60]),C=r(C,O,P,N,v,10,u[61]),N=r(N,C,O,P,l,15,u[62]),P=r(P,N,C,O,m,21,u[63]);o[0]=o[0]+O|0,o[1]=o[1]+P|0,o[2]=o[2]+N|0,o[3]=o[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=a._createHelper(c),i.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e,t=v,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(a=this.cfg).hasher.create(),r=n.create(),i=r.words,o=a.keySize,a=a.iterations;i.length>>2]}},e.BlockCipher=o.extend({cfg:o.cfg.extend({mode:a,padding:u}),reset:function(){o.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(a=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?s.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=s.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:n})}},e.SerializableCipher=t.extend({cfg:t.extend({format:a}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,l.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,n,r){return r||(r=s.random(8)),e=i.create({keySize:t+n}).compute(e,r),n=s.create(e.words.slice(t),4*n),e.sigBytes=4*t,l.create({key:e,iv:n,salt:r})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=h.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,h.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=v,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],o=[],a=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var y=0,f=0;for(g=0;256>g;g++){var m=(m=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&m^99;n[y]=m,r[m]=y;var b=p[y],w=p[b],S=p[w],k=257*p[m]^16843008*m;i[y]=k<<24|k>>>8,o[y]=k<<16|k>>>16,a[y]=k<<8|k>>>24,c[y]=k,k=16843009*S^65537*w^257*b^16843008*y,u[m]=k<<24|k>>>8,l[m]=k<<16|k>>>16,h[m]=k<<8|k>>>24,d[m]=k,y?(y=b^p[p[p[S^b]]],f^=p[p[f]]):y=f=1}var E=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o]):(o=n[(o=o<<8|o>>>24)>>>24]<<24|n[o>>>16&255]<<16|n[o>>>8&255]<<8|n[255&o],o^=E[i/t|0]<<24),r[i]=r[i-t]^o}for(e=this._invKeySchedule=[],t=0;tt||4>=i?o:u[n[o>>>24]]^l[n[o>>>16&255]]^h[n[o>>>8&255]]^d[n[255&o]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,o,a,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,o,a){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^o[255&d]^s[p++],f=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^o[255&u]^s[p++],m=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^o[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^o[255&h]^s[p++],u=y,l=f,h=m}y=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&d])^s[p++],f=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[d>>>8&255]<<8|a[255&u])^s[p++],m=(a[h>>>24]<<24|a[d>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^s[p++],d=(a[d>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^s[p++],e[t]=y,e[t+1]=f,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),v.mode.ECB=((b=v.lib.BlockCipherMode.extend()).Encryptor=b.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),b.Decryptor=b.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),b);var w=t(v);class S{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=w,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:S.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return S.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(S.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=S.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;se.toString(16).padStart(2,"0"))).join(""),n=O.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}}O.IV_LENGTH=16,O.encoder=new TextEncoder,O.decoder=new TextDecoder;class C{constructor(e){this.config=e,this.cryptor=new E(Object.assign({},e)),this.fileCryptor=new O}encrypt(e){const t="string"==typeof e?e:C.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}}C.encoder=new TextEncoder,C.decoder=new TextDecoder;class N extends o{static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new N({default:new C(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new S({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new N({default:new S({cipherKey:e.cipherKey}),cryptors:[new C(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===N.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(N.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===P.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=P.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=P.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===P.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof M)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=P.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof a)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}N.LEGACY_IDENTIFIER="";class P{static from(e,t){if(e!==P.LEGACY_IDENTIFIER)return new M(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==P.SENTINEL))return N.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>P.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+P.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let o=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return o=t[i],i+=1,255===o&&t.byteLength>=i+2&&(o=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new M(this.decoder.decode(n),o)}}P.SENTINEL="PNED",P.LEGACY_IDENTIFIER="",P.IDENTIFIER_LENGTH=4,P.VERSION=1,P.MAX_VERSION=1,P.decoder=new TextDecoder;class M{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return P.VERSION}get length(){return P.SENTINEL.length+1+P.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(P.SENTINEL)),e+=P.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=P.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}M.IDENTIFIER_LENGTH=4,M.SENTINEL="PNED";class _ extends Error{static create(e,t){return e instanceof Error?_.createFromError(e):_.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new _(s,t,0);if(e instanceof _)return e;if(e instanceof Error&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new _(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i&&(n=h.PNAccessDeniedCategory,r="Access denied"),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"!=typeof e||Array.isArray(e)||("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new _(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}}class A{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,logVerbosity:this.configuration.logVerbosity,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.scheduleEventPost(s)})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){"undefined"!=typeof SharedWorker&&(this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`),this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,logVerbosity:this.configuration.logVerbosity,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e))}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)console.log(`[SharedWorker] ${t.message}`);else if("shared-worker-console-dir"===t.type)t.message&&console.log(`[SharedWorker] ${t.message}`),console.dir(t.data);else if("shared-worker-ping"===t.type){const{logVerbosity:e,subscriptionKey:t,clientIdentifier:s}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:t,clientIdentifier:s,logVerbosity:e})}else if("request-progress-start"===t.type||"request-progress-end"===t.type)this.logRequestProgress(t);else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(_.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new _(n,e,0,new Error(n)))}}}logRequestProgress(e){var t,s;"request-progress-start"===e.type?(console.log("<<<<<"),console.log(`[${e.timestamp}] ${e.url}\n${JSON.stringify(null!==(t=e.query)&&void 0!==t?t:{})}`),console.log("-----")):(console.log(">>>>>>"),console.log(`[${e.timestamp} / ${e.duration}] ${e.url}\n${JSON.stringify(null!==(s=e.query)&&void 0!==s?s:{})}\n${e.response}`),console.log("-----"))}}const j=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),I=(e,t)=>{const s=e.map((e=>j(e)));return s.length?s.join(","):null!=t?t:""},R=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},U=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s)));class T{constructor(e=!1,t){this.keepAlive=e,this.logVerbosity=t}makeSendable(e){let t,s;return e.cancellable&&(s=new AbortController,t={abortController:s,abort:()=>null==s?void 0:s.abort()}),[this.requestFromTransportRequest(e).then((t=>{const n=(new Date).getTime();this.logRequestProcessProgress(t);const r=new Promise(((t,s)=>{const n=setTimeout((()=>{clearTimeout(n),s(new Error("Request timeout"))}),1e3*e.timeout)}));return Promise.race([fetch(t,{signal:null==s?void 0:s.signal,credentials:"omit",cache:"no-cache"}),r]).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:r,headers:i}=e[0],o={};i.forEach(((e,t)=>o[t]=e.toLowerCase()));const a={status:r,url:t.url,headers:o,body:s};if(r>=400)throw _.create(a);return this.logRequestProcessProgress(t,(new Date).getTime()-n,s),a})).catch((e=>{throw _.create(e)}))})),t]}request(e){return e}requestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){}}t=n}else e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer)&&(t=e.body);var n;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${n=e.queryParameters,Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${j(t)}`)).join("&"):`${e}=${j(t)}`})).join("&")}`),new Request(`${e.origin}${s}`,{method:e.method,headers:e.headers,redirect:"follow",body:t})}))}logRequestProcessProgress(e,t,s){if(!this.logVerbosity)return;const{protocol:n,host:r,pathname:i,search:o}=new URL(e.url),a=(new Date).toISOString();if(t){const e=s?T.decoder.decode(s):void 0;console.log(">>>>>>"),console.log(`[${a} / ${t}]`,`\n${n}//${r}${i}`,`\n${o}`,`\n${e}`),console.log("-----")}else console.log("<<<<<"),console.log(`[${a}]`,`\n${n}//${r}${i}`,`\n${o}`),console.log("-----")}}function F(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const a=e[r];if(i&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(o=String.fromCharCode(s(r)?r:parseInt(r,10)));n[o]=t(a)?F(a):a})),n}T.decoder=new TextDecoder;const x=e=>{var t,s,n;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,o,a,c,u,l,h,p,g,y;const f=Object.assign({},e);if(null!==(t=f.logVerbosity)&&void 0!==t||(f.logVerbosity=!1),null!==(s=f.ssl)&&void 0!==s||(f.ssl=!0),null!==(n=f.transactionalRequestTimeout)&&void 0!==n||(f.transactionalRequestTimeout=15),null!==(r=f.subscribeRequestTimeout)&&void 0!==r||(f.subscribeRequestTimeout=310),null!==(i=f.restore)&&void 0!==i||(f.restore=!1),null!==(o=f.useInstanceId)&&void 0!==o||(f.useInstanceId=!1),null!==(a=f.suppressLeaveEvents)&&void 0!==a||(f.suppressLeaveEvents=!1),null!==(c=f.requestMessageCountThreshold)&&void 0!==c||(f.requestMessageCountThreshold=100),null!==(u=f.autoNetworkDetection)&&void 0!==u||(f.autoNetworkDetection=!1),null!==(l=f.enableEventEngine)&&void 0!==l||(f.enableEventEngine=!1),null!==(h=f.maintainPresenceState)&&void 0!==h||(f.maintainPresenceState=!0),null!==(p=f.keepAlive)&&void 0!==p||(f.keepAlive=!1),f.userId&&f.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(g=f.userId)&&void 0!==g||(f.userId=f.uuid),!f.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=f.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");f.origin||(f.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const m={subscribeKey:f.subscribeKey,publishKey:f.publishKey,secretKey:f.secretKey};void 0!==f.presenceTimeout&&f.presenceTimeout<20&&(f.presenceTimeout=20,console.log("WARNING: Presence timeout is less than the minimum. Using minimum value: ",20)),void 0!==f.presenceTimeout?f.heartbeatInterval=f.presenceTimeout/2-1:f.presenceTimeout=300;let b=!1,v=!0,w=5,S=!1,k=100,E=!0;return void 0!==f.dedupeOnSubscribe&&"boolean"==typeof f.dedupeOnSubscribe&&(S=f.dedupeOnSubscribe),void 0!==f.maximumCacheSize&&"number"==typeof f.maximumCacheSize&&(k=f.maximumCacheSize),void 0!==f.useRequestId&&"boolean"==typeof f.useRequestId&&(E=f.useRequestId),void 0!==f.announceSuccessfulHeartbeats&&"boolean"==typeof f.announceSuccessfulHeartbeats&&(b=f.announceSuccessfulHeartbeats),void 0!==f.announceFailedHeartbeats&&"boolean"==typeof f.announceFailedHeartbeats&&(v=f.announceFailedHeartbeats),void 0!==f.fileUploadPublishRetryLimit&&"number"==typeof f.fileUploadPublishRetryLimit&&(w=f.fileUploadPublishRetryLimit),Object.assign(Object.assign({},f),{keySet:m,dedupeOnSubscribe:S,maximumCacheSize:k,useRequestId:E,announceSuccessfulHeartbeats:b,announceFailedHeartbeats:v,fileUploadPublishRetryLimit:w})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerLogVerbosity:null!==(s=e.subscriptionWorkerLogVerbosity)&&void 0!==s&&s,keepAlive:null===(n=e.keepAlive)||void 0===n||n})};var D={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(D,D.exports);var q=t(D.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const K=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=$(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.3.0"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},$=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class L{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var B,H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(B||(B={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?B.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===B.POST||t===B.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${j(e)}`)).join("&"):`${t}=${j(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=G.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:B.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===B.POST||r.method===B.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(H||(H={}));var ne=H;var re;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(re||(re={}));class ie extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return ne.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?re.Presence:re.Message),t!=re.Signal&&"string"==typeof e.d?t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}:t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:t===re.Presence?{type:re.Presence,data:this.presenceEventFromEnvelope(e)}:t==re.Signal?{type:re.Signal,data:this.signalFromEnvelope(e)}:t===re.AppContext?{type:re.AppContext,data:this.appContextFromEnvelope(e)}:t===re.MessageAction?{type:re.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(o.customMessageType=e.cmt),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(oe.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class oe extends ie{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ae{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===re.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===re.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===re.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===re.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ce{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class ue{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class le extends ce{describe(e){return new ue(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class he{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function de(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function pe(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class ye extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class fe extends ce{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new ye}abort(){this._aborted=!0,this.notify(new ye)}}class me{constructor(e,t){this.payload=e,this.dependencies=t}}class be extends me{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new fe}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const ve=e=>(t,s)=>new be(t,s,e),we=de("RECONNECT",(()=>({}))),Se=de("DISCONNECT",(()=>({}))),ke=de("JOINED",((e,t)=>({channels:e,groups:t}))),Ee=de("LEFT",((e,t)=>({channels:e,groups:t}))),Oe=de("LEFT_ALL",(()=>({}))),Ce=de("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Ne=de("HEARTBEAT_FAILURE",(e=>e)),Pe=de("HEARTBEAT_GIVEUP",(()=>({}))),Me=de("TIMES_UP",(()=>({}))),_e=pe("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=pe("LEAVE",((e,t)=>({channels:e,groups:t}))),je=pe("EMIT_STATUS",(e=>e)),Ie=ge("WAIT",(()=>({}))),Re=ge("DELAYED_HEARTBEAT",(e=>e));class Ue extends he{constructor(e,t){super(t),this.on(_e.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(Ae.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Ie.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(Me())}))))),this.on(Re.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Pe());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(je.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:ne.PNHeartbeatOperation,error:!1}))})))))}}const Te=new ue("HEARTBEAT_STOPPED");Te.on(ke.type,((e,t)=>Te.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Te.on(Ee.type,((e,t)=>Te.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Te.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Te.on(Oe.type,((e,t)=>Ge.with(void 0)));const Fe=new ue("HEARTBEAT_COOLDOWN");Fe.onEnter((()=>Ie())),Fe.onExit((()=>Ie.cancel)),Fe.on(Me.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),Fe.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),Fe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const xe=new ue("HEARTBEAT_FAILED");xe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),xe.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Se.type,((e,t)=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new ue("HEARBEAT_RECONNECTING");De.onEnter((e=>Re(e))),De.onExit((()=>Re.cancel)),De.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>{Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),De.on(Ce.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups}))),De.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),De.on(Pe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),De.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new ue("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ce.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups}))),qe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),qe.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new ue("HEARTBEAT_INACTIVE");Ge.on(ke.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class Ke{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new le,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ee(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Oe())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class $e{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Le=ge("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Be=ge("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),He=pe("EMIT_MESSAGES",(e=>e)),ze=pe("EMIT_STATUS",(e=>e)),Ve=ge("RECEIVE_RECONNECT",(e=>e)),We=ge("HANDSHAKE_RECONNECT",(e=>e)),Je=de("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Qe=de("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Ye=de("HANDSHAKE_SUCCESS",(e=>e)),Xe=de("HANDSHAKE_FAILURE",(e=>e)),Ze=de("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),et=de("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),tt=de("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),st=de("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),nt=de("RECEIVE_FAILURE",(e=>e)),rt=de("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=de("RECEIVE_RECONNECT_FAILURE",(e=>e)),ot=de("RECEIVING_RECONNECT_GIVEUP",(e=>e)),at=de("DISCONNECT",(()=>({}))),ct=de("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ut=de("UNSUBSCRIBE_ALL",(()=>({})));class lt extends he{constructor(e,t){super(t),this.on(Le.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ye(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Xe(t))}}}))))),this.on(Be.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(st(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(nt(t))}}}))))),this.on(He.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(ze.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(Ve.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ot(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(rt(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(it(t))}}}))))),this.on(We.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(tt(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(Ze(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}})))))}}const ht=new ue("HANDSHAKE_FAILED");ht.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ht.on(ct.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),ht.on(Qe.type,((e,t)=>{var s,n;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),ht.on(ut.type,(e=>vt.with()));const dt=new ue("HANDSHAKE_STOPPED");dt.on(Je.type,((e,t)=>dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ct.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),dt.on(Qe.type,((e,t)=>{var s;return dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),dt.on(ut.type,(e=>vt.with()));const pt=new ue("RECEIVE_FAILED");pt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),pt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),pt.on(ut.type,(e=>vt.with(void 0)));const gt=new ue("RECEIVE_STOPPED");gt.on(Je.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(ut.type,(()=>vt.with(void 0)));const yt=new ue("RECEIVE_RECONNECTING");yt.onEnter((e=>Ve(e))),yt.onExit((()=>Ve.cancel)),yt.on(rt.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),yt.on(it.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),yt.on(ot.type,((e,t)=>{var s;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),yt.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),yt.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(Je.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const ft=new ue("RECEIVING");ft.onEnter((e=>Be(e.channels,e.groups,e.cursor))),ft.onExit((()=>Be.cancel)),ft.on(st.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),ft.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),ft.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(nt.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),ft.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),ft.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const mt=new ue("HANDSHAKE_RECONNECTING");mt.onEnter((e=>We(e))),mt.onExit((()=>We.cancel)),mt.on(Ze.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return ft.with({channels:e.channels,groups:e.groups,cursor:r},[ze({category:h.PNConnectedCategory})])})),mt.on(et.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(tt.type,((e,t)=>{var s;return ht.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),mt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),mt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(Qe.type,((e,t)=>{var s,n;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),mt.on(ut.type,(e=>vt.with(void 0)));const bt=new ue("HANDSHAKING");bt.onEnter((e=>Le(e.channels,e.groups))),bt.onExit((()=>Le.cancel)),bt.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[ze({category:h.PNConnectedCategory})])})),bt.on(Xe.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),bt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>{var s;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),bt.on(ut.type,(e=>vt.with()));const vt=new ue("UNSUBSCRIBED");vt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups}))),vt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class wt{get _engine(){return this.engine}constructor(e){this.engine=new le,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new lt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(vt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Je(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=R(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=R(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=U(this.channels,e),i=U(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Je(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Je(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ct(e,t))}disconnect(){this.engine.transition(at()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class St extends se{constructor(e){var t,s;super({method:e.sendByPost?B.POST:B.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return ne.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${j(t)}/0${this.parameters.sendByPost?"":`/${j(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==n&&(i.store=n?"1":"0"),void 0!==r&&(i.ttl=r),void 0===s||s||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${j(s)}/0/${j(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Et extends ie{operation(){return ne.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ot extends ie{operation(){return ne.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Ct extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return ne.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Nt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${j(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class Mt extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ne.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${j(t)}`}}class At extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ne.PNGlobalHereNowOperation:ne.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw _.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${I(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class jt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${j(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class It extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${I(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return ne.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${j(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class Tt extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ne.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw _.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const s=this.processPayload(e,t),n=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:r,includeMeta:i,includeUUID:o,stringifiedTimeToken:a}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),a?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),o?{include_uuid:"true"}:{}),null!=n?{include_custom_message_type:n?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Tt.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Ft extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class xt extends se{constructor(e){super({method:B.POST}),this.parameters=e}operation(){return ne.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}/message/${s}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Dt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return ne.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${j(t)}/0/${j(this.prepareMessagePayload(o))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&"object"==typeof n?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends se{constructor(e){super({method:B.LOCAL}),this.parameters=e}operation(){return ne.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${j(e)}/files/${t}/${s}`}}class Kt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${j(s)}/files/${t}/${n}`}}class $t extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return ne.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Lt extends se{constructor(e){super({method:B.POST}),this.parameters=e}operation(){return ne.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Bt extends se{constructor(e){super({method:B.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ne.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Bt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class Ht{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ne.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(ne.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Lt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Bt({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class zt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames,channelGroups:this.groupNames})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Vt extends zt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class Wt extends zt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Vt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Jt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Wt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Yt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Xt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Wt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class es extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class ts extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}}class ss extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}/remove`}}class ns extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class rs{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ts(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new ns({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new Zt(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new ss(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class is extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class os extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ne.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class as extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ne.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class cs extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ne.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class us extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ne.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ls{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new us(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ne.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ds extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}}class ps extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class gs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class ys extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return ne.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class fs extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class ms extends se{constructor(e){var t,s,n;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class bs extends se{constructor(e){super({method:B.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class Ss extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class ks extends se{constructor(e){var t,s,n;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Es{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ys(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ss(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new bs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new hs(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new fs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new vs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Os extends se{constructor(){super()}operation(){return ne.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class Cs extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/files/${s}/${n}`}}class Ns{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Es(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new rs(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ae(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Ke({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new wt({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new Xt(e,this.eventEmitter,this)}channelGroup(e){return new Qt(e,this.eventEmitter,this)}channelMetadata(e){return new Jt(e,this.eventEmitter,this)}userMetadata(e){return new Yt(e,this.eventEmitter,this)}subscriptionSet(e){return new Vt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===ne.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Ns.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof _?s:_.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const s=new St(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const s=new oe(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new _t({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new Ct(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Pt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Nt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const s=new Pt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Ht(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:ne.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getFileUrl(e){var t;{const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${j(t)}`)).join("&"):`${e}=${j(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Cs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Os;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Ns.decoder=new TextDecoder,Ns.OPERATIONS=ne,Ns.CATEGORIES=h,Ns.ExponentialRetryPolicy=$e.ExponentialRetryPolicy,Ns.LinearRetryPolicy=$e.LinearRetryPolicy;class Ps{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Ms extends Ns{constructor(e){var t;const s=x(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web"});r.PubNubFile=a;const i=K(r,(e=>{if(e.cipherKey)return new N({default:new C(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})}));let o,u,l;o=new L(new Ps((e=>F(n.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new O;let h=new T(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(h=new A({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:h}),cryptography:l,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Ms.CryptoModule=N,Ms})); +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(D,D.exports);var q=t(D.exports),G={createUUID:()=>q.uuid?q.uuid():q()};const K=(e,t)=>{var s,n,r;null===(s=e.retryConfiguration)||void 0===s||s.validate(),null!==(n=e.useRandomIVs)&&void 0!==n||(e.useRandomIVs=true),e.origin=$(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const i=e.cryptoModule;i&&delete e.cryptoModule;const o=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_instanceId:`pn-${G.createUUID()}`,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(this.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"8.3.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?o.setCipherKey(e.cipherKey):i&&(o._cryptoModule=i),o},$=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`};class L{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),o=Object.keys(t.pat.grp),a={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(a.resources={},c){const s=a.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=a.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=a.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=o.length>0;if(h||d||p){if(a.patterns={},h){const e=a.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=a.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=a.patterns.groups={};o.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(a.meta=t.meta),a}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var B,H;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(B||(B={}));class z{constructor(e,t,s){this.publishKey=e,this.secretKey=t,this.hasher=s}signature(e){const t=e.path.startsWith("/publish")?B.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===B.POST||t===B.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=z.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${j(e)}`)).join("&"):`${t}=${j(s)}`})).join("&")}}z.textDecoder=new TextDecoder("utf-8");class V{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new z(t.publishKey,t.secretKey,s))}makeSendable(e){return this.configuration.transport.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.instanceId),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class W{constructor(){this.listeners=[]}addListener(e){this.listeners.includes(e)||this.listeners.push(e)}removeListener(e){this.listeners=this.listeners.filter((t=>t!==e))}removeAllListeners(){this.listeners=[]}announceStatus(e){this.listeners.forEach((t=>{t.status&&t.status(e)}))}announcePresence(e){this.listeners.forEach((t=>{t.presence&&t.presence(e)}))}announceMessage(e){this.listeners.forEach((t=>{t.message&&t.message(e)}))}announceSignal(e){this.listeners.forEach((t=>{t.signal&&t.signal(e)}))}announceMessageAction(e){this.listeners.forEach((t=>{t.messageAction&&t.messageAction(e)}))}announceFile(e){this.listeners.forEach((t=>{t.file&&t.file(e)}))}announceObjects(e){this.listeners.forEach((t=>{t.objects&&t.objects(e)}))}announceNetworkUp(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkUpCategory})}))}announceNetworkDown(){this.listeners.forEach((e=>{e.status&&e.status({category:h.PNNetworkDownCategory})}))}announceUser(e){this.listeners.forEach((t=>{t.user&&t.user(e)}))}announceSpace(e){this.listeners.forEach((t=>{t.space&&t.space(e)}))}announceMembership(e){this.listeners.forEach((t=>{t.membership&&t.membership(e)}))}}class J{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Q{constructor({maximumCacheSize:e}){this.maximumCacheSize=e,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t){let{channels:s,channelGroups:n}=e;const i=new Set,o=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],o.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],o.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===o.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(o),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let o;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?o=e.errorData.message:"message"in e&&"string"==typeof e.message&&(o=e.message)),this.listenerManager.announceStatus(Object.assign(Object.assign({},i),{error:null!=o&&o,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken=0,this.currentTimetoken=0,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect())}unsubscribeAll(e){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(){this.stopSubscribeLoop();const e=[...Object.keys(this.channelGroups)],t=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((t=>e.push(`${t}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>t.push(`${e}-pnpres`))),0===t.length&&0===e.length||this.subscribeCall({channels:t,channelGroups:e,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken,region:null!==this.region?this.region:void 0,filterExpression:this.configuration.filterExpression},((e,t)=>{this.processSubscribeResponse(e,t)}))}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.listenerManager.announceNetworkDown()),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.listenerManager.announceNetworkUp()),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.listenerManager.announceStatus(t)})),this.reconnectionManager.startPolling(),this.listenerManager.announceStatus(e)):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.listenerManager.announceStatus(e)):this.listenerManager.announceStatus(e))}if(this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.listenerManager.announceStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.listenerManager.announceStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{s.forEach((e=>{if(r&&"message"in e.data&&"timetoken"in e.data){if(this.dedupingManager.isDuplicate(e.data))return;this.dedupingManager.addEntry(e.data)}this.eventEmitter.emitEvent(e)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.listenerManager.announceStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.listenerManager.announceStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.listenerManager.announceNetworkDown(),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.listenerManager.announceStatus(e)}))}}class X{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class Z extends X{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class ee extends X{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class te{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new Z(this._payload.apns,e,t),this.fcm=new ee(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class se{constructor(e){this.params=e,this.requestIdentifier=G.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(){this&&this.cancellationController&&this.cancellationController.abort()}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented by subclass.")}))}request(){var e,t,s,n;const r={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:B.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,timeout:1e4,identifier:this.requestIdentifier},i=this.headers;if(i&&(r.headers=i),r.method===B.POST||r.method===B.PATCH){const[e,t]=[this.body,this.formData];t&&(r.formData=t),e&&(r.body=e)}return r}get headers(){}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=e.headers["content-type"];if(!t||-1===t.indexOf("javascript")&&-1===t.indexOf("json"))return;const s=se.decoder.decode(e.body);try{return JSON.parse(s)}catch(e){return void console.error("Error parsing JSON response:",e)}}}se.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(H||(H={}));var ne=H;var re;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(re||(re={}));class ie extends se{constructor(e){var t,s,n,r,i,o;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(o=this.parameters).channels)&&void 0!==n||(o.channels=[])}operation(){return ne.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t;try{const s=se.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?re.Presence:re.Message),t!=re.Signal&&"string"==typeof e.d?t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}:t==re.Message?{type:re.Message,data:this.messageFromEnvelope(e)}:t===re.Presence?{type:re.Presence,data:this.presenceEventFromEnvelope(e)}:t==re.Signal?{type:re.Signal,data:this.signalFromEnvelope(e)}:t===re.AppContext?{type:re.AppContext,data:this.appContextFromEnvelope(e)}:t===re.MessageAction?{type:re.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:re.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:s}}))}get headers(){return{accept:"text/javascript"}}presenceEventFromEnvelope(e){const{d:t}=e,[s,n]=this.subscriptionChannelFromEnvelope(e),r=s.replace("-pnpres",""),i=null!==n?r:null,o=null!==n?n:r;return"string"!=typeof t&&"data"in t&&(t.state=t.data,delete t.data),Object.assign({channel:r,subscription:n,actualChannel:i,subscribedChannel:o,timetoken:e.p.t},t)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const o={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(o.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(o.message=n.message,n.file&&(o.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(o.customMessageType=e.cmt),i&&(o.error=i),o}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(oe.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class oe extends ie{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,o={};return e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class ae{constructor(e){this.listenerManager=e,this.channelListenerMap=new Map,this.groupListenerMap=new Map}emitEvent(e){var t;if(e.type===re.Message)this.listenerManager.announceMessage(e.data),this.announce("message",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Signal)this.listenerManager.announceSignal(e.data),this.announce("signal",e.data,e.data.channel,e.data.subscription);else if(e.type===re.Presence)this.listenerManager.announcePresence(e.data),this.announce("presence",e.data,null!==(t=e.data.subscription)&&void 0!==t?t:e.data.channel,e.data.subscription);else if(e.type===re.AppContext){const{data:t}=e,{message:s}=t;if(this.listenerManager.announceObjects(t),this.announce("objects",t,t.channel,t.subscription),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"user"})});this.listenerManager.announceUser(u),this.announce("user",u,u.spaceId,u.subscription)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,type:a}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",type:"space"})});this.listenerManager.announceSpace(u),this.announce("space",u,u.spaceId,u.subscription)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:o,data:a}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=a,h=r(a,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===o?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.listenerManager.announceMembership(d),this.announce("membership",d,d.spaceId,d.subscription)}}else e.type===re.MessageAction?(this.listenerManager.announceMessageAction(e.data),this.announce("messageAction",e.data,e.data.channel,e.data.subscription)):e.type===re.Files&&(this.listenerManager.announceFile(e.data),this.announce("file",e.data,e.data.channel,e.data.subscription))}addListener(e,t,s){t&&s?(null==t||t.forEach((t=>{if(this.channelListenerMap.has(t)){const s=this.channelListenerMap.get(t);s.includes(e)||s.push(e)}else this.channelListenerMap.set(t,[e])})),null==s||s.forEach((t=>{if(this.groupListenerMap.has(t)){const s=this.groupListenerMap.get(t);s.includes(e)||s.push(e)}else this.groupListenerMap.set(t,[e])}))):this.listenerManager.addListener(e)}removeListener(e,t,s){t&&s?(null==t||t.forEach((t=>{this.channelListenerMap.has(t)&&this.channelListenerMap.set(t,this.channelListenerMap.get(t).filter((t=>t!==e)))})),null==s||s.forEach((t=>{this.groupListenerMap.has(t)&&this.groupListenerMap.set(t,this.groupListenerMap.get(t).filter((t=>t!==e)))}))):this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners(),this.channelListenerMap.clear(),this.groupListenerMap.clear()}announce(e,t,s,n){t&&this.channelListenerMap.has(s)&&this.channelListenerMap.get(s).forEach((s=>{const n=s[e];n&&n(t)})),n&&this.groupListenerMap.has(n)&&this.groupListenerMap.get(n).forEach((s=>{const n=s[e];n&&n(t)}))}}class ce{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class ue{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class le extends ce{describe(e){return new ue(e)}start(e,t){this.currentState=e,this.currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this.currentState)throw new Error("Start the engine first");this.notify({type:"eventReceived",event:e});const t=this.currentState.transition(this.currentContext,e);if(t){const[s,n,r]=t;for(const e of this.currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)});const i=this.currentState;this.currentState=s;const o=this.currentContext;this.currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:o,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this.currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this.currentContext)})}}}class he{constructor(e){this.dependencies=e,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if("CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function de(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function pe(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function ge(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class ye extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class fe extends ce{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new ye}abort(){this._aborted=!0,this.notify(new ye)}}class me{constructor(e,t){this.payload=e,this.dependencies=t}}class be extends me{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new fe}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const ve=e=>(t,s)=>new be(t,s,e),we=de("RECONNECT",(()=>({}))),Se=de("DISCONNECT",(()=>({}))),ke=de("JOINED",((e,t)=>({channels:e,groups:t}))),Ee=de("LEFT",((e,t)=>({channels:e,groups:t}))),Oe=de("LEFT_ALL",(()=>({}))),Ce=de("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Ne=de("HEARTBEAT_FAILURE",(e=>e)),Pe=de("HEARTBEAT_GIVEUP",(()=>({}))),Me=de("TIMES_UP",(()=>({}))),_e=pe("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),Ae=pe("LEAVE",((e,t)=>({channels:e,groups:t}))),je=pe("EMIT_STATUS",(e=>e)),Ie=ge("WAIT",(()=>({}))),Re=ge("DELAYED_HEARTBEAT",(e=>e));class Ue extends he{constructor(e,t){super(t),this.on(_e.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(Ae.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Ie.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(Me())}))))),this.on(Re.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,retryDelay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(Pe());s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},o.maintainPresenceState&&{state:i}),{heartbeat:o.presenceTimeout}));return e.transition(Ce(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Ne(t))}}}))))),this.on(je.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){var r;n.announceFailedHeartbeats&&!0===(null===(r=null==e?void 0:e.status)||void 0===r?void 0:r.error)?s(e.status):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{operation:ne.PNHeartbeatOperation,error:!1}))})))))}}const Te=new ue("HEARTBEAT_STOPPED");Te.on(ke.type,((e,t)=>Te.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Te.on(Ee.type,((e,t)=>Te.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Te.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Te.on(Oe.type,((e,t)=>Ge.with(void 0)));const Fe=new ue("HEARTBEAT_COOLDOWN");Fe.onEnter((()=>Ie())),Fe.onExit((()=>Ie.cancel)),Fe.on(Me.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),Fe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Fe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),Fe.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),Fe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const xe=new ue("HEARTBEAT_FAILED");xe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),xe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),xe.on(we.type,((e,t)=>qe.with({channels:e.channels,groups:e.groups}))),xe.on(Se.type,((e,t)=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),xe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const De=new ue("HEARBEAT_RECONNECTING");De.onEnter((e=>Re(e))),De.onExit((()=>Re.cancel)),De.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),De.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),De.on(Se.type,((e,t)=>{Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)])})),De.on(Ce.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups}))),De.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),De.on(Pe.type,((e,t)=>xe.with({channels:e.channels,groups:e.groups}))),De.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const qe=new ue("HEARTBEATING");qe.onEnter((e=>_e(e.channels,e.groups))),qe.on(Ce.type,((e,t)=>Fe.with({channels:e.channels,groups:e.groups}))),qe.on(ke.type,((e,t)=>qe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),qe.on(Ee.type,((e,t)=>qe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[Ae(t.payload.channels,t.payload.groups)]))),qe.on(Ne.type,((e,t)=>De.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),qe.on(Se.type,(e=>Te.with({channels:e.channels,groups:e.groups},[Ae(e.channels,e.groups)]))),qe.on(Oe.type,((e,t)=>Ge.with(void 0,[Ae(e.channels,e.groups)])));const Ge=new ue("HEARTBEAT_INACTIVE");Ge.on(ke.type,((e,t)=>qe.with({channels:t.payload.channels,groups:t.payload.groups})));class Ke{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.engine=new le,this.channels=[],this.groups=[],this.dispatcher=new Ue(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ge,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(ke(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(Ee(null!=e?e:[],null!=t?t:[]))}leaveAll(){this.engine.transition(Oe())}dispose(){this._unsubscribeEngine(),this.dispatcher.dispose()}}class $e{static LinearRetryPolicy(e){return{delay:e.delay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:this.delay)+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhaused.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,shouldRetry(e,t){var s;return 403!==(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)&&this.maximumRetry>t},getDelay(e,t){var s;return 1e3*((null!==(s=t.retryAfter)&&void 0!==s?s:Math.min(Math.pow(2,e),this.maximumDelay))+Math.random())},getGiveupReason(e,t){var s;return this.maximumRetry<=t?"retry attempts exhausted.":403===(null===(s=null==e?void 0:e.status)||void 0===s?void 0:s.statusCode)?"forbidden operation.":"unknown error"},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const Le=ge("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),Be=ge("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),He=pe("EMIT_MESSAGES",(e=>e)),ze=pe("EMIT_STATUS",(e=>e)),Ve=ge("RECEIVE_RECONNECT",(e=>e)),We=ge("HANDSHAKE_RECONNECT",(e=>e)),Je=de("SUBSCRIPTION_CHANGED",((e,t)=>({channels:e,groups:t}))),Qe=de("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),Ye=de("HANDSHAKE_SUCCESS",(e=>e)),Xe=de("HANDSHAKE_FAILURE",(e=>e)),Ze=de("HANDSHAKE_RECONNECT_SUCCESS",(e=>({cursor:e}))),et=de("HANDSHAKE_RECONNECT_FAILURE",(e=>e)),tt=de("HANDSHAKE_RECONNECT_GIVEUP",(e=>e)),st=de("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),nt=de("RECEIVE_FAILURE",(e=>e)),rt=de("RECEIVE_RECONNECT_SUCCESS",((e,t)=>({cursor:e,events:t}))),it=de("RECEIVE_RECONNECT_FAILURE",(e=>e)),ot=de("RECEIVING_RECONNECT_GIVEUP",(e=>e)),at=de("DISCONNECT",(()=>({}))),ct=de("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ut=de("UNSUBSCRIBE_ALL",(()=>({})));class lt extends he{constructor(e,t){super(t),this.on(Le.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const o=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(Ye(o))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(Xe(t))}}}))))),this.on(Be.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(st(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(nt(t))}}}))))),this.on(He.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitMessages:s}){e.length>0&&s(e)}))))),this.on(ze.type,ve(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){s(e)}))))),this.on(Ve.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,delay:r,config:i}){if(!i.retryConfiguration||!i.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(ot(new d(i.retryConfiguration?i.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe messages receive.")));s.throwIfAborted(),yield r(i.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression});return e.transition(rt(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(it(t))}}}))))),this.on(We.type,ve(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,delay:r,presenceState:i,config:o}){if(!o.retryConfiguration||!o.retryConfiguration.shouldRetry(t.reason,t.attempts))return e.transition(tt(new d(o.retryConfiguration?o.retryConfiguration.getGiveupReason(t.reason,t.attempts):"Unable to complete subscribe handshake")));s.throwIfAborted(),yield r(o.retryConfiguration.getDelay(t.attempts,t.reason)),s.throwIfAborted();try{const r=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:o.filterExpression},o.maintainPresenceState&&{state:i}));return e.transition(Ze(r))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(et(t))}}})))))}}const ht=new ue("HANDSHAKE_FAILED");ht.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),ht.on(ct.type,((e,t)=>bt.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor||e.cursor}))),ht.on(Qe.type,((e,t)=>{var s,n;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region?t.payload.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),ht.on(ut.type,(e=>vt.with()));const dt=new ue("HANDSHAKE_STOPPED");dt.on(Je.type,((e,t)=>dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),dt.on(ct.type,((e,t)=>bt.with(Object.assign(Object.assign({},e),{cursor:t.payload.cursor||e.cursor})))),dt.on(Qe.type,((e,t)=>{var s;return dt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),dt.on(ut.type,(e=>vt.with()));const pt=new ue("RECEIVE_FAILED");pt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),pt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),pt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),pt.on(ut.type,(e=>vt.with(void 0)));const gt=new ue("RECEIVE_STOPPED");gt.on(Je.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),gt.on(Qe.type,((e,t)=>gt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),gt.on(ct.type,((e,t)=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.payload.cursor.timetoken?null===(s=t.payload.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}})})),gt.on(ut.type,(()=>vt.with(void 0)));const yt=new ue("RECEIVE_RECONNECTING");yt.onEnter((e=>Ve(e))),yt.onExit((()=>Ve.cancel)),yt.on(rt.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),yt.on(it.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),yt.on(ot.type,((e,t)=>{var s;return pt.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),yt.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),yt.on(Qe.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),yt.on(Je.type,((e,t)=>ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),yt.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const ft=new ue("RECEIVING");ft.onEnter((e=>Be(e.channels,e.groups,e.cursor))),ft.onExit((()=>Be.cancel)),ft.on(st.type,((e,t)=>ft.with({channels:e.channels,groups:e.groups,cursor:t.payload.cursor},[He(t.payload.events)]))),ft.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({cursor:e.cursor,channels:t.payload.channels,groups:t.payload.groups}))),ft.on(Qe.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):ft.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||e.cursor.region}}))),ft.on(nt.type,((e,t)=>yt.with(Object.assign(Object.assign({},e),{attempts:0,reason:t.payload})))),ft.on(at.type,(e=>gt.with({channels:e.channels,groups:e.groups,cursor:e.cursor},[ze({category:h.PNDisconnectedCategory})]))),ft.on(ut.type,(e=>vt.with(void 0,[ze({category:h.PNDisconnectedCategory})])));const mt=new ue("HANDSHAKE_RECONNECTING");mt.onEnter((e=>We(e))),mt.onExit((()=>We.cancel)),mt.on(Ze.type,((e,t)=>{var s,n;const r={timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region};return ft.with({channels:e.channels,groups:e.groups,cursor:r},[ze({category:h.PNConnectedCategory})])})),mt.on(et.type,((e,t)=>mt.with(Object.assign(Object.assign({},e),{attempts:e.attempts+1,reason:t.payload})))),mt.on(tt.type,((e,t)=>{var s;return ht.with({groups:e.groups,channels:e.channels,cursor:e.cursor,reason:t.payload},[ze({category:h.PNConnectionErrorCategory,error:null===(s=t.payload)||void 0===s?void 0:s.message})])})),mt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),mt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),mt.on(Qe.type,((e,t)=>{var s,n;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:(null===(s=t.payload.cursor)||void 0===s?void 0:s.region)||(null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.region)||0}})})),mt.on(ut.type,(e=>vt.with(void 0)));const bt=new ue("HANDSHAKING");bt.onEnter((e=>Le(e.channels,e.groups))),bt.onExit((()=>Le.cancel)),bt.on(Je.type,((e,t)=>0===t.payload.channels.length&&0===t.payload.groups.length?vt.with(void 0):bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:e.cursor}))),bt.on(Ye.type,((e,t)=>{var s,n;return ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=null==e?void 0:e.cursor)||void 0===n?void 0:n.timetoken:t.payload.timetoken,region:t.payload.region}},[ze({category:h.PNConnectedCategory})])})),bt.on(Xe.type,((e,t)=>mt.with({channels:e.channels,groups:e.groups,cursor:e.cursor,attempts:0,reason:t.payload}))),bt.on(at.type,(e=>dt.with({channels:e.channels,groups:e.groups,cursor:e.cursor}))),bt.on(Qe.type,((e,t)=>{var s;return bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:{timetoken:t.payload.cursor.timetoken,region:t.payload.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),bt.on(ut.type,(e=>vt.with()));const vt=new ue("UNSUBSCRIBED");vt.on(Je.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups}))),vt.on(Qe.type,((e,t)=>bt.with({channels:t.payload.channels,groups:t.payload.groups,cursor:t.payload.cursor})));class wt{get _engine(){return this.engine}constructor(e){this.engine=new le,this.channels=[],this.groups=[],this.dependencies=e,this.dispatcher=new lt(this.engine,e),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(vt,void 0)}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(Qe(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(Je(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=R(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=R(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=U(this.channels,e),i=U(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Je(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(){this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Je(this.channels.slice(0),this.groups.slice(0))),this.dependencies.leaveAll&&this.dependencies.leaveAll()}reconnect({timetoken:e,region:t}){this.engine.transition(ct(e,t))}disconnect(){this.engine.transition(at()),this.dependencies.leaveAll&&this.dependencies.leaveAll()}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(),this._unsubscribeEngine(),this.dispatcher.dispose()}}class St extends se{constructor(e){var t,s;super({method:e.sendByPost?B.POST:B.GET}),this.parameters=e,null!==(t=(s=this.parameters).sendByPost)&&void 0!==t||(s.sendByPost=false)}operation(){return ne.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${j(t)}/0${this.parameters.sendByPost?"":`/${j(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==n&&(i.store=n?"1":"0"),void 0!==r&&(i.ttl=r),void 0===s||s||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){return{"Content-Type":"application/json"}}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class kt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${j(s)}/0/${j(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Et extends ie{operation(){return ne.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ot extends ie{operation(){return ne.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${I(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={tt:0,ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Ct extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return ne.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);const{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Nt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{state:t.payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=s?s:[],",")}/uuid/${j(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Pt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${I(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class Mt extends se{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return ne.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${I(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class _t extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${j(t)}`}}class At extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?ne.PNGlobalHereNowOperation:ne.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e);if(!n)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(n.status>=400)throw _.create(e);const r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_channels,o={};let a={};if("occupancy"in n){const e=this.parameters.channels[0];a[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else a=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(a).forEach((e=>{const t=a[e];o[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:o}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${I(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class jt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${j(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class It extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${I(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Rt extends se{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return ne.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));const s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${j(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Rt.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class Tt extends se{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const o=null!==(t=e.includeMessageActions)&&void 0!==t&&t,a=e.channels.length>1||o?25:100;e.count?e.count=Math.min(e.count,a):e.count=a,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return ne.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e);if(!s)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(s.status>=400)throw _.create(e);const n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const s=this.processPayload(e,t),n=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${I(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:r,includeMeta:i,includeUUID:o,stringifiedTimeToken:a}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),a?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),o?{include_uuid:"true"}:{}),null!=n?{include_custom_message_type:n?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Tt.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Ft extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class xt extends se{constructor(e){super({method:B.POST}),this.parameters=e}operation(){return ne.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}/message/${s}`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify(this.parameters.action)}}class Dt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{data:t.data}}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${j(t)}/message/${n}/action/${s}`}}class qt extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return ne.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,o=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${j(t)}/0/${j(this.prepareMessagePayload(o))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&"object"==typeof n?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends se{constructor(e){super({method:B.LOCAL}),this.parameters=e}operation(){return ne.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${j(e)}/files/${t}/${s}`}}class Kt extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${j(s)}/files/${t}/${n}`}}class $t extends se{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return ne.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Lt extends se{constructor(e){super({method:B.POST}),this.parameters=e}operation(){return ne.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/generate-upload-url`}get headers(){return{"Content-Type":"application/json"}}get body(){return JSON.stringify({name:this.parameters.name})}}class Bt extends se{constructor(e){super({method:B.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return ne.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Bt.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class Ht{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:ne.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(ne.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Lt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:o,url:a,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Bt({fileId:i,fileName:o,file:this.file,uploadUrl:a,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let o,a={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{a=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(o=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:a.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=o.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=o.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class zt{subscribe(e){const t=null==e?void 0:e.timetoken;this.pubnub.subscribe(Object.assign({channels:this.channelNames,channelGroups:this.groupNames},null!==t&&""!==t&&{timetoken:t}))}unsubscribe(){this.pubnub.unsubscribe({channels:this.channelNames,channelGroups:this.groupNames})}set onMessage(e){this.listener.message=e}set onPresence(e){this.listener.presence=e}set onSignal(e){this.listener.signal=e}set onObjects(e){this.listener.objects=e}set onMessageAction(e){this.listener.messageAction=e}set onFile(e){this.listener.file=e}addListener(e){this.eventEmitter.addListener(e,this.channelNames,this.groupNames)}removeListener(e){this.eventEmitter.removeListener(e,this.channelNames,this.groupNames)}get channels(){return this.channelNames.slice(0)}get channelGroups(){return this.groupNames.slice(0)}}class Vt extends zt{constructor({channels:e=[],channelGroups:t=[],subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.subscriptionList=[],this.options=s,this.eventEmitter=n,this.pubnub=r,e.forEach((e=>{const t=this.pubnub.channel(e).subscription(this.options);this.channelNames=[...this.channelNames,...t.channels],this.subscriptionList.push(t)})),t.forEach((e=>{const t=this.pubnub.channelGroup(e).subscription(this.options);this.groupNames=[...this.groupNames,...t.channelGroups],this.subscriptionList.push(t)})),this.listener={},n.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){this.subscriptionList.push(e),this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscription(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>t!==e)),this.eventEmitter.removeListener(this.listener,t,s)}addSubscriptionSet(e){this.subscriptionList=[...this.subscriptionList,...e.subscriptions],this.channelNames=[...this.channelNames,...e.channels],this.groupNames=[...this.groupNames,...e.channelGroups],this.eventEmitter.addListener(this.listener,e.channels,e.channelGroups)}removeSubscriptionSet(e){const t=e.channels,s=e.channelGroups;this.channelNames=this.channelNames.filter((e=>!t.includes(e))),this.groupNames=this.groupNames.filter((e=>!s.includes(e))),this.subscriptionList=this.subscriptionList.filter((t=>!e.subscriptions.includes(t))),this.eventEmitter.removeListener(this.listener,t,s)}get subscriptions(){return this.subscriptionList.slice(0)}}class Wt extends zt{constructor({channels:e,channelGroups:t,subscriptionOptions:s,eventEmitter:n,pubnub:r}){super(),this.channelNames=[],this.groupNames=[],this.channelNames=e,this.groupNames=t,this.options=s,this.pubnub=r,this.eventEmitter=n,this.listener={},n.addListener(this.listener,this.channelNames,this.groupNames)}addSubscription(e){return new Vt({channels:[...this.channelNames,...e.channels],channelGroups:[...this.groupNames,...e.channelGroups],subscriptionOptions:Object.assign(Object.assign({},this.options),null==e?void 0:e.options),eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Jt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Qt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Wt({channels:[],channelGroups:t,subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Yt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.id=e}subscription(e){return new Wt({channels:[this.id],channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}class Xt{constructor(e,t,s){this.eventEmitter=t,this.pubnub=s,this.name=e}subscription(e){{const t=[this.name];return(null==e?void 0:e.receivePresenceEvents)&&!this.name.endsWith("-pnpres")&&t.push(`${this.name}-pnpres`),new Wt({channels:t,channelGroups:[],subscriptionOptions:e,eventEmitter:this.eventEmitter,pubnub:this.pubnub})}}}class Zt extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class es extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class ts extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{channels:t.payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}`}}class ss extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${j(t)}/remove`}}class ns extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return{groups:t.payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class rs{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new ts(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}listGroups(e){return i(this,void 0,void 0,(function*(){const t=new ns({keySet:this.keySet});return e?this.sendRequest(t,e):this.sendRequest(t)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new es(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new Zt(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){const s=new ss(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class is extends se{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){throw Error("Should be implemented in subclass.")}))}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class os extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return ne.PNRemovePushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class as extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return ne.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{channels:t}}))}}class cs extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return ne.PNAddPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class us extends is{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return ne.PNRemoveAllPushNotificationsOperation}parse(e){return i(this,void 0,void 0,(function*(){if(!this.deserializeResponse(e))throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{}}))}}class ls{constructor(e,t){this.sendRequest=t,this.keySet=e}listChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){const s=new us(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class hs extends se{constructor(e){var t,s,n,r,i,o;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(o=e.include).totalCount)&&void 0!==n||(o.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return ne.PNGetAllChannelMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ds extends se{constructor(e){super({method:B.DELETE}),this.parameters=e}operation(){return ne.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}}class ps extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).channelFields)&&void 0!==i||(p.channelFields=false),null!==(o=(g=e.include).customChannelFields)&&void 0!==o||(g.customChannelFields=false),null!==(a=(y=e.include).channelStatusField)&&void 0!==a||(y.channelStatusField=false),null!==(c=(f=e.include).channelTypeField)&&void 0!==c||(f.channelTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.channelStatusField&&o.push("channel.status"),e.channelTypeField&&o.push("channel.type"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class gs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).channelFields)&&void 0!==r||(u.channelFields=false),null!==(i=(l=e.include).customChannelFields)&&void 0!==i||(l.customChannelFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["channel.status","channel.type","status"];return e.customFields&&o.push("custom"),e.channelFields&&o.push("channel"),e.customChannelFields&&o.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,custom:e.custom}))})}}class ys extends se{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return ne.PNGetAllUUIDMetadataOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class fs extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class ms extends se{constructor(e){var t,s,n;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return ne.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class bs extends se{constructor(e){super({method:B.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}}class vs extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l,h,d,p,g,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(l=e.include).customFields)&&void 0!==s||(l.customFields=false),null!==(n=(h=e.include).totalCount)&&void 0!==n||(h.totalCount=false),null!==(r=(d=e.include).statusField)&&void 0!==r||(d.statusField=false),null!==(i=(p=e.include).UUIDFields)&&void 0!==i||(p.UUIDFields=false),null!==(o=(g=e.include).customUUIDFields)&&void 0!==o||(g.customUUIDFields=false),null!==(a=(y=e.include).UUIDStatusField)&&void 0!==a||(y.UUIDStatusField=false),null!==(c=(f=e.include).UUIDTypeField)&&void 0!==c||(f.UUIDTypeField=false),null!==(u=e.limit)&&void 0!==u||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=[];return e.statusField&&o.push("status"),e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.UUIDStatusField&&o.push("uuid.status"),e.UUIDTypeField&&o.push("uuid.type"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class ws extends se{constructor(e){var t,s,n,r,i,o,a,c,u,l;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(a=e.include).customFields)&&void 0!==s||(a.customFields=false),null!==(n=(c=e.include).totalCount)&&void 0!==n||(c.totalCount=false),null!==(r=(u=e.include).UUIDFields)&&void 0!==r||(u.UUIDFields=false),null!==(i=(l=e.include).customUUIDFields)&&void 0!==i||(l.customUUIDFields=false),null!==(o=e.limit)&&void 0!==o||(e.limit=100)}operation(){return ne.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${j(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const o=["uuid.status","uuid.type","type"];return e.customFields&&o.push("custom"),e.UUIDFields&&o.push("uuid"),e.customUUIDFields&&o.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},o.length>0?{include:o.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,custom:e.custom}))})}}class Ss extends se{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class ks extends se{constructor(e){var t,s,n;super({method:B.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return ne.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));if(t.status>=400)throw _.create(e);return t}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${j(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Es{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ys(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Ss(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new bs(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new hs(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new fs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ms(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new vs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){const s=new ws(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new ps(Object.assign(Object.assign({},n),{keySet:this.keySet}));return t?this.sendRequest(r,t):this.sendRequest(r)}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new gs(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if("spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},o=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?o(s):s)})):this.getMemberships(i).then(o)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,o,a;if("spaceId"in e){const i=e,o={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(o,t):this.setChannelMembers(o)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(a=null===(o=c.spaces)||void 0===o?void 0:o.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==a?a:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Os extends se{constructor(){super()}operation(){return ne.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);if(!t)throw new d("Service response error, check status for details",p("Unable to deserialize service response"));return{timetoken:t[0]}}))}get path(){return"/time/0"}}class Cs extends se{constructor(e){super(),this.parameters=e}operation(){return ne.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,o=e.headers["content-type"];let a,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(a=yield s.decryptFile(i.create({data:c,name:r,mimeType:o}),i))),a||i.create({data:c,name:r,mimeType:o})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${j(t)}/files/${s}/${n}`}}class Ns{static notificationPayload(e,t){return new te(e,t)}static generateUUID(){return G.createUUID()}constructor(e){if(this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this._objects=new Es(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new rs(this._configuration.keySet,this.sendRequest.bind(this)),this._push=new ls(this._configuration.keySet,this.sendRequest.bind(this)),this.listenerManager=new W,this.eventEmitter=new ae(this.listenerManager),this._configuration.enableEventEngine){let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Ke({heartbeat:this.heartbeat.bind(this),leave:e=>this.makeUnsubscribe(e,(()=>{})),heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),retryDelay:e=>new Promise((t=>setTimeout(t,e))),emitStatus:e=>this.listenerManager.announceStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new wt({handshake:this.subscribeHandshake.bind(this),receiveMessages:this.subscribeReceiveMessages.bind(this),delay:e=>new Promise((t=>setTimeout(t,e))),join:this.join.bind(this),leave:this.leave.bind(this),leaveAll:this.leaveAll.bind(this),presenceState:this.presenceState,config:this._configuration,emitMessages:e=>{try{e.forEach((e=>this.eventEmitter.emitEvent(e)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.listenerManager.announceStatus(t)}},emitStatus:e=>this.listenerManager.announceStatus(e)})}else this.subscriptionManager=new Y(this._configuration,this.listenerManager,this.eventEmitter,this.makeSubscribe.bind(this),this.heartbeat.bind(this),this.makeUnsubscribe.bind(this),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this._configuration.setFilterExpression(e)}setFilterExpression(e){this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.cipherKey=e}set heartbeatInterval(e){this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.heartbeatInterval=e}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){return new Xt(e,this.eventEmitter,this)}channelGroup(e){return new Qt(e,this.eventEmitter,this)}channelMetadata(e){return new Jt(e,this.eventEmitter,this)}userMetadata(e){return new Yt(e,this.eventEmitter,this)}subscriptionSet(e){return new Vt(Object.assign(Object.assign({},e),{eventEmitter:this.eventEmitter,pubnub:this}))}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){if(t)return t(p(s),null);throw new d("Validation failed, check status for details",p(s))}const n=e.request();n.formData&&n.formData.length>0?n.timeout=300:e.operation()===ne.PNSubscribeOperation?n.timeout=this._configuration.getSubscribeTimeout():n.timeout=this._configuration.getTransactionTimeout();const r={error:!1,operation:e.operation(),category:h.PNAcknowledgmentCategory,statusCode:0},[i,o]=this.transport.makeSendable(n);return e.cancellationController=o||null,i.then((t=>{if(r.statusCode=t.status,200!==t.status&&204!==t.status){const e=t.headers["content-type"];if(e||-1!==e.indexOf("javascript")||-1!==e.indexOf("json")){const e=JSON.parse(Ns.decoder.decode(t.body));"object"==typeof e&&"error"in e&&e.error&&"object"==typeof e.error&&(r.errorData=e.error)}}return e.parse(t)})).then((e=>t?t(r,e):e)).catch((s=>{const n=s instanceof _?s:_.create(s);if(t)return t(n.toStatus(e.operation()),null);throw n.toPubNubError(e.operation(),"REST API request processing error, check status for details")}))}))}destroy(e){this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.dispose()}stop(){this.destroy()}addListener(e){this.listenerManager.addListener(e)}removeListener(e){this.listenerManager.removeListener(e)}removeAllListeners(){this.listenerManager.removeAllListeners()}publish(e,t){return i(this,void 0,void 0,(function*(){{const s=new St(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{const s=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}subscribe(e){this.subscriptionManager?this.subscriptionManager.subscribe(e):this.eventEngine&&this.eventEngine.subscribe(e)}makeSubscribe(e,t){{const s=new oe(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort();e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){this.subscriptionManager?this.subscriptionManager.unsubscribe(e):this.eventEngine&&this.eventEngine.unsubscribe(e)}makeUnsubscribe(e,t){this.sendRequest(new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),t)}unsubscribeAll(){this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(){this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect()}reconnect(e){this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort()}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{const s=new jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}history(e,t){return i(this,void 0,void 0,(function*(){{const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new _t({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet});return t?this.sendRequest(n,t):this.sendRequest(n)}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{const n=new Ct(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{const{keySet:r,userId:i}=this._configuration,o=this._configuration.getPresenceTimeout();let a;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}return a="withHeartbeat"in e?new Pt(Object.assign(Object.assign({},e),{keySet:r,heartbeat:o})):new Nt(Object.assign(Object.assign({},e),{keySet:r,uuid:i})),this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(a,t):this.sendRequest(a)}}))}presence(e){var t;null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{const s=new Pt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}join(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.join(e)}leave(e){var t;null===(t=this.presenceEventEngine)||void 0===t||t.leave(e)}leaveAll(){var e;null===(e=this.presenceEventEngine)||void 0===e||e.leaveAll()}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if("spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,o={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(o,t):this.objects.removeMemberships(o)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Ht(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:ne.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0};return s.process().then((e=>(n.statusCode=e.status,t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),t&&s&&t(s,null),new d("REST API request processing error, check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}getFileUrl(e){var t;{const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${j(t)}`)).join("&"):`${e}=${j(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");const s=new Cs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()}));return t?this.sendRequest(s,t):yield this.sendRequest(s)}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}}))}time(e){return i(this,void 0,void 0,(function*(){const t=new Os;return e?this.sendRequest(t,e):this.sendRequest(t)}))}encrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Ns.decoder=new TextDecoder,Ns.OPERATIONS=ne,Ns.CATEGORIES=h,Ns.ExponentialRetryPolicy=$e.ExponentialRetryPolicy,Ns.LinearRetryPolicy=$e.LinearRetryPolicy;class Ps{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Ms extends Ns{constructor(e){var t;const s=x(e),r=Object.assign(Object.assign({},s),{sdkFamily:"Web"});r.PubNubFile=a;const i=K(r,(e=>{if(e.cipherKey)return new N({default:new C(Object.assign({},e)),cryptors:[new S({cipherKey:e.cipherKey})]})}));let o,u,l;o=new L(new Ps((e=>F(n.decode(e))),c)),(i.getCipherKey()||i.secretKey)&&(u=new E({secretKey:i.secretKey,cipherKey:i.getCipherKey(),useRandomIVs:i.getUseRandomIVs(),customEncrypt:i.getCustomEncrypt(),customDecrypt:i.getCustomDecrypt()})),l=new O;let h=new T(i.keepAlive,i.logVerbosity);s.subscriptionWorkerUrl&&(h=new A({clientIdentifier:i._instanceId,subscriptionKey:i.subscribeKey,userId:i.getUserId(),workerUrl:s.subscriptionWorkerUrl,sdkVersion:i.getVersion(),logVerbosity:i.logVerbosity,workerLogVerbosity:r.subscriptionWorkerLogVerbosity,transport:h}));super({configuration:i,transport:new V({clientConfiguration:i,tokenManager:o,transport:h}),cryptography:l,tokenManager:o,crypto:u}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.listenerManager.announceNetworkDown(),this._configuration.restore?this.disconnect():this.destroy(!0)}networkUpDetected(){this.listenerManager.announceNetworkUp(),this.reconnect()}}return Ms.CryptoModule=N,Ms})); diff --git a/lib/core/components/configuration.js b/lib/core/components/configuration.js index 4b4748a7d..9265fe676 100644 --- a/lib/core/components/configuration.js +++ b/lib/core/components/configuration.js @@ -112,7 +112,7 @@ const makeConfiguration = (base, setupCryptoModule) => { return base.PubNubFile; }, get version() { - return '8.3.0'; + return '8.3.1'; }, getVersion() { return this.version; diff --git a/package.json b/package.json index 3be93b13f..e515925ca 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "8.3.0", + "version": "8.3.1", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index 385ddef16..db44fcc57 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -171,7 +171,7 @@ export const makeConfiguration = ( return base.PubNubFile; }, get version(): string { - return '8.3.0'; + return '8.3.1'; }, getVersion(): string { return this.version;