pusher-js
Version:
Pusher Channels JavaScript library for browsers, React Native, NodeJS and web workers
2 lines • 54.3 kB
JavaScript
/*! For license information please see pusher.worker.min.js.LICENSE.txt */
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Pusher=e():t.Pusher=e()}(this,()=>(()=>{var t={594(t,e){"use strict";var n,i=this&&this.__extends||(n=function(t,e){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},n(t,e)},function(t,e){function i(){this.constructor=t}n(t,e),t.prototype=null===e?Object.create(e):(i.prototype=e.prototype,new i)});Object.defineProperty(e,"__esModule",{value:!0});var s=256,r=function(){function t(t){void 0===t&&(t="="),this._paddingCharacter=t}return t.prototype.encodedLength=function(t){return this._paddingCharacter?(t+2)/3*4|0:(8*t+5)/6|0},t.prototype.encode=function(t){for(var e="",n=0;n<t.length-2;n+=3){var i=t[n]<<16|t[n+1]<<8|t[n+2];e+=this._encodeByte(i>>>18&63),e+=this._encodeByte(i>>>12&63),e+=this._encodeByte(i>>>6&63),e+=this._encodeByte(i>>>0&63)}var s=t.length-n;return s>0&&(i=t[n]<<16|(2===s?t[n+1]<<8:0),e+=this._encodeByte(i>>>18&63),e+=this._encodeByte(i>>>12&63),e+=2===s?this._encodeByte(i>>>6&63):this._paddingCharacter||"",e+=this._paddingCharacter||""),e},t.prototype.maxDecodedLength=function(t){return this._paddingCharacter?t/4*3|0:(6*t+7)/8|0},t.prototype.decodedLength=function(t){return this.maxDecodedLength(t.length-this._getPaddingLength(t))},t.prototype.decode=function(t){if(0===t.length)return new Uint8Array(0);for(var e=this._getPaddingLength(t),n=t.length-e,i=new Uint8Array(this.maxDecodedLength(n)),r=0,o=0,a=0,c=0,h=0,u=0,l=0;o<n-4;o+=4)c=this._decodeChar(t.charCodeAt(o+0)),h=this._decodeChar(t.charCodeAt(o+1)),u=this._decodeChar(t.charCodeAt(o+2)),l=this._decodeChar(t.charCodeAt(o+3)),i[r++]=c<<2|h>>>4,i[r++]=h<<4|u>>>2,i[r++]=u<<6|l,a|=c&s,a|=h&s,a|=u&s,a|=l&s;if(o<n-1&&(c=this._decodeChar(t.charCodeAt(o)),h=this._decodeChar(t.charCodeAt(o+1)),i[r++]=c<<2|h>>>4,a|=c&s,a|=h&s),o<n-2&&(u=this._decodeChar(t.charCodeAt(o+2)),i[r++]=h<<4|u>>>2,a|=u&s),o<n-3&&(l=this._decodeChar(t.charCodeAt(o+3)),i[r++]=u<<6|l,a|=l&s),0!==a)throw new Error("Base64Coder: incorrect characters for decoding");return i},t.prototype._encodeByte=function(t){var e=t;return e+=65,e+=25-t>>>8&6,e+=51-t>>>8&-75,e+=61-t>>>8&-15,e+=62-t>>>8&3,String.fromCharCode(e)},t.prototype._decodeChar=function(t){var e=s;return e+=(42-t&t-44)>>>8&-256+t-43+62,e+=(46-t&t-48)>>>8&-256+t-47+63,e+=(47-t&t-58)>>>8&-256+t-48+52,(e+=(64-t&t-91)>>>8&-256+t-65+0)+((96-t&t-123)>>>8&-256+t-97+26)},t.prototype._getPaddingLength=function(t){var e=0;if(this._paddingCharacter){for(var n=t.length-1;n>=0&&t[n]===this._paddingCharacter;n--)e++;if(t.length<4||e>2)throw new Error("Base64Coder: incorrect padding")}return e},t}();e.Coder=r;var o=new r;e.encode=function(t){return o.encode(t)},e.decode=function(t){return o.decode(t)};var a=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype._encodeByte=function(t){var e=t;return e+=65,e+=25-t>>>8&6,e+=51-t>>>8&-75,e+=61-t>>>8&-13,e+=62-t>>>8&49,String.fromCharCode(e)},e.prototype._decodeChar=function(t){var e=s;return e+=(44-t&t-46)>>>8&-256+t-45+62,e+=(94-t&t-96)>>>8&-256+t-95+63,e+=(47-t&t-58)>>>8&-256+t-48+52,(e+=(64-t&t-91)>>>8&-256+t-65+0)+((96-t&t-123)>>>8&-256+t-97+26)},e}(r);e.URLSafeCoder=a;var c=new a;e.encodeURLSafe=function(t){return c.encode(t)},e.decodeURLSafe=function(t){return c.decode(t)},e.encodedLength=function(t){return o.encodedLength(t)},e.maxDecodedLength=function(t){return o.maxDecodedLength(t)},e.decodedLength=function(t){return o.decodedLength(t)}},978(t,e){"use strict";var n="utf8: invalid source encoding";e.D4=function(t){for(var e=[],i=0;i<t.length;i++){var s=t[i];if(128&s){var r=void 0;if(s<224){if(i>=t.length)throw new Error(n);if(128!=(192&(o=t[++i])))throw new Error(n);s=(31&s)<<6|63&o,r=128}else if(s<240){if(i>=t.length-1)throw new Error(n);var o=t[++i],a=t[++i];if(128!=(192&o)||128!=(192&a))throw new Error(n);s=(15&s)<<12|(63&o)<<6|63&a,r=2048}else{if(!(s<248))throw new Error(n);if(i>=t.length-2)throw new Error(n);o=t[++i],a=t[++i];var c=t[++i];if(128!=(192&o)||128!=(192&a)||128!=(192&c))throw new Error(n);s=(15&s)<<18|(63&o)<<12|(63&a)<<6|63&c,r=65536}if(s<r||s>=55296&&s<=57343)throw new Error(n);if(s>=65536){if(s>1114111)throw new Error(n);s-=65536,e.push(String.fromCharCode(55296|s>>10)),s=56320|1023&s}}e.push(String.fromCharCode(s))}return e.join("")}},721(t,e,n){t.exports=n(288).default},288(t,e,n){"use strict";n.d(e,{default:()=>Be});for(var i=String.fromCharCode,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r={},o=0;o<64;o++)r[s.charAt(o)]=o;var a=function(t){var e=t.charCodeAt(0);return e<128?t:e<2048?i(192|e>>>6)+i(128|63&e):i(224|e>>>12&15)+i(128|e>>>6&63)+i(128|63&e)},c=function(t){var e=[0,2,1][t.length%3],n=t.charCodeAt(0)<<16|(t.length>1?t.charCodeAt(1):0)<<8|(t.length>2?t.charCodeAt(2):0);return[s.charAt(n>>>18),s.charAt(n>>>12&63),e>=2?"=":s.charAt(n>>>6&63),e>=1?"=":s.charAt(63&n)].join("")},h=self.btoa||function(t){return t.replace(/[\s\S]{1,3}/g,c)};const u=class{constructor(t,e,n,i){this.clear=e,this.timer=t(()=>{this.timer&&(this.timer=i(this.timer))},n)}isRunning(){return null!==this.timer}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}};function l(t){self.clearTimeout(t)}function d(t){self.clearInterval(t)}class p extends u{constructor(t,e){super(setTimeout,l,t,function(t){return e(),null})}}class g extends u{constructor(t,e){super(setInterval,d,t,function(t){return e(),t})}}var f={now:()=>Date.now?Date.now():(new Date).valueOf(),defer:t=>new p(0,t),method(t,...e){var n=Array.prototype.slice.call(arguments,1);return function(e){return e[t].apply(e,n.concat(arguments))}}};const b=f;function m(t,...e){for(var n=0;n<e.length;n++){var i=e[n];for(var s in i)i[s]&&i[s].constructor&&i[s].constructor===Object?t[s]=m(t[s]||{},i[s]):t[s]=i[s]}return t}function v(){for(var t=["Pusher"],e=0;e<arguments.length;e++)"string"==typeof arguments[e]?t.push(arguments[e]):t.push(E(arguments[e]));return t.join(" : ")}function y(t,e){var n=Array.prototype.indexOf;if(null===t)return-1;if(n&&t.indexOf===n)return t.indexOf(e);for(var i=0,s=t.length;i<s;i++)if(t[i]===e)return i;return-1}function S(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(t[n],n,t)}function _(t){var e=[];return S(t,function(t,n){e.push(n)}),e}function w(t,e,n){for(var i=0;i<t.length;i++)e.call(n||self,t[i],i,t)}function k(t,e){for(var n=[],i=0;i<t.length;i++)n.push(e(t[i],i,t,n));return n}function C(t,e){e=e||function(t){return!!t};for(var n=[],i=0;i<t.length;i++)e(t[i],i,t,n)&&n.push(t[i]);return n}function T(t,e){var n={};return S(t,function(i,s){(e&&e(i,s,t,n)||Boolean(i))&&(n[s]=i)}),n}function P(t,e){for(var n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1}function x(t){return e=function(t){return"object"==typeof t&&(t=E(t)),encodeURIComponent((e=t.toString(),h(e.replace(/[^\x00-\x7F]/g,a))));var e},n={},S(t,function(t,i){n[i]=e(t)}),n;var e,n}function E(t){try{return JSON.stringify(t)}catch(i){return JSON.stringify((e=[],n=[],function t(i,s){var r,o,a;switch(typeof i){case"object":if(!i)return null;for(r=0;r<e.length;r+=1)if(e[r]===i)return{$ref:n[r]};if(e.push(i),n.push(s),"[object Array]"===Object.prototype.toString.apply(i))for(a=[],r=0;r<i.length;r+=1)a[r]=t(i[r],s+"["+r+"]");else for(o in a={},i)Object.prototype.hasOwnProperty.call(i,o)&&(a[o]=t(i[o],s+"["+JSON.stringify(o)+"]"));return a;case"number":case"string":case"boolean":return i}}(t,"$")))}var e,n}const O="8.5.0",L=7,A=80,R=443,I="",D="sockjs.pusher.com",U=80,N=443,j="/pusher",H="stats.pusher.com",M="/pusher/auth",z="ajax",B=12e4,q=3e4,F=1e4,$={endpoint:"/pusher/user-auth",transport:"ajax"},J={endpoint:"/pusher/auth",transport:"ajax"};function W(t,e,n){return t+(e.useTLS?"s":"")+"://"+(e.useTLS?e.hostTLS:e.hostNonTLS)+n}function X(t,e){return"/app/"+t+"?protocol="+L+"&client=js&version="+O+(e?"&"+e:"")}var G={getInitial:function(t,e){return W("ws",e,(e.httpPath||"")+X(t,"flash=false"))}},Y={getInitial:function(t,e){return W("http",e,(e.httpPath||"/pusher")+X(t))}};class K{constructor(){this._callbacks={}}get(t){return this._callbacks[Q(t)]}add(t,e,n){var i=Q(t);this._callbacks[i]=this._callbacks[i]||[],this._callbacks[i].push({fn:e,context:n})}remove(t,e,n){if(t||e||n){var i=t?[Q(t)]:_(this._callbacks);e||n?this.removeCallback(i,e,n):this.removeAllCallbacks(i)}else this._callbacks={}}removeCallback(t,e,n){w(t,function(t){this._callbacks[t]=C(this._callbacks[t]||[],function(t){return e&&e!==t.fn||n&&n!==t.context}),0===this._callbacks[t].length&&delete this._callbacks[t]},this)}removeAllCallbacks(t){w(t,function(t){delete this._callbacks[t]},this)}}function Q(t){return"_"+t}class V{constructor(t){this.callbacks=new K,this.global_callbacks=[],this.failThrough=t}bind(t,e,n){return this.callbacks.add(t,e,n),this}bind_global(t){return this.global_callbacks.push(t),this}unbind(t,e,n){return this.callbacks.remove(t,e,n),this}unbind_global(t){return t?(this.global_callbacks=C(this.global_callbacks||[],e=>e!==t),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(t,e,n){for(var i=0;i<this.global_callbacks.length;i++)this.global_callbacks[i](t,e);var s=this.callbacks.get(t),r=[];if(n?r.push(e,n):e&&r.push(e),s&&s.length>0)for(i=0;i<s.length;i++)s[i].fn.apply(s[i].context||self,r);else this.failThrough&&this.failThrough(t,e);return this}}const Z=new class{constructor(){this.globalLog=t=>{self.console&&self.console.log&&self.console.log(t)}}debug(...t){this.log(this.globalLog,t)}warn(...t){this.log(this.globalLogWarn,t)}error(...t){this.log(this.globalLogError,t)}globalLogWarn(t){self.console&&self.console.warn?self.console.warn(t):this.globalLog(t)}globalLogError(t){self.console&&self.console.error?self.console.error(t):this.globalLogWarn(t)}log(t,...e){var n=v.apply(this,arguments);Be.log?Be.log(n):Be.logToConsole&&t.bind(this)(n)}};class tt extends V{constructor(t,e,n,i,s){super(),this.initialize=ye.transportConnectionInitializer,this.hooks=t,this.name=e,this.priority=n,this.key=i,this.options=s,this.state="new",this.timeline=s.timeline,this.activityTimeout=s.activityTimeout,this.id=this.timeline.generateUniqueID()}handlesActivityChecks(){return Boolean(this.hooks.handlesActivityChecks)}supportsPing(){return Boolean(this.hooks.supportsPing)}connect(){if(this.socket||"initialized"!==this.state)return!1;var t=this.hooks.urls.getInitial(this.key,this.options);try{this.socket=this.hooks.getSocket(t,this.options)}catch(t){return b.defer(()=>{this.onError(t),this.changeState("closed")}),!1}return this.bindListeners(),Z.debug("Connecting",{transport:this.name,url:t}),this.changeState("connecting"),!0}close(){return!!this.socket&&(this.socket.close(),!0)}send(t){return"open"===this.state&&(b.defer(()=>{this.socket&&this.socket.send(t)}),!0)}ping(){"open"===this.state&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(t){this.emit("error",{type:"WebSocketError",error:t}),this.timeline.error(this.buildTimelineMessage({error:t.toString()}))}onClose(t){t?this.changeState("closed",{code:t.code,reason:t.reason,wasClean:t.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(t){this.emit("message",t)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=t=>{this.onError(t)},this.socket.onclose=t=>{this.onClose(t)},this.socket.onmessage=t=>{this.onMessage(t)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(t,e){this.state=t,this.timeline.info(this.buildTimelineMessage({state:t,params:e})),this.emit(t,e)}buildTimelineMessage(t){return m({cid:this.id},t)}}class et{constructor(t){this.hooks=t}isSupported(t){return this.hooks.isSupported(t)}createConnection(t,e,n,i){return new tt(this.hooks,t,e,n,i)}}var nt=new et({urls:G,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return Boolean(ye.getWebSocketAPI())},isSupported:function(){return Boolean(ye.getWebSocketAPI())},getSocket:function(t){return ye.createWebSocket(t)}}),it={urls:Y,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},st=m({getSocket:function(t){return ye.HTTPFactory.createStreamingSocket(t)}},it),rt=m({getSocket:function(t){return ye.HTTPFactory.createPollingSocket(t)}},it),ot={isSupported:function(){return ye.isXHRSupported()}};const at={ws:nt,xhr_streaming:new et(m({},st,ot)),xhr_polling:new et(m({},rt,ot))};class ct{constructor(t,e,n){this.manager=t,this.transport=e,this.minPingDelay=n.minPingDelay,this.maxPingDelay=n.maxPingDelay,this.pingDelay=void 0}createConnection(t,e,n,i){i=m({},i,{activityTimeout:this.pingDelay});var s=this.transport.createConnection(t,e,n,i),r=null,o=function(){s.unbind("open",o),s.bind("closed",a),r=b.now()},a=t=>{if(s.unbind("closed",a),1002===t.code||1003===t.code)this.manager.reportDeath();else if(!t.wasClean&&r){var e=b.now()-r;e<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(e/2,this.minPingDelay))}};return s.bind("open",o),s}isSupported(t){return this.manager.isAlive()&&this.transport.isSupported(t)}}const ht={decodeMessage:function(t){try{var e=JSON.parse(t.data),n=e.data;if("string"==typeof n)try{n=JSON.parse(e.data)}catch(t){}var i={event:e.event,channel:e.channel,data:n};return e.user_id&&(i.user_id=e.user_id),i}catch(e){throw{type:"MessageParseError",error:e,data:t.data}}},encodeMessage:function(t){return JSON.stringify(t)},processHandshake:function(t){var e=ht.decodeMessage(t);if("pusher:connection_established"===e.event){if(!e.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:e.data.socket_id,activityTimeout:1e3*e.data.activity_timeout}}if("pusher:error"===e.event)return{action:this.getCloseAction(e.data),error:this.getCloseError(e.data)};throw"Invalid handshake"},getCloseAction:function(t){return t.code<4e3?t.code>=1002&&t.code<=1004?"backoff":null:4e3===t.code?"tls_only":t.code<4100?"refused":t.code<4200?"backoff":t.code<4300?"retry":"refused"},getCloseError:function(t){return 1e3!==t.code&&1001!==t.code?{type:"PusherError",data:{code:t.code,message:t.reason||t.message}}:null}},ut=ht;class lt extends V{constructor(t,e){super(),this.id=t,this.transport=e,this.activityTimeout=e.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(t){return this.transport.send(t)}send_event(t,e,n){var i={event:t,data:e};return n&&(i.channel=n),Z.debug("Event sent",i),this.send(ut.encodeMessage(i))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var t={message:t=>{var e;try{e=ut.decodeMessage(t)}catch(e){this.emit("error",{type:"MessageParseError",error:e,data:t.data})}if(void 0!==e){switch(Z.debug("Event recd",e),e.event){case"pusher:error":this.emit("error",{type:"PusherError",data:e.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong")}this.emit("message",e)}},activity:()=>{this.emit("activity")},error:t=>{this.emit("error",t)},closed:t=>{e(),t&&t.code&&this.handleCloseEvent(t),this.transport=null,this.emit("closed")}},e=()=>{S(t,(t,e)=>{this.transport.unbind(e,t)})};S(t,(t,e)=>{this.transport.bind(e,t)})}handleCloseEvent(t){var e=ut.getCloseAction(t),n=ut.getCloseError(t);n&&this.emit("error",n),e&&this.emit(e,{action:e,error:n})}}class dt{constructor(t,e){this.transport=t,this.callback=e,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=t=>{var e;this.unbindListeners();try{e=ut.processHandshake(t)}catch(t){return this.finish("error",{error:t}),void this.transport.close()}"connected"===e.action?this.finish("connected",{connection:new lt(e.id,this.transport),activityTimeout:e.activityTimeout}):(this.finish(e.action,{error:e.error}),this.transport.close())},this.onClosed=t=>{this.unbindListeners();var e=ut.getCloseAction(t)||"backoff",n=ut.getCloseError(t);this.finish(e,{error:n})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(t,e){this.callback(m({transport:this.transport,action:t},e))}}class pt{constructor(t,e){this.timeline=t,this.options=e||{}}send(t,e){this.timeline.isEmpty()||this.timeline.send(ye.TimelineTransport.getAgent(this,t),e)}}class gt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class ft extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}Error;class bt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class mt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class vt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class yt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class St extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype)}}class _t extends Error{constructor(t,e){super(e),this.status=t,Object.setPrototypeOf(this,new.target.prototype)}}const wt={baseUrl:"https://pusher.com",urls:{authenticationEndpoint:{path:"/docs/channels/server_api/authenticating_users"},authorizationEndpoint:{path:"/docs/channels/server_api/authorizing-users/"},javascriptQuickStart:{path:"/docs/javascript_quick_start"},triggeringClientEvents:{path:"/docs/client_api_guide/client_events#trigger-events"},encryptedChannelSupport:{fullUrl:"https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support"}}},kt=function(t){const e=wt.urls[t];if(!e)return"";let n;return e.fullUrl?n=e.fullUrl:e.path&&(n=wt.baseUrl+e.path),n?`See: ${n}`:""};class Ct extends V{constructor(t,e){super(function(e,n){Z.debug("No callbacks on "+t+" for "+e)}),this.name=t,this.pusher=e,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(t,e){return e(null,{auth:""})}trigger(t,e){if(0!==t.indexOf("client-"))throw new gt("Event '"+t+"' does not start with 'client-'");if(!this.subscribed){var n=kt("triggeringClientEvents");Z.warn(`Client event triggered before channel 'subscription_succeeded' event . ${n}`)}return this.pusher.send_event(t,e,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(t){var e=t.event,n=t.data;"pusher_internal:subscription_succeeded"===e?this.handleSubscriptionSucceededEvent(t):"pusher_internal:subscription_count"===e?this.handleSubscriptionCountEvent(t):0!==e.indexOf("pusher_internal:")&&this.emit(e,n,{})}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",t.data)}handleSubscriptionCountEvent(t){t.data.subscription_count&&(this.subscriptionCount=t.data.subscription_count),this.emit("pusher:subscription_count",t.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(t,e)=>{t?(this.subscriptionPending=!1,Z.error(t.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:t.message},t instanceof _t?{status:t.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:e.auth,channel_data:e.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class Tt extends Ct{authorize(t,e){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:t},e)}}class Pt{constructor(){this.reset()}get(t){return Object.prototype.hasOwnProperty.call(this.members,t)?{id:t,info:this.members[t]}:null}each(t){S(this.members,(e,n)=>{t(this.get(n))})}setMyID(t){this.myID=t}onSubscription(t){this.members=t.presence.hash,this.count=t.presence.count,this.me=this.get(this.myID)}addMember(t){return null===this.get(t.user_id)&&this.count++,this.members[t.user_id]=t.user_info,this.get(t.user_id)}removeMember(t){var e=this.get(t.user_id);return e&&(delete this.members[t.user_id],this.count--),e}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}class xt extends Tt{constructor(t,e){super(t,e),this.members=new Pt}authorize(t,e){super.authorize(t,(t,n)=>{return i=this,s=void 0,o=function*(){if(!t)if(null!=n.channel_data){var i=JSON.parse(n.channel_data);this.members.setMyID(i.user_id)}else{if(yield this.pusher.user.signinDonePromise,null==this.pusher.user.user_data){let t=kt("authorizationEndpoint");return Z.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${t}, or the user should be signed in.`),void e("Invalid auth response")}this.members.setMyID(this.pusher.user.user_data.id)}e(t,n)},new((r=void 0)||(r=Promise))(function(t,e){function n(t){try{c(o.next(t))}catch(t){e(t)}}function a(t){try{c(o.throw(t))}catch(t){e(t)}}function c(e){var i;e.done?t(e.value):(i=e.value,i instanceof r?i:new r(function(t){t(i)})).then(n,a)}c((o=o.apply(i,s||[])).next())});var i,s,r,o})}handleEvent(t){var e=t.event;if(0===e.indexOf("pusher_internal:"))this.handleInternalEvent(t);else{var n=t.data,i={};t.user_id&&(i.user_id=t.user_id),this.emit(e,n,i)}}handleInternalEvent(t){var e=t.event,n=t.data;switch(e){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(t);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(t);break;case"pusher_internal:member_added":var i=this.members.addMember(n);this.emit("pusher:member_added",i);break;case"pusher_internal:member_removed":var s=this.members.removeMember(n);s&&this.emit("pusher:member_removed",s)}}handleSubscriptionSucceededEvent(t){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(t.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Et=n(978),Ot=n(594);class Lt extends Tt{constructor(t,e,n){super(t,e),this.key=null,this.nacl=n}authorize(t,e){super.authorize(t,(t,n)=>{if(t)return void e(t,n);let i=n.shared_secret;i?(this.key=(0,Ot.decode)(i),delete n.shared_secret,e(null,n)):e(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null)})}trigger(t,e){throw new vt("Client events are not currently supported for encrypted channels")}handleEvent(t){var e=t.event,n=t.data;0!==e.indexOf("pusher_internal:")&&0!==e.indexOf("pusher:")?this.handleEncryptedEvent(e,n):super.handleEvent(t)}handleEncryptedEvent(t,e){if(!this.key)return void Z.debug("Received encrypted event before key has been retrieved from the authEndpoint");if(!e.ciphertext||!e.nonce)return void Z.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+e);let n=(0,Ot.decode)(e.ciphertext);if(n.length<this.nacl.secretbox.overheadLength)return void Z.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${n.length}`);let i=(0,Ot.decode)(e.nonce);if(i.length<this.nacl.secretbox.nonceLength)return void Z.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${i.length}`);let s=this.nacl.secretbox.open(n,i,this.key);if(null===s)return Z.debug("Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint..."),void this.authorize(this.pusher.connection.socket_id,(e,r)=>{e?Z.error(`Failed to make a request to the authEndpoint: ${r}. Unable to fetch new key, so dropping encrypted event`):(s=this.nacl.secretbox.open(n,i,this.key),null!==s?this.emit(t,this.getDataToEmit(s)):Z.error("Failed to decrypt event with new key. Dropping encrypted event"))});this.emit(t,this.getDataToEmit(s))}getDataToEmit(t){let e=(0,Et.D4)(t);try{return JSON.parse(e)}catch(t){return e}}}class At extends V{constructor(t,e){super(),this.state="initialized",this.connection=null,this.key=t,this.options=e,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var n=ye.getNetwork();n.bind("online",()=>{this.timeline.info({netinfo:"online"}),"connecting"!==this.state&&"unavailable"!==this.state||this.retryIn(0)}),n.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(t){this.key=t,this.updateStrategy(),this.retryIn(0)}connect(){this.connection||this.runner||(this.strategy.isSupported()?(this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()):this.updateState("failed"))}send(t){return!!this.connection&&this.connection.send(t)}send_event(t,e,n){return!!this.connection&&this.connection.send_event(t,e,n)}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var t=(e,n)=>{e?this.runner=this.strategy.connect(0,t):"error"===n.action?(this.emit("error",{type:"HandshakeError",error:n.error}),this.timeline.error({handshakeError:n.error})):(this.abortConnecting(),this.handshakeCallbacks[n.action](n))};this.runner=this.strategy.connect(0,t)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection&&this.abandonConnection().close()}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(t){this.timeline.info({action:"retry",delay:t}),t>0&&this.emit("connecting_in",Math.round(t/1e3)),this.retryTimer=new p(t||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new p(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new p(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new p(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(t){return m({},t,{message:t=>{this.resetActivityCheck(),this.emit("message",t)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:t=>{this.emit("error",t)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(t){return m({},t,{connected:t=>{this.activityTimeout=Math.min(this.options.activityTimeout,t.activityTimeout,t.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(t.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let t=t=>e=>{e.error&&this.emit("error",{type:"WebSocketError",error:e.error}),t(e)};return{tls_only:t(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:t(()=>{this.disconnect()}),backoff:t(()=>{this.retryIn(1e3)}),retry:t(()=>{this.retryIn(0)})}}setConnection(t){for(var e in this.connection=t,this.connectionCallbacks)this.connection.bind(e,this.connectionCallbacks[e]);this.resetActivityCheck()}abandonConnection(){if(this.connection){for(var t in this.stopActivityCheck(),this.connectionCallbacks)this.connection.unbind(t,this.connectionCallbacks[t]);var e=this.connection;return this.connection=null,e}}updateState(t,e){var n=this.state;if(this.state=t,n!==t){var i=t;"connected"===i&&(i+=" with new socket ID "+e.socket_id),Z.debug("State changed",n+" -> "+i),this.timeline.info({state:t,params:e}),this.emit("state_change",{previous:n,current:t}),this.emit(t,e)}}shouldRetry(){return"connecting"===this.state||"connected"===this.state}}class Rt{constructor(){this.channels={}}add(t,e){return this.channels[t]||(this.channels[t]=function(t,e){if(0===t.indexOf("private-encrypted-")){if(e.config.nacl)return Dt.createEncryptedChannel(t,e,e.config.nacl);let n="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",i=kt("encryptedChannelSupport");throw new vt(`${n}. ${i}`)}if(0===t.indexOf("private-"))return Dt.createPrivateChannel(t,e);if(0===t.indexOf("presence-"))return Dt.createPresenceChannel(t,e);if(0===t.indexOf("#"))throw new ft('Cannot create a channel with name "'+t+'".');return Dt.createChannel(t,e)}(t,e)),this.channels[t]}all(){return t=this.channels,e=[],S(t,function(t){e.push(t)}),e;var t,e}find(t){return this.channels[t]}remove(t){var e=this.channels[t];return delete this.channels[t],e}disconnect(){S(this.channels,function(t){t.disconnect()})}}var It={createChannels:()=>new Rt,createConnectionManager:(t,e)=>new At(t,e),createChannel:(t,e)=>new Ct(t,e),createPrivateChannel:(t,e)=>new Tt(t,e),createPresenceChannel:(t,e)=>new xt(t,e),createEncryptedChannel:(t,e,n)=>new Lt(t,e,n),createTimelineSender:(t,e)=>new pt(t,e),createHandshake:(t,e)=>new dt(t,e),createAssistantToTheTransportManager:(t,e,n)=>new ct(t,e,n)};const Dt=It;class Ut{constructor(t){this.options=t||{},this.livesLeft=this.options.lives||1/0}getAssistant(t){return Dt.createAssistantToTheTransportManager(this,t,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Nt{constructor(t,e){this.strategies=t,this.loop=Boolean(e.loop),this.failFast=Boolean(e.failFast),this.timeout=e.timeout,this.timeoutLimit=e.timeoutLimit}isSupported(){return P(this.strategies,b.method("isSupported"))}connect(t,e){var n=this.strategies,i=0,s=this.timeout,r=null,o=(a,c)=>{c?e(null,c):(i+=1,this.loop&&(i%=n.length),i<n.length?(s&&(s*=2,this.timeoutLimit&&(s=Math.min(s,this.timeoutLimit))),r=this.tryStrategy(n[i],t,{timeout:s,failFast:this.failFast},o)):e(!0))};return r=this.tryStrategy(n[i],t,{timeout:s,failFast:this.failFast},o),{abort:function(){r.abort()},forceMinPriority:function(e){t=e,r&&r.forceMinPriority(e)}}}tryStrategy(t,e,n,i){var s=null,r=null;return n.timeout>0&&(s=new p(n.timeout,function(){r.abort(),i(!0)})),r=t.connect(e,function(t,e){t&&s&&s.isRunning()&&!n.failFast||(s&&s.ensureAborted(),i(t,e))}),{abort:function(){s&&s.ensureAborted(),r.abort()},forceMinPriority:function(t){r.forceMinPriority(t)}}}}class jt{constructor(t){this.strategies=t}isSupported(){return P(this.strategies,b.method("isSupported"))}connect(t,e){return function(t,n){var i=k(t,function(t,i,s,r){return t.connect(n,function(t,n){return function(i,s){n[t].error=i,i?function(t){return function(t,e){for(var n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0}(t,function(t){return Boolean(t.error)})}(n)&&e(!0):(w(n,function(t){t.forceMinPriority(s.transport.priority)}),e(null,s))}}(i,r))});return{abort:function(){w(i,Ht)},forceMinPriority:function(t){w(i,function(e){e.forceMinPriority(t)})}}}(this.strategies,t)}}function Ht(t){t.error||t.aborted||(t.abort(),t.aborted=!0)}class Mt{constructor(t,e,n){this.strategy=t,this.transports=e,this.ttl=n.ttl||18e5,this.usingTLS=n.useTLS,this.timeline=n.timeline}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.usingTLS,i=function(t){var e=ye.getLocalStorage();if(e)try{var n=e[zt(t)];if(n)return JSON.parse(n)}catch(e){Bt(t)}return null}(n),s=i&&i.cacheSkipCount?i.cacheSkipCount:0,r=[this.strategy];if(i&&i.timestamp+this.ttl>=b.now()){var o=this.transports[i.transport];o&&(["ws","wss"].includes(i.transport)||s>3?(this.timeline.info({cached:!0,transport:i.transport,latency:i.latency}),r.push(new Nt([o],{timeout:2*i.latency+1e3,failFast:!0}))):s++)}var a=b.now(),c=r.pop().connect(t,function i(o,h){o?(Bt(n),r.length>0?(a=b.now(),c=r.pop().connect(t,i)):e(o)):(function(t,e,n,i){var s=ye.getLocalStorage();if(s)try{s[zt(t)]=E({timestamp:b.now(),transport:e,latency:n,cacheSkipCount:i})}catch(t){}}(n,h.transport.name,b.now()-a,s),e(null,h))});return{abort:function(){c.abort()},forceMinPriority:function(e){t=e,c&&c.forceMinPriority(e)}}}}function zt(t){return"pusherTransport"+(t?"TLS":"NonTLS")}function Bt(t){var e=ye.getLocalStorage();if(e)try{delete e[zt(t)]}catch(t){}}class qt{constructor(t,{delay:e}){this.strategy=t,this.options={delay:e}}isSupported(){return this.strategy.isSupported()}connect(t,e){var n,i=this.strategy,s=new p(this.options.delay,function(){n=i.connect(t,e)});return{abort:function(){s.ensureAborted(),n&&n.abort()},forceMinPriority:function(e){t=e,n&&n.forceMinPriority(e)}}}}class Ft{constructor(t,e,n){this.test=t,this.trueBranch=e,this.falseBranch=n}isSupported(){return(this.test()?this.trueBranch:this.falseBranch).isSupported()}connect(t,e){return(this.test()?this.trueBranch:this.falseBranch).connect(t,e)}}class $t{constructor(t){this.strategy=t}isSupported(){return this.strategy.isSupported()}connect(t,e){var n=this.strategy.connect(t,function(t,i){i&&n.abort(),e(t,i)});return n}}function Jt(t){return function(){return t.isSupported()}}class Wt extends V{constructor(t,e,n){super(),this.hooks=t,this.method=e,this.url=n}start(t){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},ye.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(t)}close(){this.unloader&&(ye.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(t,e){for(;;){var n=this.advanceBuffer(e);if(!n)break;this.emit("chunk",{status:t,data:n})}this.isBufferTooLong(e)&&this.emit("buffer_too_long")}advanceBuffer(t){var e=t.slice(this.position),n=e.indexOf("\n");return-1!==n?(this.position+=n+1,e.slice(0,n)):null}isBufferTooLong(t){return this.position===t.length&&t.length>262144}}var Xt;!function(t){t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSED=3]="CLOSED"}(Xt||(Xt={}));const Gt=Xt;var Yt=1;function Kt(t){var e=-1===t.indexOf("?")?"?":"&";return t+e+"t="+ +new Date+"&n="+Yt++}function Qt(t){return ye.randomInt(t)}const Vt=class{constructor(t,e){this.hooks=t,this.session=Qt(1e3)+"/"+function(){for(var t=[],e=0;e<8;e++)t.push(Qt(32).toString(32));return t.join("")}(),this.location=function(t){var e=/([^\?]*)\/*(\??.*)/.exec(t);return{base:e[1],queryString:e[2]}}(e),this.readyState=Gt.CONNECTING,this.openStream()}send(t){return this.sendRaw(JSON.stringify([t]))}ping(){this.hooks.sendHeartbeat(this)}close(t,e){this.onClose(t,e,!0)}sendRaw(t){if(this.readyState!==Gt.OPEN)return!1;try{return ye.createSocketRequest("POST",Kt((e=this.location,n=this.session,e.base+"/"+n+"/xhr_send"))).start(t),!0}catch(t){return!1}var e,n}reconnect(){this.closeStream(),this.openStream()}onClose(t,e,n){this.closeStream(),this.readyState=Gt.CLOSED,this.onclose&&this.onclose({code:t,reason:e,wasClean:n})}onChunk(t){var e;if(200===t.status)switch(this.readyState===Gt.OPEN&&this.onActivity(),t.data.slice(0,1)){case"o":e=JSON.parse(t.data.slice(1)||"{}"),this.onOpen(e);break;case"a":e=JSON.parse(t.data.slice(1)||"[]");for(var n=0;n<e.length;n++)this.onEvent(e[n]);break;case"m":e=JSON.parse(t.data.slice(1)||"null"),this.onEvent(e);break;case"h":this.hooks.onHeartbeat(this);break;case"c":e=JSON.parse(t.data.slice(1)||"[]"),this.onClose(e[0],e[1],!0)}}onOpen(t){var e,n,i;this.readyState===Gt.CONNECTING?(t&&t.hostname&&(this.location.base=(e=this.location.base,n=t.hostname,(i=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(e))[1]+n+i[3])),this.readyState=Gt.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(t){this.readyState===Gt.OPEN&&this.onmessage&&this.onmessage({data:t})}onActivity(){this.onactivity&&this.onactivity()}onError(t){this.onerror&&this.onerror(t)}openStream(){this.stream=ye.createSocketRequest("POST",Kt(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",t=>{this.onChunk(t)}),this.stream.bind("finished",t=>{this.hooks.onFinished(this,t)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(t){b.defer(()=>{this.onError(t),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}},Zt={getReceiveURL:function(t,e){return t.base+"/"+e+"/xhr_streaming"+t.queryString},onHeartbeat:function(t){t.sendRaw("[]")},sendHeartbeat:function(t){t.sendRaw("[]")},onFinished:function(t,e){t.onClose(1006,"Connection interrupted ("+e+")",!1)}},te={getReceiveURL:function(t,e){return t.base+"/"+e+"/xhr"+t.queryString},onHeartbeat:function(){},sendHeartbeat:function(t){t.sendRaw("[]")},onFinished:function(t,e){200===e?t.reconnect():t.onClose(1006,"Connection interrupted ("+e+")",!1)}},ee={getRequest:function(t){var e=new(ye.getXHRAPI());return e.onreadystatechange=e.onprogress=function(){switch(e.readyState){case 3:e.responseText&&e.responseText.length>0&&t.onChunk(e.status,e.responseText);break;case 4:e.responseText&&e.responseText.length>0&&t.onChunk(e.status,e.responseText),t.emit("finished",e.status),t.close()}},e},abortRequest:function(t){t.onreadystatechange=null,t.abort()}};const ne={getDefaultStrategy:function(t,e,n){var i={};function s(e,s,r,o,a){var c=n(t,e,s,r,o,a);return i[e]=c,c}var r,o=Object.assign({},e,{hostNonTLS:t.wsHost+":"+t.wsPort,hostTLS:t.wsHost+":"+t.wssPort,httpPath:t.wsPath}),a=m({},o,{useTLS:!0}),c=Object.assign({},e,{hostNonTLS:t.httpHost+":"+t.httpPort,hostTLS:t.httpHost+":"+t.httpsPort,httpPath:t.httpPath}),h={loop:!0,timeout:15e3,timeoutLimit:6e4},u=new Ut({minPingDelay:1e4,maxPingDelay:t.activityTimeout}),l=new Ut({lives:2,minPingDelay:1e4,maxPingDelay:t.activityTimeout}),d=s("ws","ws",3,o,u),p=s("wss","ws",3,a,u),g=s("xhr_streaming","xhr_streaming",1,c,l),f=s("xhr_polling","xhr_polling",1,c),b=new Nt([d],h),v=new Nt([p],h),y=new Nt([g],h),S=new Nt([f],h),_=new Nt([new Ft(Jt(y),new jt([y,new qt(S,{delay:4e3})]),S)],h);return r=e.useTLS?new jt([b,new qt(_,{delay:2e3})]):new jt([b,new qt(v,{delay:2e3}),new qt(_,{delay:5e3})]),new Mt(new $t(new Ft(Jt(d),r,_)),i,{ttl:18e5,timeline:e.timeline,useTLS:e.useTLS})},Transports:at,transportConnectionInitializer:function(){var t=this;t.timeline.info(t.buildTimelineMessage({transport:t.name+(t.options.useTLS?"s":"")})),t.hooks.isInitialized()?t.changeState("initialized"):t.onClose()},HTTPFactory:{createStreamingSocket(t){return this.createSocket(Zt,t)},createPollingSocket(t){return this.createSocket(te,t)},createSocket:(t,e)=>new Vt(t,e),createXHR(t,e){return this.createRequest(ee,t,e)},createRequest:(t,e,n)=>new Wt(t,e,n)},setup(t){t.ready()},getLocalStorage(){},getClientFeatures:()=>_(T({ws:at.ws},function(t){return t.isSupported({})})),getProtocol:()=>"http:",isXHRSupported:()=>!0,createSocketRequest(t,e){if(this.isXHRSupported())return this.HTTPFactory.createXHR(t,e);throw"Cross-origin HTTP requests are not supported"},createXHR(){return new(this.getXHRAPI())},createWebSocket(t){return new(this.getWebSocketAPI())(t)},addUnloadListener(t){},removeUnloadListener(t){}};var ie=new class extends V{isOnline(){return!0}};const se=function(t,e,n,i,s){var r=new Headers;for(var o in r.set("Content-Type","application/x-www-form-urlencoded"),n.headers)r.set(o,n.headers[o]);if(null!=n.headersProvider){const t=n.headersProvider();for(var o in t)r.set(o,t[o])}var a=e,c=new Request(n.endpoint,{headers:r,body:a,credentials:"same-origin",method:"POST"});return fetch(c).then(t=>{let{status:e}=t;if(200===e)return t.text();throw new _t(e,`Could not get ${i.toString()} info from your auth endpoint, status: ${e}`)}).then(t=>{let e;try{e=JSON.parse(t)}catch(e){throw new _t(200,`JSON returned from ${i.toString()} endpoint was invalid, yet status code was 200. Data was: ${t}`)}s(null,e)}).catch(t=>{s(t,null)})},re={name:"xhr",getAgent:function(t,e){return function(n,i){var s="http"+(e?"s":"")+"://"+(t.host||t.options.host)+t.options.path,r=function(t){var e,n;return k((e=x(T(t,function(t){return void 0!==t})),n=[],S(e,function(t,e){n.push([e,t])}),n),b.method("join","=")).join("&")}(n);fetch(s+="/2?"+r).then(t=>{if(200!==t.status)throw`received ${t.status} from stats.pusher.com`;return t.json()}).then(({host:e})=>{e&&(t.host=e)}).catch(t=>{Z.debug("TimelineSender Error: ",t)})}}},{getDefaultStrategy:oe,Transports:ae,setup:ce,getProtocol:he,isXHRSupported:ue,getLocalStorage:le,createXHR:de,createWebSocket:pe,addUnloadListener:ge,removeUnloadListener:fe,transportConnectionInitializer:be,createSocketRequest:me,HTTPFactory:ve}=ne,ye={getDefaultStrategy:oe,Transports:ae,setup:ce,getProtocol:he,isXHRSupported:ue,getLocalStorage:le,createXHR:de,createWebSocket:pe,addUnloadListener:ge,removeUnloadListener:fe,transportConnectionInitializer:be,createSocketRequest:me,HTTPFactory:ve,TimelineTransport:re,getAuthorizers:()=>({ajax:se}),getWebSocketAPI:()=>WebSocket,getXHRAPI:()=>XMLHttpRequest,getNetwork:()=>ie,randomInt:t=>Math.floor((globalThis.crypto||globalThis.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)*t)};var Se;!function(t){t[t.ERROR=3]="ERROR",t[t.INFO=6]="INFO",t[t.DEBUG=7]="DEBUG"}(Se||(Se={}));const _e=Se;class we{constructor(t,e,n){this.key=t,this.session=e,this.events=[],this.options=n||{},this.sent=0,this.uniqueID=0}log(t,e){t<=this.options.level&&(this.events.push(m({},e,{timestamp:b.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(t){this.log(_e.ERROR,t)}info(t){this.log(_e.INFO,t)}debug(t){this.log(_e.DEBUG,t)}isEmpty(){return 0===this.events.length}send(t,e){var n=m({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],t(n,(t,n)=>{t||this.sent++,e&&e(t,n)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class ke{constructor(t,e,n,i){this.name=t,this.priority=e,this.transport=n,this.options=i||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(t,e){if(!this.isSupported())return Ce(new St,e);if(this.priority<t)return Ce(new bt,e);var n=!1,i=this.transport.createConnection(this.name,this.priority,this.options.key,this.options),s=null,r=function(){i.unbind("initialized",r),i.connect()},o=function(){s=Dt.createHandshake(i,function(t){n=!0,h(),e(null,t)})},a=function(t){h(),e(t)},c=function(){var t;h(),t=E(i),e(new mt(t))},h=function(){i.unbind("initialized",r),i.unbind("open",o),i.unbind("error",a),i.unbind("closed",c)};return i.bind("initialized",r),i.bind("open",o),i.bind("error",a),i.bind("closed",c),i.initialize(),{abort:()=>{n||(h(),s?s.close():i.close())},forceMinPriority:t=>{n||this.priority<t&&(s?s.close():i.close())}}}}function Ce(t,e){return b.defer(function(){e(t)}),{abort:function(){},forceMinPriority:function(){}}}const{Transports:Te}=ye;var Pe,xe=function(t,e,n,i,s,r){var o,a=Te[n];if(!a)throw new yt(n);return t.enabledTransports&&-1===y(t.enabledTransports,e)||t.disabledTransports&&-1!==y(t.disabledTransports,e)?o=Ee:(s=Object.assign({ignoreNullOrigin:t.ignoreNullOrigin},s),o=new ke(e,i,r?r.getAssistant(a):a,s)),o},Ee={isSupported:function(){return!1},connect:function(t,e){var n=b.defer(function(){e(new St)});return{abort:function(){n.ensureAborted()},forceMinPriority:function(){}}}};!function(t){t.UserAuthentication="user-authentication",t.ChannelAuthorization="channel-authorization"}(Pe||(Pe={}));const Oe=(t,e,n)=>{const i={authTransport:e.transport,authEndpoint:e.endpoint,auth:{params:e.params,headers:e.headers}};return(e,s)=>{const r=t.channel(e.channelName);n(r,i).authorize(e.socketId,s)}};function Le(t,e){let n={activityTimeout:t.activityTimeout||B,cluster:t.cluster,httpPath:t.httpPath||j,httpPort:t.httpPort||U,httpsPort:t.httpsPort||N,pongTimeout:t.pongTimeout||q,statsHost:t.statsHost||H,unavailableTimeout:t.unavailableTimeout||F,wsPath:t.wsPath||I,wsPort:t.wsPort||A,wssPort:t.wssPort||R,enableStats:De(t),httpHost:Ae(t),useTLS:Ie(t),wsHost:Re(t),userAuthenticator:Ne(t),channelAuthorizer:je(t,e)};return"disabledTransports"in t&&(n.disabledTransports=t.disabledTransports),"enabledTransports"in t&&(n.enabledTransports=t.enabledTransports),"ignoreNullOrigin"in t&&(n.ignoreNullOrigin=t.ignoreNullOrigin),"timelineParams"in t&&(n.timelineParams=t.timelineParams),"nacl"in t&&(n.nacl=t.nacl),n}function Ae(t){return t.httpHost?t.httpHost:t.cluster?`sockjs-${t.cluster}.pusher.com`:D}function Re(t){return t.wsHost?t.wsHost:`ws-${t.cluster}.pusher.com`}function Ie(t){return"https:"===ye.getProtocol()||!1!==t.forceTLS}function De(t){return"enableStats"in t?t.enableStats:"disableStats"in t&&!t.disableStats}const Ue=t=>"customHandler"in t&&null!=t.customHandler;function Ne(t){const e=Object.assign(Object.assign({},$),t.userAuthentication);return Ue(e)?e.customHandler:(t=>{if(void 0===ye.getAuthorizers()[t.transport])throw`'${t.transport}' is not a recognized auth transport`;return(e,n)=>{const i=((t,e)=>{var n="socket_id="+encodeURIComponent(t.socketId);for(var i in e.params)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e.params[i]);if(null!=e.paramsProvider){let t=e.paramsProvider();for(var i in t)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(t[i])}return n})(e,t);ye.getAuthorizers()[t.transport](ye,i,t,Pe.UserAuthentication,n)}})(e)}function je(t,e){const n=function(t,e){let n;if("channelAuthorization"in t)n=Object.assign(Object.assign({},J),t.channelAuthorization);else if(n={transport:t.authTransport||z,endpoint:t.authEndpoint||M},"auth"in t&&("params"in t.auth&&(n.params=t.auth.params),"headers"in t.auth&&(n.headers=t.auth.headers)),"authorizer"in t)return{customHandler:Oe(e,n,t.authorizer)};return n}(t,e);return Ue(n)?n.customHandler:(t=>{if(void 0===ye.getAuthorizers()[t.transport])throw`'${t.transport}' is not a recognized auth transport`;return(e,n)=>{const i=((t,e)=>{var n="socket_id="+encodeURIComponent(t.socketId);for(var i in n+="&channel_name="+encodeURIComponent(t.channelName),e.params)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(e.params[i]);if(null!=e.paramsProvider){let t=e.paramsProvider();for(var i in t)n+="&"+encodeURIComponent(i)+"="+encodeURIComponent(t[i])}return n})(e,t);ye.getAuthorizers()[t.transport](ye,i,t,Pe.ChannelAuthorization,n)}})(n)}class He extends V{constructor(t){super(function(t,e){Z.debug(`No callbacks on watchlist events for ${t}`)}),this.pusher=t,this.bindWatchlistInternalEvent()}handleEvent(t){t.data.events.forEach(t=>{this.emit(t.name,t)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",t=>{"pusher_internal:watchlist_events"===t.event&&this.handleEvent(t)})}}class Me extends V{constructor(t){super(function(t,e){Z.debug("No callbacks on user for "+t)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(t,e)=>{if(t)return Z.warn(`Error during signin: ${t}`),void this._cleanup();this.pusher.send_event("pusher:signin",{auth:e.auth,user_data:e.user_data})},this.pusher=t,this.pusher.connection.bind("state_change",({previous:t,current:e})=>{"connected"!==t&&"connected"===e&&this._signin(),"connected"===t&&"connected"!==e&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new He(t),this.pusher.connection.bind("message",t=>{"pusher:signin_success"===t.event&&this._onSigninSuccess(t.data),this.serverToUserChannel&&this.serverToUserChannel.name===t.channel&&this.serverToUserChannel.handleEvent(t)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),"connected"===this.pusher.connection.state&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(t){try{this.user_data=JSON.parse(t.user_data)}catch(e){return Z.error(`Failed parsing user data after signin: ${t.user_data}`),void this._cleanup()}if("string"!=typeof this.user_data.id||""===this.user_data.id)return Z.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),void this._cleanup();this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){this.serverToUserChannel=new Ct(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((t,e)=>{0!==t.indexOf("pusher_internal:")&&0!==t.indexOf("pusher:")&&this.emit(t,e)}),(t=>{t.subscriptionPending&&t.subscriptionCancelled?t.reinstateSubscription():t.subscriptionPending||"connected"!==this.pusher.connection.state||t.subscribe()})(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested)return;if(this.si