/*! * @license Copyright 2021, Ably * * Ably JavaScript Library v1.2.14 * https://github.com/ably/ably-js * * Ably Realtime Messaging * https://www.ably.com * * Released under the Apache Licence v2.0 */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Ably=t():e.Ably=t()}(window,(function(){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=50)}([function(e,t,n){"use strict";(function(e){var i=n(3),r=function(){var t,n;function r(e,t){return("000"+e).slice(-2-(t||0))}"undefined"==typeof Window&&"undefined"==typeof WorkerGlobalScope||e.console&&e.console.log&&"function"==typeof e.console.log.apply?(t=function(){console.log.apply(console,arguments)},n=console.warn?function(){console.warn.apply(console,arguments)}:t):t=n=e.console&&e.console.log?function(){Function.prototype.apply.call(console.log,console,arguments)}:function(){};var o=1;function s(e){return i.a.logTimestamps?function(t){var n=new Date;e(r(n.getHours())+":"+r(n.getMinutes())+":"+r(n.getSeconds())+"."+r(n.getMilliseconds(),!0)+" "+t)}:e}var a=s(t),c=s(n);function u(e){}return u.LOG_NONE=0,u.LOG_ERROR=1,u.LOG_MAJOR=2,u.LOG_MINOR=3,u.LOG_MICRO=4,u.LOG_DEFAULT=1,u.LOG_DEBUG=4,u.logAction=function(e,t,n){u.shouldLog(e)&&(1===e?c:a)("Ably: "+t+": "+n)},u.deprecated=function(e,t){u.deprecatedWithMsg(e,"Please use '"+t+"' instead.")},u.deprecatedWithMsg=function(e,t){u.shouldLog(1)&&c("Ably: Deprecation warning - '"+e+"' is deprecated and will be removed from a future version. "+t)},u.shouldLog=function(e){return e<=o},u.setLog=function(e,t){void 0!==e&&(o=e),void 0!==t&&(a=c=t)},u}();t.a=r}).call(this,n(17))},function(e,t,n){"use strict";var i=n(3),r=n(4),o=n(5),s=Object.prototype.hasOwnProperty,a=function(){var e=i.a.msgpack;function t(){}function n(e){return Math.floor(Math.random()*e.length)}t.mixin=function(e){for(var t=1;t-1||(e+="; see "+this.href+" "),e+="]"},e.fromValues=function(t){var n=i.a.mixin(new e,t);return t instanceof Error&&(n.message=t.message),n.code&&!n.href&&(n.href="https://help.ably.io/error/"+n.code),n},e}();t.a=r},function(e,t,n){"use strict";(function(e,i){var r=n(24);"undefined"==typeof Window&&"undefined"==typeof WorkerGlobalScope&&console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var o,s=e.navigator&&e.navigator.userAgent.toString(),a={agent:"browser",logTimestamps:!0,userAgent:s,currentUrl:e.location&&e.location.href,noUpgrade:s&&s.match(/MSIE\s8\.0/),binaryType:"arraybuffer",WebSocket:e.WebSocket||e.MozWebSocket,xhrSupported:e.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,jsonpSupported:"undefined"!=typeof document,allowComet:(o=e.location,!e.WebSocket||!o||!o.origin||o.origin.indexOf("http")>-1),streamingSupported:!0,useProtocolHeartbeats:!0,createHmac:null,msgpack:r.a,supportsBinary:!!e.TextDecoder,preferBinary:!1,ArrayBuffer:e.ArrayBuffer,atob:e.atob,nextTick:void 0!==i?e.setImmediate.bind(e):function(e){setTimeout(e,0)},addEventListener:e.addEventListener,inspect:JSON.stringify,stringByteSize:function(t){return e.TextDecoder&&(new e.TextEncoder).encode(t).length||t.length},TextEncoder:e.TextEncoder,TextDecoder:e.TextDecoder,Promise:e.Promise,getRandomValues:function(e){if(void 0!==e)return function(t,n){e.getRandomValues(t),n&&n(null)}}(e.crypto||e.msCrypto)};t.a=a}).call(this,n(17),n(42).setImmediate)},function(e,t,n){"use strict";var i=n(3),r={internetUpUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",jsonpInternetUpUrl:"https://internet-up.ably-realtime.com/is-the-internet-up-0-9.js",defaultTransports:["xhr_polling","xhr_streaming","jsonp","web_socket"],baseTransportOrder:["xhr_polling","xhr_streaming","jsonp","web_socket"],transportPreferenceOrder:["jsonp","xhr_polling","xhr_streaming","web_socket"],upgradeTransports:["xhr_streaming","web_socket"]};i.a.noUpgrade&&(r.upgradeTransports=[]);var o=r,s=n(1),a=n(5),c=n(0),u=n(2);o.ENVIRONMENT="",o.REST_HOST="rest.ably.io",o.REALTIME_HOST="realtime.ably.io",o.FALLBACK_HOSTS=["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"],o.PORT=80,o.TLS_PORT=443,o.TIMEOUTS={disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,preferenceConnectTimeout:6e3,parallelUpgradeDelay:6e3},o.httpMaxRetryCount=3,o.maxMessageSize=65536,o.errorReportingUrl="https://errors.ably.io/api/15/store/",o.errorReportingHeaders={"X-Sentry-Auth":"Sentry sentry_version=7, sentry_key=a04e33c8674c451f8a310fbec029acf5, sentry_client=ably-js/0.1","Content-Type":"application/json"},o.version="1.2.14",o.apiVersion="1.2";var l="ably-js/"+o.version;function h(e){if("string"!=typeof e)throw new u.a("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new u.a("host must not be zero-length",4e4,400)}i.a.agent&&(l+=" "+i.a.agent),o.agent=l,o.getHost=function(e,t,n){return t=n?t==e.restHost&&e.realtimeHost||t||e.realtimeHost:t||e.restHost},o.getPort=function(e,t){return t||e.tls?e.tlsPort:e.port},o.getHttpScheme=function(e){return e.tls?"https://":"http://"},o.environmentFallbackHosts=function(e){return[e+"-a-fallback.ably-realtime.com",e+"-b-fallback.ably-realtime.com",e+"-c-fallback.ably-realtime.com",e+"-d-fallback.ably-realtime.com",e+"-e-fallback.ably-realtime.com"]},o.getFallbackHosts=function(e){var t=e.fallbackHosts,n=void 0!==e.httpMaxRetryCount?e.httpMaxRetryCount:o.httpMaxRetryCount;return t?s.a.arrChooseN(t,n):[]},o.getHosts=function(e){return[e.restHost].concat(o.getFallbackHosts(e))},o.objectifyOptions=function(e){return"string"==typeof e?-1==e.indexOf(":")?{token:e}:{key:e}:e},o.normaliseOptions=function(e){if(e.host&&(c.a.deprecated("host","restHost"),e.restHost=e.host),e.wsHost&&(c.a.deprecated("wsHost","realtimeHost"),e.realtimeHost=e.wsHost),e.queueEvents&&(c.a.deprecated("queueEvents","queueMessages"),e.queueMessages=e.queueEvents),e.fallbackHostsUseDefault){if(e.fallbackHosts){var t="fallbackHosts and fallbackHostsUseDefault cannot both be set";throw c.a.logAction(c.a.LOG_ERROR,"Defaults.normaliseOptions",t),new u.a(t,4e4,400)}if(e.port||e.tlsPort){t="fallbackHostsUseDefault cannot be set when port or tlsPort are set";throw c.a.logAction(c.a.LOG_ERROR,"Defaults.normaliseOptions",t),new u.a(t,4e4,400)}e.environment?c.a.deprecatedWithMsg("fallbackHostsUseDefault","There is no longer a need to set this when the environment option is also set since the library will now generate the correct fallback hosts using the environment option."):c.a.deprecated("fallbackHostsUseDefault","fallbackHosts: Ably.Defaults.FALLBACK_HOSTS"),e.fallbackHosts=o.FALLBACK_HOSTS}!0===e.recover&&(c.a.deprecated("{recover: true}","{recover: function(lastConnectionDetails, cb) { cb(true); }}"),e.recover=function(e,t){t(!0)}),"function"==typeof e.recover&&!0===e.closeOnUnload&&(c.a.logAction(c.a.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),e.recover=null),"closeOnUnload"in e||(e.closeOnUnload=!e.recover),e.transports&&s.a.arrIn(e.transports,"xhr")&&(c.a.deprecated('transports: ["xhr"]','transports: ["xhr_streaming"]'),s.a.arrDeleteValue(e.transports,"xhr"),e.transports.push("xhr_streaming")),"queueMessages"in e||(e.queueMessages=!0);var n=e.environment&&String(e.environment).toLowerCase()||o.ENVIRONMENT,r=!n||"production"===n;for(var l in e.fallbackHosts||e.restHost||e.realtimeHost||e.port||e.tlsPort||(e.fallbackHosts=r?o.FALLBACK_HOSTS:o.environmentFallbackHosts(n)),e.realtimeHost||(e.restHost?(c.a.logAction(c.a.LOG_WARN,"Defaults.normaliseOptions",'restHost is set to "'+e.restHost+'" but realtimeHost is not set, so setting realtimeHost to "'+e.restHost+'" too. If this is not what you want, please set realtimeHost explicitly.'),e.realtimeHost=e.restHost):e.realtimeHost=r?o.REALTIME_HOST:n+"-"+o.REALTIME_HOST),e.restHost||(e.restHost=r?o.REST_HOST:n+"-"+o.REST_HOST),s.a.arrForEach((e.fallbackHosts||[]).concat(e.restHost,e.realtimeHost),h),e.port=e.port||o.PORT,e.tlsPort=e.tlsPort||o.TLS_PORT,e.maxMessageSize=e.maxMessageSize||o.maxMessageSize,"tls"in e||(e.tls=!0),e.timeouts={},o.TIMEOUTS)e.timeouts[l]=e[l]||o.TIMEOUTS[l];(e.useBinaryProtocol="useBinaryProtocol"in e?i.a.supportsBinary&&e.useBinaryProtocol:i.a.preferBinary,e.clientId)&&((e.headers=e.headers||{})["X-Ably-ClientId"]=a.a.base64Encode(a.a.utf8Encode(e.clientId)));if("idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0),e.promises&&!i.a.Promise&&(c.a.logAction(c.a.LOG_ERROR,"Defaults.normaliseOptions","{promises: true} was specified, but no Promise constructor found; disabling promises"),e.promises=!1),e.agents)for(var p in e.agents)o.agent+=" "+p+"/"+e.agents[p];return e};t.a=o},function(e,t,n){"use strict";var i=n(32),r=n(33),o=n(18),s=n(10),a=n.n(s),c=n(3),u=function(){var e=c.a.ArrayBuffer,t=c.a.atob,n=c.a.TextEncoder,s=c.a.TextDecoder,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function l(e){return null!=e&&void 0!==e.sigBytes}function h(t){return null!=t&&t.constructor===e}function p(t){return e&&e.isView&&e.isView(t)}function f(){}f.base64CharSet=u,f.hexCharSet="0123456789abcdef";var d=f.isBuffer=function(e){return h(e)||l(e)||p(e)},g=f.toBuffer=function(t){if(!e)throw new Error("Can't convert to Buffer: browser does not support the necessary types");if(h(t))return new Uint8Array(t);if(p(t))return new Uint8Array(t.buffer);if(l(t)){for(var n=new e(t.sigBytes),i=new Uint8Array(n),r=0;r>>2]>>>24-r%4*8&255;return i}throw new Error("BufferUtils.toBuffer expected an arraybuffer, typed array, or CryptoJS wordarray")};return f.toArrayBuffer=function(e){return h(e)?e:g(e).buffer},f.toWordArray=function(e){return p(e)&&(e=e.buffer),l(e)?e:a.a.create(e)},f.base64Encode=function(e){return l(e)?Object(o.stringify)(e):function(e){for(var t,n="",i=u,r=e.byteLength,o=r%3,s=r-o,a=0;a>18]+i[(258048&t)>>12]+i[(4032&t)>>6]+i[63&t];return 1==o?n+=i[(252&(t=e[s]))>>2]+i[(3&t)<<4]+"==":2==o&&(n+=i[(64512&(t=e[s]<<8|e[s+1]))>>10]+i[(1008&t)>>4]+i[(15&t)<<2]+"="),n}(g(e))},f.base64Decode=function(n){return e&&t?function(e){for(var n=t(e),i=n.length,r=new Uint8Array(i),o=0;o=500&&t<=504}function s(e){var t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(r.a.getFallbackHosts(e.options)):r.a.getHosts(e.options)}return t._getHosts=s,t.methods=["get","delete","post","put","patch"],t.methodsWithoutBody=["get","delete"],t.methodsWithBody=i.a.arrSubtract(t.methods,t.methodsWithoutBody),i.a.arrForEach(t.methodsWithoutBody,(function(e){t[e]=function(n,i,r,o,s){t.do(e,n,i,r,null,o,s)},t[e+"Uri"]=function(n,i,r,o,s){t.doUri(e,n,i,r,null,o,s)}})),i.a.arrForEach(t.methodsWithBody,(function(e){t[e]=function(n,i,r,o,s,a){t.do(e,n,i,r,o,s,a)},t[e+"Uri"]=function(n,i,r,o,s,a){t.doUri(e,n,i,r,o,s,a)}})),t.do=function(i,r,a,c,u,l,h){h=h||e;var p="function"==typeof a?a:function(e){return r.baseUri(e)+a},f=(c&&c.accept,arguments),d=r._currentFallback;if(d){if(d.validUntil>n())return void t.Request(i,r,p(d.host),c,l,u,(function(e){if(e&&o(e))return r._currentFallback=null,void t.do.apply(t,f);h.apply(null,arguments)}));r._currentFallback=null}var g=s(r);if(1!=g.length){var m=function(e,s){var a=e.shift();t.doUri(i,r,p(a),c,u,l,(function(t){t&&o(t)&&e.length?m(e,!0):(s&&(r._currentFallback={host:a,validUntil:n()+r.options.timeouts.fallbackRetryTimeout}),h.apply(null,arguments))}))};m(g)}else t.doUri(i,r,p(g[0]),c,u,l,h)},t.doUri=function(e,n,i,r,o,s,a){t.Request(e,n,i,r,s,o,a)},t.supportsAuthHeaders=!1,t.supportsLinkHeaders=!1,t}();t.a=o},function(e,t,n){"use strict";var i=n(1),r=n(0),o=n(3),s=Object.prototype.hasOwnProperty,a=function(){function e(){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}function t(e,t,n){try{t.apply(e,n)}catch(e){r.a.logAction(r.a.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+e+"; stack = "+(e&&e.stack))}}function n(e,t,r){var o,a,c,u;for(u=0;u0},e.prototype.setFlag=function(e){return this.flags=this.flags|n[e]},e.prototype.getMode=function(){return this.flags&&this.flags&n.MODE_ALL},e.prototype.encodeModesToFlags=function(e){var t=this;i.a.arrForEach(e,(function(e){t.setFlag(e)}))},e.prototype.decodeModesFromFlags=function(){var t=[],n=this;return i.a.arrForEach(e.channelModes,(function(e){n.hasFlag(e)&&t.push(e)})),t.length>0?t:void 0},e.serialize=i.a.encodeBody,e.deserialize=function(t,n){var r=i.a.decodeBody(t,n);return e.fromDeserialized(r)},e.fromDeserialized=function(t){var n=t.error;n&&(t.error=r.a.fromValues(n));var a=t.messages;if(a)for(var c=0;c0&&(p+="; "),p+=e+"="+t.params[e]})),p.length>0&&(l+="; params=["+p+"]")}return l+="]"},e.isDuplicate=function(e,n){if(e&&n&&(e.action===t.MESSAGE||e.action===t.PRESENCE)&&e.action===n.action&&e.channel===n.channel&&e.id===n.id){if(e.action===t.PRESENCE)return!0;if(e.messages.length===n.messages.length){for(var i=0;i0){var n=this.encoding;e.encoding=n?n+"/base64":"base64",t=i.a.base64Encode(t)}else t=i.a.toBuffer(t);return e.data=t,e},e.prototype.toString=function(){var e="[Message";return this.name&&(e+="; name="+this.name),this.id&&(e+="; id="+this.id),this.timestamp&&(e+="; timestamp="+this.timestamp),this.clientId&&(e+="; clientId="+this.clientId),this.connectionId&&(e+="; connectionId="+this.connectionId),this.encoding&&(e+="; encoding="+this.encoding),this.extras&&(e+="; extras ="+JSON.stringify(this.extras)),this.data&&("string"==typeof this.data?e+="; data="+this.data:i.a.isBuffer(this.data)?e+="; data (buffer)="+i.a.base64Encode(this.data):e+="; data (json)="+JSON.stringify(this.data)),this.extras&&(e+="; extras="+JSON.stringify(this.extras)),e+="]"},e.encrypt=function(e,t,n){var r=e.data,o=e.encoding,s=t.channelCipher;o=o?o+"/":"",i.a.isBuffer(r)||(r=i.a.utf8Encode(String(r)),o+="utf-8/"),s.encrypt(r,(function(t,i){t?n(t):(e.data=i,e.encoding=o+"cipher+"+s.algorithm,n(null,e))}))},e.encode=function(t,n,o){var s,c=t.data;if(!("string"==typeof c||i.a.isBuffer(c)||null==c)){if(!r.a.isObject(c)&&!r.a.isArray(c))throw new a.a("Data type is unsupported",40013,400);t.data=JSON.stringify(c),t.encoding=(s=t.encoding)?s+"/json":"json"}null!=n&&n.cipher?e.encrypt(t,n,o):o(null,t)},e.encodeArray=function(t,n,i){for(var r=0,o=0;o0;){var l=s[--c].match(/([\-\w]+)(\+([\w\-]+))?/);if(!l)break;var h=l[1];switch(h){case"base64":u=i.a.base64Decode(String(u)),o==s.length&&(n=u);continue;case"utf-8":u=i.a.utf8Decode(u);continue;case"json":u=JSON.parse(u);continue;case"cipher":if(null!=t.channelOptions&&t.channelOptions.cipher){var p=l[3],f=t.channelOptions.channelCipher;if(p!=f.algorithm)throw new Error("Unable to decrypt message with given cipher; incompatible cipher params");u=f.decrypt(u);continue}throw new Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!t.plugins||!t.plugins.vcdiff)throw new a.a("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new a.a("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{var d=t.baseEncodedPreviousPayload;"string"==typeof d&&(d=i.a.utf8Encode(d)),d=i.a.toBuffer(d),u=i.a.toBuffer(u),n=u=i.a.typedArrayToBuffer(t.plugins.vcdiff.decode(u,d))}catch(e){throw new a.a("Vcdiff delta decode failed with "+e,40018,400)}continue;default:throw new Error("Unknown encoding")}break}}catch(e){throw new a.a("Error processing the "+h+" encoding, decoder returned ‘"+e.message+"’",e.code||40013,400)}finally{e.encoding=o<=0?null:s.slice(0,o).join("/"),e.data=u}}t.baseEncodedPreviousPayload=n},e.fromResponseBody=function(t,n,i){i&&(t=r.a.decodeBody(t,i));for(var s=0;s>>2]|=e[r]<<24-r%4*8;t.call(this,i,n)}else t.apply(this,arguments)}).prototype=e}}(),i.lib.WordArray)},function(e,t,n){"use strict";var i=n(3),r=n(0),o=n(5),s=n(9),a=n(1),c=function(){i.a.msgpack;function e(e){return a.a.arrIndexOf(t.Actions,e)}function t(){this.action=void 0,this.id=void 0,this.timestamp=void 0,this.clientId=void 0,this.connectionId=void 0,this.data=void 0,this.encoding=void 0,this.size=void 0}return t.Actions=["absent","present","enter","leave","update"],t.prototype.isSynthesized=function(){return this.id.substring(this.connectionId.length,0)!==this.connectionId},t.prototype.parseId=function(){var e=this.id.split(":");return{connectionId:e[0],msgSerial:parseInt(e[1],10),index:parseInt(e[2],10)}},t.prototype.toJSON=function(){var t={clientId:this.clientId,action:e(this.action),encoding:this.encoding},n=this.data;if(n&&o.a.isBuffer(n))if(arguments.length>0){var i=this.encoding;t.encoding=i?i+"/base64":"base64",n=o.a.base64Encode(n)}else n=o.a.toBuffer(n);return t.data=n,t},t.prototype.toString=function(){var e="[PresenceMessage";return e+="; action="+this.action,this.id&&(e+="; id="+this.id),this.timestamp&&(e+="; timestamp="+this.timestamp),this.clientId&&(e+="; clientId="+this.clientId),this.connectionId&&(e+="; connectionId="+this.connectionId),this.encoding&&(e+="; encoding="+this.encoding),this.data&&("string"==typeof this.data?e+="; data="+this.data:o.a.isBuffer(this.data)?e+="; data (buffer)="+o.a.base64Encode(this.data):e+="; data (json)="+JSON.stringify(this.data)),e+="]"},t.encode=s.a.encode,t.decode=s.a.decode,t.fromResponseBody=function(e,n,i){i&&(e=a.a.decodeBody(e,i));for(var o=0;o>>2]>>>24-o%4*8&255;t[i+o>>>2]|=s<<24-(i+o)%4*8}else for(o=0;o>>2]=n[o>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=u.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n>>2]>>>24-r%4*8&255;i.push((o>>>4).toString(16)),i.push((15&o).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,n=[],i=0;i>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new l.init(n,t/2)}},f=h.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,i=[],r=0;r>>2]>>>24-r%4*8&255;i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var t=e.length,n=[],i=0;i>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new l.init(n,t)}},d=h.Utf8={stringify:function(e){try{return decodeURIComponent(escape(f.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return f.parse(unescape(encodeURIComponent(e)))}},g=c.BufferedBlockAlgorithm=u.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=d.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n,i=this._data,r=i.words,o=i.sigBytes,s=this.blockSize,a=o/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,u=e.min(4*c,o);if(c){for(var h=0;h=500)return!0;var t=!1;return r.a.valuesArray(o).forEach((function(n){n.code&&n.code==e.code&&(t=!0)})),t}};t.a=o},function(e,t,n){"use strict";var i=n(0),r=n(3),o=n(1),s=n(6),a=n(22),c=n(5),u=n(2),l=function(){function e(){this.buffer=[]}e.prototype.append=function(e){return this.buffer.push(e),this},e.prototype.toString=function(){return this.buffer.join("")};var t={codex:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(i){for(var r=new e,o=t.codex,s=new n(i);s.moveNext();){var a=s.current;s.moveNext();var c=s.current;s.moveNext();var u=s.current,l=a>>2,h=(3&a)<<4|c>>4,p=(15&c)<<2|u>>6,f=63&u;isNaN(c)?p=f=64:isNaN(u)&&(f=64),r.append(o.charAt(l)+o.charAt(h)+o.charAt(p)+o.charAt(f))}return r.toString()},decode:function(t){for(var n=new e,r=new i(t);r.moveNext();){var o=r.current;if(o<128)n.append(String.fromCharCode(o));else if(o>191&&o<224){r.moveNext();var s=r.current;n.append(String.fromCharCode((31&o)<<6|63&s))}else{r.moveNext();s=r.current;r.moveNext();var a=r.current;n.append(String.fromCharCode((15&o)<<12|(63&s)<<6|63&a))}}return n.toString()}};function n(e){this._input=e,this._index=-1,this._buffer=[]}function i(e){this._input=e,this._index=-1,this._buffer=[]}return n.prototype={current:Number.NaN,moveNext:function(){if(this._buffer.length>0)return this.current=this._buffer.shift(),!0;if(this._index>=this._input.length-1)return this.current=Number.NaN,!1;var e=this._input.charCodeAt(++this._index);return 13==e&&10==this._input.charCodeAt(this._index+1)&&(e=10,this._index+=2),e<128?this.current=e:e>127&&e<2048?(this.current=e>>6|192,this._buffer.push(63&e|128)):(this.current=e>>12|224,this._buffer.push(e>>6&63|128),this._buffer.push(63&e|128)),!0}},i.prototype={current:64,moveNext:function(){if(this._buffer.length>0)return this.current=this._buffer.shift(),!0;if(this._index>=this._input.length-1)return this.current=64,!1;var e=t.codex.indexOf(this._input.charAt(++this._index)),n=t.codex.indexOf(this._input.charAt(++this._index)),i=t.codex.indexOf(this._input.charAt(++this._index)),r=t.codex.indexOf(this._input.charAt(++this._index)),o=e<<2|n>>4,s=(15&n)<<4|i>>2,a=(3&i)<<6|r;return this.current=o,64!=i&&this._buffer.push(s),64!=r&&this._buffer.push(a),!0}},t}(),h=n(38),p=n.n(h),f=n(18),d=function(){var e,t,n=Math.pow(2,17);function h(){}function d(){return("000000"+Math.floor(1e16*Math.random())).slice(-16)}function g(e){return o.a.isErrorInfo(e)?(e.code||(403===e.statusCode?e.code=40300:(e.code=40170,e.statusCode=401)),e):new u.a(o.a.inspectError(e),e.code||40170,e.statusCode||401)}function m(e){if(!e)return"";"string"==typeof e&&(e=JSON.parse(e));var t=Object.create(null),n=o.a.keysArray(e,!0);if(!n)return"";n.sort();for(var i=0;i-1){var f=o.a.parseQueryString(t.authUrl.slice(p));t.authUrl=t.authUrl.slice(0,p),t.authParams=o.a.mixin(f,t.authParams)}}var d=o.a.mixin({},t.authParams||{},e),g=function(e,t,s,a){var l;if(e?i.a.logAction(i.a.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+o.a.inspectError(e)):(l=s["content-type"],i.a.logAction(i.a.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+l+"; body: "+o.a.inspectBody(t))),e||a)return r(e,t);if(c.a.isBuffer(t)&&(t=t.toString()),l){var h=l.indexOf("application/json")>-1,p=l.indexOf("text/plain")>-1||l.indexOf("application/jwt")>-1;if(h||p){if(h){if(t.length>n)return void r(new u.a("authUrl response exceeded max permitted length",40170,401));try{t=JSON.parse(t)}catch(e){return void r(new u.a("Unexpected error processing authURL response; err = "+e.message,40170,401))}}r(null,t,l)}else r(new u.a("authUrl responded with unacceptable content-type "+l+", should be either text/plain, application/jwt or application/json",40170,401))}else r(new u.a("authUrl response is missing a content-type header",40170,401))};if(i.a.logAction(i.a.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+t.authUrl+"; Params: "+JSON.stringify(d)+"; method: "+(h?"POST":"GET")),h){var m=a||{};m["content-type"]="application/x-www-form-urlencoded";var y=o.a.toQueryString(d).slice(1);s.a.postUri(l,t.authUrl,m,y,{},g)}else s.a.getUri(l,t.authUrl,a||{},d,g)};else{if(!t.key){var p="Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)";return i.a.logAction(i.a.LOG_ERROR,"Auth()","library initialized with a token literal without any way to renew the token when it expires (no authUrl, authCallback, or key). See https://help.ably.io/error/40171 for help"),void r(new u.a(p,40171,403))}var f=this;i.a.logAction(i.a.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),a=function(e,n){f.createTokenRequest(e,t,n)}}"capability"in e&&(e.capability=m(e.capability));var d=function(e,n){var r="/keys/"+e.keyName+"/requestToken",a=o.a.defaultPostHeaders();t.requestHeaders&&o.a.mixin(a,t.requestHeaders),i.a.logAction(i.a.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+r+"; Token params: "+JSON.stringify(e)),e=JSON.stringify(e),s.a.post(l,(function(e){return l.baseUri(e)+r}),a,e,null,n)},y=!1,v=this.client.options.timeouts.realtimeRequestTimeout,O=setTimeout((function(){y=!0;var e="Token request callback timed out after "+v/1e3+" seconds";i.a.logAction(i.a.LOG_ERROR,"Auth.requestToken()",e),r(new u.a(e,40170,401))}),v);a(e,(function(e,s,a){if(!y){if(clearTimeout(O),e)return i.a.logAction(i.a.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+o.a.inspectError(e)),void r(g(e));if("string"!=typeof s){if("object"!=typeof s){var c="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof s;return i.a.logAction(i.a.LOG_ERROR,"Auth.requestToken()",c),void r(new u.a(c,40170,401))}var l=JSON.stringify(s).length;if(l>n&&!t.suppressMaxLengthCheck)r(new u.a("Token request/details object exceeded max permitted stringified size (was "+l+" bytes)",40170,401));else if("issued"in s)r(null,s);else{if(!("keyName"in s)){c="Expected token request callback to call back with a token string, token request object, or token details object";return i.a.logAction(i.a.LOG_ERROR,"Auth.requestToken()",c),void r(new u.a(c,40170,401))}d(s,(function(e,t,n,s){if(e)return i.a.logAction(i.a.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+o.a.inspectError(e)),void r(g(e));s||(t=JSON.parse(t)),i.a.logAction(i.a.LOG_MINOR,"Auth.getToken()","token received"),r(null,t)}))}}else 0===s.length?r(new u.a("Token string is empty",40170,401)):s.length>n?r(new u.a("Token string exceeded max permitted length (was "+s.length+" bytes)",40170,401)):"undefined"===s||"null"===s?r(new u.a("Token string was literal null/undefined",40170,401)):"{"!==s[0]||a&&a.indexOf("application/jwt")>-1?r(null,{token:s}):r(new u.a("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401))}}))},O.prototype.createTokenRequest=function(t,n,r){if("function"!=typeof t||r?"function"!=typeof n||r||(r=n,n=null):(r=t,n=t=null),!r&&this.client.options.promises)return o.a.promisify(this,"createTokenRequest",arguments);n=n||this.authOptions,t=t||o.a.copy(this.tokenParams);var s=n.key;if(s){var a=s.split(":"),c=a[0],l=a[1];if(l)if(""!==t.clientId){"capability"in t&&(t.capability=m(t.capability));var h,p=o.a.mixin({keyName:c},t),f=t.clientId||"",g=t.ttl||"",y=t.capability||"",v=this;h=function(){var t=p.nonce||(p.nonce=d()),n=p.timestamp,o=p.keyName+"\n"+g+"\n"+y+"\n"+f+"\n"+n+"\n"+t+"\n";p.mac=p.mac||e(o,l),i.a.logAction(i.a.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),r(null,p)},p.timestamp?h():v.getTimestamp(n&&n.queryTime,(function(e,t){e?r(e):(p.timestamp=t,h())}))}else r(new u.a("clientId can’t be an empty string",40012,400));else r(new u.a("Invalid key specified",40101,403))}else r(new u.a("No key specified",40101,403))},O.prototype.getAuthParams=function(e){"basic"==this.method?e(null,{key:this.key}):this._ensureValidAuthCredentials(!1,(function(t,n){t?e(t):e(null,{access_token:n.token})}))},O.prototype.getAuthHeaders=function(e){"basic"==this.method?e(null,{authorization:"Basic "+this.basicKey}):this._ensureValidAuthCredentials(!1,(function(n,i){n?e(n):e(null,{authorization:"Bearer "+t(i.token)})}))},O.prototype.getTimestamp=function(e,t){this.isTimeOffsetSet()||!e&&!this.authOptions.queryTime?t(null,this.getTimestampUsingOffset()):this.client.time(t)},O.prototype.getTimestampUsingOffset=function(){return o.a.now()+(this.client.serverTimeOffset||0)},O.prototype.isTimeOffsetSet=function(){return null!==this.client.serverTimeOffset},O.prototype._saveBasicOptions=function(e){this.method="basic",this.key=e.key,this.basicKey=t(e.key),this.authOptions=e||{},"clientId"in e&&this._userSetClientId(e.clientId)},O.prototype._saveTokenOptions=function(e,t){this.method="token",e&&(this.tokenParams=e),t&&(t.token&&(t.tokenDetails="string"==typeof t.token?{token:t.token}:t.token),t.tokenDetails&&(this.tokenDetails=t.tokenDetails),"clientId"in t&&this._userSetClientId(t.clientId),this.authOptions=t)},O.prototype._ensureValidAuthCredentials=function(e,t){var n=this,r=this.tokenDetails;if(r){if(this._tokenClientIdMismatch(r.clientId))return void t(new u.a("Mismatch between clientId in token ("+r.clientId+") and current clientId ("+this.clientId+")",40102,403));if(!this.isTimeOffsetSet()||!r.expires||r.expires>=this.getTimestampUsingOffset())return i.a.logAction(i.a.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+r.expires),void t(null,r);i.a.logAction(i.a.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}if((this.waitingForTokenRequest||(this.waitingForTokenRequest=Object(a.a)())).push(t),null===this.currentTokenRequestId||e){var o=this.currentTokenRequestId=v++;this.requestToken(this.tokenParams,this.authOptions,(function(e,t){if(n.currentTokenRequestId>o)i.a.logAction(i.a.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one");else{n.currentTokenRequestId=null;var r=n.waitingForTokenRequest||h;n.waitingForTokenRequest=null,e?r(e):r(null,n.tokenDetails=t)}}))}},O.prototype._userSetClientId=function(e){if("string"!=typeof e&&null!==e)throw new u.a("clientId must be either a string or null",40012,400);if("*"===e)throw new u.a('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, instantiate the library with {defaultTokenParams: {clientId: "*"}}), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);var t=this._uncheckedSetClientId(e);if(t)throw t},O.prototype._uncheckedSetClientId=function(e){if(this._tokenClientIdMismatch(e)){var t="Unexpected clientId mismatch: client has "+this.clientId+", requested "+e,n=new u.a(t,40102,401);return i.a.logAction(i.a.LOG_ERROR,"Auth._uncheckedSetClientId()",t),n}return this.clientId=this.tokenParams.clientId=e,null},O.prototype._tokenClientIdMismatch=function(e){return this.clientId&&"*"!==this.clientId&&e&&"*"!==e&&this.clientId!==e},O.isTokenErr=function(e){return e.code&&e.code>=40140&&e.code<40150},O}();t.a=d},function(e,t,n){"use strict";var i=n(1),r=n(8),o=n(20),s=n(0),a=n(4),c=n(13),u=n(14),l=n(2),h=function(){function e(e){return function(e){return!!e.code&&(!u.a.isTokenErr(e)&&(!!i.a.arrIn([80015,80017,80030],e.code)||e.code>=4e4&&e.code<5e4))}(e)?[r.a.fromValues({action:r.a.Action.ERROR,error:e})]:[r.a.fromValues({action:r.a.Action.DISCONNECTED,error:e})]}function t(e,t,n){n.format=void 0,n.heartbeats=!0,o.a.call(this,e,t,n),this.stream=!("stream"in n)||n.stream,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}return i.a.inherits(t,o.a),t.REQ_SEND=0,t.REQ_RECV=1,t.REQ_RECV_POLL=2,t.REQ_RECV_STREAM=3,t.prototype.connect=function(){s.a.logAction(s.a.LOG_MINOR,"CometTransport.connect()","starting"),o.a.prototype.connect.call(this);var t=this,n=this.params,r=n.options,c=a.a.getHost(r,n.host),u=a.a.getPort(r),h=r.tls?"https://":"http://";this.baseUri=h+c+":"+u+"/comet/";var p=this.baseUri+"connect";s.a.logAction(s.a.LOG_MINOR,"CometTransport.connect()","uri: "+p),this.auth.getAuthParams((function(n,r){if(n)t.disconnect(n);else if(!t.isDisposed){t.authParams=r;var o=t.params.getConnectParams(r);"stream"in o&&(t.stream=o.stream),s.a.logAction(s.a.LOG_MINOR,"CometTransport.connect()","connectParams:"+i.a.toQueryString(o));var a=!1,c=t.recvRequest=t.createRequest(p,null,o,null,t.stream?3:1);c.on("data",(function(e){t.recvRequest&&(a||(a=!0,t.emit("preconnect")),t.onData(e))})),c.on("complete",(function(n,r,o){t.recvRequest||(n=n||new l.a("Request cancelled",80003,400)),t.recvRequest=null,a||n||(a=!0,t.emit("preconnect")),t.onActivity(),n?n.code?t.onData(e(n)):t.disconnect(n):i.a.nextTick((function(){t.recv()}))})),c.exec()}}))},t.prototype.requestClose=function(){s.a.logAction(s.a.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)},t.prototype.requestDisconnect=function(){s.a.logAction(s.a.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)},t.prototype._requestCloseOrDisconnect=function(e){var t=e?this.closeUri:this.disconnectUri;if(t){var n=this,r=this.createRequest(t,null,this.authParams,null,0);r.on("complete",(function(t){t&&(s.a.logAction(s.a.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+i.a.inspectError(t)),n.finish("disconnected",t))})),r.exec()}},t.prototype.dispose=function(){if(s.a.logAction(s.a.LOG_MINOR,"CometTransport.dispose()",""),!this.isDisposed){this.isDisposed=!0,this.recvRequest&&(s.a.logAction(s.a.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",c.a.disconnected);var e=this;i.a.nextTick((function(){e.emit("disposed")}))}},t.prototype.onConnect=function(e){if(!this.isDisposed){var t=e.connectionKey;o.a.prototype.onConnect.call(this,e);var n=this.baseUri+t;s.a.logAction(s.a.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+n+"; connectionKey = "+e.connectionKey),this.sendUri=n+"/send",this.recvUri=n+"/recv",this.closeUri=n+"/close",this.disconnectUri=n+"/disconnect"}},t.prototype.send=function(e){if(this.sendRequest)return this.pendingItems=this.pendingItems||[],void this.pendingItems.push(e);var t=this.pendingItems||[];t.push(e),this.pendingItems=null,this.sendItems(t)},t.prototype.sendAnyPending=function(){var e=this.pendingItems;e&&(this.pendingItems=null,this.sendItems(e))},t.prototype.sendItems=function(t){var n=this,r=this.sendRequest=n.createRequest(n.sendUri,null,n.authParams,this.encodeRequest(t),0);r.on("complete",(function(t,r){t&&s.a.logAction(s.a.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+i.a.inspectError(t)),n.sendRequest=null,t?t.code?n.onData(e(t)):n.disconnect(t):(r&&n.onData(r),n.pendingItems&&i.a.nextTick((function(){n.sendRequest||n.sendAnyPending()})))})),r.exec()},t.prototype.recv=function(){if(!this.recvRequest&&this.isConnected){var t=this,n=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,t.stream?3:2);n.on("data",(function(e){t.onData(e)})),n.on("complete",(function(n){t.recvRequest=null,t.onActivity(),n?n.code?t.onData(e(n)):t.disconnect(n):i.a.nextTick((function(){t.recv()}))})),n.exec()}},t.prototype.onData=function(e){try{var t=this.decodeResponse(e);if(t&&t.length)for(var n=0;n>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,a=0;a<4&&o+.75*a>>6*(3-a)&63));var c=i.charAt(64);if(c)for(;r.length%4;)r.push(c);return r.join("")},parse:function(e){var t=e.length,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i=this._reverseMap;if(!i){i=this._reverseMap=[];for(var o=0;o>>6-s%4*2,u=a|c;i[o>>>2]|=u<<24-o%4*8,o++}return r.create(i,o)}(e,t,i)}},o.enc.Base64)},function(e,t,n){"use strict";var i=n(10),r=n.n(i),o=n(18),s=n(28),a=n.n(s),c=n(3),u=n(0),l=n(5),h=function(){var e;if(c.a.getRandomWordArray)e=c.a.getRandomWordArray;else if("undefined"!=typeof Uint32Array&&c.a.getRandomValues){var t=new Uint32Array(4);e=function(e,n){var i=e/4,r=4==i?t:new Uint32Array(i);c.a.getRandomValues(r,(function(e){n(e,l.a.toWordArray(r))}))}}else e=function(e,t){u.a.logAction(u.a.LOG_MAJOR,"Ably.Crypto.generateRandom()","Warning: the browser you are using does not support secure cryptographically secure randomness generation; falling back to insecure Math.random()");for(var n=e/4,i=new Array(n),o=0;o>>0&127|0);else if(o<2048)e.setUint8(t++,o>>>6&31|192),e.setUint8(t++,o>>>0&63|128);else if(o<65536)e.setUint8(t++,o>>>12&15|224),e.setUint8(t++,o>>>6&63|128),e.setUint8(t++,o>>>0&63|128);else{if(!(o<1114112))throw new Error("bad codepoint "+o);e.setUint8(t++,o>>>18&7|240),e.setUint8(t++,o>>>12&63|128),e.setUint8(t++,o>>>6&63|128),e.setUint8(t++,o>>>0&63|128)}}}function n(e,t,n){for(var i="",r=t,o=t+n;r20){i.push("...");break}var o=t.getUint8(r).toString(16);1===o.length&&(o="0"+o),i.push(o)}return"<"+n+" "+i.join(" ")+">"},e.utf8Write=t,e.utf8Read=n,e.utf8ByteCount=i,e.encode=function(e,n){var r=function e(t,n){var r=typeof t;if("string"===r){if((s=i(t))<32)return 1+s;if(s<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}ArrayBuffer.isView&&ArrayBuffer.isView(t)&&(t=t.buffer);if(t instanceof ArrayBuffer){if((s=t.byteLength)<256)return 2+s;if(s<65536)return 3+s;if(s<4294967296)return 5+s}if("number"===r){if(Math.floor(t)!==t)return 9;if(t>=0){if(t<128)return 1;if(t<256)return 2;if(t<65536)return 3;if(t<4294967296)return 5;if(t<0x10000000000000000)return 9;throw new Error("Number too big 0x"+t.toString(16))}if(t>=-32)return 1;if(t>=-128)return 2;if(t>=-32768)return 3;if(t>=-2147483648)return 5;if(t>=-0x8000000000000000)return 9;throw new Error("Number too small -0x"+t.toString(16).substr(1))}if("boolean"===r)return 1;if(null===t)return n?0:1;if(void 0===t)return n?0:3;if("function"==typeof t.toJSON)return e(t.toJSON(),n);if("object"===r){var s,a=0;if(Array.isArray(t)){s=t.length;for(var c=0;c=0){if(n<128)return r.setUint8(s,n),1;if(n<256)return r.setUint8(s,204),r.setUint8(s+1,n),2;if(n<65536)return r.setUint8(s,205),r.setUint16(s+1,n),3;if(n<4294967296)return r.setUint8(s,206),r.setUint32(s+1,n),5;if(n<0x10000000000000000)return r.setUint8(s,207),function(e,t,n){n<0x10000000000000000?(e.setUint32(t,Math.floor(2.3283064365386963e-10*n)),e.setInt32(t+4,-1&n)):(e.setUint32(t,4294967295),e.setUint32(t+4,4294967295))}(r,s+1,n),9;throw new Error("Number too big 0x"+n.toString(16))}if(n>=-32)return r.setInt8(s,n),1;if(n>=-128)return r.setUint8(s,208),r.setInt8(s+1,n),2;if(n>=-32768)return r.setUint8(s,209),r.setInt16(s+1,n),3;if(n>=-2147483648)return r.setUint8(s,210),r.setInt32(s+1,n),5;if(n>=-0x8000000000000000)return r.setUint8(s,211),function(e,t,n){n<0x8000000000000000?(e.setInt32(t,Math.floor(2.3283064365386963e-10*n)),e.setInt32(t+4,-1&n)):(e.setUint32(t,2147483647),e.setUint32(t+4,2147483647))}(r,s+1,n),9;throw new Error("Number too small -0x"+(-n).toString(16).substr(1))}if("undefined"===c)return a?0:(r.setUint8(s,212),r.setUint8(s+1,0),r.setUint8(s+2,0),3);if(null===n)return a?0:(r.setUint8(s,192),1);if("boolean"===c)return r.setUint8(s,n?195:194),1;if("function"==typeof n.toJSON)return e(n.toJSON(),r,s,a);if("object"===c){var u,l=0,h=Array.isArray(n);if(h)u=n.length;else{var p=o(n,a);u=p.length}if(u<16?(r.setUint8(s,u|(h?144:128)),l=1):u<65536?(r.setUint8(s,h?220:222),r.setUint16(s+1,u),l=3):u<4294967296&&(r.setUint8(s,h?221:223),r.setUint32(s+1,u),l=5),h)for(var f=0;fr.a.arrIndexOf(S,a.shortName))?(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Scheduling transport upgrade; transport = "+t),void this.realtime.channels.onceNopending((function(r){var s;if(r)l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Unable to activate transport; transport = "+t+"; err = "+r);else{if(!t.isConnected)return l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+t.shortName+"is no longer connected; abandoning upgrade"),void h();if(c.state===c.states.connected)l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Currently connected, so temporarily pausing events until the upgrade is complete"),c.state=c.states.synchronizing,s=c.activeProtocol;else if(c.state!==c.states.connecting)return l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Current connection state ("+c.state.state+(c.state===c.states.synchronizing?", but with an upgrade already in progress":"")+") is not valid to upgrade in; abandoning upgrade to "+t.shortName),void h();var a=n!==c.connectionId,u=a?o:c;a&&l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Upgrade resulted in new connectionId; resetting library connection position from "+(c.timeSerial||c.connectionSerial)+" to "+(u.timeSerial||u.connectionSerial)+"; upgrade error was "+e),l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Syncing transport; transport = "+t),c.sync(t,u,(function(n,r,o){if(n)c.state===c.states.synchronizing&&(l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.scheduleTransportActivation()","Unexpected error attempting to sync transport; transport = "+t+"; err = "+n),c.disconnectAllTransports());else{var a=function(){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Activating transport; transport = "+t),c.activateTransport(e,t,r,i,o),c.state===c.states.synchronizing?(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, sending queued messages on upgraded transport; transport = "+t),c.state=c.states.connected):l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Pre-upgrade protocol idle, but state is now "+c.state.state+", so leaving unchanged"),c.state.sendEvents&&c.sendQueuedMessages()};s?s.onceIdle(a):a()}}))}}))):(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.scheduleTransportActivation()","Proposed transport "+t.shortName+" is no better than current active transport "+u.shortName+" - abandoning upgrade"),void h())},I.prototype.activateTransport=function(e,t,n,i,s){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+t),e&&l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+e),n&&l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+n),i&&l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(i)),s&&l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.activateTransport()","serial = "+(s.timeSerial||s.connectionSerial)),this.persistTransportPreference(t);var a=this.state,c=this.states.connected.state;if(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+a.state),a.state==this.states.closing.state||a.state==this.states.closed.state||a.state==this.states.failed.state)return l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),t.disconnect(),!1;if(r.a.arrDeleteValue(this.pendingTransports,t),!t.isConnected)return l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+t+" since it appears to no longer be connected"),!1;var u=this.activeProtocol;this.activeProtocol=new o.a(t),this.host=t.params.host;var p=i.connectionKey;p&&this.connectionKey!=p&&this.setConnection(n,i,s,!!e),this.onConnectionDetailsUpdate(i,t);var f=this;if(r.a.nextTick((function(){t.on("connected",(function(e,n,i){f.onConnectionDetailsUpdate(i,t),f.emit("update",new h.a(c,c,null,e))}))})),a.state===this.states.connected.state?e&&(this.errorReason=this.realtime.connection.errorReason=e,this.emit("update",new h.a(c,c,null,e))):(this.notifyState({state:"connected",error:e}),this.errorReason=this.realtime.connection.errorReason=e||null),this.emit("transport.active",t),u)if(u.messageQueue.count()>0&&l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+u.transport.shortName+", new one is "+t.shortName+") finishing with "+u.messageQueue.count()+" messages still pending"),u.transport===t){var d="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+t.shortName+"; stack = "+(new Error).stack;l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.activateTransport()",d),v.a.report("error",d,"transport-previously-active")}else u.finish();return r.a.safeArrForEach(this.pendingTransports,(function(e){if(e===t){var n="Assumption violated: activating a transport that is still marked as a pending transport; transport = "+t.shortName+"; stack = "+(new Error).stack;l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.activateTransport()",n),v.a.report("error",n,"transport-activating-pending"),r.a.arrDeleteValue(f.pendingTransports,t)}else e.disconnect()})),r.a.safeArrForEach(this.proposedTransports,(function(e){if(e===t){var n="Assumption violated: activating a transport that is still marked as a proposed transport; transport = "+t.shortName+"; stack = "+(new Error).stack;l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.activateTransport()",n),v.a.report("error",n,"transport-activating-proposed"),r.a.arrDeleteValue(f.proposedTransports,t)}else e.dispose()})),!0},I.prototype.deactivateTransport=function(e,t,n){var i=this.activeProtocol,o=i&&i.getTransport()===e,s=r.a.arrDeleteValue(this.pendingTransports,e),a=r.a.arrDeleteValue(this.proposedTransports,e),c=this.noTransportsScheduledForActivation();if(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+e),l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+t+(o?"; was active":s?"; was pending":a?"; was proposed":"")+(c?"":"; another transport is scheduled for activation")),n&&n.message&&l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+n.message),o&&(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(i.getPendingMessages()),r.a.nextTick((function(){i.clearPendingMessages()})),this.activeProtocol=this.host=null,clearTimeout(this.channelResumeCheckTimer)),this.emit("transport.inactive",e),o&&c||o&&"failed"===t||"closed"===t||null===i&&s&&0===this.pendingTransports.length){if("disconnected"===t&&n&&n.statusCode>500&&this.httpHosts.length>1)return this.unpersistTransportPreference(),this.forceFallbackHost=!0,void this.notifyState({state:t,error:n,retryImmediately:!0});var u="failed"===t&&d.a.isTokenErr(n)?"disconnected":t;this.notifyState({state:u,error:n})}else o&&"disconnected"===t&&this.state!==this.states.synchronizing&&(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.deactivateTransport()","wasActive but another transport is connected and scheduled for activation, so going into the connecting state until it activates"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),this.notifyState({state:"connecting",error:n}))},I.prototype.noTransportsScheduledForActivation=function(){return r.a.isEmpty(this.pendingTransports)||this.pendingTransports.every((function(e){return!e.isConnected}))},I.prototype.sync=function(e,t,n){var r=setTimeout((function(){e.off("sync"),n(new f.a("Timeout waiting for sync response",5e4,500))}),this.options.timeouts.realtimeRequestTimeout),o=i.a.fromValues({action:b.SYNC,connectionKey:this.connectionKey});t.timeSerial?o.timeSerial=t.timeSerial:void 0!==t.connectionSerial&&(o.connectionSerial=t.connectionSerial),e.send(o),e.once("sync",(function(e,t){clearTimeout(r),n(null,e,t)}))},I.prototype.setConnection=function(e,t,n,i){var o=this,s=this.connectionid,a=s&&s!==e;(a||!s&&i)&&(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0),this.connectionId!==e?(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),r.a.nextTick((function(){o.realtime.channels.reattach()}))):this.options.checkChannelsOnResume&&(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.setConnection()","Same connectionId; checkChannelsOnResume is enabled"),clearTimeout(this.channelResumeCheckTimer),this.realtime.channels.resetAttachedMsgIndicators(),this.channelResumeCheckTimer=setTimeout((function(){o.realtime.channels.checkAttachedMsgIndicators(e)}),3e4)),this.realtime.connection.id=this.connectionId=e,this.realtime.connection.key=this.connectionKey=t.connectionKey;var c=a||!s;this.setConnectionSerial(n,c)},I.prototype.clearConnection=function(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.clearConnectionSerial(),this.msgSerial=0,this.unpersistConnection()},I.prototype.setConnectionSerial=function(e,t){var n=e.timeSerial,i=e.connectionSerial;if(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.setConnectionSerial()","Updating connection serial; serial = "+i+"; timeSerial = "+n+"; force = "+t+"; previous = "+this.connectionSerial),void 0!==n)return n<=this.timeSerial&&!t?(l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.setConnectionSerial()","received message with timeSerial "+n+", but current timeSerial is "+this.timeSerial+"; assuming message is a duplicate and discarding it"),!0):(this.realtime.connection.timeSerial=this.timeSerial=n,void this.setRecoveryKey());if(void 0!==i){if(i<=this.connectionSerial&&!t)return l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.setConnectionSerial()","received message with connectionSerial "+i+", but current connectionSerial is "+this.connectionSerial+"; assuming message is a duplicate and discarding it"),!0;this.realtime.connection.serial=this.connectionSerial=i,this.setRecoveryKey()}},I.prototype.clearConnectionSerial=function(){this.realtime.connection.serial=this.connectionSerial=void 0,this.realtime.connection.timeSerial=this.timeSerial=void 0,this.clearRecoveryKey()},I.prototype.setRecoveryKey=function(){this.realtime.connection.recoveryKey=this.connectionKey+":"+(this.timeSerial||this.connectionSerial)+":"+this.msgSerial},I.prototype.clearRecoveryKey=function(){this.realtime.connection.recoveryKey=null},I.prototype.checkConnectionStateFreshness=function(){if(this.lastActivity&&this.connectionId){var e=r.a.now()-this.lastActivity;e>this.connectionStateTtl+this.maxIdleInterval&&(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+e+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended",this.states.connecting.queueEvents=!1)}},I.prototype.persistConnection=function(){if(n){var t=this.realtime.connection.recoveryKey;t&&(i={recoveryKey:t,disconnectedAt:r.a.now(),location:e.location,clientId:this.realtime.auth.clientId},this.connectionStateTtl,n&&O.a.setSession("ably-connection-recovery",i))}var i},I.prototype.unpersistConnection=function(){n&&O.a.removeSession("ably-connection-recovery")},I.prototype.getError=function(){return this.errorReason||this.getStateError()},I.prototype.getStateError=function(){return p.a[this.state.state]},I.prototype.activeState=function(){return this.state.queueEvents||this.state.sendEvents},I.prototype.enactStateChange=function(e){var t="failed"===e.current?l.a.LOG_ERROR:l.a.LOG_MAJOR;l.a.logAction(t,"Connection state",e.current+(e.reason?"; reason: "+e.reason:"")),l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+e.current+"; reason = "+(e.reason&&e.reason.message));var n=this.state=this.states[e.current];e.reason&&(this.errorReason=e.reason,this.realtime.connection.errorReason=e.reason),(n.terminal||"suspended"===n.state)&&this.clearConnection(),this.emit("connectionstate",e)},I.prototype.startTransitionTimer=function(e){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+e.state),this.transitionTimer&&(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer));var t=this;this.transitionTimer=setTimeout((function(){t.transitionTimer&&(t.transitionTimer=null,l.a.logAction(l.a.LOG_MINOR,"ConnectionManager "+e.state+" timer expired","requesting new state: "+e.failState),t.notifyState({state:e.failState}))}),e.retryDelay)},I.prototype.cancelTransitionTimer=function(){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)},I.prototype.startSuspendTimer=function(){var e=this;this.suspendTimer||(this.suspendTimer=setTimeout((function(){e.suspendTimer&&(e.suspendTimer=null,l.a.logAction(l.a.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),e.states.connecting.failState="suspended",e.states.connecting.queueEvents=!1,e.notifyState({state:"suspended"}))}),this.connectionStateTtl))},I.prototype.checkSuspendTimer=function(e){"disconnected"!==e&&"suspended"!==e&&"connecting"!==e&&this.cancelSuspendTimer()},I.prototype.cancelSuspendTimer=function(){this.states.connecting.failState="disconnected",this.states.connecting.queueEvents=!0,this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)},I.prototype.startRetryTimer=function(e){var t=this;this.retryTimer=setTimeout((function(){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),t.retryTimer=null,t.requestState({state:"connecting"})}),e)},I.prototype.cancelRetryTimer=function(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)},I.prototype.notifyState=function(e){var t=e.state,n=this,i="disconnected"===t&&(this.state===this.states.connected||this.state===this.states.synchronizing||e.retryImmediately||this.state===this.states.connecting&&e.error&&d.a.isTokenErr(e.error)&&!(this.errorReason&&d.a.isTokenErr(this.errorReason)));if(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+t+(i?"; will retry connection immediately":"")),t!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(e.state),!this.state.terminal)){var o=this.states[e.state],s=new h.a(this.state.state,o.state,o.retryDelay,e.error||p.a[o.state]);if(i){var a=function(){n.state===n.states.disconnected&&(n.lastAutoReconnectAttempt=r.a.now(),n.requestState({state:"connecting"}))},c=this.lastAutoReconnectAttempt&&r.a.now()-this.lastAutoReconnectAttempt+1;c&&c<1e3?(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+c+"ms ago, waiting another "+(1e3-c)+"ms before trying again"),setTimeout(a,1e3-c)):r.a.nextTick(a)}else"disconnected"!==t&&"suspended"!==t||this.startRetryTimer(o.retryDelay);("disconnected"===t&&!i||"suspended"===t||o.terminal)&&r.a.nextTick((function(){n.disconnectAllTransports()})),"connected"!=t||this.activeProtocol||l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(s),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(t,s.reason),this.failQueuedMessages(s.reason))}},I.prototype.requestState=function(e){var t=e.state,n=this;if(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+t+"; current state: "+this.state.state),t!=this.state.state&&(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(t),!("connecting"==t&&"connected"==this.state.state||"closing"==t&&"closed"==this.state.state))){var i=this.states[t],o=new h.a(this.state.state,i.state,null,e.error||p.a[i.state]);this.enactStateChange(o),"connecting"==t&&r.a.nextTick((function(){n.startConnect()})),"closing"==t&&this.closeImpl()}},I.prototype.startConnect=function(){if(this.state===this.states.connecting){var e=this.realtime.auth,t=this,n=++this.connectCounter,i=function(){t.checkConnectionStateFreshness(),t.getTransportParams((function(e){n===t.connectCounter&&t.connectImpl(e,n)}))};if(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),"basic"===e.method)i();else{var r=function(e){n===t.connectCounter&&(e?t.actOnErrorFromAuthorize(e):i())};this.errorReason&&d.a.isTokenErr(this.errorReason)?e._forceNewToken(null,null,r):e._ensureValidAuthCredentials(!1,r)}}else l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state)},I.prototype.connectImpl=function(e,t){var n=this.state.state;n!==this.states.connecting.state&&n!==this.states.connected.state?l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect (or connected to upgrade), but was "+n):this.pendingTransports.length?l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.connectImpl()","Transports "+this.pendingTransports[0].toString()+" currently pending; taking no action"):n==this.states.connected.state?this.upgradeIfNeeded(e):this.transports.length>1&&this.getTransportPreference()?this.connectPreference(e):this.connectBase(e,t)},I.prototype.connectPreference=function(e){var t=this.getTransportPreference(),n=this,i=!1;r.a.arrIn(this.transports,t)||(this.unpersistTransportPreference(),this.connectImpl(e)),l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.connectPreference()","Trying to connect with stored transport preference "+t);var o=setTimeout((function(){i=!0,n.state.state!==n.states.connected.state&&(l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.connectPreference()","Shortcircuit connection attempt with "+t+" failed; clearing preference and trying from scratch"),n.disconnectAllTransports(),n.unpersistTransportPreference()),n.connectImpl(e)}),this.options.timeouts.preferenceConnectTimeout);e.host=n.httpHosts[0],n.tryATransport(e,t,(function(t,s){clearTimeout(o),i&&s?(s.off(),s.disconnect(),r.a.arrDeleteValue(this.pendingTransports,s)):s||t||(n.unpersistTransportPreference(),n.connectImpl(e))}))},I.prototype.connectBase=function(e,t){var n=this,i=function(e){n.notifyState({state:n.states.connecting.failState,error:e})},o=this.httpHosts.slice(),s=function(e,i){t===n.connectCounter&&(i||e||c())};l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.connectBase()","Trying to connect with base transport "+this.baseTransport);var a=o.shift();if(a){if(e.host=a,this.forceFallbackHost&&o.length)return this.forceFallbackHost=!1,void c();this.tryATransport(e,this.baseTransport,s)}else i(new f.a("Unable to connect (no available host)",80003,404));function c(){o.length?g.a.checkConnectivity((function(a,c){t===n.connectCounter&&(a?i(a):c?(e.host=r.a.arrPopRandomElement(o),n.tryATransport(e,n.baseTransport,s)):i(new f.a("Unable to connect (network unreachable)",80003,404)))})):i(new f.a("Unable to connect (and no more fallback hosts to try)",80003,404))}},I.prototype.getUpgradePossibilities=function(){var e=this.activeProtocol.getTransport().shortName,t=r.a.arrIndexOf(this.upgradeTransports,e);return this.upgradeTransports.slice(t+1)},I.prototype.upgradeIfNeeded=function(e){var t=this.getUpgradePossibilities(),n=this;l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.upgradeIfNeeded()","upgrade possibilities: "+r.a.inspect(t)),t.length&&r.a.arrForEach(t,(function(t){var i=n.createTransportParams(e.host,"upgrade");n.tryATransport(i,t,w)}))},I.prototype.closeImpl=function(){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),r.a.safeArrForEach(this.pendingTransports,(function(e){l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+e),e&&e.close()})),r.a.safeArrForEach(this.proposedTransports,(function(e){l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.closeImpl()","Disposing of proposed transport: "+e),e&&e.dispose()})),this.activeProtocol&&(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})},I.prototype.onAuthUpdated=function(e,t){var n=this;switch(this.state.state){case"connected":if(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport"),(this.pendingTransports.length||this.proposedTransports.length)&&n.state!==n.states.synchronizing){this.disconnectAllTransports(!0);var o=this.activeProtocol.getTransport().params;r.a.nextTick((function(){"connected"===n.state.state&&n.upgradeIfNeeded(o)}))}this.activeProtocol.getTransport().onAuthUpdated(e);var s=i.a.fromValues({action:b.AUTH,auth:{accessToken:e.token}});this.send(s);var a=function(){n.off(c),t(null,e)},c=function(e){"failed"===e.current&&(n.off(a),n.off(c),t(e.reason||n.getStateError()))};this.once("connectiondetails",a),this.on("connectionstate",c);break;case"connecting":l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");var u=function(i){switch(i.current){case"connected":n.off(u),t(null,e);break;case"failed":case"closed":case"suspended":n.off(u),t(i.reason||n.getStateError())}};n.on("connectionstate",u),"connecting"===this.state.state?n.startConnect():n.requestState({state:"connecting"})}},I.prototype.disconnectAllTransports=function(e){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"+(e?" except the active transport":"")),this.connectCounter++,r.a.safeArrForEach(this.pendingTransports,(function(e){l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+e),e&&e.disconnect()})),this.pendingTransports=[],r.a.safeArrForEach(this.proposedTransports,(function(e){l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disposing of proposed transport: "+e),e&&e.dispose()})),this.proposedTransports=[],this.activeProtocol&&!e&&(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())},I.prototype.send=function(e,t,n){n=n||w;var r=this.state;if(r.sendEvents)return l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.send()","sending event"),void this.sendImpl(new C(e,n));if(!(t&&r.queueEvents||r.forceQueueEvents)){var o="rejecting event, queueEvent was "+t+", state was "+r.state;return l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.send()",o),void n(this.errorReason||new f.a(o,9e4,400))}l.a.shouldLog(l.a.LOG_MICRO)&&l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+i.a.stringify(e)),this.queue(e,n)},I.prototype.sendImpl=function(e){var t=e.message;e.ackRequired&&!e.sendAttempted&&(t.msgSerial=this.msgSerial++,this.setRecoveryKey());try{this.activeProtocol.send(e)}catch(e){l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+e.stack)}},I.prototype.queue=function(e,t){l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.queue()","queueing event");var n=this.queuedMessages.last(),i=this.options.maxMessageSize;n&&!n.sendAttempted&&function(e,t,n){var i;if(e.channel!==t.channel)return!1;if((i=e.action)!==b.PRESENCE&&i!==b.MESSAGE)return!1;if(i!==t.action)return!1;var o=i===b.PRESENCE?"presence":"messages",s=e[o].concat(t[o]);return!(m.a.getMessagesSize(s)>n)&&(!!r.a.allSame(s,"clientId")&&(!!r.a.arrEvery(s,(function(e){return!e.id}))&&(e[o]=s,!0)))}(n.message,e,i)?(n.merged||(n.callback=Object(y.a)([n.callback]),n.merged=!0),n.callback.push(t)):this.queuedMessages.push(new C(e,t))},I.prototype.sendQueuedMessages=function(){var e;for(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");e=this.queuedMessages.shift();)this.sendImpl(e)},I.prototype.queuePendingMessages=function(e){e&&e.length&&(l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+e.length+" pending messages"),this.queuedMessages.prepend(e))},I.prototype.failQueuedMessages=function(e){var t=this.queuedMessages.count();t>0&&(l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+t+" queued messages, err = "+r.a.inspectError(e)),this.queuedMessages.completeAllMessages(e))},I.prototype.onChannelMessage=function(e,t){var n=this.activeProtocol&&t===this.activeProtocol.getTransport(),o=r.a.arrIn(this.pendingTransports,t)&&this.state==this.states.synchronizing,s=e.action===b.MESSAGE||e.action===b.PRESENCE;if(n||o){if(s){if(this.setConnectionSerial(e))return;if(i.a.isDuplicate(e,this.mostRecentMsg))return void l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.onChannelMessage()","received message with different connectionSerial, but same message id as a previous; discarding; id = "+e.id);this.mostRecentMsg=e}this.realtime.channels.onChannelMessage(e)}else r.a.arrIndexOf([b.ACK,b.NACK,b.ERROR],e.action)>-1?this.realtime.channels.onChannelMessage(e):l.a.logAction(l.a.LOG_MICRO,"ConnectionManager.onChannelMessage()","received message "+JSON.stringify(e)+"on defunct transport; discarding")},I.prototype.ping=function(e,t){if(e){l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.ping()","transport = "+e);var n=r.a.now(),i=r.a.cheapRandStr(),o=function(a){if(a===i){e.off("heartbeat",o),clearTimeout(s);var c=r.a.now()-n;t(null,c)}},s=setTimeout((function(){e.off("heartbeat",o),t(new f.a("Timeout waiting for heartbeat response",5e4,500))}),this.options.timeouts.realtimeRequestTimeout);return e.on("heartbeat",o),void e.ping(i)}if("connected"===this.state.state){var a=!1,c=this,u=function(){a||(a=!0,r.a.nextTick((function(){c.ping(null,t)})))};this.on("transport.active",u),this.ping(this.activeProtocol.getTransport(),(function(e,n){c.off("transport.active",u),a||(a=!0,t(e,n))}))}else t(new f.a("Unable to ping service; not connected",4e4,400))},I.prototype.abort=function(e){this.activeProtocol.getTransport().fail(e)},I.prototype.registerProposedTransport=function(e){this.proposedTransports.push(e)},I.prototype.getTransportPreference=function(){return this.transportPreference||t&&O.a.get("ably-transport-preference")},I.prototype.persistTransportPreference=function(e){r.a.arrIn(s.a.upgradeTransports,e.shortName)&&(this.transportPreference=e.shortName,t&&O.a.set("ably-transport-preference",e.shortName))},I.prototype.unpersistTransportPreference=function(){this.transportPreference=null,t&&O.a.remove("ably-transport-preference")},I.prototype.actOnErrorFromAuthorize=function(e){if(40171===e.code)this.notifyState({state:"failed",error:e});else if(403===e.statusCode){var t="Client configured authentication provider returned 403; failing the connection";l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",t),this.notifyState({state:"failed",error:new f.a(t,80019,403,e)})}else{t="Client configured authentication provider request failed";l.a.logAction(l.a.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",t),this.notifyState({state:this.state.failState,error:new f.a(t,80019,401,e)})}},I.prototype.onConnectionDetailsUpdate=function(e,t){if(e){this.connectionDetails=e,e.maxMessageSize&&(this.options.maxMessageSize=e.maxMessageSize);var n=e.clientId;if(n){var i=this.realtime.auth._uncheckedSetClientId(n);if(i)return l.a.logAction(l.a.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",i.message),void t.fail(i)}var r=e.connectionStateTtl;r&&(this.connectionStateTtl=r),this.maxIdleInterval=e.maxIdleInterval,this.emit("connectiondetails",e)}},I}();t.a=b}).call(this,n(17))},function(e,t,n){"use strict";var i=n(1),r=n(7),o=n(0),s=function(){function e(){r.a.call(this),this.messages=[]}return i.a.inherits(e,r.a),e.prototype.count=function(){return this.messages.length},e.prototype.push=function(e){this.messages.push(e)},e.prototype.shift=function(){return this.messages.shift()},e.prototype.last=function(){return this.messages[this.messages.length-1]},e.prototype.copyAll=function(){return this.messages.slice()},e.prototype.append=function(e){this.messages.push.apply(this.messages,e)},e.prototype.prepend=function(e){this.messages.unshift.apply(this.messages,e)},e.prototype.completeMessages=function(e,t,n){o.a.logAction(o.a.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+e+"; count = "+t),n=n||null;var i=this.messages,r=i[0];if(r){var s=r.message.msgSerial,a=e+t;if(a>s)for(var c=i.splice(0,a-s),u=0;u-1&&"string"!=typeof r&&(r=JSON.stringify(r)));for(var f in u.open(o,this.uri,!0),u.responseType=p,"authorization"in a&&(u.withCredentials=!0),a)u.setRequestHeader(f,a[f]);var d=function(e,n,i,r){var o=n+" (event type: "+e.type+")"+(t.xhr.statusText?", current statusText is "+t.xhr.statusText:"");c.a.logAction(c.a.LOG_ERROR,"Request.on"+e.type+"()",o),t.complete(new s.a(o,i,r))};u.onerror=function(e){d(e,"XHR error occurred",null,400)},u.onabort=function(e){t.timedOut?d(e,"Request aborted due to request timeout expiring",null,408):d(e,"Request cancelled",null,400)},u.ontimeout=function(e){d(e,"Request timed out",null,408)};var g,m,y,v,O=0,R=!1;function A(){try{var e,n,r=function(e,t){return e.getResponseHeader&&e.getResponseHeader(t)}(u,"content-type");(r?r.indexOf("application/json")>=0:"text"==u.responseType)?((n="arraybuffer"===u.responseType?l.a.utf8Decode(u.response):String(u.responseText)).length&&(n=JSON.parse(n)),R=!0):n=u.response,void 0!==n.response?(m=n.statusCode,v=m<400,e=n.headers,n=n.response):e=function(e){for(var t=i.a.trim(e.getAllResponseHeaders()).split("\r\n"),n={},r=0;r-1;)t=y.slice(O,e),O=e+1,C(t)}function C(e){try{e=JSON.parse(e)}catch(e){return void t.complete(new s.a("Malformed response body from server: "+e.message,null,400))}t.emit("data",e)}u.onreadystatechange=function(){var e=u.readyState;e<3||0!==u.status&&(void 0===m&&(1223===(m=u.status)&&(m=204),clearTimeout(n),v=m<400,204!=m?g=3==t.requestMode&&v&&function(e){return e.getResponseHeader&&(e.getResponseHeader("transfer-encoding")||!e.getResponseHeader("content-length"))}(u):t.complete(null,null,null,null,m)),3==e&&g?b():4==e&&(g?(b(),t.streamComplete=!0,i.a.nextTick((function(){t.complete()}))):A()))},u.send(r)},g.prototype.dispose=function(){var e=this.xhr;if(e){e.onreadystatechange=e.onerror=e.onabort=e.ontimeout=t,this.xhr=null;var n=this.timer;n&&(clearTimeout(n),this.timer=null),this.requestComplete||e.abort()}delete p[this.id]},o.a.xhrSupported&&("object"==typeof h.a&&h.a.addUnloadListener((function(){for(var e in p)p[e].dispose()})),void 0!==a.a&&(a.a.supportsAuthHeaders=!0,a.a.Request=function(e,t,n,i,r,o,s){var a=m(n,i,r,o,0,t&&t.options.timeouts,e);return a.once("complete",s),a.exec(),a},a.a.checkConnectivity=function(e){var t=u.a.internetUpUrl;c.a.logAction(c.a.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+t),a.a.getUri(null,t,null,null,(function(t,n){var i=!t&&"yes"==n.replace(/\n/,"");c.a.logAction(c.a.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+i),e(null,i)}))})),g}();t.a=p}).call(this,n(17))},function(e,t,n){var i;e.exports=(i=n(12),n(10),n(46),n(18),n(37),n(36),n(29),n(30),n(31),n(47),n(48),i)},function(e,t,n){var i,r,o,s;e.exports=(i=n(12),o=(r=i).lib.Base,s=r.enc.Utf8,void(r.algo.HMAC=o.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=s.parse(t));var n=e.blockSize,i=4*n;t.sigBytes>i&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),o=this._iKey=t.clone(),a=r.words,c=o.words,u=0;u>>2];e.sigBytes-=t}},o.BlockCipher=p.extend({cfg:p.cfg.extend({mode:g,padding:m}),reset:function(){var e;p.reset.call(this);var t=this.cfg,n=t.iv,i=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=i.createEncryptor:(e=i.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,n&&n.words):(this._mode=e.call(i,this,n&&n.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4}),y=o.CipherParams=s.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),v=(r.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,n=e.salt;return(n?a.create([1398893684,1701076831]).concat(n).concat(t):t).toString(l)},parse:function(e){var t,n=l.parse(e),i=n.words;return 1398893684==i[0]&&1701076831==i[1]&&(t=a.create(i.slice(2,4)),i.splice(0,4),n.sigBytes-=16),y.create({ciphertext:n,salt:t})}},O=o.SerializableCipher=s.extend({cfg:s.extend({format:v}),encrypt:function(e,t,n,i){i=this.cfg.extend(i);var r=e.createEncryptor(n,i),o=r.finalize(t),s=r.cfg;return y.create({ciphertext:o,key:n,iv:s.iv,algorithm:e,mode:s.mode,padding:s.padding,blockSize:e.blockSize,formatter:i.format})},decrypt:function(e,t,n,i){return i=this.cfg.extend(i),t=this._parse(t,i.format),e.createDecryptor(n,i).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),R=(r.kdf={}).OpenSSL={execute:function(e,t,n,i){i||(i=a.random(8));var r=h.create({keySize:t+n}).compute(e,i),o=a.create(r.words.slice(t),4*n);return r.sigBytes=4*t,y.create({key:r,iv:o,salt:i})}},A=o.PasswordBasedCipher=O.extend({cfg:O.cfg.extend({kdf:R}),encrypt:function(e,t,n,i){var r=(i=this.cfg.extend(i)).kdf.execute(n,e.keySize,e.ivSize);i.iv=r.iv;var o=O.encrypt.call(this,e,t,r.key,i);return o.mixIn(r),o},decrypt:function(e,t,n,i){i=this.cfg.extend(i),t=this._parse(t,i.format);var r=i.kdf.execute(n,e.keySize,e.ivSize,t.salt);return i.iv=r.iv,O.decrypt.call(this,e,t,r.key,i)}}))))},function(e,t,n){var i;e.exports=(i=n(12),i.enc.Hex)},function(e,t,n){var i;e.exports=(i=n(12),i.enc.Utf8)},function(e,t,n){"use strict";var i=n(8),r=n(1),o=n(7),s=n(0),a=n(26),c=n(2),u=function(){var e=i.a.Action;function t(e){o.a.call(this),this.transport=e,this.messageQueue=new a.a;var t=this;e.on("ack",(function(e,n){t.onAck(e,n)})),e.on("nack",(function(e,n,i){t.onNack(e,n,i)}))}return r.a.inherits(t,o.a),t.prototype.onAck=function(e,t){s.a.logAction(s.a.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages(e,t)},t.prototype.onNack=function(e,t,n){s.a.logAction(s.a.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+r.a.inspectError(n)),n||(n=new c.a("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages(e,t,n)},t.prototype.onceIdle=function(e){var t=this.messageQueue;0!==t.count()?t.once("idle",e):e()},t.prototype.send=function(e){e.ackRequired&&this.messageQueue.push(e),s.a.shouldLog(s.a.LOG_MICRO)&&s.a.logAction(s.a.LOG_MICRO,"Protocol.send()","sending msg; "+i.a.stringify(e.message)),e.sendAttempted=!0,this.transport.send(e.message)},t.prototype.getTransport=function(){return this.transport},t.prototype.getPendingMessages=function(){return this.messageQueue.copyAll()},t.prototype.clearPendingMessages=function(){return this.messageQueue.clear()},t.prototype.finish=function(){var e=this.transport;this.onceIdle((function(){e.disconnect()}))},t.PendingMessage=function(t,n){this.message=t,this.callback=n,this.merged=!1;var i=t.action;this.sendAttempted=!1,this.ackRequired=i==e.MESSAGE||i==e.PRESENCE},t}();t.a=u},function(e,t,n){"use strict";(function(e){var n=function(){function t(){}return t.addListener=function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent("on"+t,(function(){n.apply(e,arguments)}))},t.removeListener=function(e,t,n){e.removeEventListener?e.removeEventListener(t,n,!1):e.detachEvent("on"+t,(function(){n.apply(e,arguments)}))},t.addMessageListener=function(e,n){t.addListener(e,"message",n)},t.removeMessageListener=function(e,n){t.removeListener(e,"message",n)},t.addUnloadListener=function(n){t.addListener(e,"unload",n)},t}();t.a=n}).call(this,n(17))},function(e,t,n){var i;e.exports=(i=n(12),function(e){var t=i,n=t.lib,r=n.WordArray,o=n.Hasher,s=t.algo,a=[],c=[];!function(){function t(t){for(var n=e.sqrt(t),i=2;i<=n;i++)if(!(t%i))return!1;return!0}function n(e){return 4294967296*(e-(0|e))|0}for(var i=2,r=0;r<64;)t(i)&&(r<8&&(a[r]=n(e.pow(i,.5))),c[r]=n(e.pow(i,1/3)),r++),i++}();var u=[],l=s.SHA256=o.extend({_doReset:function(){this._hash=new r.init(a.slice(0))},_doProcessBlock:function(e,t){for(var n=this._hash.words,i=n[0],r=n[1],o=n[2],s=n[3],a=n[4],l=n[5],h=n[6],p=n[7],f=0;f<64;f++){if(f<16)u[f]=0|e[t+f];else{var d=u[f-15],g=(d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3,m=u[f-2],y=(m<<15|m>>>17)^(m<<13|m>>>19)^m>>>10;u[f]=g+u[f-7]+y+u[f-16]}var v=i&r^i&o^r&o,O=(i<<30|i>>>2)^(i<<19|i>>>13)^(i<<10|i>>>22),R=p+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&l^~a&h)+c[f]+u[f];p=h,h=l,l=a,a=s+R|0,s=o,o=r,r=i,i=R+(O+v)|0}n[0]=n[0]+i|0,n[1]=n[1]+r|0,n[2]=n[2]+o|0,n[3]=n[3]+s|0,n[4]=n[4]+a|0,n[5]=n[5]+l|0,n[6]=n[6]+h|0,n[7]=n[7]+p|0},_doFinalize:function(){var t=this._data,n=t.words,i=8*this._nDataBytes,r=8*t.sigBytes;return n[r>>>5]|=128<<24-r%32,n[14+(r+64>>>9<<4)]=e.floor(i/4294967296),n[15+(r+64>>>9<<4)]=i,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=o._createHelper(l),t.HmacSHA256=o._createHmacHelper(l)}(Math),i.SHA256)},function(e,t,n){var i,r,o,s,a,c,u,l;e.exports=(l=n(12),r=(i=l).lib,o=r.WordArray,s=r.Hasher,a=i.algo,c=[],u=a.SHA1=s.extend({_doReset:function(){this._hash=new o.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var n=this._hash.words,i=n[0],r=n[1],o=n[2],s=n[3],a=n[4],u=0;u<80;u++){if(u<16)c[u]=0|e[t+u];else{var l=c[u-3]^c[u-8]^c[u-14]^c[u-16];c[u]=l<<1|l>>>31}var h=(i<<5|i>>>27)+a+c[u];h+=u<20?1518500249+(r&o|~r&s):u<40?1859775393+(r^o^s):u<60?(r&o|r&s|o&s)-1894007588:(r^o^s)-899497514,a=s,s=o,o=r<<30|r>>>2,r=i,i=h}n[0]=n[0]+i|0,n[1]=n[1]+r|0,n[2]=n[2]+o|0,n[3]=n[3]+s|0,n[4]=n[4]+a|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,i=8*e.sigBytes;return t[i>>>5]|=128<<24-i%32,t[14+(i+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(i+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}}),i.SHA1=s._createHelper(u),i.HmacSHA1=s._createHmacHelper(u),l.SHA1)},function(e,t,n){var i;e.exports=(i=n(12),n(36),n(29),i.HmacSHA256)},function(e,t,n){"use strict";(function(e){var i=n(1),r=n(15),o=n(3),s=n(7),a=n(6),c=n(2),u=n(4),l=n(0);t.a=function(t){var n=function(){},h=e._ablyjs_jsonp={};h._=function(e){return h["_"+e]||n};var p=1,f=null;function d(e,t,n){n.stream=!1,r.a.call(this,e,t,n),this.shortName="jsonp"}i.a.inherits(d,r.a),d.isAvailable=function(){return o.a.jsonpSupported&&o.a.allowComet},d.isAvailable()&&(t.supportedTransports.jsonp=d),o.a.jsonpSupported&&(f=document.getElementsByTagName("head")[0]);var g=null;e.JSONPTransport=d,d.tryConnect=function(e,t,n,i){var r=new d(e,t,n),o=function(e){i({event:this.event,error:e})};r.on(["failed","disconnected"],o),r.on("preconnect",(function(){l.a.logAction(l.a.LOG_MINOR,"JSONPTransport.tryConnect()","viable transport "+r),r.off(["failed","disconnected"],o),i(null,r)})),r.connect()},d.prototype.toString=function(){return"JSONPTransport; uri="+this.baseUri+"; isConnected="+this.isConnected};var m=d.prototype.createRequest=function(e,t,n,r,o,s,a){return s=this&&this.timeouts||s||u.a.TIMEOUTS,new y(void 0,e,t,i.a.copy(n),r,o,s,a)};function y(e,t,n,r,o,a,c,u){s.a.call(this),void 0===e&&(e=p++),this.id=e,this.uri=t,this.params=r||{},this.params.rnd=i.a.cheapRandStr(),n&&(n["X-Ably-Version"]&&(this.params.v=n["X-Ably-Version"]),n["Ably-Agent"]&&(this.params.agent=n["Ably-Agent"])),this.body=o,this.method=u,this.requestMode=a,this.timeouts=c,this.requestComplete=!1}return i.a.inherits(y,s.a),y.prototype.exec=function(){var e=this.id,t=this.body,n=this.method,o=this.uri,s=this.params,a=this;s.callback="_ablyjs_jsonp._("+e+")",s.envelope="jsonp",t&&(s.body=t),n&&"get"!==n&&(s.method=n);var u=this.script=document.createElement("script"),p=o+i.a.toQueryString(s);u.src=p,u.src.split("/").slice(-1)[0]!==p.split("/").slice(-1)[0]&&l.a.logAction(l.a.LOG_ERROR,"JSONP Request.exec()","Warning: the browser appears to have truncated the script URI. This will likely result in the request failing due to an unparseable body param"),u.async=!0,u.type="text/javascript",u.charset="UTF-8",u.onerror=function(e){a.complete(new c.a("JSONP script error (event: "+i.a.inspect(e)+")",null,400))},h["_"+e]=function(e){if(e.statusCode){var t=e.response;if(204==e.statusCode)a.complete(null,null,null,e.statusCode);else if(t)if(e.statusCode<400||i.a.isArray(t))a.complete(null,t,e.headers,e.statusCode);else{var n=t.error||new c.a("Error response received from server",null,e.statusCode);a.complete(n)}else a.complete(new c.a("Invalid server response: no envelope detected",null,500))}else a.complete(null,e)};var d=this.requestMode==r.a.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout;this.timer=setTimeout((function(){a.abort()}),d),f.insertBefore(u,f.firstChild)},y.prototype.complete=function(e,t,n,i){var r;(n=n||{},this.requestComplete)||(this.requestComplete=!0,t&&(r="string"==typeof t?"text/plain":"application/json",n["content-type"]=r,this.emit("data",t)),this.emit("complete",e,t,n,!0,i),this.dispose())},y.prototype.abort=function(){this.dispose()},y.prototype.dispose=function(){var e=this.timer;e&&(clearTimeout(e),this.timer=null);var t=this.script;t.parentNode&&t.parentNode.removeChild(t),delete h[this.id],this.emit("disposed")},o.a.jsonpSupported&&!a.a.Request&&(a.a.Request=function(e,t,n,o,s,a,c){var u=m(n,o,s,a,r.a.REQ_SEND,t&&t.options.timeouts,e);return u.once("complete",c),i.a.nextTick((function(){u.exec()})),u},a.a.checkConnectivity=function(e){var t=u.a.jsonpInternetUpUrl;if(g)g.push(e);else{g=[e],l.a.logAction(l.a.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Sending; "+t);var n=new y("isTheInternetUp",t,null,null,null,r.a.REQ_SEND,u.a.TIMEOUTS);n.once("complete",(function(e,t){var n=!e&&t;l.a.logAction(l.a.LOG_MICRO,"(JSONP)Http.checkConnectivity()","Result: "+n);for(var i=0;i=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n(43),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(17))},function(e,t,n){(function(e,t){!function(e,n){"use strict";if(!e.setImmediate){var i,r,o,s,a,c=1,u={},l=!1,h=e.document,p=Object.getPrototypeOf&&Object.getPrototypeOf(e);p=p&&p.setTimeout?p:e,"[object process]"==={}.toString.call(e.process)?i=function(e){t.nextTick((function(){d(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=n,t}}()?e.MessageChannel?((o=new MessageChannel).port1.onmessage=function(e){d(e.data)},i=function(e){o.port2.postMessage(e)}):h&&"onreadystatechange"in h.createElement("script")?(r=h.documentElement,i=function(e){var t=h.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):i=function(e){setTimeout(d,0,e)}:(s="setImmediate$"+Math.random()+"$",a=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(s)&&d(+t.data.slice(s.length))},e.addEventListener?e.addEventListener("message",a,!1):e.attachEvent("onmessage",a),i=function(t){e.postMessage(s+t,"*")}),p.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n1)for(var n=1;n>>8&16711935}n.Utf16=n.Utf16BE={stringify:function(e){for(var t=e.words,n=e.sigBytes,i=[],r=0;r>>2]>>>16-r%4*8&65535;i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var n=e.length,i=[],r=0;r>>1]|=e.charCodeAt(r)<<16-r%2*16;return t.create(i,2*n)}},n.Utf16LE={stringify:function(e){for(var t=e.words,n=e.sigBytes,i=[],o=0;o>>2]>>>16-o%4*8&65535);i.push(String.fromCharCode(s))}return i.join("")},parse:function(e){for(var n=e.length,i=[],o=0;o>>1]|=r(e.charCodeAt(o)<<16-o%2*16);return t.create(i,2*n)}}}(),i.enc.Utf16)},function(e,t,n){var i,r,o,s;e.exports=(s=n(12),n(31),r=(i=s).lib.CipherParams,o=i.enc.Hex,i.format.Hex={stringify:function(e){return e.ciphertext.toString(o)},parse:function(e){var t=o.parse(e);return r.create({ciphertext:t})}},s.format.Hex)},function(e,t,n){var i;e.exports=(i=n(12),n(18),n(49),n(30),n(31),function(){var e=i,t=e.lib.BlockCipher,n=e.algo,r=[],o=[],s=[],a=[],c=[],u=[],l=[],h=[],p=[],f=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var n=0,i=0;for(t=0;t<256;t++){var d=i^i<<1^i<<2^i<<3^i<<4;d=d>>>8^255&d^99,r[n]=d,o[d]=n;var g=e[n],m=e[g],y=e[m],v=257*e[d]^16843008*d;s[n]=v<<24|v>>>8,a[n]=v<<16|v>>>16,c[n]=v<<8|v>>>24,u[n]=v,v=16843009*y^65537*m^257*g^16843008*n,l[d]=v<<24|v>>>8,h[d]=v<<16|v>>>16,p[d]=v<<8|v>>>24,f[d]=v,n?(n=g^e[e[e[y^g]]],i^=e[e[i]]):n=i=1}}();var d=[0,1,2,4,8,16,32,64,128,27,54],g=n.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,n=e.sigBytes/4,i=4*((this._nRounds=n+6)+1),o=this._keySchedule=[],s=0;s6&&s%n==4&&(u=r[u>>>24]<<24|r[u>>>16&255]<<16|r[u>>>8&255]<<8|r[255&u]):(u=r[(u=u<<8|u>>>24)>>>24]<<24|r[u>>>16&255]<<16|r[u>>>8&255]<<8|r[255&u],u^=d[s/n|0]<<24),o[s]=o[s-n]^u);for(var a=this._invKeySchedule=[],c=0;c>>24]]^h[r[u>>>16&255]]^p[r[u>>>8&255]]^f[r[255&u]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,s,a,c,u,r)},decryptBlock:function(e,t){var n=e[t+1];e[t+1]=e[t+3],e[t+3]=n,this._doCryptBlock(e,t,this._invKeySchedule,l,h,p,f,o),n=e[t+1],e[t+1]=e[t+3],e[t+3]=n},_doCryptBlock:function(e,t,n,i,r,o,s,a){for(var c=this._nRounds,u=e[t]^n[0],l=e[t+1]^n[1],h=e[t+2]^n[2],p=e[t+3]^n[3],f=4,d=1;d>>24]^r[l>>>16&255]^o[h>>>8&255]^s[255&p]^n[f++],m=i[l>>>24]^r[h>>>16&255]^o[p>>>8&255]^s[255&u]^n[f++],y=i[h>>>24]^r[p>>>16&255]^o[u>>>8&255]^s[255&l]^n[f++],v=i[p>>>24]^r[u>>>16&255]^o[l>>>8&255]^s[255&h]^n[f++];u=g,l=m,h=y,p=v}g=(a[u>>>24]<<24|a[l>>>16&255]<<16|a[h>>>8&255]<<8|a[255&p])^n[f++],m=(a[l>>>24]<<24|a[h>>>16&255]<<16|a[p>>>8&255]<<8|a[255&u])^n[f++],y=(a[h>>>24]<<24|a[p>>>16&255]<<16|a[u>>>8&255]<<8|a[255&l])^n[f++],v=(a[p>>>24]<<24|a[u>>>16&255]<<16|a[l>>>8&255]<<8|a[255&h])^n[f++],e[t]=g,e[t+1]=m,e[t+2]=y,e[t+3]=v},keySize:8});e.AES=t._createHelper(g)}(),i.AES)},function(e,t,n){var i;e.exports=(i=n(12),function(e){var t=i,n=t.lib,r=n.WordArray,o=n.Hasher,s=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var c=s.MD5=o.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var n=0;n<16;n++){var i=t+n,r=e[i];e[i]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8)}var o=this._hash.words,s=e[t+0],c=e[t+1],f=e[t+2],d=e[t+3],g=e[t+4],m=e[t+5],y=e[t+6],v=e[t+7],O=e[t+8],R=e[t+9],A=e[t+10],b=e[t+11],C=e[t+12],w=e[t+13],S=e[t+14],T=e[t+15],_=o[0],I=o[1],M=o[2],k=o[3];_=u(_,I,M,k,s,7,a[0]),k=u(k,_,I,M,c,12,a[1]),M=u(M,k,_,I,f,17,a[2]),I=u(I,M,k,_,d,22,a[3]),_=u(_,I,M,k,g,7,a[4]),k=u(k,_,I,M,m,12,a[5]),M=u(M,k,_,I,y,17,a[6]),I=u(I,M,k,_,v,22,a[7]),_=u(_,I,M,k,O,7,a[8]),k=u(k,_,I,M,R,12,a[9]),M=u(M,k,_,I,A,17,a[10]),I=u(I,M,k,_,b,22,a[11]),_=u(_,I,M,k,C,7,a[12]),k=u(k,_,I,M,w,12,a[13]),M=u(M,k,_,I,S,17,a[14]),_=l(_,I=u(I,M,k,_,T,22,a[15]),M,k,c,5,a[16]),k=l(k,_,I,M,y,9,a[17]),M=l(M,k,_,I,b,14,a[18]),I=l(I,M,k,_,s,20,a[19]),_=l(_,I,M,k,m,5,a[20]),k=l(k,_,I,M,A,9,a[21]),M=l(M,k,_,I,T,14,a[22]),I=l(I,M,k,_,g,20,a[23]),_=l(_,I,M,k,R,5,a[24]),k=l(k,_,I,M,S,9,a[25]),M=l(M,k,_,I,d,14,a[26]),I=l(I,M,k,_,O,20,a[27]),_=l(_,I,M,k,w,5,a[28]),k=l(k,_,I,M,f,9,a[29]),M=l(M,k,_,I,v,14,a[30]),_=h(_,I=l(I,M,k,_,C,20,a[31]),M,k,m,4,a[32]),k=h(k,_,I,M,O,11,a[33]),M=h(M,k,_,I,b,16,a[34]),I=h(I,M,k,_,S,23,a[35]),_=h(_,I,M,k,c,4,a[36]),k=h(k,_,I,M,g,11,a[37]),M=h(M,k,_,I,v,16,a[38]),I=h(I,M,k,_,A,23,a[39]),_=h(_,I,M,k,w,4,a[40]),k=h(k,_,I,M,s,11,a[41]),M=h(M,k,_,I,d,16,a[42]),I=h(I,M,k,_,y,23,a[43]),_=h(_,I,M,k,R,4,a[44]),k=h(k,_,I,M,C,11,a[45]),M=h(M,k,_,I,T,16,a[46]),_=p(_,I=h(I,M,k,_,f,23,a[47]),M,k,s,6,a[48]),k=p(k,_,I,M,v,10,a[49]),M=p(M,k,_,I,S,15,a[50]),I=p(I,M,k,_,m,21,a[51]),_=p(_,I,M,k,C,6,a[52]),k=p(k,_,I,M,d,10,a[53]),M=p(M,k,_,I,A,15,a[54]),I=p(I,M,k,_,c,21,a[55]),_=p(_,I,M,k,O,6,a[56]),k=p(k,_,I,M,T,10,a[57]),M=p(M,k,_,I,y,15,a[58]),I=p(I,M,k,_,w,21,a[59]),_=p(_,I,M,k,g,6,a[60]),k=p(k,_,I,M,b,10,a[61]),M=p(M,k,_,I,f,15,a[62]),I=p(I,M,k,_,R,21,a[63]),o[0]=o[0]+_|0,o[1]=o[1]+I|0,o[2]=o[2]+M|0,o[3]=o[3]+k|0},_doFinalize:function(){var t=this._data,n=t.words,i=8*this._nDataBytes,r=8*t.sigBytes;n[r>>>5]|=128<<24-r%32;var o=e.floor(i/4294967296),s=i;n[15+(r+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),n[14+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),t.sigBytes=4*(n.length+1),this._process();for(var a=this._hash,c=a.words,u=0;u<4;u++){var l=c[u];c[u]=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8)}return a},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,n,i,r,o,s){var a=e+(t&n|~t&i)+r+s;return(a<>>32-o)+t}function l(e,t,n,i,r,o,s){var a=e+(t&i|n&~i)+r+s;return(a<>>32-o)+t}function h(e,t,n,i,r,o,s){var a=e+(t^n^i)+r+s;return(a<>>32-o)+t}function p(e,t,n,i,r,o,s){var a=e+(n^(t|~i))+r+s;return(a<>>32-o)+t}t.MD5=o._createHelper(c),t.HmacMD5=o._createHmacHelper(c)}(Math),i.MD5)},function(e,t,n){"use strict";n.r(t);var i=n(3),r=n(1),o=n(0),s=n(4),a=n(14),c=function(){function e(){this.id=void 0,this.deviceSecret=void 0,this.platform=void 0,this.formFactor=void 0,this.clientId=void 0,this.metadata=void 0,this.deviceIdentityToken=void 0,this.push={recipient:void 0,state:void 0,error:void 0}}return e.prototype.toJSON=function(){return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:this.push.recipient,state:this.push.state,error:this.push.error}}},e.prototype.toString=function(){var e="[DeviceDetails";return this.id&&(e+="; id="+this.id),this.platform&&(e+="; platform="+this.platform),this.formFactor&&(e+="; formFactor="+this.formFactor),this.clientId&&(e+="; clientId="+this.clientId),this.metadata&&(e+="; metadata="+this.metadata),this.deviceIdentityToken&&(e+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),this.push.recipient&&(e+="; push.recipient="+JSON.stringify(this.push.recipient)),this.push.state&&(e+="; push.state="+this.push.state),this.push.error&&(e+="; push.error="+JSON.stringify(this.push.error)),this.push.metadata&&(e+="; push.metadata="+this.push.metadata),e+="]"},e.toRequestBody=r.a.encodeBody,e.fromResponseBody=function(t,n){return n&&(t=r.a.decodeBody(t,n)),r.a.isArray(t)?e.fromValuesArray(t):e.fromValues(t)},e.fromValues=function(t){return t.error=t.error&&ErrorInfo.fromValues(t.error),r.a.mixin(new e,t)},e.fromValuesArray=function(t){for(var n=t.length,i=new Array(n),r=0;r=300){var h=u&&u.error||n;return h||((h=new Error("Error in unenveloping "+i)).statusCode=c),void e(h,u,l,!0,c)}e(n,u,l,!0,c)}else e(n,i,o,!0,a)}else e(n)}}(m,g),(d=d||{}).envelope=g),n(i,f,d,m,(function s(l,g){o.a.shouldLog(o.a.LOG_MICRO)&&o.a.logAction(o.a.LOG_MICRO,"Resource."+t+"()","Sending; "+c(h,g));var y=[i,h,l,p,g,function(e,t,r,o,c){e&&a.a.isTokenErr(e)?i.auth.authorize(null,null,(function(e){e?m(e):n(i,f,d,m,s)})):m(e,t,r,o,c)}];if(p||y.splice(3,1),o.a.shouldLog(o.a.LOG_MICRO)){var v=p;if((l["content-type"]||"").indexOf("msgpack")>0)try{v=e.decode(p)}catch(e){o.a.logAction(o.a.LOG_MICRO,"Resource."+t+"()","Sending MsgPack Decoding Error: "+r.a.inspectError(e))}o.a.logAction(o.a.LOG_MICRO,"Resource."+t+"()","Sending; "+c(h,g)+"; Body: "+v)}u.a[t].apply(this,y)}))},t}(),p=function(){function e(e,t,n,i,r,o){this.rest=e,this.path=t,this.headers=n,this.envelope=i,this.bodyHandler=r,this.useHttpPaginatedResponse=o||!1}function t(e,t,n){if(this.resource=e,this.items=t,n){var i=this;"first"in n&&(this.first=function(e){if(!e&&i.resource.rest.options.promises)return r.a.promisify(i,"first",[]);i.get(n.first,e)}),"current"in n&&(this.current=function(e){if(!e&&i.resource.rest.options.promises)return r.a.promisify(i,"current",[]);i.get(n.current,e)}),this.next=function(e){if(!e&&i.resource.rest.options.promises)return r.a.promisify(i,"next",[]);"next"in n?i.get(n.next,e):e(null,null)},this.hasNext=function(){return"next"in n},this.isLast=function(){return!this.hasNext()}}}function n(e,n,i,r,o,s){t.call(this,e,n,o),this.statusCode=r,this.success=r<300&&r>=200,this.headers=i,this.errorCode=s&&s.code,this.errorMessage=s&&s.message}return r.a.arrForEach(u.a.methodsWithoutBody,(function(t){e.prototype[t]=function(e,n){var i=this;h[t](i.rest,i.path,i.headers,e,i.envelope,(function(e,t,r,o,s){i.handlePage(e,t,r,o,s,n)}))}})),r.a.arrForEach(u.a.methodsWithBody,(function(t){e.prototype[t]=function(e,n,i){var r=this;h[t](r.rest,r.path,n,r.headers,e,r.envelope,(function(e,t,n,o,s){i&&r.handlePage(e,t,n,o,s,i)}))}})),e.prototype.handlePage=function(e,i,s,a,c,u){if(e&&function(e,t,n){return!(n&&(t||"number"==typeof e.code))}(e,i,this.useHttpPaginatedResponse))return o.a.logAction(o.a.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+r.a.inspectError(e)),void u(e);var l,h,p;try{l=this.bodyHandler(i,s,a)}catch(t){return void u(e||t)}s&&(h=s.Link||s.link)&&(p=function(e){"string"==typeof e&&(e=e.split(","));for(var t,n,i={},o=0;o;\s*rel="(\w+)"$/);if(s){var a=(t=s[1],n=void 0,(n=t.match(/^\.\/(\w+)\?(.*)$/))&&r.a.parseQueryString(n[2]));a&&(i[s[2]]=a)}}return i}(h)),this.useHttpPaginatedResponse?u(null,new n(this,l,s,c,p,e)):u(null,new t(this,l,p))},t.prototype.get=function(e,t){var n=this.resource;h.get(n.rest,n.path,n.headers,e,n.envelope,(function(e,i,r,o,s){n.handlePage(e,i,r,o,s,t)}))},r.a.inherits(n,t),e}(),f=n(2),d=function(){function e(){this.channel=void 0,this.deviceId=void 0,this.clientId=void 0}return e.prototype.toJSON=function(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}},e.prototype.toString=function(){var e="[PushChannelSubscription";return this.channel&&(e+="; channel="+this.channel),this.deviceId&&(e+="; deviceId="+this.deviceId),this.clientId&&(e+="; clientId="+this.clientId),e+="]"},e.toRequestBody=r.a.encodeBody,e.fromResponseBody=function(t,n){return n&&(t=r.a.decodeBody(t,n)),r.a.isArray(t)?e.fromValuesArray(t):e.fromValues(t)},e.fromValues=function(t){return r.a.mixin(new e,t)},e.fromValuesArray=function(t){for(var n=t.length,i=new Array(n),r=0;rr?c(new f.a("Maximum size of messages that can be published at once exceeded ( was "+n+" bytes; limit is "+r+" bytes)",40009,400)):u._publish(R.a.serialize(t,p),g,i,c)}}))},t.prototype._publish=function(e,t,n,i){h.post(this.rest,this.basePath+"/messages",e,t,n,!1,i)},t}(),b=function(){function e(e){this.count=e&&e.count||0,this.data=e&&e.data||0,this.uncompressedData=e&&e.uncompressedData||0,this.failed=e&&e.failed||0,this.refused=e&&e.refused||0}function t(t){var n=this;e.call(this,t),this.category=void 0,t&&t.category&&(this.category={},r.a.forInOwnNonNullProps(t.category,(function(i){n.category[i]=new e(t.category[i])})))}function n(e){this.peak=e&&e.peak||0,this.min=e&&e.min||0,this.mean=e&&e.mean||0,this.opened=e&&e.opened||0,this.refused=e&&e.refused||0}function i(e){this.succeeded=e&&e.succeeded||0,this.failed=e&&e.failed||0,this.refused=e&&e.refused||0}function o(e){this.plain=new n(e&&e.plain),this.tls=new n(e&&e.tls),this.all=new n(e&&e.all)}function s(e){this.messages=new t(e&&e.messages),this.presence=new t(e&&e.presence),this.all=new t(e&&e.all)}function a(e){this.realtime=new s(e&&e.realtime),this.rest=new s(e&&e.rest),this.webhook=new s(e&&e.webhook),this.sharedQueue=new s(e&&e.sharedQueue),this.externalQueue=new s(e&&e.externalQueue),this.httpEvent=new s(e&&e.httpEvent),this.push=new s(e&&e.push),this.all=new s(e&&e.all)}function c(e){this.all=new s(e&&e.all),this.inbound=new a(e&&e.inbound),this.outbound=new a(e&&e.outbound)}function u(e){this.all=new s(e&&e.all),this.producerPaid=new c(e&&e.producerPaid),this.consumerPaid=new c(e&&e.consumerPaid)}function l(e){this.messages=e&&e.messages||0;var t=e&&e.notifications;this.notifications={invalid:t&&t.invalid||0,attempted:t&&t.attempted||0,successful:t&&t.successful||0,failed:t&&t.failed||0},this.directPublishes=e&&e.directPublishes||0}function h(e){this.succeeded=e&&e.succeeded||0,this.skipped=e&&e.skipped||0,this.failed=e&&e.failed||0}function p(e){var t=this;this.delta=void 0,e&&e.delta&&(this.delta={},r.a.forInOwnNonNullProps(e.delta,(function(n){t.delta[n]=new h(e.delta[n])})))}function f(e){c.call(this,e),this.persisted=new s(e&&e.persisted),this.connections=new o(e&&e.connections),this.channels=new n(e&&e.channels),this.apiRequests=new i(e&&e.apiRequests),this.tokenRequests=new i(e&&e.tokenRequests),this.xchgProducer=new u(e&&e.xchgProducer),this.xchgConsumer=new u(e&&e.xchgConsumer),this.push=new l(e&&e.pushStats),this.processed=new p(e&&e.processed),this.inProgress=e&&e.inProgress||void 0,this.unit=e&&e.unit||void 0,this.intervalId=e&&e.intervalId||void 0}return f.fromValues=function(e){return new f(e)},f}(),C=function(){var e=function(){},t=i.a.msgpack;function n(e){if(!(this instanceof n))return new n(e);if(!e){var t="no options provided";throw o.a.logAction(o.a.LOG_ERROR,"Rest()",t),new Error(t)}if((e=s.a.objectifyOptions(e)).log&&o.a.setLog(e.log.level,e.log.handler),o.a.logAction(o.a.LOG_MICRO,"Rest()","initialized with clientOptions "+r.a.inspect(e)),this.options=s.a.normaliseOptions(e),e.key){var i=e.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!i){t="invalid key parameter";throw o.a.logAction(o.a.LOG_ERROR,"Rest()",t),new Error(t)}e.keyName=i[1],e.keySecret=i[2]}if("clientId"in e){if("string"!=typeof e.clientId&&null!==e.clientId)throw new f.a("clientId must be either a string or null",40012,400);if("*"===e.clientId)throw new f.a('Can’t use "*" as a clientId as that string is reserved. (To change the default token request behaviour to use a wildcard clientId, use {defaultTokenParams: {clientId: "*"}})',40012,400)}o.a.logAction(o.a.LOG_MINOR,"Rest()","started; version = "+s.a.libstring),this.baseUri=this.authority=function(t){return s.a.getHttpScheme(e)+t+":"+s.a.getPort(e,!1)},this._currentFallback=null,this.serverTimeOffset=null,this.auth=new a.a(this,e),this.channels=new c(this),this.push=new g(this)}function c(e){this.rest=e,this.all=Object.create(null)}return n.prototype.stats=function(t,n){if(void 0===n)if("function"==typeof t)n=t,t=null;else{if(this.options.promises)return r.a.promisify(this,"stats",arguments);n=e}var i=r.a.defaultGetHeaders(),o=this.options.useBinaryProtocol?"msgpack":"json",s=u.a.supportsLinkHeaders?void 0:o;this.options.headers&&r.a.mixin(i,this.options.headers),new p(this,"/stats",i,s,(function(e,t,n){for(var i=n?e:JSON.parse(e),r=0;rt.timestamp;var n=e.parseId(),i=t.parseId();return n.msgSerial===i.msgSerial?n.index>i.index:n.msgSerial>i.msgSerial}return r.a.inherits(s,v),s.prototype.enter=function(e,t){if(n(this))throw new f.a("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,e,"enter",t)},s.prototype.update=function(e,t){if(n(this))throw new f.a("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,e,"update",t)},s.prototype.enterClient=function(e,t,n){return this._enterOrUpdateClient(e,t,"enter",n)},s.prototype.updateClient=function(e,t,n){return this._enterOrUpdateClient(e,t,"update",n)},s.prototype._enterOrUpdateClient=function(t,n,i,s){if(!s)if("function"==typeof n)s=n,n=null;else{if(this.channel.realtime.options.promises)return r.a.promisify(this,"_enterOrUpdateClient",[t,n,i]);s=e}var a=this.channel;if(a.connectionManager.activeState()){o.a.logAction(o.a.LOG_MICRO,"RealtimePresence."+i+"Client()","channel = "+a.name+", client = "+(t||"(implicit) "+this.channel.realtime.auth.clientId));var c=y.a.fromValues({action:i,data:n});t&&(c.clientId=t);var u=this;y.a.encode(c,a.channelOptions,(function(e){if(e)s(e);else switch(a.state){case"attached":a.sendPresence(c,s);break;case"initialized":case"detached":a.attach();case"attaching":u.pendingPresence.push({presence:c,callback:s});break;default:(e=new f.a("Unable to "+i+" presence channel while in "+a.state+" state",90001)).code=90001,s(e)}}))}else s(a.connectionManager.getError())},s.prototype.leave=function(e,t){if(n(this))throw new f.a("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,e,t)},s.prototype.leaveClient=function(t,n,i){if(!i)if("function"==typeof n)i=n,n=null;else{if(this.channel.realtime.options.promises)return r.a.promisify(this,"leaveClient",[t,n]);i=e}var s=this.channel;if(s.connectionManager.activeState()){o.a.logAction(o.a.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+t);var a=y.a.fromValues({action:"leave",data:n});switch(t&&(a.clientId=t),s.state){case"attached":s.sendPresence(a,i);break;case"attaching":this.pendingPresence.push({presence:a,callback:i});break;case"initialized":case"failed":i(new f.a("Unable to leave presence channel (incompatible state)",90001));break;default:i(M.a.failed)}}else i(s.connectionManager.getError())},s.prototype.get=function(){var t=Array.prototype.slice.call(arguments);1==t.length&&"function"==typeof t[0]&&t.unshift(null);var n=t[0],o=t[1],s=!n||!("waitForSync"in n)||n.waitForSync;if(!o){if(this.channel.realtime.options.promises)return r.a.promisify(this,"get",t);o=e}function a(e){o(null,n?e.list(n):e.values())}if("suspended"!==this.channel.state){var c=this;i(this.channel,o,(function(){var e=c.members;s?e.waitSync((function(){a(e)})):a(e)}))}else s?o(f.a.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):a(this.members)},s.prototype.history=function(t,n){if(o.a.logAction(o.a.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name),void 0===n)if("function"==typeof t)n=t,t=null;else{if(this.channel.realtime.options.promises)return r.a.promisify(this,"history",arguments);n=e}t&&t.untilAttach&&("attached"===this.channel.state?(delete t.untilAttach,t.from_serial=this.channel.properties.attachSerial):n(new f.a("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400))),v.prototype._history.call(this,t,n)},s.prototype.setPresence=function(e,t,n){o.a.logAction(o.a.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);var i,r,s=this.members,a=this._myMembers,c=[],u=this.channel.connectionManager.connectionId;t&&(this.members.startSync(),n&&(r=n.match(/^[\w\-]+:(.*)$/))&&(i=r[1]));for(var l=0;ls?i(new f.a("Maximum size of messages that can be published at once exceeded ( was "+t+" bytes; limit is "+s+" bytes)",40009,400)):o._publish(n,i)}}))}else i(this.connectionManager.getError())},n.prototype._publish=function(t,i){o.a.logAction(o.a.LOG_MICRO,"RealtimeChannel.publish()","message count = "+t.length);var r=this.state;switch(r){case"failed":case"suspended":i(f.a.fromValues(n.invalidStateError(r)));break;default:o.a.logAction(o.a.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+r);var s=new I.a;s.action=e.MESSAGE,s.channel=this.name,s.messages=t,this.sendMessage(s,i)}},n.prototype.onEvent=function(e){o.a.logAction(o.a.LOG_MICRO,"RealtimeChannel.onEvent()","received message");for(var t=this.subscriptions,n=0;n