1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8841],{28594:function(e,t,n){/*@license Copyright 2015-2022 Ably Real-time Ltd (ably.com) 2 3Ably JavaScript Library v2.0.4 4https://github.com/ably/ably-js 5 6Released under the Apache Licence v2.0*/e.exports=(()=>{"use strict";var e,t,s,i,r,o,a,c,l,h={},u={exports:h},d=Object.defineProperty,p=Object.defineProperties,f=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertyNames,y=Object.getOwnPropertySymbols,b=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,n)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,__spreadValues=(e,t)=>{for(var n in t||(t={}))b.call(t,n)&&__defNormalProp(e,n,t[n]);if(y)for(var n of y(t))v.call(t,n)&&__defNormalProp(e,n,t[n]);return e},__spreadProps=(e,t)=>p(e,g(t)),__objRest=(e,t)=>{var n={};for(var s in e)b.call(e,s)&&0>t.indexOf(s)&&(n[s]=e[s]);if(null!=e&&y)for(var s of y(e))0>t.indexOf(s)&&v.call(e,s)&&(n[s]=e[s]);return n},__export=(e,t)=>{for(var n in t)d(e,n,{get:t[n],enumerable:!0})},C={};__export(C,{ErrorInfo:()=>A,Realtime:()=>eQ,Rest:()=>eg,default:()=>tf,msgpack:()=>td,protocolMessageFromDeserialized:()=>fromDeserializedIncludingDependencies}),u.exports=((e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of m(t))b.call(e,n)||void 0===n||d(e,n,{get:()=>t[n],enumerable:!(s=f(t,n))||s.enumerable});return e})(d({},"__esModule",{value:!0}),C);var R=class{},O=void 0!==n.g?n.g:"undefined"!=typeof window?window:self;function pad(e,t){return`${e}`.padStart(t?3:2,"0")}function getHandler(e){return R.Config.logTimestamps?function(t){let n=new Date;e(pad(n.getHours())+":"+pad(n.getMinutes())+":"+pad(n.getSeconds())+"."+pad(n.getMilliseconds(),1)+" "+t)}:e}var getDefaultLoggers=()=>{var e;let t,n;return"function"==typeof(null==(e=null==O?void 0:O.console)?void 0:e.log)?(t=function(...e){console.log.apply(console,e)},n=console.warn?function(...e){console.warn.apply(console,e)}:t):t=n=function(){},[t,n].map(getHandler)},w=class _Logger{constructor(){_Logger.logLevel=_Logger.LOG_DEFAULT}static initLogHandlers(){let[e,t]=getDefaultLoggers();this.logHandler=e,this.logErrorHandler=t}static logActionNoStrip(e,t,n){_Logger.shouldLog(e)&&(1===e?_Logger.logErrorHandler:_Logger.logHandler)("Ably: "+t+": "+n)}static renamedClientOption(e,t){_Logger.deprecationWarning(`The \`${e}\` client option has been renamed to \`${t}\`. Please update your code to use \`${t}\` instead. \`${e}\` will be removed in a future version.`)}static renamedMethod(e,t,n){_Logger.deprecationWarning(`\`${e}\`\u2019s \`${t}\` method has been renamed to \`${n}\`. Please update your code to use \`${n}\` instead. \`${t}\` will be removed in a future version.`)}static deprecationWarning(e){_Logger.shouldLog(1)&&_Logger.logErrorHandler(`Ably: Deprecation warning - ${e}`)}};w.logLevel=1,w.LOG_NONE=0,w.LOG_ERROR=1,w.LOG_MAJOR=2,w.LOG_MINOR=3,w.LOG_MICRO=4,w.LOG_DEFAULT=1,w.LOG_DEBUG=4,w.logAction=(e,t,n)=>{w.logActionNoStrip(e,t,n)},w.deprecated=(e,t)=>{w.deprecationWarning(`${e} is deprecated and will be removed in a future version. ${t}`)},w.shouldLog=e=>e<=w.logLevel,w.setLog=(e,t)=>{void 0!==e&&(w.logLevel=e),void 0!==t&&(w.logHandler=w.logErrorHandler=t)};var S={};function toString(e){let t="["+e.constructor.name;return e.message&&(t+=": "+e.message),e.statusCode&&(t+="; statusCode="+e.statusCode),e.code&&(t+="; code="+e.code),e.cause&&(t+="; cause="+inspectError(e.cause)),e.href&&!(e.message&&e.message.indexOf("help.ably.io")>-1)&&(t+="; see "+e.href+" "),t+="]"}__export(S,{Format:()=>T,allSame:()=>allSame,allToLowerCase:()=>allToLowerCase,allToUpperCase:()=>allToUpperCase,arrChooseN:()=>arrChooseN,arrDeleteValue:()=>arrDeleteValue,arrEquals:()=>arrEquals,arrIntersect:()=>arrIntersect,arrIntersectOb:()=>arrIntersectOb,arrPopRandomElement:()=>arrPopRandomElement,arrSubtract:()=>arrSubtract,arrWithoutValue:()=>arrWithoutValue,cheapRandStr:()=>cheapRandStr,containsValue:()=>containsValue,copy:()=>copy,createMissingPluginError:()=>createMissingPluginError,dataSizeBytes:()=>dataSizeBytes,decodeBody:()=>decodeBody,encodeBody:()=>encodeBody,ensureArray:()=>ensureArray,forInOwnNonNullProperties:()=>forInOwnNonNullProperties,getBackoffCoefficient:()=>getBackoffCoefficient,getGlobalObject:()=>getGlobalObject,getJitterCoefficient:()=>getJitterCoefficient,getRetryTime:()=>getRetryTime,inherits:()=>inherits,inspectBody:()=>inspectBody,inspectError:()=>inspectError,intersect:()=>intersect,isEmpty:()=>isEmpty,isErrorInfoOrPartialErrorInfo:()=>isErrorInfoOrPartialErrorInfo,isNil:()=>isNil,isObject:()=>isObject,keysArray:()=>keysArray,matchDerivedChannel:()=>matchDerivedChannel,mixin:()=>mixin,parseQueryString:()=>parseQueryString,prototypicalClone:()=>prototypicalClone,randomString:()=>randomString,shallowClone:()=>
6shallowClone,shallowEquals:()=>shallowEquals,throwMissingPluginError:()=>throwMissingPluginError,toBase64:()=>toBase64,toQueryString:()=>toQueryString,valuesArray:()=>valuesArray,whenPromiseSettles:()=>whenPromiseSettles});var A=class _ErrorInfo extends Error{constructor(e,t,n,s){super(e),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,_ErrorInfo.prototype),this.code=t,this.statusCode=n,this.cause=s}toString(){return toString(this)}static fromValues(e){let{message:t,code:n,statusCode:s}=e;if("string"!=typeof t||"number"!=typeof n||"number"!=typeof s)throw Error("ErrorInfo.fromValues(): invalid values: "+R.Config.inspect(e));let i=Object.assign(new _ErrorInfo(t,n,s),e);return i.code&&!i.href&&(i.href="https://help.ably.io/error/"+i.code),i}},k=class _PartialErrorInfo extends Error{constructor(e,t,n,s){super(e),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,_PartialErrorInfo.prototype),this.code=t,this.statusCode=n,this.cause=s}toString(){return toString(this)}};function mixin(e,...t){for(let n=0;n<t.length;n++){let s=t[n];if(!s)break;for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=s[t])}return e}function copy(e){return mixin({},e)}function ensureArray(e){return isNil(e)?[]:Array.isArray(e)?e:[e]}function isObject(e){return"[object Object]"==Object.prototype.toString.call(e)}function isEmpty(e){for(let t in e)return!1;return!0}function isNil(e){return null==e}function shallowClone(e){let t={};for(let n in e)t[n]=e[n];return t}function prototypicalClone(e,t){let F=class F{};F.prototype=e;let n=new F;return t&&mixin(n,t),n}var inherits=function(e,t){if(R.Config.inherits){R.Config.inherits(e,t);return}e.super_=t,e.prototype=prototypicalClone(t.prototype,{constructor:e})};function containsValue(e,t){for(let n in e)if(e[n]==t)return!0;return!1}function intersect(e,t){return Array.isArray(t)?arrIntersect(e,t):arrIntersectOb(e,t)}function arrIntersect(e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s];-1!=t.indexOf(i)&&n.push(i)}return n}function arrIntersectOb(e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s];i in t&&n.push(i)}return n}function arrSubtract(e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s];-1==t.indexOf(i)&&n.push(i)}return n}function arrDeleteValue(e,t){let n=e.indexOf(t),s=-1!=n;return s&&e.splice(n,1),s}function arrWithoutValue(e,t){let n=e.slice();return arrDeleteValue(n,t),n}function keysArray(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(s);return n}function valuesArray(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(e[s]);return n}function forInOwnNonNullProperties(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function allSame(e,t){if(0===e.length)return!0;let n=e[0][t];return e.every(function(e){return e[t]===n})}var T=((e=T||{}).msgpack="msgpack",e.json="json",e);function arrPopRandomElement(e){return e.splice(Math.floor(Math.random()*e.length),1)[0]}function toQueryString(e){let t=[];if(e)for(let n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function parseQueryString(e){let t;let n=/([^?&=]+)=?([^&]*)/g,s={};for(;t=n.exec(e);)s[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return s}function isErrorInfoOrPartialErrorInfo(e){return"object"==typeof e&&null!==e&&(e instanceof A||e instanceof k)}function inspectError(e){var t,n;return e instanceof Error||(null==(t=null==e?void 0:e.constructor)?void 0:t.name)==="ErrorInfo"||(null==(n=null==e?void 0:e.constructor)?void 0:n.name)==="PartialErrorInfo"?e.toString():R.Config.inspect(e)}function inspectBody(e){return R.BufferUtils.isBuffer(e)?e.toString():"string"==typeof e?e:R.Config.inspect(e)}function dataSizeBytes(e){if(R.BufferUtils.isBuffer(e))return R.BufferUtils.byteLength(e);if("string"==typeof e)return R.Config.stringByteSize(e);throw Error("Expected input of Utils.dataSizeBytes to be a buffer or string, but was: "+typeof e)}function cheapRandStr(){return String(Math.random()).substr(2)}var randomString=async e=>{let t=await R.Config.getRandomArrayBuffer(e);return R.BufferUtils.base64Encode(t)};function arrChooseN(e,t){let n=Math.min(t,e.length),s=e.slice(),i=[];for(let e=0;e<n;e++)i.push(arrPopRandomElement(s));return i}function whenPromiseSettles(e,t){e.then(e=>{null==t||t(null,e)}).catch(e=>{null==t||t(e)})}function decodeBody(e,t,n){return"msgpack"==n?(t||throwMissingPluginError("MsgPack"),t.decode(e)):JSON.parse(String(e))}function encodeBody(e,t,n){return"msgpack"==n?(t||throwMissingPluginError("MsgPack"),t.encode(e,!0)):JSON.stringify(e)}function allToLowerCase(e){return e.map(function(e){return e&&e.toLowerCase()})}function allToUpperCase(e){return e.map(function(e){return e&&e.toUpperCase()})}function getBackoffCoefficient(e){return Math.min((e+2)/3,2)}function getJitterCoefficient(){return 1-.2*Math.random()}function getRetryTime(e,t){return e*getBackoffCoefficient(t)*getJitterCoefficient()}function getGlobalObject(){return void 0!==n.g?n.g:"undefined"!=typeof window?window:self}function shallowEquals(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}
6function matchDerivedChannel(e){let t=e.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!t||!t.length||t.length<5)throw new A("regex match failed",400,40010);if(t[2])throw new A(`cannot use a derived option with a ${t[2]} channel`,400,40010);return{qualifierParam:t[3]||"",channelName:t[4]}}function toBase64(e){let t=R.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function arrEquals(e,t){return e.length===t.length&&e.every(function(e,n){return e===t[n]})}function createMissingPluginError(e){return new A(`${e} plugin not provided`,40019,400)}function throwMissingPluginError(e){throw createMissingPluginError(e)}var _="2.0.4",M={ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FALLBACK_HOSTS:["A.ably-realtime.com","B.ably-realtime.com","C.ably-realtime.com","D.ably-realtime.com","E.ably-realtime.com"],PORT:80,TLS_PORT:443,TIMEOUTS:{disconnectedRetryTimeout:15e3,suspendedRetryTimeout:3e4,httpRequestTimeout:1e4,httpMaxRetryDuration:15e3,channelRetryTimeout:15e3,fallbackRetryTimeout:6e5,connectionStateTtl:12e4,realtimeRequestTimeout:1e4,recvTimeout:9e4,webSocketConnectTimeout:1e4,webSocketSlowTimeout:4e3},httpMaxRetryCount:3,maxMessageSize:65536,version:_,protocolVersion:3,agent:"ably-js/"+_,getHost,getPort:function(e,t){return t||e.tls?e.tlsPort:e.port},getHttpScheme:function(e){return e.tls?"https://":"http://"},environmentFallbackHosts,getFallbackHosts,getHosts:function(e,t){let n=[e.restHost].concat(getFallbackHosts(e));return t?n.map(t=>getHost(e,t,!0)):n},checkHost,objectifyOptions:function(e,t,n,s){let i;if(void 0===e){let e=t?`${n} must be initialized with either a client options object, an Ably API key, or an Ably Token`:`${n} must be initialized with a client options object`;throw w.logAction(w.LOG_ERROR,`${n}()`,e),Error(e)}if("string"==typeof e){if(-1==e.indexOf(":")){if(!t){let e=`${n} cannot be initialized with just an Ably Token; you must provide a client options object with a \`plugins\` property. (Set this Ably Token as the object\u2019s \`token\` property.)`;throw w.logAction(w.LOG_ERROR,`${n}()`,e),Error(e)}i={token:e}}else{if(!t){let e=`${n} cannot be initialized with just an Ably API key; you must provide a client options object with a \`plugins\` property. (Set this Ably API key as the object\u2019s \`key\` property.)`;throw w.logAction(w.LOG_ERROR,`${n}()`,e),Error(e)}i={key:e}}}else i=e;return s&&(i=__spreadProps(__spreadValues({},i),{plugins:__spreadValues(__spreadValues({},s),i.plugins)})),i},normaliseOptions:function(e,t){"function"==typeof e.recover&&!0===e.closeOnUnload&&(w.logAction(w.LOG_ERROR,"Defaults.normaliseOptions","closeOnUnload was true and a session recovery function was set - these are mutually exclusive, so unsetting the latter"),e.recover=void 0),"closeOnUnload"in e||(e.closeOnUnload=!e.recover),"queueMessages"in e||(e.queueMessages=!0);let n=e.environment&&String(e.environment).toLowerCase()||M.ENVIRONMENT,s=!n||"production"===n;e.fallbackHosts||e.restHost||e.realtimeHost||e.port||e.tlsPort||(e.fallbackHosts=s?M.FALLBACK_HOSTS:environmentFallbackHosts(n));let i=e.restHost||(s?M.REST_HOST:n+"-"+M.REST_HOST),r=e.realtimeHost?e.realtimeHost:e.restHost?(w.logAction(w.LOG_MINOR,"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.restHost):s?M.REALTIME_HOST:n+"-"+M.REALTIME_HOST;(e.fallbackHosts||[]).concat(i,r).forEach(checkHost),e.port=e.port||M.PORT,e.tlsPort=e.tlsPort||M.TLS_PORT,"tls"in e||(e.tls=!0);let o=function(e){let t={};for(let n in M.TIMEOUTS)t[n]=e[n]||M.TIMEOUTS[n];return t}(e);t?"useBinaryProtocol"in e?e.useBinaryProtocol=R.Config.supportsBinary&&e.useBinaryProtocol:e.useBinaryProtocol=R.Config.preferBinary:e.useBinaryProtocol=!1;let a={};e.clientId&&(a["X-Ably-ClientId"]=R.BufferUtils.base64Encode(R.BufferUtils.utf8Encode(e.clientId))),"idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0);let c=null,l=e.connectivityCheckUrl;if(e.connectivityCheckUrl){let[t,n]=e.connectivityCheckUrl.split("?");c=n?parseQueryString(n):{},-1===t.indexOf("://")&&(t="https://"+t),l=t}return __spreadProps(__spreadValues({},e),{realtimeHost:r,restHost:i,maxMessageSize:e.maxMessageSize||M.maxMessageSize,timeouts:o,connectivityCheckParams:c,connectivityCheckUrl:l,headers:a})},defaultGetHeaders:function(e,{format:t=I.format,protocolVersion:n=I.protocolVersion}={}){let s=E[t];return{accept:s,"X-Ably-Version":n.toString(),"Ably-Agent":getAgentString(e)}},defaultPostHeaders:function(e,{format:t=I.format,protocolVersion:n=I.protocolVersion}={}){let s;let i=s=E[t];return{accept:i,"content-type":s,"X-Ably-Version":n.toString(),"Ably-Agent":getAgentString(e)}}};function getHost(e,t,n){return t=n?t==e.restHost&&e.realtimeHost||t||e.realtimeHost:t||e.restHost}function environmentFallbackHosts(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"]}function getFallbackHosts(e){let t=e.fallbackHosts,n=void 0!==e.httpMaxRetryCount?e.httpMaxRetryCount:M.httpMaxRetryCount;return t?arrChooseN(t,n):[]}function checkHost(e){if("string"!=typeof e)throw new A("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new A("host must not be zero-length",4e4,400)}function getAgentString(e){let t=M.agent;if(e.agents)for(var n in e.agents)t+=" "+n+"/"+e.agents[n];return t}function normaliseChannelOptions(e,t){let n=t||{};if(n.cipher){e||throwMissingPluginError("Crypto");let t=e.getCipher(n.cipher);n.cipher=t.cipherParams,n.channelCipher=t.cipher}else"cipher"in n&&(n.cipher=void 0,n.channelCipher=null);return n}var E={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack"},I={format:"json",protocolVersion:M.protocolVersion},P=class _Multicaster{constructor(e){this.members=e||[]}call(e,t){for(let n of this.members)if(n)try{n(e,t)}catch(e){w.logAction(w.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+e+"; stack = "+e.stack)}}push(...e){this.members.push(...e)}createPromise(){return new Promise((e,t)=>
6{this.push((n,s)=>{n?t(n):e(s)})})}resolveAll(e){this.call(null,e)}rejectAll(e){this.call(e)}static create(e){let t=new _Multicaster(e);return Object.assign((e,n)=>t.call(e,n),{push:e=>t.push(e),createPromise:()=>t.createPromise(),resolveAll:e=>t.resolveAll(e),rejectAll:e=>t.rejectAll(e)})}},L=((t=L||{}).Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t),U=((s=U||{})[s.Success=200]="Success",s[s.NoContent=204]="NoContent",s[s.BadRequest=400]="BadRequest",s[s.Unauthorized=401]="Unauthorized",s[s.Forbidden=403]="Forbidden",s[s.RequestTimeout=408]="RequestTimeout",s[s.InternalServerError=500]="InternalServerError",s);function normaliseAuthcallbackError(e){return isErrorInfoOrPartialErrorInfo(e)?(e.code||(403===e.statusCode?e.code=40300:(e.code=40170,e.statusCode=401)),e):new A(inspectError(e),e.code||40170,e.statusCode||401)}var hmac=(e,t)=>{let n=R.BufferUtils,s=n.utf8Encode(e),i=n.utf8Encode(t),r=n.hmacSha256(s,i);return n.base64Encode(r)};function c14n(e){if(!e)return"";"string"==typeof e&&(e=JSON.parse(e));let t=Object.create(null),n=keysArray(e,!0);if(!n)return"";n.sort();for(let s=0;s<n.length;s++)t[n[s]]=e[n[s]].sort();return JSON.stringify(t)}function logAndValidateTokenAuthMethod(e){if(e.authCallback)w.logAction(w.LOG_MINOR,"Auth()","using token auth with authCallback");else if(e.authUrl)w.logAction(w.LOG_MINOR,"Auth()","using token auth with authUrl");else if(e.key)w.logAction(w.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(e.tokenDetails)w.logAction(w.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let e="authOptions must include valid authentication parameters";throw w.logAction(w.LOG_ERROR,"Auth()",e),Error(e)}}function useTokenAuth(e){return e.useTokenAuth||!("useTokenAuth"in e&&!e.useTokenAuth)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}var x=0,N=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,useTokenAuth(t))t.key||t.authCallback||t.authUrl||w.logAction(w.LOG_ERROR,"Auth()","Warning: 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"),this._saveTokenOptions(t.defaultTokenParams,t),logAndValidateTokenAuthMethod(this.authOptions);else{if(!t.key){let e="No authentication options provided; need one of: key, authUrl, or authCallback (or for testing only, token or tokenDetails)";throw w.logAction(w.LOG_ERROR,"Auth()",e),new A(e,40160,401)}w.logAction(w.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(t)}}async authorize(e,t){if(t&&t.key&&this.authOptions.key!==t.key)throw new A("Unable to update auth options with incompatible key",40102,401);try{let n=await this._forceNewToken(null!=e?e:null,null!=t?t:null);if(this.client.connection)return new Promise((e,t)=>{this.client.connection.connectionManager.onAuthUpdated(n,(n,s)=>n?t(n):e(s))});return n}catch(e){throw this.client.connection&&e.statusCode===U.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(e),e}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),logAndValidateTokenAuthMethod(this.authOptions);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}async requestToken(e,t){let n=t||this.authOptions,s=e||copy(this.tokenParams),i,r=this.client;if(n.authCallback)w.logAction(w.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),i=n.authCallback;else if(n.authUrl)w.logAction(w.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),i=(e,t)=>{let s;let i=mixin({accept:"application/json, text/plain"},n.authHeaders),r=n.authMethod&&"post"===n.authMethod.toLowerCase(),o=n.authUrl.indexOf("?");o>-1&&(s=parseQueryString(n.authUrl.slice(o)),n.authUrl=n.authUrl.slice(0,o),r||(n.authParams=mixin(s,n.authParams)));let a=mixin({},n.authParams||{},e),authUrlRequestCallback=function(e){var n,s;let i=null!=(n=e.body)?n:null,r=null;if(e.error)w.logAction(w.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+inspectError(e.error));else{let t=null!=(s=e.headers["content-type"])?s:null;r=Array.isArray(t)?t.join(", "):t,w.logAction(w.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received;
6 content-type: "+r+"; body: "+inspectBody(i))}if(e.error){t(e.error,null);return}if(e.unpacked){t(null,i);return}if(R.BufferUtils.isBuffer(i)&&(i=i.toString()),!r){t(new A("authUrl response is missing a content-type header",40170,401),null);return}let o=r.indexOf("application/json")>-1,a=r.indexOf("text/plain")>-1||r.indexOf("application/jwt")>-1;if(!o&&!a){t(new A("authUrl responded with unacceptable content-type "+r+", should be either text/plain, application/jwt or application/json",40170,401),null);return}if(o){if(i.length>131072){t(new A("authUrl response exceeded max permitted length",40170,401),null);return}try{i=JSON.parse(i)}catch(e){t(new A("Unexpected error processing authURL response; err = "+e.message,40170,401),null);return}}t(null,i,r)};if(w.logAction(w.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Requesting token from "+n.authUrl+"; Params: "+JSON.stringify(a)+"; method: "+(r?"POST":"GET")),r){let e=i||{};e["content-type"]="application/x-www-form-urlencoded";let t=toQueryString(a).slice(1);whenPromiseSettles(this.client.http.doUri(L.Post,n.authUrl,e,t,s),(e,t)=>e?authUrlRequestCallback(e):authUrlRequestCallback(t))}else whenPromiseSettles(this.client.http.doUri(L.Get,n.authUrl,i||{},null,a),(e,t)=>e?authUrlRequestCallback(e):authUrlRequestCallback(t))};else if(n.key)w.logAction(w.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),i=(e,t)=>{whenPromiseSettles(this.createTokenRequest(e,n),(e,n)=>t(e,null!=n?n:null))};else throw w.logAction(w.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"),new A("Need a new token, but authOptions does not include any way to request one (no authUrl, authCallback, or key)",40171,403);"capability"in s&&(s.capability=c14n(s.capability));let tokenRequest=(e,t)=>{let s=e.keyName,i="/keys/"+s+"/requestToken",o=M.defaultPostHeaders(this.client.options);n.requestHeaders&&mixin(o,n.requestHeaders),w.logAction(w.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+i+"; Token params: "+JSON.stringify(e)),whenPromiseSettles(this.client.http.do(L.Post,function(e){return r.baseUri(e)+i},o,JSON.stringify(e),null),(e,n)=>e?t(e):t(n.error,n.body,n.unpacked))};return new Promise((e,t)=>{let r=!1,o=this.client.options.timeouts.realtimeRequestTimeout,a=setTimeout(function(){r=!0;let e="Token request callback timed out after "+o/1e3+" seconds";w.logAction(w.LOG_ERROR,"Auth.requestToken()",e),t(new A(e,40170,401))},o);i(s,function(s,i,o){if(r)return;if(clearTimeout(a),s){w.logAction(w.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+inspectError(s)),t(normaliseAuthcallbackError(s));return}if("string"==typeof i){0===i.length?t(new A("Token string is empty",40170,401)):i.length>131072?t(new A("Token string exceeded max permitted length (was "+i.length+" bytes)",40170,401)):"undefined"===i||"null"===i?t(new A("Token string was literal null/undefined",40170,401)):"{"!==i[0]||o&&o.indexOf("application/jwt")>-1?e({token:i}):t(new A("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401));return}if("object"!=typeof i||null===i){let e="Expected token request callback to call back with a token string or token request/details object, but got a "+typeof i;w.logAction(w.LOG_ERROR,"Auth.requestToken()",e),t(new A(e,40170,401));return}let c=JSON.stringify(i).length;if(c>131072&&!n.suppressMaxLengthCheck){t(new A("Token request/details object exceeded max permitted stringified size (was "+c+" bytes)",40170,401));return}if("issued"in i){e(i);return}if(!("keyName"in i)){let e="Expected token request callback to call back with a token string, token request object, or token details object";w.logAction(w.LOG_ERROR,"Auth.requestToken()",e),t(new A(e,40170,401));return}tokenRequest(i,function(n,s,i){if(n){w.logAction(w.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+inspectError(n)),t(normaliseAuthcallbackError(n));return}i||(s=JSON.parse(s)),w.logAction(w.LOG_MINOR,"Auth.getToken()","token received"),e(s)})})})}async createTokenRequest(e,t){t=t||this.authOptions,e=e||copy(this.tokenParams);let n=t.key;if(!n)throw new A("No key specified",40101,403);let s=n.split(":"),i=s[0],r=s[1];if(!r)throw new A("Invalid key specified",40101,403);if(""===e.clientId)throw new A("clientId canât be an empty string",40012,400);"capability"in e&&(e.capability=c14n(e.capability));let o=mixin({keyName:i},e),a=e.clientId||"",c=e.ttl||"",l=e.capability||"";o.timestamp||(o.timestamp=await this.getTimestamp(t&&t.queryTime));let h=o.nonce||(o.nonce=("000000"+Math.floor(1e16*Math.random())).slice(-16)),u=o.timestamp,d=o.keyName+"\n"+c+"\n"+l+"\n"+a+"\n"+u+"\n"+h+"\n";return o.mac=o.mac||hmac(d,r),w.logAction(w.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),o}
6async getAuthParams(){if("basic"==this.method)return{key:this.key};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{access_token:e.token}}}async getAuthHeaders(){if("basic"==this.method)return{authorization:"Basic "+this.basicKey};{let e=await this._ensureValidAuthCredentials(!1);if(!e)throw Error("Auth.getAuthParams(): _ensureValidAuthCredentials returned no error or tokenDetails");return{authorization:"Bearer "+toBase64(e.token)}}}async getTimestamp(e){return!this.isTimeOffsetSet()&&(e||this.authOptions.queryTime)?this.client.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.client.serverTimeOffset||0)}isTimeOffsetSet(){return null!==this.client.serverTimeOffset}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=toBase64(e.key),this.authOptions=e||{},"clientId"in e&&this._userSetClientId(e.clientId)}_saveTokenOptions(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)}async _ensureValidAuthCredentials(e){let t=this.tokenDetails;if(t){if(this._tokenClientIdMismatch(t.clientId))throw new A("Mismatch between clientId in token ("+t.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.isTimeOffsetSet()||!t.expires||t.expires>=this.getTimestampUsingOffset())return w.logAction(w.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+t.expires),t;w.logAction(w.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let n=(this.waitingForTokenRequest||(this.waitingForTokenRequest=P.create())).createPromise();if(null!==this.currentTokenRequestId&&!e)return n;let s=this.currentTokenRequestId=x++,i,r=null;try{i=await this.requestToken(this.tokenParams,this.authOptions)}catch(e){r=e}if(this.currentTokenRequestId>s)return w.logAction(w.LOG_MINOR,"Auth._ensureValidAuthCredentials()","Discarding token request response; overtaken by newer one"),n;this.currentTokenRequestId=null;let o=this.waitingForTokenRequest;return(this.waitingForTokenRequest=null,r)?null==o||o.rejectAll(r):null==o||o.resolveAll(this.tokenDetails=i),n}_userSetClientId(e){if("string"==typeof e||null===e){if("*"===e)throw new 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);{let t=this._uncheckedSetClientId(e);if(t)throw t}}else throw new A("clientId must be either a string or null",40012,400)}_uncheckedSetClientId(e){if(!this._tokenClientIdMismatch(e))return this.clientId=this.tokenParams.clientId=e,null;{let t="Unexpected clientId mismatch: client has "+this.clientId+", requested "+e,n=new A(t,40102,401);return w.logAction(w.LOG_ERROR,"Auth._uncheckedSetClientId()",t),n}}_tokenClientIdMismatch(e){return!!(this.clientId&&"*"!==this.clientId&&e&&"*"!==e&&this.clientId!==e)}static isTokenErr(e){return e.code&&e.code>=40140&&e.code<40150}revokeTokens(e,t){return this.client.rest.revokeTokens(e,t)}};function paramString(e){let t=[];if(e)for(let n in e)t.push(n+"="+e[n]);return t.join("&")}function appendingParams(e,t){return e+(t?"?":"")+paramString(t)}var G=class{constructor(e){this.client=e,this.platformHttp=new R.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get supportsAuthHeaders(){return this.platformHttp.supportsAuthHeaders}get supportsLinkHeaders(){return this.platformHttp.supportsLinkHeaders}_getHosts(e){let t=e.connection,n=t&&t.connectionManager.host;return n?[n].concat(M.getFallbackHosts(e.options)):M.getHosts(e.options)}async do(e,t,n,s,i){try{let r=this.client;if(!r)return{error:new A("http.do called without client",5e4,500)};let o="function"==typeof t?t:function(e){return r.baseUri(e)+t},a=r._currentFallback;if(a){if(a.validUntil>Date.now()){let c=await this.doUri(e,o(a.host),n,s,i);if(c.error&&this.platformHttp.shouldFallback(c.error))return r._currentFallback=null,this.do(e,t,n,s,i);return c}r._currentFallback=null}let c=this._getHosts(r);if(1===c.length)return this.doUri(e,o(c[0]),n,s,i);let l=null,tryAHost=async(t,a)=>{let c=t.shift();l=null!=l?l:new Date;let h=await this.doUri(e,o(c),n,s,i);if(h.error&&this.platformHttp.shouldFallback(h.error)&&t.length){let e=Date.now()-l.getTime();return e>r.options.timeouts.httpMaxRetryDuration?{error:new A(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${r.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:tryAHost(t,!0)}return a&&(r._currentFallback={host:c,validUntil:Date.now()+r.options.timeouts.fallbackRetryTimeout}),h};return tryAHost(c)}catch(e){return{error:new A(`Unexpected error in Http.do: ${inspectError(e)}`,500,5e4)}}}async doUri(e,t,n,s,i){try{w.shouldLog(w.LOG_MICRO)&&w.logActionNoStrip(w.LOG_MICRO,"Http."+e+"()","Sending; "+appendingParams(t,i)+"; Body"+(R.BufferUtils.isBuffer(s)?" (Base64): "+R.BufferUtils.base64Encode(s):": "+s));let r=await this.platformHttp.doUri(e,t,n,s,i);return w.shouldLog(w.LOG_MICRO)&&(r.error?w.logActionNoStrip(w.LOG_MICRO,"Http."+e+"()","Received Error; "+appendingParams(t,i)+"; Error: "+inspectError(r.error)):w.logActionNoStrip(w.LOG_MICRO,"Http."+e+"()","Received; "+appendingParams(t,i)+"; Headers: "+paramString(r.headers)+"; StatusCode: "+r.statusCode+"; Body"+(R.BufferUtils.isBuffer(r.body)?" (Base64): "+R.BufferUtils.base64Encode(r.body):": "+r.body))),r}catch(e){return{error:new A(`Unexpected error in Http.doUri: ${inspectError(e)}`,500,5e4)}}}},B=class{constructor(e){var t,n,s,i,r,o,a,c;this._additionalHTTPRequestImplementations=null!=(t=e.plugins)?t:null,w.setLog(e.logLevel,e.logHandler),w.logAction(w.LOG_MICRO,"BaseClient()","initialized with clientOptions "+R.Config.inspect(e)),this._MsgPack=null!=(s=null==(n=e.plugins)?void 0:n.MsgPack)?s:null;let l=this.options=M.normaliseOptions(e,this._MsgPack);
6if(l.key){let e=l.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!e){let e="invalid key parameter";throw w.logAction(w.LOG_ERROR,"BaseClient()",e),new A(e,40400,404)}l.keyName=e[1],l.keySecret=e[2]}if("clientId"in l){if("string"==typeof l.clientId||null===l.clientId){if("*"===l.clientId)throw new 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)}else throw new A("clientId must be either a string or null",40012,400)}w.logAction(w.LOG_MINOR,"BaseClient()","started; version = "+M.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new G(this),this.auth=new N(this,l),this._rest=(null==(i=e.plugins)?void 0:i.Rest)?new e.plugins.Rest(this):null,this._Crypto=null!=(o=null==(r=e.plugins)?void 0:r.Crypto)?o:null,this.__FilteredSubscriptions=null!=(c=null==(a=e.plugins)?void 0:a.MessageInteractions)?c:null}get rest(){return this._rest||throwMissingPluginError("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||throwMissingPluginError("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}baseUri(e){return M.getHttpScheme(this.options)+e+":"+M.getPort(this.options,!1)}async stats(e){return this.rest.stats(e)}async time(e){return this.rest.time(e)}async request(e,t,n,s,i,r){return this.rest.request(e,t,n,s,i,r)}batchPublish(e){return this.rest.batchPublish(e)}batchPresence(e){return this.rest.batchPresence(e)}setLog(e){w.setLog(e.level,e.handler)}};B.Platform=R;var q=B,D=class _DeviceDetails{toJSON(){var e,t,n;return{id:this.id,deviceSecret:this.deviceSecret,platform:this.platform,formFactor:this.formFactor,clientId:this.clientId,metadata:this.metadata,deviceIdentityToken:this.deviceIdentityToken,push:{recipient:null==(e=this.push)?void 0:e.recipient,state:null==(t=this.push)?void 0:t.state,error:null==(n=this.push)?void 0:n.error}}}toString(){var e,t,n,s;let i="[DeviceDetails";return this.id&&(i+="; id="+this.id),this.platform&&(i+="; platform="+this.platform),this.formFactor&&(i+="; formFactor="+this.formFactor),this.clientId&&(i+="; clientId="+this.clientId),this.metadata&&(i+="; metadata="+this.metadata),this.deviceIdentityToken&&(i+="; deviceIdentityToken="+JSON.stringify(this.deviceIdentityToken)),(null==(e=this.push)?void 0:e.recipient)&&(i+="; push.recipient="+JSON.stringify(this.push.recipient)),(null==(t=this.push)?void 0:t.state)&&(i+="; push.state="+this.push.state),(null==(n=this.push)?void 0:n.error)&&(i+="; push.error="+JSON.stringify(this.push.error)),(null==(s=this.push)?void 0:s.metadata)&&(i+="; push.metadata="+this.push.metadata),i+="]"}static toRequestBody(e,t,n){return encodeBody(e,t,n)}static fromResponseBody(e,t,n){return(n&&(e=decodeBody(e,t,n)),Array.isArray(e))?_DeviceDetails.fromValuesArray(e):_DeviceDetails.fromValues(e)}static fromValues(e){return e.error=e.error&&A.fromValues(e.error),Object.assign(new _DeviceDetails,e)}static fromValuesArray(e){let t=e.length,n=Array(t);for(let s=0;s<t;s++)n[s]=_DeviceDetails.fromValues(e[s]);return n}};async function withAuthDetails(e,t,n,s){if(e.http.supportsAuthHeaders){let i=await e.auth.getAuthHeaders();return s(mixin(i,t),n)}{let i=await e.auth.getAuthParams();return s(t,mixin(i,n))}}var H=class _Resource{static async get(e,t,n,s,i,r){return _Resource.do(L.Get,e,t,null,n,s,i,null!=r&&r)}static async delete(e,t,n,s,i,r){return _Resource.do(L.Delete,e,t,null,n,s,i,r)}static async post(e,t,n,s,i,r,o){return _Resource.do(L.Post,e,t,n,s,i,r,o)}static async patch(e,t,n,s,i,r,o){return _Resource.do(L.Patch,e,t,n,s,i,r,o)}static async put(e,t,n,s,i,r,o){return _Resource.do(L.Put,e,t,n,s,i,r,o)}static async do(e,t,n,s,i,r,o,a){async function doRequest(i,r){var o;if(w.shouldLog(w.LOG_MICRO)){let a=s;if((null==(o=i["content-type"])?void 0:o.indexOf("msgpack"))>0)try{t._MsgPack||throwMissingPluginError("MsgPack"),a=t._MsgPack.decode(s)}catch(t){w.logAction(w.LOG_MICRO,"Resource."+e+"()","Sending MsgPack Decoding Error: "+inspectError(t))}w.logAction(w.LOG_MICRO,"Resource."+e+"()","Sending; "+appendingParams(n,r)+"; Body: "+a)}let a=await t.http.do(e,n,i,s,r);return a.error&&N.isTokenErr(a.error)?(await t.auth.authorize(null,null),withAuthDetail
6s(t,i,r,doRequest)):{err:a.error,body:a.body,headers:a.headers,unpacked:a.unpacked,statusCode:a.statusCode}}o&&((r=r||{}).envelope=o);let c=await withAuthDetails(t,i,r,doRequest);if(o&&(c=function(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===U.NoContent)return __spreadProps(__spreadValues({},e),{body:[],unpacked:!0});let s=e.body;if(!e.unpacked)try{s=decodeBody(s,t,n)}catch(e){if(isErrorInfoOrPartialErrorInfo(e))return{err:e};return{err:new k(inspectError(e),null)}}if(!s)return{err:new k("unenvelope(): Response body is missing",null)};let{statusCode:i,response:r,headers:o}=s;if(void 0===i)return __spreadProps(__spreadValues({},e),{body:s,unpacked:!0});if(i<200||i>=300){let t=r&&r.error||e.err;return t||((t=Error("Error in unenveloping "+s)).statusCode=i),{err:t,body:r,headers:o,unpacked:!0,statusCode:i}}return{err:e.err,body:r,headers:o,unpacked:!0,statusCode:i}}(c,t._MsgPack,o)),w.shouldLog(w.LOG_MICRO)){var l,h;l=c,h=r,l.err?w.logAction(w.LOG_MICRO,"Resource."+e+"()","Received Error; "+appendingParams(n,h)+"; Error: "+inspectError(l.err)):w.logAction(w.LOG_MICRO,"Resource."+e+"()","Received; "+appendingParams(n,h)+"; Headers: "+paramString(l.headers)+"; StatusCode: "+l.statusCode+"; Body: "+(R.BufferUtils.isBuffer(l.body)?" (Base64): "+R.BufferUtils.base64Encode(l.body):": "+R.Config.inspect(l.body)))}if(a){if(c.err)throw c.err;{let e=__spreadValues({},c);return delete e.err,e}}return c}},V=class{constructor(e,t,n,s,i,r){this.client=e,this.path=t,this.headers=n,this.envelope=null!=s?s:null,this.bodyHandler=i,this.useHttpPaginatedResponse=r||!1}async get(e){let t=await H.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){let t=await H.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){let n=await H.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){let n=await H.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){let n=await H.patch(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async handlePage(e){var t,n;let s,i,r;if(e.err&&(t=e.err,n=e.body,!(this.useHttpPaginatedResponse&&(n||"number"==typeof t.code))))throw w.logAction(w.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+inspectError(e.err)),e.err;try{s=e.statusCode==U.NoContent?[]:await this.bodyHandler(e.body,e.headers||{},e.unpacked)}catch(t){throw e.err||t}return(e.headers&&(i=e.headers.Link||e.headers.link)&&(r=function(e){"string"==typeof e&&(e=e.split(","));let t={};for(let n=0;n<e.length;n++){let s=e[n].match(/^\s*<(.+)>;\s*rel="(\w+)"$/);if(s){let e=function(e){let t=e.match(/^\.\/(\w+)\?(.*)$/);return t&&t[2]&&parseQueryString(t[2])}(s[1]);e&&(t[s[2]]=e)}}return t}(i)),this.useHttpPaginatedResponse)?new W(this,s,e.headers||{},e.statusCode,r,e.err):new j(this,s,r)}},j=class{constructor(e,t,n){this.resource=e,this.items=t;let s=this;n&&("first"in n&&(this.first=async function(){return s.get(n.first)}),"current"in n&&(this.current=async function(){return s.get(n.current)}),this.next=async function(){return"next"in n?s.get(n.next):null},this.hasNext=function(){return"next"in n},this.isLast=()=>{var e;return!(null==(e=this.hasNext)?void 0:e.call(this))})}async get(e){let t=this.resource,n=await H.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}},W=class extends j{constructor(e,t,n,s,i,r){super(e,t,i),this.statusCode=s,this.success=s<300&&s>=200,this.headers=n,this.errorCode=r&&r.code,this.errorMessage=r&&r.message}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage}}},z=class _PushChannelSubscription{toJSON(){return{channel:this.channel,deviceId:this.deviceId,clientId:this.clientId}}toString(){let e="[PushChannelSubscription";return this.channel&&(e+="; channel="+this.channel),this.deviceId&&(e+="; deviceId="+this.deviceId),this.clientId&&(e+="; clientId="+this.clientId),e+="]"}static fromResponseBody(e,t,n){return(n&&(e=decodeBody(e,t,n)),Array.isArray(e))?_PushChannelSubscription.fromValuesArray(e):_PushChannelSubscription.fromValues(e)}static fromValues(e){return Object.assign(new _PushChannelSubscription,e)}static fromValuesArray(e){let t=e.length,n=Array(t);for(let s=0;s<t;s++)n[s]=_PushChannelSubscription.fromValues(e[s]);return n}};z.toRequestBody=encodeBody;var J=class{constructor(e){this.client=e,this.admin=new K(e)}},K=class{constructor(e){this.client=e,this.deviceRegistrations=new Q(e),this.channelSubscriptions=new $(e)}async publish(e,t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=M.defaultPostHeaders(n.options,{format:s}),r={},o=mixin({recipient:e},t);mixin(i,n.options.headers),n.options.pushFullWait&&mixin(r,{fullWait:"true"});let a=encodeBody(o,n._MsgPack,s);await H.post(n,"/push/publish",a,i,r,null,!0)}},Q=class{constructor(e){this.client=e}async save(e){let t=this.client,n=D.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=M.defaultPostHeaders(t.options,{format:s}),r={};mixin(i,t.options.headers),t.options.pushFullWait&&mixin(r,{fullWait:"true"});let o=encodeBody(n,t._MsgPack,s),a=await H.put(t,"/push/deviceRegistrations/"+encodeURIComponent(e.id),o,i,r,null,!0);return D.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:s)}async get(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=M.defaultGetHeaders(t.options,{format:n}),i=e.id||e;if("string"!=typeof i||!i.length)throw new A("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);mixin(s,t.options.headers);let r=await H.get(t,"/push/deviceRegistrations/"+encodeURIComponent(i),s,{},null,!0);return D.fromResponseBody(r.body,t._MsgPack,r.unpacked?void 0:n)}async list(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,i=M.defaultGetHeaders(t.options,{format:n});return mixin(i,t.options.headers),new V(t,"/push/deviceRegistrations",i,s,async function(e,s,i){return D.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async remove(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=M.defaultGetHeaders(t.options,{format:n}),i={},r=e.id||e;if("string"!=typeof r||!r.length)throw new A("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);mixin(s,t.options.headers),t.options.pushFullWait&&mixin(i,{fullWait:"true"}),await H.delete(t,"/push/deviceRegistrations/"+encodeURIComponent(r),s,i,null,!0)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=M.defaultGetHeaders(t.options,{format:n});mixin(s,t.options.headers),t.options.pushFullWait&&mixin(e,{fullWait:"true"}),await H.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},$=class _ChannelSubscriptions{constructor(e){this.remove=_ChannelSubscriptions.prototype.removeWhere,this.client=e}async save(e){let t=this.client,n=z.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=M.defaultPostHeaders(t.options,{format:s}),r={};mixin(i,t.options.headers),t.options.pushFullWait&&mixin(r,{fullWait:"true"});let o=encodeBody(n,t._MsgPack,s),a=await H.post(t,"/push/channelSubscriptions",o,i,r,null,!0);return z.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:s)}async list(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,i=M.defaultGetHeaders(t.options,{format:n});return mixin(i,t.options.headers),new V(t,"/push/channelSubscriptions",i,s,async function(e,s,i){return z.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=M.defaultGetHeaders(t.options,{format:n});mixin(s,t.options.headers),t.options.pushFullWait&&mixin(e,{fullWait:"true"}),await H.delete(t,"/push/channelSubscriptions",s,e,null,!0)}async listChannels(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n,i=M.defaultGetHeaders(t.options,{format:n});return mixin(i,t.options.headers),t.options.pushFullWait&&mixin(e,{fullWait:"true"}),new V(t,"/push/channels",i,s,async function(e,s,i){let r=!i&&n?decodeBody(e,t._MsgPack,n):e;for(let e=0;e<r.length;e++)r[e]=String(r[e]);return r}).get(e)}};
6async function fromEncoded(e,t,n){let s=fromValues(t),i=function(e,t){if(t&&t.cipher){e||throwMissingPluginError("Crypto");let n=e.getCipher(t.cipher);return{cipher:n.cipherParams,channelCipher:n.cipher}}return null!=t?t:{}}(e,null!=n?n:null);try{await decode(s,i)}catch(e){w.logAction(w.LOG_ERROR,"Message.fromEncoded()",e.toString())}return s}async function fromEncodedArray(e,t,n){return Promise.all(t.map(function(t){return fromEncoded(e,t,n)}))}async function encrypt(e,t){let n=e.data,s=e.encoding,i=t.channelCipher;s=s?s+"/":"",R.BufferUtils.isBuffer(n)||(n=R.BufferUtils.utf8Encode(String(n)),s+="utf-8/");let r=await i.encrypt(n);return e.data=r,e.encoding=s+"cipher+"+i.algorithm,e}async function encode(e,t){let n=e.data,s="string"==typeof n||R.BufferUtils.isBuffer(n)||null==n;if(!s){if(isObject(n)||Array.isArray(n))e.data=JSON.stringify(n),e.encoding=e.encoding?e.encoding+"/json":"json";else throw new A("Data type is unsupported",40013,400)}return null!=t&&t.cipher?encrypt(e,t):e}async function encodeArray(e,t){return Promise.all(e.map(e=>encode(e,t)))}async function decode(e,t){let n=t&&t.channelOptions?t:{channelOptions:t,plugins:{},baseEncodedPreviousPayload:void 0},s=e.data,i=e.encoding;if(i){let t=i.split("/"),r,o=t.length,a=e.data,c="";try{for(;(r=o)>0;){let e=t[--o].match(/([-\w]+)(\+([\w-]+))?/);if(!e)break;switch(c=e[1]){case"base64":a=R.BufferUtils.base64Decode(String(a)),r==t.length&&(s=a);continue;case"utf-8":a=R.BufferUtils.utf8Decode(a);continue;case"json":a=JSON.parse(a);continue;case"cipher":if(null!=n.channelOptions&&n.channelOptions.cipher&&n.channelOptions.channelCipher){let t=e[3],s=n.channelOptions.channelCipher;if(t!=s.algorithm)throw Error("Unable to decrypt message with given cipher; incompatible cipher params");a=await s.decrypt(a);continue}throw Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!n.plugins||!n.plugins.vcdiff)throw new A("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new A("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let e=n.baseEncodedPreviousPayload;"string"==typeof e&&(e=R.BufferUtils.utf8Encode(e));let t=R.BufferUtils.toBuffer(e);a=R.BufferUtils.toBuffer(a),s=a=R.BufferUtils.arrayBufferViewToBuffer(n.plugins.vcdiff.decode(a,t))}catch(e){throw new A("Vcdiff delta decode failed with "+e,40018,400)}continue;default:throw Error("Unknown encoding")}}}catch(e){throw new A("Error processing the "+c+" encoding, decoder returned â"+e.message+"â",e.code||40013,400)}finally{e.encoding=r<=0?null:t.slice(0,r).join("/"),e.data=a}}n.baseEncodedPreviousPayload=s}async function fromResponseBody(e,t,n,s){s&&(e=decodeBody(e,n,s));for(let n=0;n<e.length;n++){let s=e[n]=fromValues(e[n]);try{await decode(s,t)}catch(e){w.logAction(w.LOG_ERROR,"Message.fromResponseBody()",e.toString())}}return e}function fromValues(e){return Object.assign(new X,e)}function fromValuesArray(e){let t=e.length,n=Array(t);for(let s=0;s<t;s++)n[s]=fromValues(e[s]);return n}function getMessagesSize(e){let t,n=0;for(let s=0;s<e.length;s++)n+=(t=e[s]).size||(t.size=function(e){let t=0;return e.name&&(t+=e.name.length),e.clientId&&(t+=e.clientId.length),e.extras&&(t+=JSON.stringify(e.extras).length),e.data&&(t+=dataSizeBytes(e.data)),t}(t));return n}var X=class{toJSON(){let e=this.encoding,t=this.data;return t&&R.BufferUtils.isBuffer(t)&&(arguments.length>0?(e=e?e+"/base64":"base64",t=R.BufferUtils.base64Encode(t)):t=R.BufferUtils.toBuffer(t)),{name:this.name,id:this.id,clientId:this.clientId,connectionId:this.connectionId,connectionKey:this.connectionKey,extras:this.extras,encoding:e,data:t}}toString(){let 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:R.BufferUtils.isBuffer(this.data)?e+="; data (buffer)="+R.BufferUtils.base64Encode(this.data):e+="; data (json)="+JSON.stringify(this.data)),this.extras&&(e+="; extras="+JSON.stringify(this.extras)),e+="]"}},Y=X,Z=["absent","present","enter","leave","update"];
6async function fromEncoded2(e,t){let n=fromValues2(e,!0);try{await ee(n,null!=t?t:{})}catch(e){w.logAction(w.LOG_ERROR,"PresenceMessage.fromEncoded()",e.toString())}return n}async function fromEncodedArray2(e,t){return Promise.all(e.map(function(e){return fromEncoded2(e,t)}))}function fromValues2(e,t){return t&&(e.action=Z[e.action]),Object.assign(new et,e)}var ee=decode;async function fromResponseBody2(e,t,n,s){let i=[];s&&(e=decodeBody(e,n,s));for(let n=0;n<e.length;n++){let s=i[n]=fromValues2(e[n],!0);try{await ee(s,t)}catch(e){w.logAction(w.LOG_ERROR,"PresenceMessage.fromResponseBody()",e.toString())}}return i}function fromValuesArray2(e){let t=e.length,n=Array(t);for(let s=0;s<t;s++)n[s]=fromValues2(e[s]);return n}function fromData(e){return e instanceof et?e:fromValues2({data:e})}var et=class{isSynthesized(){return!this.id||!this.connectionId||this.id.substring(this.connectionId.length,0)!==this.connectionId}parseId(){if(!this.id)throw Error("parseId(): Presence message does not contain an id");let e=this.id.split(":");return{connectionId:e[0],msgSerial:parseInt(e[1],10),index:parseInt(e[2],10)}}toJSON(){var e;let t=this.data,n=this.encoding;return t&&R.BufferUtils.isBuffer(t)&&(arguments.length>0?(n=n?n+"/base64":"base64",t=R.BufferUtils.base64Encode(t)):t=R.BufferUtils.toBuffer(t)),{id:this.id,clientId:this.clientId,action:(e=this.action,Z.indexOf(e)),data:t,encoding:n,extras:this.extras}}toString(){let 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:R.BufferUtils.isBuffer(this.data)?e+="; data (buffer)="+R.BufferUtils.base64Encode(this.data):e+="; data (json)="+JSON.stringify(this.data)),this.extras&&(e+="; extras="+JSON.stringify(this.extras)),e+="]"}},en=et,es=class{constructor(e){this.channel=e}async get(e){w.logAction(w.LOG_MICRO,"RestPresence.get()","channel = "+this.channel.name);let t=this.channel.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=this.channel.client.http.supportsLinkHeaders?void 0:n,i=M.defaultGetHeaders(t.options,{format:n});mixin(i,t.options.headers);let r=this.channel.channelOptions;return new V(t,this.channel.client.rest.presenceMixin.basePath(this),i,s,async function(e,s,i){return await fromResponseBody2(e,r,t._MsgPack,i?void 0:n)}).get(e)}async history(e){return w.logAction(w.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},ei=class{constructor(e,t,n){var s;w.logAction(w.LOG_MINOR,"RestChannel()","started; name = "+t),this.name=t,this.client=e,this.presence=new es(this),this.channelOptions=normaliseChannelOptions(null!=(s=e._Crypto)?s:null,n)}setOptions(e){var t;this.channelOptions=normaliseChannelOptions(null!=(t=this.client._Crypto)?t:null,e)}async history(e){return w.logAction(w.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,e)}async publish(...e){let t,n;let s=e[0],i=e[1];if("string"==typeof s||null===s)t=[fromValues({name:s,data:i})],n=e[2];else if(isObject(s))t=[fromValues(s)],n=e[1];else if(Array.isArray(s))t=fromValuesArray(s),n=e[1];else throw new A("The single-argument form of publish() expects a message object or an array of message objects",40013,400);n||(n={});let r=this.client,o=r.options,a=o.useBinaryProtocol?"msgpack":"json",c=r.options.idempotentRestPublishing,l=M.defaultPostHeaders(r.options,{format:a});if(mixin(l,o.headers),c&&t.every(function(e){return!e.id})){let e=await randomString(9);t.forEach(function(t,n){t.id=e+":"+n.toString()})}await encodeArray(t,this.channelOptions);let h=getMessagesSize(t),u=o.maxMessageSize;if(h>u)throw new A("Maximum size of messages that can be published at once exceeded ( was "+h+" bytes; limit is "+u+" bytes)",40009,400);await this._publish(encodeBody(t,r._MsgPack,a),l,n)}async _publish(e,t,n){await H.post(this.client,this.client.rest.channelMixin.basePath(this)+"/messages",e,t,n,null,!0)}async status(){return this.client.rest.channelMixin.status(this)}},er=class _Stats{constructor(e){this.entries=e&&e.entries||void 0,this.schema=e&&e.schema||void 0,this.appId=e&&e.appId||void 0,this.inProgress=e&&e.inProgress||void 0,this.unit=e&&e.unit||void 0,this.intervalId=e&&e.intervalId||void 0}static fromValues(e){return new _Stats(e)}},eo=class{static basePath(e){return"/channels/"+encodeURIComponent(e.name)}
6static history(e,t){let n=e.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.client.http.supportsLinkHeaders?void 0:s,r=M.defaultGetHeaders(n.options,{format:s});mixin(r,n.options.headers);let o=e.channelOptions;return new V(n,this.basePath(e)+"/messages",r,i,async function(e,t,i){return await fromResponseBody(e,o,n._MsgPack,i?void 0:s)}).get(t)}static async status(e){let t=e.client.options.useBinaryProtocol?"msgpack":"json",n=M.defaultPostHeaders(e.client.options,{format:t}),s=await H.get(e.client,this.basePath(e),n,{},t,!0);return s.body}},ea=class{static basePath(e){return eo.basePath(e.channel)+"/presence"}static async history(e,t){let n=e.channel.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.channel.client.http.supportsLinkHeaders?void 0:s,r=M.defaultGetHeaders(n.options,{format:s});mixin(r,n.options.headers);let o=e.channel.channelOptions;return new V(n,this.basePath(e)+"/history",r,i,async function(e,t,i){return await fromResponseBody2(e,o,n._MsgPack,i?void 0:s)}).get(t)}},ec=class{constructor(e){this.channelMixin=eo,this.presenceMixin=ea,this.client=e,this.channels=new el(this.client),this.push=new J(this.client)}async stats(e){let t=M.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return mixin(t,this.client.options.headers),new V(this.client,"/stats",t,s,function(e,t,n){let s=n?e:JSON.parse(e);for(let e=0;e<s.length;e++)s[e]=er.fromValues(s[e]);return s}).get(e)}async time(e){let t=M.defaultGetHeaders(this.client.options);this.client.options.headers&&mixin(t,this.client.options.headers);let{error:n,body:s,unpacked:i}=await this.client.http.do(L.Get,e=>this.client.baseUri(e)+"/time",t,null,e);if(n)throw n;i||(s=JSON.parse(s));let r=s[0];if(!r)throw new A("Internal error (unexpected result type from GET /time)",5e4,500);return this.client.serverTimeOffset=r-Date.now(),r}async request(e,t,n,s,i,r){var o;let[a,c,l]=this.client.options.useBinaryProtocol?(this.client._MsgPack||throwMissingPluginError("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],h=this.client.http.supportsLinkHeaders?void 0:l;s=s||{};let u=e.toLowerCase(),d="get"==u?M.defaultGetHeaders(this.client.options,{format:l,protocolVersion:n}):M.defaultPostHeaders(this.client.options,{format:l,protocolVersion:n});"string"!=typeof i&&(i=null!=(o=a(i))?o:null),mixin(d,this.client.options.headers),r&&mixin(d,r);let p=new V(this.client,t,d,h,async function(e,t,n){return ensureArray(n?e:c(e))},!0);if(!R.Http.methods.includes(u))throw new A("Unsupported method "+u,40500,405);return R.Http.methodsWithBody.includes(u)?p[u](s,i):p[u](s)}async batchPublish(e){let t,n;Array.isArray(e)?(t=e,n=!1):(t=[e],n=!0);let s=this.client.options.useBinaryProtocol?"msgpack":"json",i=M.defaultPostHeaders(this.client.options,{format:s});this.client.options.headers&&mixin(i,this.client.options.headers);let r=encodeBody(t,this.client._MsgPack,s),o=await H.post(this.client,"/messages",r,i,{},null,!0),a=o.unpacked?o.body:decodeBody(o.body,this.client._MsgPack,s);return n?a[0]:a}async batchPresence(e){let t=this.client.options.useBinaryProtocol?"msgpack":"json",n=M.defaultPostHeaders(this.client.options,{format:t});this.client.options.headers&&mixin(n,this.client.options.headers);let s=e.join(","),i=await H.get(this.client,"/presence",n,{channels:s},null,!0);return i.unpacked?i.body:decodeBody(i.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(useTokenAuth(this.client.options))throw new A("Cannot revoke tokens when using token auth",40162,401);let n=this.client.options.keyName,s=null!=t?t:{},i=__spreadValues({targets:e.map(e=>`${e.type}:${e.value}`)},s),r=this.client.options.useBinaryProtocol?"msgpack":"json",o=M.defaultPostHeaders(this.client.options,{format:r});this.client.options.headers&&mixin(o,this.client.options.headers);let a=encodeBody(i,this.client._MsgPack,r),c=await H.post(this.client,`/keys/${n}/revokeTokens`,a,o,{},null,!0);return c.unpacked?c.body:decodeBody(c.body,this.client._MsgPack,r)}setLog(e){w.setLog(e.level,e.handler)}},el=class{constructor(e){this.client=e,this.all=Object.create(null)}get(e,t){e=String(e);let n=this.all[e];return n?t&&n.setOptions(t):this.all[e]=n=new ei(this.client,e,t),n}release(e){delete this.all[String(e)]}},eh=class extends q{constructor(e){super(M.objectifyOptions(e,!1,"BaseRest",{Rest:ec}))}},eu={Rest:ec},ed=class extends Y{static async fromEncoded(e,t){return fromEncoded(R.Crypto,e,t)}static async fromEncodedArray(e,t){return fromEncodedArray(R.Crypto,e,t)}static fromValues(e){return Object.assign(new Y,e)}static async encode(e,t){return encode(e,t)}static async decode(e,t){return decode(e,t)}},ep=class extends en{static async fromEncoded(e,t){return fromEncoded2(e,t)}static async fromEncodedArray(e,t){return fromEncodedArray2(e,t)}static fromValues(e,t){return fromValues2(e,t)}},ef=class _DefaultRest extends eh{constructor(e){var t,n;let s=_DefaultRest._MsgPack;if(!s)throw Error("Expected DefaultRest._MsgPack to have been set");
6super(M.objectifyOptions(e,!0,"Rest",__spreadProps(__spreadValues({},eu),{Crypto:null!=(t=_DefaultRest.Crypto)?t:void 0,MsgPack:null!=(n=_DefaultRest._MsgPack)?n:void 0})))}static get Crypto(){if(null===this._Crypto)throw Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(e){this._Crypto=e}};ef._Crypto=null,ef.Message=ed,ef.PresenceMessage=ep,ef._MsgPack=null,ef._Http=G;var eg=ef;function removeListener(e,t,n){let s,i,r;for(let o=0;o<e.length;o++)if(s=e[o],n&&(s=s[n]),Array.isArray(s)){for(;-1!==(i=s.indexOf(t));)s.splice(i,1);n&&0===s.length&&delete e[o][n]}else if(isObject(s))for(r in s)Object.prototype.hasOwnProperty.call(s,r)&&Array.isArray(s[r])&&removeListener([s],t,r)}var em=class{constructor(){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null)}on(...e){if(1===e.length){let t=e[0];if("function"==typeof t)this.any.push(t);else throw Error("EventListener.on(): Invalid arguments: "+R.Config.inspect(e))}if(2===e.length){let[t,n]=e;if("function"!=typeof n)throw Error("EventListener.on(): Invalid arguments: "+R.Config.inspect(e));if(isNil(t))this.any.push(n);else if(Array.isArray(t))t.forEach(e=>{this.on(e,n)});else{if("string"!=typeof t)throw Error("EventListener.on(): Invalid arguments: "+R.Config.inspect(e));let s=this.events[t]||(this.events[t]=[]);s.push(n)}}}off(...e){if(0==e.length||isNil(e[0])&&isNil(e[1])){this.any=[],this.events=Object.create(null),this.anyOnce=[],this.eventsOnce=Object.create(null);return}let[t,n]=e,s=null,i=null;if(1!==e.length&&n){if("function"!=typeof n)throw Error("EventEmitter.off(): invalid arguments:"+R.Config.inspect(e));[i,s]=[t,n]}else"function"==typeof t?s=t:i=t;if(s&&isNil(i)){removeListener([this.any,this.events,this.anyOnce,this.eventsOnce],s);return}if(Array.isArray(i)){i.forEach(e=>{this.off(e,s)});return}if("string"!=typeof i)throw Error("EventEmitter.off(): invalid arguments:"+R.Config.inspect(e));s?removeListener([this.events,this.eventsOnce],s,i):(delete this.events[i],delete this.eventsOnce[i])}listeners(e){if(e){let t=this.events[e]||[];return this.eventsOnce[e]&&Array.prototype.push.apply(t,this.eventsOnce[e]),t.length?t:null}return this.any.length?this.any:null}emit(e,...t){let n={event:e},s=[];this.anyOnce.length&&(Array.prototype.push.apply(s,this.anyOnce),this.anyOnce=[]),this.any.length&&Array.prototype.push.apply(s,this.any);let i=this.eventsOnce[e];i&&(Array.prototype.push.apply(s,i),delete this.eventsOnce[e]);let r=this.events[e];r&&Array.prototype.push.apply(s,r),s.forEach(function(e){!function(e,t,n){try{t.apply(e,n)}catch(e){w.logAction(w.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+e+"; stack = "+(e&&e.stack))}}(n,e,t)})}once(...e){let t=e.length;if(0===t||1===t&&"function"!=typeof e[0]){let t=e[0];return new Promise(e=>{this.once(t,e)})}let[n,s]=e;if(1===e.length&&"function"==typeof n)this.anyOnce.push(n);else if(isNil(n)){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+R.Config.inspect(e));this.anyOnce.push(s)}else if(Array.isArray(n)){let t=this,listenerWrapper=function(){let i=Array.prototype.slice.call(arguments);if(n.forEach(function(e){t.off(e,listenerWrapper)}),"function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+R.Config.inspect(e));s.apply(this,i)};n.forEach(function(e){t.on(e,listenerWrapper)})}else{if("string"!=typeof n)throw Error("EventEmitter.once(): Invalid arguments:"+R.Config.inspect(e));let t=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(s){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+R.Config.inspect(e));t.push(s)}}}async whenState(e,t){if("string"!=typeof e||"string"!=typeof t)throw Error("whenState requires a valid state String argument");return e===t?null:this.once(e)}},ey={HEARTBEAT:0,ACK:1,NACK:2,CONNECT:3,CONNECTED:4,DISCONNECT:5,DISCONNECTED:6,CLOSE:7,CLOSED:8,ERROR:9,ATTACH:10,ATTACHED:11,DETACH:12,DETACHED:13,PRESENCE:14,MESSAGE:15,SYNC:16,AUTH:17,ACTIVATE:18},eb=[];Object.keys(ey).forEach(function(e){eb[ey[e]]=e});var ev={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,PRESENCE:65536,PUBLISH:131072,SUBSCRIBE:262144,PRESENCE_SUBSCRIBE:524288},eC=Object.keys(ev);function toStringArray(e){let t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}ev.MODE_ALL=ev.PRESENCE|ev.PUBLISH|ev.SUBSCRIBE|ev.PRESENCE_SUBSCRIBE;var eR=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE"];function fromDeserialized(e,t){let n=e.error;n&&(e.error=A.fromValues(n));let s=e.messages;if(s)for(let e=0;e<s.length;e++)s[e]=fromValues(s[e]);let i=t?e.presence:void 0;if(t&&i&&t)for(let e=0;e<i.length;
6e++)i[e]=t.presenceMessageFromValues(i[e],!0);return Object.assign(new eO,__spreadProps(__spreadValues({},e),{presence:i}))}function fromDeserializedIncludingDependencies(e){return fromDeserialized(e,{presenceMessageFromValues:fromValues2,presenceMessagesFromValuesArray:fromValuesArray2})}function fromValues3(e){return Object.assign(new eO,e)}function stringify(e,t){let n,s="[ProtocolMessage";void 0!==e.action&&(s+="; action="+eb[e.action]);let i=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"];for(let t=0;t<i.length;t++)void 0!==e[n=i[t]]&&(s+="; "+n+"="+e[n]);if(e.messages&&(s+="; messages="+toStringArray(fromValuesArray(e.messages))),e.presence&&t&&(s+="; presence="+toStringArray(t.presenceMessagesFromValuesArray(e.presence))),e.error&&(s+="; error="+A.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(s+="; token="+e.auth.accessToken),e.flags&&(s+="; flags="+eC.filter(e.hasFlag).join(",")),e.params){let t="";forInOwnNonNullProperties(e.params,function(n){t.length>0&&(t+="; "),t+=n+"="+e.params[n]}),t.length>0&&(s+="; params=["+t+"]")}return s+"]"}var eO=class{constructor(){this.hasFlag=e=>(this.flags&ev[e])>0}setFlag(e){return this.flags=this.flags|ev[e]}getMode(){return this.flags&&this.flags&ev.MODE_ALL}encodeModesToFlags(e){e.forEach(e=>this.setFlag(e))}decodeModesFromFlags(){let e=[];return eR.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},ew=class extends em{constructor(){super(),this.messages=[]}count(){return this.messages.length}push(e){this.messages.push(e)}shift(){return this.messages.shift()}last(){return this.messages[this.messages.length-1]}copyAll(){return this.messages.slice()}append(e){this.messages.push.apply(this.messages,e)}prepend(e){this.messages.unshift.apply(this.messages,e)}completeMessages(e,t,n){w.logAction(w.LOG_MICRO,"MessageQueue.completeMessages()","serial = "+e+"; count = "+t),n=n||null;let s=this.messages;if(0===s.length)throw Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let i=s[0];if(i){let r=i.message.msgSerial,o=e+t;if(o>r){let e=s.splice(0,o-r);for(let t of e)t.callback(n)}0==s.length&&this.emit("idle")}}completeAllMessages(e){this.completeMessages(0,Number.MAX_SAFE_INTEGER||Number.MAX_VALUE,e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){w.logAction(w.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},eS=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;let n=e.action;this.sendAttempted=!1,this.ackRequired=n==ey.MESSAGE||n==ey.PRESENCE}},eA=class extends em{constructor(e){super(),this.transport=e,this.messageQueue=new ew,e.on("ack",(e,t)=>{this.onAck(e,t)}),e.on("nack",(e,t,n)=>{this.onNack(e,t,n)})}onAck(e,t){w.logAction(w.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages(e,t)}onNack(e,t,n){w.logAction(w.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+inspectError(n)),n||(n=new A("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages(e,t,n)}onceIdle(e){let t=this.messageQueue;if(0===t.count()){e();return}t.once("idle",e)}send(e){e.ackRequired&&this.messageQueue.push(e),w.shouldLog(w.LOG_MICRO)&&w.logActionNoStrip(w.LOG_MICRO,"Protocol.send()","sending msg; "+stringify(e.message,this.transport.connectionManager.realtime._RealtimePresence)),e.sendAttempted=!0,this.transport.send(e.message)}getTransport(){return this.transport}getPendingMessages(){return this.messageQueue.copyAll()}clearPendingMessages(){return this.messageQueue.clear()}finish(){let e=this.transport;this.onceIdle(function(){e.disconnect()})}},ek=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},eT={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},e_={disconnected:()=>A.fromValues({statusCode:400,code:eT.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>A.fromValues({statusCode:400,code:eT.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>A.fromValues({statusCode:400,code:eT.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>A.fromValues({statusCode:400,code:eT.CLOSING,message:"Connection closing"}),closed:()=>A.fromValues({statusCode:400,code:eT.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>A.fromValues({statusCode:500,code:eT.UNKNOWN_CONNECTION_ERR,message:"Internal
6connection error"}),unknownChannelErr:()=>A.fromValues({statusCode:500,code:eT.UNKNOWN_CONNECTION_ERR,message:"Internal channel error"})},eM=fromValues3({action:ey.CLOSE}),eE=fromValues3({action:ey.DISCONNECT}),eI=class extends em{constructor(e,t,n,s){super(),s&&(n.format=void 0,n.heartbeats=!0),this.connectionManager=e,this.auth=t,this.params=n,this.timeouts=n.options.timeouts,this.format=n.format,this.isConnected=!1,this.isFinished=!1,this.isDisposed=!1,this.maxIdleInterval=null,this.idleTimer=null,this.lastActivity=null}connect(){}close(){this.isConnected&&this.requestClose(),this.finish("closed",e_.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||e_.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||e_.failed())}finish(e,t){var n;this.isFinished||(this.isFinished=!0,this.isConnected=!1,this.maxIdleInterval=null,clearTimeout(null!=(n=this.idleTimer)?n:void 0),this.idleTimer=null,this.emit(e,t),this.dispose())}onProtocolMessage(e){switch(w.shouldLog(w.LOG_MICRO)&&w.logActionNoStrip(w.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+stringify(e,this.connectionManager.realtime._RealtimePresence)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case ey.HEARTBEAT:w.logActionNoStrip(w.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case ey.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case ey.CLOSED:this.onClose(e);break;case ey.DISCONNECTED:this.onDisconnect(e);break;case ey.ACK:this.emit("ack",e.msgSerial,e.count);break;case ey.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case ey.SYNC:this.connectionManager.onChannelMessage(e,this);break;case ey.ACTIVATE:break;case ey.AUTH:whenPromiseSettles(this.auth.authorize(),function(e){e&&w.logAction(w.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+inspectError(e))});break;case ey.ERROR:if(w.logAction(w.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+R.Config.inspect(e.error)+(e.channel?", channel: "+e.channel:"")),void 0===e.channel){this.onFatalError(e);break}this.connectionManager.onChannelMessage(e,this);break;default:this.connectionManager.onChannelMessage(e,this)}}onConnect(e){if(this.isConnected=!0,!e.connectionDetails)throw Error("Transport.onConnect(): Connect message recieved without connectionDetails");let t=e.connectionDetails.maxIdleInterval;t&&(this.maxIdleInterval=t+this.timeouts.realtimeRequestTimeout,this.onActivity())}onDisconnect(e){let t=e&&e.error;w.logAction(w.LOG_MINOR,"Transport.onDisconnect()","err = "+inspectError(t)),this.finish("disconnected",t)}onFatalError(e){let t=e&&e.error;w.logAction(w.LOG_MINOR,"Transport.onFatalError()","err = "+inspectError(t)),this.finish("failed",t)}onClose(e){let t=e&&e.error;w.logAction(w.LOG_MINOR,"Transport.onClose()","err = "+inspectError(t)),this.finish("closed",t)}requestClose(){w.logAction(w.LOG_MINOR,"Transport.requestClose()",""),this.send(eM)}requestDisconnect(){w.logAction(w.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(eE)}ping(e){let t={action:ey.HEARTBEAT};e&&(t.id=e),this.send(fromValues3(t))}
6dispose(){w.logAction(w.LOG_MINOR,"Transport.dispose()",""),this.isDisposed=!0,this.off()}onActivity(){this.maxIdleInterval&&(this.lastActivity=this.connectionManager.lastActivity=Date.now(),this.setIdleTimer(this.maxIdleInterval+100))}setIdleTimer(e){this.idleTimer||(this.idleTimer=setTimeout(()=>{this.onIdleTimerExpire()},e))}onIdleTimerExpire(){if(!this.lastActivity||!this.maxIdleInterval)throw Error("Transport.onIdleTimerExpire(): lastActivity/maxIdleInterval not set");this.idleTimer=null;let e=Date.now()-this.lastActivity,t=this.maxIdleInterval-e;if(t<=0){let t="No activity seen from realtime in "+e+"ms; assuming connection has dropped";w.logAction(w.LOG_ERROR,"Transport.onIdleTimerExpire()",t),this.disconnect(new A(t,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,s,i){let r;let o=new e(t,n,s),errorCb=function(e){clearTimeout(r),i({event:this.event,error:e})},a=t.options.timeouts.realtimeRequestTimeout;return r=setTimeout(()=>{o.off(["preconnect","disconnected","failed"]),o.dispose(),errorCb.call({event:"disconnected"},new A("Timeout waiting for transport to indicate itself viable",5e4,500))},a),o.on(["failed","disconnected"],errorCb),o.on("preconnect",function(){w.logAction(w.LOG_MINOR,"Transport.tryConnect()","viable transport "+o),clearTimeout(r),o.off(["failed","disconnected"],errorCb),i(null,o)}),o.connect(),o}static isAvailable(){throw new A("isAvailable not implemented for transport",5e4,500)}};(i=o||(o={})).WebSocket="web_socket",i.Comet="comet",i.XhrPolling="xhr_polling";var eP=void 0!==n.g?n.g:"undefined"!=typeof window?window:self,haveWebStorage=()=>{var e;return void 0!==R.WebStorage&&(null==(e=R.WebStorage)?void 0:e.localSupported)},haveSessionStorage=()=>{var e;return void 0!==R.WebStorage&&(null==(e=R.WebStorage)?void 0:e.sessionSupported)},noop=function(){},eL="ably-transport-preference",eU="ably-connection-recovery";function decodeRecoveryKey(e){try{return JSON.parse(e)}catch(e){return null}}var ex=class{constructor(e,t,n,s){this.options=e,this.host=t,this.mode=n,this.connectionKey=s,this.format=e.useBinaryProtocol?"msgpack":"json"}getConnectParams(e){let t=e?copy(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":{let e=decodeRecoveryKey(n.recover);e&&(t.recover=e.connectionKey)}}return void 0!==n.clientId&&(t.clientId=n.clientId),!1===n.echoMessages&&(t.echo="false"),void 0!==this.format&&(t.format=this.format),void 0!==this.stream&&(t.stream=this.stream),void 0!==this.heartbeats&&(t.heartbeats=this.heartbeats),t.v=M.protocolVersion,t.agent=getAgentString(this.options),void 0!==n.transportParams&&mixin(t,n.transportParams),t}toString(){let e="[mode="+this.mode;return this.host&&(e+=",host="+this.host),this.connectionKey&&(e+=",connectionKey="+this.connectionKey),this.format&&(e+=",format="+this.format),e+="]"}},eN=class _ConnectionManager extends em{constructor(e,t){super(),this.supportedTransports={},this.disconnectedRetryCount=0,this.pendingChannelMessagesState={isProcessing:!1,queue:[]},this.realtime=e,this.initTransports(),this.options=t;let n=t.timeouts,s=n.webSocketConnectTimeout+n.realtimeRequestTimeout;if(this.states={initialized:{state:"initialized",terminal:!1,queueEvents:!0,sendEvents:!1,failState:"disconnected"},connecting:{state:"connecting",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:s,failState:"disconnected"},connected:{state:"connected",terminal:!1,queueEvents:!1,sendEvents:!0,failState:"disconnected"},disconnected:{state:"disconnected",terminal:!1,queueEvents:!0,sendEvents:!1,retryDelay:n.disconnectedRetryTimeout,failState:"disconnected"},suspended:{state:"suspended",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.suspendedRetryTimeout,failState:"suspended"},closing:{state:"closing",terminal:!1,queueEvents:!1,sendEvents:!1,retryDelay:n.realtimeRequestTimeout,failState:"closed"},closed:{state:"closed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"closed"},failed:{state:"failed",terminal:!0,queueEvents:!1,sendEvents:!1,failState:"failed"}},this.state=this.states.initialized,this.errorReason=null,this.queuedMessages=new ew,this.msgSerial=0,this.connectionDetail
6s=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=n.connectionStateTtl,this.maxIdleInterval=null,this.transports=intersect(t.transports||M.defaultTransports,this.supportedTransports),this.transportPreference=null,this.transports.includes(o.WebSocket)&&(this.webSocketTransportAvailable=!0),this.transports.includes(o.XhrPolling)?this.baseTransport=o.XhrPolling:this.transports.includes(o.Comet)&&(this.baseTransport=o.Comet),this.httpHosts=M.getHosts(t),this.wsHosts=M.getHosts(t,!0),this.activeProtocol=null,this.host=null,this.lastAutoReconnectAttempt=null,this.lastActivity=null,this.forceFallbackHost=!1,this.connectCounter=0,this.wsCheckResult=null,this.webSocketSlowTimer=null,this.webSocketGiveUpTimer=null,this.abandonedWebSocket=!1,w.logAction(w.LOG_MINOR,"Realtime.ConnectionManager()","started"),w.logAction(w.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(t.transports||M.defaultTransports)+"]"),w.logAction(w.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),w.logAction(w.LOG_MICRO,"Realtime.ConnectionManager()","http hosts = ["+this.httpHosts+"]"),!this.transports.length){let e="no requested transports available";throw w.logAction(w.LOG_ERROR,"realtime.ConnectionManager()",e),Error(e)}let i=R.Config.addEventListener;i&&(haveSessionStorage()&&"function"==typeof t.recover&&i("beforeunload",this.persistConnection.bind(this)),!0===t.closeOnUnload&&i("beforeunload",()=>{w.logAction(w.LOG_MAJOR,"Realtime.ConnectionManager()","beforeunload event has triggered the connection to close as closeOnUnload is true"),this.requestState({state:"closing"})}),i("online",()=>{var e;this.state==this.states.disconnected||this.state==this.states.suspended?(w.logAction(w.LOG_MINOR,"ConnectionManager caught browser âonlineâ event","reattempting connection"),this.requestState({state:"connecting"})):this.state==this.states.connecting&&(null==(e=this.pendingTransport)||e.off(),this.disconnectAllTransports(),this.startConnect())}),i("offline",()=>{this.state==this.states.connected&&(w.logAction(w.LOG_MINOR,"ConnectionManager caught browser âofflineâ event","disconnecting active transport"),this.disconnectAllTransports())}))}static supportedTransports(e){let t={supportedTransports:{}};return this.initTransports(e,t),t.supportedTransports}static initTransports(e,t){let n=__spreadValues(__spreadValues({},R.Transports.bundledImplementations),e);[o.WebSocket,...R.Transports.order].forEach(e=>{let s=n[e];s&&s.isAvailable()&&(t.supportedTransports[e]=s)})}initTransports(){_ConnectionManager.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(e,t){return new ex(this.options,e,t,this.connectionKey)}getTransportParams(e){(e=>{var t,n;if(this.connectionKey){e("resume");return}if("string"==typeof this.options.recover){e("recover");return}let s=this.options.recover,i=haveSessionStorage()&&(null==(n=null==(t=R.WebStorage)?void 0:t.getSession)?void 0:n.call(t,eU));if(i&&"function"==typeof s){w.logAction(w.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data"),s(i,t=>{t?(this.options.recover=i.recoveryKey,e("recover")):e("clean")});return}e("clean")})(t=>{let n=this.createTransportParams(null,t);if("recover"===t){w.logAction(w.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let e=decodeRecoveryKey(this.options.recover);e&&(this.msgSerial=e.msgSerial)}else w.logAction(w.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+n.toString());e(n)})}tryATransport(e,t,n){w.logAction(w.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+t),this.proposedTransport=eI.tryConnect(this.supportedTransports[t],this,this.realtime.auth,e,(s,i)=>{let r=this.state;if(r==this.states.closing||r==this.states.closed||r==this.states.failed){i&&(w.logAction(w.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+r.state+" while we were attempting the transport; closing "+i),i.close()),n(!0);return}if(s){if(w.logAction(w.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+t+" "+s.event+", err: "+s.error.toString()),N.isTokenErr(s.error)&&!(this.errorReason&&N.isTokenErr(this.errorReason)))this.errorReason=s.error,whenPromiseSettles(this.realtime.auth._forceNewToken(null,null),s=>
6{if(s){this.actOnErrorFromAuthorize(s);return}this.tryATransport(e,t,n)});else if("failed"===s.event)this.notifyState({state:"failed",error:s.error}),n(!0);else if("disconnected"===s.event){var o;!(o=s.error).statusCode||!o.code||o.statusCode>=500||Object.values(eT).includes(o.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:s.error}),n(!0))}return}w.logAction(w.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+t+"; setting pending"),this.setTransportPending(i,e),n(null,i)})}setTransportPending(e,t){let n=t.mode;w.logAction(w.LOG_MINOR,"ConnectionManager.setTransportPending()","transport = "+e+"; mode = "+n),this.pendingTransport=e,this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),e.once("connected",(t,s,i)=>{this.activateTransport(t,e,s,i),"recover"===n&&this.options.recover&&(delete this.options.recover,this.unpersistConnection())});let s=this;e.on(["disconnected","closed","failed"],function(t){s.deactivateTransport(e,this.event,t)}),this.emit("transport.pending",e)}activateTransport(e,t,n,s){w.logAction(w.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+t),e&&w.logAction(w.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+e),n&&w.logAction(w.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+n),s&&w.logAction(w.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetails = "+JSON.stringify(s)),this.persistTransportPreference(t);let i=this.state,r=this.states.connected.state;if(w.logAction(w.LOG_MINOR,"ConnectionManager.activateTransport()","current state = "+i.state),i.state==this.states.closing.state||i.state==this.states.closed.state||i.state==this.states.failed.state)return w.logAction(w.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),t.disconnect(),!1;if(delete this.pendingTransport,!t.isConnected)return w.logAction(w.LOG_MINOR,"ConnectionManager.activateTransport()","Declining to activate transport "+t+" since it appears to no longer be connected"),!1;let o=this.activeProtocol;this.activeProtocol=new eA(t),this.host=t.params.host;let a=s.connectionKey;if(a&&this.connectionKey!=a&&this.setConnection(n,s,!!e),this.onConnectionDetailsUpdate(s,t),R.Config.nextTick(()=>{t.on("connected",(e,n,s)=>{this.onConnectionDetailsUpdate(s,t),this.emit("update",new ek(r,r,null,e))})}),i.state===this.states.connected.state?e&&(this.errorReason=this.realtime.connection.errorReason=e,this.emit("update",new ek(r,r,null,e))):(this.notifyState({state:"connected",error:e}),this.errorReason=this.realtime.connection.errorReason=e||null),this.emit("transport.active",t),o){if(o.messageQueue.count()>0&&w.logAction(w.LOG_ERROR,"ConnectionManager.activateTransport()","Previous active protocol (for transport "+o.transport.shortName+", new one is "+t.shortName+") finishing with "+o.messageQueue.count()+" messages still pending"),o.transport===t){let e="Assumption violated: activating a transport that was also the transport for the previous active protocol; transport = "+t.shortName+"; stack = "+Error().stack;w.logAction(w.LOG_ERROR,"ConnectionManager.activateTransport()",e)}else o.finish()}return!0}deactivateTransport(e,t,n){let s=this.activeProtocol,i=s&&s.getTransport()===e,r=e===this.pendingTransport,o=this.noTransportsScheduledForActivation();if(w.logAction(w.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+e),w.logAction(w.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+t+(i?"; was active":r?"; was pending":"")+(o?"":"; another transport is scheduled for activation")),n&&n.message&&w.logAction(w.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+n.message),i&&(w.logAction(w.LOG_MICRO,"ConnectionManager.deactivateTransport()","Getting, clearing, and requeuing "+this.activeProtocol.messageQueue.count()+" pending messages"),this.queuePendingMessages(s.getPendingMessages()),s.clearPendingMessages(),this.activeProtocol=this.host=null),this.emit("transport.inactive",e),i&&o||i&&"failed"===t||"closed"===t||null===s&&r){if("disconnected"===t&&n&&n.statusCode>500&&this.httpHosts.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:t,error:n,retryImmediately:!0});return}let e="failed"===t&&N.isTokenErr(n)?"disconnected":t;this.notifyState({state:e,error:n});return}}noTransportsScheduledForActivation(){return!this.pendingTransport||!this.pendingTransport.isConnected}setConnection(e,t,n){let s=this.connectionId;(s&&s!==e||!s&&n)&&(w.logAction(w.LOG_MINOR,"ConnectionManager.setConnection()","Re
6setting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==e&&w.logAction(w.LOG_MINOR,"ConnectionManager.setConnection()","New connectionId; reattaching any attached channels"),this.realtime.connection.id=this.connectionId=e,this.realtime.connection.key=this.connectionKey=t.connectionKey}clearConnection(){this.realtime.connection.id=this.connectionId=void 0,this.realtime.connection.key=this.connectionKey=void 0,this.msgSerial=0,this.unpersistConnection()}createRecoveryKey(){return this.connectionKey?JSON.stringify({connectionKey:this.connectionKey,msgSerial:this.msgSerial,channelSerials:this.realtime.channels.channelSerials()}):null}checkConnectionStateFreshness(){if(!this.lastActivity||!this.connectionId)return;let e=Date.now()-this.lastActivity;e>this.connectionStateTtl+this.maxIdleInterval&&(w.logAction(w.LOG_MINOR,"ConnectionManager.checkConnectionStateFreshness()","Last known activity from realtime was "+e+"ms ago; discarding connection state"),this.clearConnection(),this.states.connecting.failState="suspended")}persistConnection(){if(haveSessionStorage()){let s=this.createRecoveryKey();if(s){var e,t,n;e={recoveryKey:s,disconnectedAt:Date.now(),location:eP.location,clientId:this.realtime.auth.clientId},haveSessionStorage()&&(null==(n=null==(t=R.WebStorage)?void 0:t.setSession)||n.call(t,eU,e))}}}unpersistConnection(){var e,t;haveSessionStorage()&&(null==(t=null==(e=R.WebStorage)?void 0:e.removeSession)||t.call(e,eU))}getError(){return this.errorReason||this.getStateError()}getStateError(){var e;return null==(e=e_[this.state.state])?void 0:e.call(e_)}activeState(){return this.state.queueEvents||this.state.sendEvents}enactStateChange(e){let t="Connection state",n=e.current+(e.reason?"; reason: "+e.reason:"");"failed"===e.current?w.logAction(w.LOG_ERROR,t,n):w.logAction(w.LOG_MAJOR,t,n),w.logAction(w.LOG_MINOR,"ConnectionManager.enactStateChange","setting new state: "+e.current+"; reason = "+(e.reason&&e.reason.message));let s=this.state=this.states[e.current];e.reason&&(this.errorReason=e.reason,this.realtime.connection.errorReason=e.reason),(s.terminal||"suspended"===s.state)&&this.clearConnection(),this.emit("connectionstate",e)}startTransitionTimer(e){w.logAction(w.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+e.state),this.transitionTimer&&(w.logAction(w.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,w.logAction(w.LOG_MINOR,"ConnectionManager "+e.state+" timer expired","requesting new state: "+e.failState),this.notifyState({state:e.failState}))},e.retryDelay)}cancelTransitionTimer(){w.logAction(w.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,w.logAction(w.LOG_MINOR,"ConnectionManager suspend timer expired","requesting new state: suspended"),this.states.connecting.failState="suspended",this.notifyState({state:"suspended"}))},this.connectionStateTtl))}checkSuspendTimer(e){"disconnected"!==e&&"suspended"!==e&&"connecting"!==e&&this.cancelSuspendTimer()}cancelSuspendTimer(){this.states.connecting.failState="disconnected",this.suspendTimer&&(clearTimeout(this.suspendTimer),this.suspendTimer=null)}startRetryTimer(e){this.retryTimer=setTimeout(()=>{w.logAction(w.LOG_MINOR,"ConnectionManager retry timer expired","retrying"),this.retryTimer=null,this.requestState({state:"connecting"})},e)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}startWebSocketSlowTimer(){this.webSocketSlowTimer=setTimeout(()=>{w.logAction(w.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),null===this.wsCheckResult&&this.checkWsConnectivity().then(()=>{w.logAction(w.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{w.logAction(w.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&whenPromiseSettles(this.realtime.http.checkConnectivity(),(e,t)=>{e||!t?(w.logAction(w.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new A("new ErrorInfo('Unable to connect (network unreachable)'",80003,404)})):w.logAction(w.LOG_MINOR,"ConnectionManager WebSocket slow timer","http connectivity check succeeded")})},this.options.timeouts.webSocketSlowTimeout)}cancelWebSocketSlowTimer(){this.webSocketSlowTimer&&(clearTimeout(this.webSocketSlowTimer),this.webSocketSlowTimer=null)}startWebSocketGiveUpTimer(e){this.webSocketGiveUpTimer=setTimeout(()=>{var t,n;this.wsCheckResult||(w.logAction(w.LOG_MINOR,"ConnectionManager WebSocket give up timer","websocket connection took more than 10s; "+(this.baseTransport?"trying base transport":"")),this.baseTransport?(this.abandonedWebSocket=!0,null==(t=this.proposedTransport)||t.dispose(),null==(n=this.pendingTransport)||n.dispose(),this.connectBase(e,++this.connectCounter)):w.logAction(w.LOG_MAJOR,"ConnectionManager WebSocket give up timer","websocket connectivity appears to be unavailable but no other transports to try"))},this.options.timeouts.webSocketConnectTimeout)}cancelWebSocketGiveUpTimer(){this.webSocketGiveUpTimer&&(clearTimeout(this.webSocketGiveUpTimer),this.webSocketGiveUpTimer=null)}notifyState(e){var t;let n=e.state,s="disconnected"===n&&(this.state===this.states.connected||e.retryImmediately||this.state===this.states.connecting&&e.error&&N.isTokenErr(e.error)&&!(this.errorReason&&N.isTokenErr(this.errorReason)));if(w.logAction(w.LOG_MINOR,"ConnectionManager.notifyState()","new state: "+n+(s?"; will retry connection immediately":"")),n==this.state.state||(this.cancelTransitionTimer(),this.cancelRetryTimer(),this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.checkSuspendTimer(e.state),("suspended"===n||"connected"===n)&&(this.disconnectedRetryCount=0),this.state.terminal))return;let i=this.states[e.state],r=i.retryDelay;"disconnected"===i.state&&(this.disconnectedRetryCount++,r=getRetryTime(i.retryDelay,this.disconnectedRetryCount));let o=new ek(this.state.state,i.state,r,e.error||(null==(t=e_[i.state])?void 0:t.call(e_)));if(s){let autoReconnect=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},e=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;e&&e<1e3?(w.logAction(w.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+e+"ms ago, waiting another "+(1e3-e)+"ms before trying again"),setTimeout(autoReconnect,1e3-e)):R.Config.nextTick(autoReconnect)}else("disconnected"===n||"suspended"===n)&&this.startRetryTimer(r);("disconnected"===n&&!s||"suspended"===n||i.terminal)&&R.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=n||this.activeProtocol||w.logAction(w.LOG_ERROR,"ConnectionManager.notifyState()","Broken invariant: attempted to go into connected state, but there is no active protocol"),this.enactStateChange(o),this.state.sendEvents?this.sendQueuedMessages():this.state.queueEvents||(this.realtime.channels.propogateConnectionInterruption(n,o.reason),this.failQueuedMessages(o.reason))}requestState(e){var t;let n=e.state;if(w.logAction(w.LOG_MINOR,"ConnectionManager.requestState()","requested state: "+n+"; current state: "+this.state.state),n==this.state.state||(this.cancelWebSocketSlowTimer(),this.cancelWebSocketGiveUpTimer(),this.cancelTransitionTimer(),this.cancelRetryTimer(),this.checkSuspendTimer(n),"connecting"==n&&"connected"==this.state.state||"closing"==n&&"closed"==this.state.state))return;let s=this.states[n],i=new ek(this.state.state,s.state,null,e.error||(null==(t=e_[s.state])?void 0:t.call(e_)));this.enactStateChange(i),"connecting"==n&&R.Config.nextTick(()=>{this.startConnect()}),"closing"==n&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting){w.logAction(w.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);return}let e=this.realtime.auth,t=++this.connectCounter,connect=()=>
6{this.checkConnectionStateFreshness(),this.getTransportParams(e=>{if("recover"===e.mode&&e.options.recover){let t=decodeRecoveryKey(e.options.recover);t&&this.realtime.channels.recoverChannels(t.channelSerials)}t===this.connectCounter&&this.connectImpl(e,t)})};if(w.logAction(w.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),"basic"===e.method)connect();else{let authCb=e=>{t===this.connectCounter&&(e?this.actOnErrorFromAuthorize(e):connect())};this.errorReason&&N.isTokenErr(this.errorReason)?whenPromiseSettles(e._forceNewToken(null,null),authCb):whenPromiseSettles(e._ensureValidAuthCredentials(!1),authCb)}}connectImpl(e,t){let n=this.state.state;if(n!==this.states.connecting.state){w.logAction(w.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+n);return}let s=this.getTransportPreference();s&&s===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.wsCheckResult=!0,this.abandonedWebSocket=!1,this.unpersistTransportPreference(),this.state===this.states.connecting&&(w.logAction(w.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(e,++this.connectCounter))}).catch(noop),s&&s===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(e,t):this.connectWs(e,t)}connectWs(e,t){w.logAction(w.LOG_DEBUG,"ConnectionManager.connectWs()"),this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(e),this.tryTransportWithFallbacks("web_socket",e,!0,t,()=>!1!==this.wsCheckResult&&!this.abandonedWebSocket)}connectBase(e,t){w.logAction(w.LOG_DEBUG,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,e,!1,t,()=>!0):this.notifyState({state:"disconnected",error:new A("No transports left to try",8e4,404)})}tryTransportWithFallbacks(e,t,n,s,i){w.logAction(w.LOG_DEBUG,"ConnectionManager.tryTransportWithFallbacks()",e);let giveUp=e=>{this.notifyState({state:this.states.connecting.failState,error:e})},r=n?this.wsHosts.slice():this.httpHosts.slice(),hostAttemptCb=(e,t)=>{if(s===this.connectCounter){if(!i()){t&&t.dispose();return}t||e||tryFallbackHosts()}},o=r.shift();if(!o){giveUp(new A("Unable to connect (no available host)",80003,404));return}t.host=o;let tryFallbackHosts=()=>
6{if(!r.length){giveUp(new A("Unable to connect (and no more fallback hosts to try)",80003,404));return}if(!this.realtime.http.checkConnectivity){giveUp(new k("Internal error: Http.checkConnectivity not set",null,500));return}whenPromiseSettles(this.realtime.http.checkConnectivity(),(n,o)=>{if(s===this.connectCounter&&i()){if(n){giveUp(n);return}if(!o){giveUp(new A("Unable to connect (network unreachable)",80003,404));return}t.host=arrPopRandomElement(r),this.tryATransport(t,e,hostAttemptCb)}})};if(this.forceFallbackHost&&r.length){this.forceFallbackHost=!1,tryFallbackHosts();return}this.tryATransport(t,e,hostAttemptCb)}closeImpl(){w.logAction(w.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(w.logAction(w.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(w.logAction(w.LOG_MICRO,"ConnectionManager.closeImpl()","Closing active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().close()),this.notifyState({state:"closed"})}onAuthUpdated(e,t){var n;switch(this.state.state){case"connected":{w.logAction(w.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Sending AUTH message on active transport");let s=null==(n=this.activeProtocol)?void 0:n.getTransport();s&&s.onAuthUpdated&&s.onAuthUpdated(e);let i=fromValues3({action:ey.AUTH,auth:{accessToken:e.token}});this.send(i);let successListener=()=>{this.off(failureListener),t(null,e)},failureListener=e=>{"failed"===e.current&&(this.off(successListener),this.off(failureListener),t(e.reason||this.getStateError()))};this.once("connectiondetails",successListener),this.on("connectionstate",failureListener);break}case"connecting":w.logAction(w.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{w.logAction(w.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");let listener=n=>{switch(n.current){case"connected":this.off(listener),t(null,e);break;case"failed":case"closed":case"suspended":this.off(listener),t(n.reason||this.getStateError())}};this.on("connectionstate",listener),"connecting"===this.state.state?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){w.logAction(w.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(w.logAction(w.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(w.logAction(w.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(w.logAction(w.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(e,t,n){n=n||noop;let s=this.state;if(s.sendEvents){w.logAction(w.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new eS(e,n));return}let i=t&&s.queueEvents;if(!i){let e="rejecting event, queueEvent was "+t+", state was "+s.state;w.logAction(w.LOG_MICRO,"ConnectionManager.send()",e),n(this.errorReason||new A(e,9e4,400));return}w.shouldLog(w.LOG_MICRO)&&w.logAction(w.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+stringify(e,this.realtime._RealtimePresence)),this.queue(e,n)}sendImpl(e){let t=e.message;e.ackRequired&&!e.sendAttempted&&(t.msgSerial=this.msgSerial++);try{this.activeProtocol.send(e)}catch(e){w.logAction(w.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+e.stack)}}queue(e,t){w.logAction(w.LOG_MICRO,"ConnectionManager.queue()","queueing event");
6let n=this.queuedMessages.last(),s=this.options.maxMessageSize;n&&!n.sendAttempted&&function(e,t,n){let s;if(e.channel!==t.channel||(s=e.action)!==ey.PRESENCE&&s!==ey.MESSAGE||s!==t.action)return!1;let i=s===ey.PRESENCE?"presence":"messages",r=e[i].concat(t[i]),o=getMessagesSize(r);return!!(!(o>n)&&allSame(r,"clientId")&&r.every(function(e){return!e.id}))&&(e[i]=r,!0)}(n.message,e,s)?(n.merged||(n.callback=P.create([n.callback]),n.merged=!0),n.callback.push(t)):this.queuedMessages.push(new eS(e,t))}sendQueuedMessages(){let e;for(w.logAction(w.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");e=this.queuedMessages.shift();)this.sendImpl(e)}queuePendingMessages(e){e&&e.length&&(w.logAction(w.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+e.length+" pending messages"),this.queuedMessages.prepend(e))}failQueuedMessages(e){let t=this.queuedMessages.count();t>0&&(w.logAction(w.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+t+" queued messages, err = "+inspectError(e)),this.queuedMessages.completeAllMessages(e))}onChannelMessage(e,t){this.pendingChannelMessagesState.queue.push({message:e,transport:t}),this.pendingChannelMessagesState.isProcessing||this.processNextPendingChannelMessage()}processNextPendingChannelMessage(){if(this.pendingChannelMessagesState.queue.length>0){this.pendingChannelMessagesState.isProcessing=!0;let e=this.pendingChannelMessagesState.queue.shift();this.processChannelMessage(e.message).catch(e=>{w.logAction(w.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",e)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(e){await this.realtime.channels.processChannelMessage(e)}ping(e,t){if(e){w.logAction(w.LOG_MINOR,"ConnectionManager.ping()","transport = "+e);let n=Date.now(),s=cheapRandStr(),onHeartbeat=function(r){if(r===s){e.off("heartbeat",onHeartbeat),clearTimeout(i);let s=Date.now()-n;t(null,s)}},i=setTimeout(function(){e.off("heartbeat",onHeartbeat),t(new A("Timeout waiting for heartbeat response",5e4,500))},this.options.timeouts.realtimeRequestTimeout);e.on("heartbeat",onHeartbeat),e.ping(s);return}if("connected"!==this.state.state){t(new A("Unable to ping service; not connected",4e4,400));return}let n=!1,onTransportActive=()=>{n||(n=!0,R.Config.nextTick(()=>{this.ping(null,t)}))};this.on("transport.active",onTransportActive),this.ping(this.activeProtocol.getTransport(),(e,s)=>{this.off("transport.active",onTransportActive),n||(n=!0,t(e,s))})}abort(e){this.activeProtocol.getTransport().fail(e)}getTransportPreference(){var e,t;return this.transportPreference||haveWebStorage()&&(null==(t=null==(e=R.WebStorage)?void 0:e.get)?void 0:t.call(e,eL))}persistTransportPreference(e){var t,n;this.transportPreference=e.shortName,haveWebStorage()&&(null==(n=null==(t=R.WebStorage)?void 0:t.set)||n.call(t,eL,e.shortName))}unpersistTransportPreference(){var e,t;this.transportPreference=null,haveWebStorage()&&(null==(t=null==(e=R.WebStorage)?void 0:e.remove)||t.call(e,eL))}actOnErrorFromAuthorize(e){if(40171===e.code)this.notifyState({state:"failed",error:e});else if(40102===e.code)this.notifyState({state:"failed",error:e});else if(e.statusCode===U.Forbidden){let t="Client configured authentication provider returned 403; failing the connection";w.logAction(w.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",t),this.notifyState({state:"failed",error:new A(t,80019,403,e)})}else{let t="Client configured authentication provider request failed";w.logAction(w.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",t),this.notifyState({state:this.state.failState,error:new A(t,80019,401,e)})}}onConnectionDetailsUpdate(e,t){if(!e)return;this.connectionDetails=e,e.maxMessageSize&&(this.options.maxMessageSize=e.maxMessageSize);let n=e.clientId;if(n){let e=this.realtime.auth._uncheckedSetClientId(n);if(e){w.logAction(w.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",e.message),t.fail(e);return}}let s=e.connectionStateTtl;s&&(this.connectionStateTtl=s),this.maxIdleInterval=e.maxIdleInterval,this.emit
6("connectiondetails",e)}checkWsConnectivity(){let e=new R.Config.WebSocket(M.wsConnectivityUrl);return new Promise((t,n)=>{let s=!1;e.onopen=()=>{s||(s=!0,t(),e.close())},e.onclose=e.onerror=()=>{s||(s=!0,n())}})}},eG=class extends em{constructor(e,t){super(),this.whenState=e=>em.prototype.whenState.call(this,e,this.state),this.ably=e,this.connectionManager=new eN(e,t),this.state=this.connectionManager.state.state,this.key=void 0,this.id=void 0,this.errorReason=null,this.connectionManager.on("connectionstate",e=>{let t=this.state=e.current;R.Config.nextTick(()=>{this.emit(t,e)})}),this.connectionManager.on("update",e=>{R.Config.nextTick(()=>{this.emit("update",e)})})}connect(){w.logAction(w.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}async ping(){return w.logAction(w.LOG_MINOR,"Connection.ping()",""),new Promise((e,t)=>{this.connectionManager.ping(null,(n,s)=>n?t(n):e(s))})}close(){w.logAction(w.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return w.deprecationWarning("The `Connection.recoveryKey` attribute has been replaced by the `Connection.createRecoveryKey()` method. Replace your usage of `recoveryKey` with the return value of `createRecoveryKey()`. `recoveryKey` will be removed in a future version."),this.createRecoveryKey()}createRecoveryKey(){return this.connectionManager.createRecoveryKey()}},eB=class{constructor(e,t,n,s,i){this.previous=e,this.current=t,"attached"===t&&(this.resumed=n,this.hasBacklog=s),i&&(this.reason=i)}},noop2=function(){},eq=class _RealtimeChannel extends em{constructor(e,t,n){var s;super(),this.retryCount=0,this.history=async function(e){w.logAction(w.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let t=this.client.rest.channelMixin;if(e&&e.untilAttach){if("attached"!==this.state)throw new A("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new A("untilAttach was specified and channel is attached, but attachSerial is not defined",4e4,400);delete e.untilAttach,e.from_serial=this.properties.attachSerial}return t.history(this,e)},this.whenState=e=>em.prototype.whenState.call(this,e,this.state),w.logAction(w.LOG_MINOR,"RealtimeChannel()","started; name = "+t),this.name=t,this.channelOptions=normaliseChannelOptions(null!=(s=e._Crypto)?s:null,n),this.client=e,this._presence=e._RealtimePresence?new e._RealtimePresence.RealtimePresence(this):null,this.connectionManager=e.connection.connectionManager,this.state="initialized",this.subscriptions=new em,this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=null,this._requestedFlags=null,this._mode=null,this._attachResume=!1,this._decodingContext={channelOptions:this.channelOptions,plugins:e.options.plugins||{},baseEncodedPreviousPayload:void 0},this._lastPayload={messageId:null,protocolMessageChannelSerial:null,decodeFailureRecoveryInProgress:null},this._allChannelChanges=new em}get presence(){return this._presence||throwMissingPluginError("RealtimePresence"),this._presence}invalidStateError(){return new A("Channel operation failed as channel state is "+this.state,90001,400,this.errorReason||void 0)}static processListenerArgs(e){return"function"==typeof(e=Array.prototype.slice.call(e))[0]&&e.unshift(null),e}async setOptions(e){var t;let n=this.channelOptions,s=function(e){if(e&&"params"in e&&!isObject(e.params))return new A("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new A("options.modes must be an array",4e4,400);for(let t=0;t<e.modes.length;t++){let n=e.modes[t];if(!n||"string"!=typeof n||!eR.includes(String.prototype.toUpperCase.call(n)))return new A("Invalid channel mode: "+n,4e4,400)}}}(e);if(s)throw s;if(this.channelOptions=normaliseChannelOptions(null!=(t=this.client._Crypto)?t:null,e),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(e,n))return this.attachImpl(),new Promise((e,t)=>
6{this._allChannelChanges.once(["attached","update","detached","failed"],function(n){switch(this.event){case"update":case"attached":e();break;default:t(n.reason)}})})}_shouldReattachToSetOptions(e,t){if(!("attached"===this.state||"attaching"===this.state))return!1;if(null==e?void 0:e.params){let n=omitAgent(e.params),s=omitAgent(t.params);if(Object.keys(n).length!==Object.keys(s).length||!shallowEquals(s,n))return!0}return null!=e&&!!e.modes&&(!t.modes||!arrEquals(e.modes,t.modes))}async publish(...e){let t=e[0],n=e.length;if(!this.connectionManager.activeState())throw this.connectionManager.getError();if(1==n){if(isObject(t))t=[fromValues(t)];else if(Array.isArray(t))t=fromValuesArray(t);else throw new A("The single-argument form of publish() expects a message object or an array of message objects",40013,400)}else t=[fromValues({name:e[0],data:e[1]})];let s=this.client.options.maxMessageSize;await encodeArray(t,this.channelOptions);let i=getMessagesSize(t);if(i>s)throw new A("Maximum size of messages that can be published at once exceeded ( was "+i+" bytes; limit is "+s+" bytes)",40009,400);return new Promise((e,n)=>{this._publish(t,t=>t?n(t):e())})}_publish(e,t){w.logAction(w.LOG_MICRO,"RealtimeChannel.publish()","message count = "+e.length);let n=this.state;switch(n){case"failed":case"suspended":t(A.fromValues(this.invalidStateError()));break;default:{w.logAction(w.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+n);let s=new eO;s.action=ey.MESSAGE,s.channel=this.name,s.messages=e,this.sendMessage(s,t)}}}onEvent(e){w.logAction(w.LOG_MICRO,"RealtimeChannel.onEvent()","received message");let t=this.subscriptions;for(let n=0;n<e.length;n++){let s=e[n];t.emit(s.name,s)}}async attach(){return"attached"===this.state?null:new Promise((e,t)=>{this._attach(!1,null,(n,s)=>n?t(n):e(s))})}_attach(e,t,n){n||(n=function(e){e&&w.logAction(w.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+e.toString())});let s=this.connectionManager;if(!s.activeState()){n(s.getError());return}("attaching"!==this.state||e)&&this.requestState("attaching",t),this.once(function(e){switch(this.event){case"attached":null==n||n(null,e);break;case"detached":case"suspended":case"failed":null==n||n(e.reason||s.getError()||new A("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new A("Attach request superseded by a subsequent detach request",9e4,409))}})}attachImpl(){w.logAction(w.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let e=fromValues3({action:ey.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this._requestedFlags?e.encodeModesToFlags(this._requestedFlags):this.channelOptions.modes&&e.encodeModesToFlags(allToUpperCase(this.channelOptions.modes)),this._attachResume&&e.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(e.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.sendMessage(e,noop2)}async detach(){let e=this.connectionManager;if(!e.activeState())throw e.getError();switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new A("Unable to detach; channel state = failed",90001,400);default:this.requestState("detaching");case"detaching":return new Promise((t,n)=>{this.once(function(s){switch(this.event){case"detached":t();break;case"attached":case"suspended":case"failed":n(s.reason||e.getError()||new A("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":n(new A("Detach request superseded by a subsequent attach request",9e4,409))}})})}}detachImpl(e){w.logAction(w.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let t=fromValues3({action:ey.DETACH,channel:this.name});this.sendMessage(t,e||noop2)}async subscribe(...e){let[t,n]=_RealtimeChannel.processListenerArgs(e);if("failed"===this.state)throw A.fromValues(this.invalidStateError());return t&&"object"==typeof t&&!Array.isArray(t)?this.client._FilteredSubscriptions.subscribeFilter(this,t,n):this.subscriptions.on(t,n),this.attach()}unsubscribe(...e){var t;let[n,s]=_RealtimeChannel.processListenerArgs(e);if("object"==typeof n&&!s||(null==(t=this.filteredSubscriptions)?void 0:t.has(s))){this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,n,s).forEac
6h(e=>this.subscriptions.off(e));return}this.subscriptions.off(n,s)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new k("Unable to sync to channel; not attached",4e4)}let e=this.connectionManager;if(!e.activeState())throw e.getError();let t=fromValues3({action:ey.SYNC,channel:this.name});this.syncChannelSerial&&(t.channelSerial=this.syncChannelSerial),e.send(t)}sendMessage(e,t){this.connectionManager.send(e,this.client.options.queueMessages,t)}sendPresence(e,t){let n=fromValues3({action:ey.PRESENCE,channel:this.name,presence:Array.isArray(e)?this.client._RealtimePresence.presenceMessagesFromValuesArray(e):[this.client._RealtimePresence.presenceMessageFromValues(e)]});this.sendMessage(n,t)}async processMessage(e){(e.action===ey.ATTACHED||e.action===ey.MESSAGE||e.action===ey.PRESENCE)&&this.setChannelSerial(e.channelSerial);let t,n=!1;switch(e.action){case ey.ATTACHED:{this.properties.attachSerial=e.channelSerial,this._mode=e.getMode(),this.params=e.params||{};let t=e.decodeModesFromFlags();this.modes=t&&allToLowerCase(t)||void 0;let n=e.hasFlag("RESUMED"),s=e.hasFlag("HAS_PRESENCE"),i=e.hasFlag("HAS_BACKLOG");if("attached"===this.state){!n&&this._presence&&this._presence.onAttached(s);let t=new eB(this.state,this.state,n,i,e.error);this._allChannelChanges.emit("update",t),(!n||this.channelOptions.updateOnAttached)&&this.emit("update",t)}else"detaching"===this.state?this.checkPendingState():this.notifyState("attached",e.error,n,s,i);break}case ey.DETACHED:{let t=e.error?A.fromValues(e.error):new A("Channel detached",90001,404);"detaching"===this.state?this.notifyState("detached",t):"attaching"===this.state?this.notifyState("suspended",t):this.requestState("attaching",t);break}case ey.SYNC:if(n=!0,t=this.syncChannelSerial=e.channelSerial,!e.presence)break;case ey.PRESENCE:{let s;let i=e.presence;if(!i)break;let{id:r,connectionId:o,timestamp:a}=e,c=this.channelOptions;for(let e=0;e<i.length;e++)try{s=i[e],await ee(s,c),s.connectionId||(s.connectionId=o),s.timestamp||(s.timestamp=a),s.id||(s.id=r+":"+e)}catch(e){w.logAction(w.LOG_ERROR,"RealtimeChannel.processMessage()",e.toString())}this._presence&&this._presence.setPresence(i,n,t);break}case ey.MESSAGE:{if("attached"!==this.state){w.logAction(w.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+e.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');return}let t=e.messages,n=t[0],s=t[t.length-1],i=e.id,r=e.connectionId,o=e.timestamp;if(n.extras&&n.extras.delta&&n.extras.delta.from!==this._lastPayload.messageId){let t='Delta message decode failure - previous message not available for message "'+e.id+'" on this channel "'+this.name+'".';w.logAction(w.LOG_ERROR,"RealtimeChannel.processMessage()",t),this._startDecodeFailureRecovery(new A(t,40018,400));break}for(let e=0;e<t.length;e++){let n=t[e];try{await decode(n,this._decodingContext)}catch(e){switch(w.logAction(w.LOG_ERROR,"RealtimeChannel.processMessage()",e.toString()),e.code){case 40018:this._startDecodeFailureRecovery(e);return;case 40019:case 40021:this.notifyState("failed",e);return}}n.connectionId||(n.connectionId=r),n.timestamp||(n.timestamp=o),n.id||(n.id=i+":"+e)}this._lastPayload.messageId=s.id,this._lastPayload.protocolMessageChannelSerial=e.channelSerial,this.onEvent(t);break}case ey.ERROR:{let t=e.error;t&&80016==t.code?this.checkPendingState():this.notifyState("failed",A.fromValues(t));break}default:w.logAction(w.LOG_ERROR,"RealtimeChannel.processMessage()","Fatal protocol error: unrecognised action ("+e.action+")"),this.connectionManager.abort(e_.unknownChannelErr())}}_startDecodeFailureRecovery(e){this._lastPayload.decodeFailureRecoveryInProgress||(w.logAction(w.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,e,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){w.logAction(w.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(e,t,n,s,i){if(w.logAction(w.LOG_MICRO,"RealtimeChannel.notifyState","name = "+this.name+", current state = "+this.state+", notifying state "+e),this.clearStateTimer(),["detached","suspended","failed"].includes(e)&&(this.properties.channelSerial=null),e===this.state)return;this._presence&&this._presence.actOnChannelState(e,s,t),"suspended"===e&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),t&&(this.errorReason=t);let r=new eB(this.state,e,n,i,t),o='Channel state for channel "'+this.name+'"',a=e+(t?"; reason: "+t:"");"failed"===e?w.logAction(w.LOG_ERROR,o,a):w.logAction(w.LOG_MAJOR,o,a),"attaching"!==e&&"suspended"!==e&&(this.retryCount=0),"attached"===e&&this.onAttached(),"attached"===e?this._attachResume=!0:("detaching"===e||"failed"===e)&&(this._attachResume=!1),this.state=e,this._allChannelChanges.emit(e,r),this.emit
6(e,r)}requestState(e,t){w.logAction(w.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+e),this.notifyState(e,t),this.checkPendingState()}checkPendingState(){let e=this.connectionManager.state;if(!e.sendEvents){w.logAction(w.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);return}switch(w.logAction(w.LOG_MINOR,"RealtimeChannel.checkPendingState","name = "+this.name+", state = "+this.state),this.state){case"attaching":this.startStateTimerIfNotRunning(),this.attachImpl();break;case"detaching":this.startStateTimerIfNotRunning(),this.detachImpl();break;case"attached":this.sync()}}timeoutPendingState(){switch(this.state){case"attaching":{let e=new A("Channel attach timed out",90007,408);this.notifyState("suspended",e);break}case"detaching":{let e=new A("Channel detach timed out",90007,408);this.notifyState("attached",e);break}default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{w.logAction(w.LOG_MINOR,"RealtimeChannel.startStateTimerIfNotRunning","timer expired"),this.stateTimer=null,this.timeoutPendingState()},this.client.options.timeouts.realtimeRequestTimeout))}clearStateTimer(){let e=this.stateTimer;e&&(clearTimeout(e),this.stateTimer=null)}startRetryTimer(){if(this.retryTimer)return;this.retryCount++;let e=getRetryTime(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,w.logAction(w.LOG_MINOR,"RealtimeChannel retry timer expired","attempting a new attach"),this.requestState("attaching"))},e)}cancelRetryTimer(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null)}getReleaseErr(){let e=this.state;return"initialized"===e||"detached"===e||"failed"===e?null:new A("Can only release a channel in a state where there is no possibility of further updates from the server being received (initialized, detached, or failed); was "+e,90001,400)}setChannelSerial(e){w.logAction(w.LOG_MICRO,"RealtimeChannel.setChannelSerial()","Updating channel serial; serial = "+e+"; previous = "+this.properties.channelSerial),e&&(this.properties.channelSerial=e)}async status(){return this.client.rest.channelMixin.status(this)}};function omitAgent(e){let t=e||{},{agent:n}=t,s=__objRest(t,["agent"]);return s}var eD=class _BaseRealtime extends q{constructor(e){var t,n;if(super(M.objectifyOptions(e,!1,"BaseRealtime")),w.logAction(w.LOG_MINOR,"Realtime()",""),"string"==typeof EdgeRuntime)throw new A('Ably.Realtime instance cannot be used in Vercel Edge runtime. If you are running Vercel Edge functions, please replace your "new Ably.Realtime()" with "new Ably.Rest()" and use Ably Rest API instead of the Realtime API. If you are server-rendering your application in the Vercel Edge runtime, please use the condition "if (typeof EdgeRuntime === \'string\')" to prevent instantiating Ably.Realtime instance during SSR in the Vercel Edge runtime.',4e4,400);this._additionalTransportImplementations=_BaseRealtime.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=null!=(n=null==(t=this.options.plugins)?void 0:t.RealtimePresence)?n:null,this.connection=new eG(this,this.options),this._channels=new eH(this),!1!==this.options.autoConnect&&this.connect()}static transportImplementationsFromPlugins(e){let t={};return(null==e?void 0:e.WebSocketTransport)&&(t[o.WebSocket]=e.WebSocketTransport),(null==e?void 0:e.XHRPolling)&&(t[o.XhrPolling]=e.XHRPolling),t}get channels(){return this._channels}connect(){w.logAction(w.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){w.logAction(w.LOG_MINOR,"Realtime.close()",""),this.connection.close()}},eH=class extends em{constructor(e){super(),this.realtime=e,this.all=Object.create(null),e.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let e={};for(let t of keysArray(this.all,!0)){let n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(let t of keysArray(e,!0)){let n=this.get(t);n.properties.channelSerial=e[t]}}async processChannelMessage(e){let t=e.channel;if(void 0===t){w.logAction(w.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action);return}let n=this.all[t];if(!n){w.logAction(w.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+t);return}await n.processMessage(e)}onTransportActive(){for(let e in this.all){let t=this.all[e];"attaching"===t.state||"detaching"===t.state?t.checkPendingState():"suspended"===t.state?t._attach(!1,null):"attached"===t.state&&t.requestState("attaching")}}propogateConnectionInterruption(e,t){let n=["attaching","attached","detaching","suspended"],s={closing:"detached",closed:"detached",failed:"failed",suspended:"suspended"}[e];for(let e in this.all){let i=this.all[e];n.includes(i.state)&&i.notifyState(s,t)}}get(e,t){e=String(e);let n=this.all[e];if(n){if(t){if(n._shouldReattachToSetOptions(t,n.channelOptions))throw new A("Channels.get() cannot be used to set channel options that would cause the channel to reattach. Please, use RealtimeChannel.setOptions() instead.",4e4,400);n.setOptions(t)}}else n=this.all[e]=new eq(this.realtime,e,t);return n}getDerived(e,t,n){if(t.filter){let n=toBase64(t.filter),s=matchDerivedChannel
6(e);e=`[filter=${n}${s.qualifierParam}]${s.channelName}`}return this.get(e,n)}release(e){e=String(e);let t=this.all[e];if(!t)return;let n=t.getReleaseErr();if(n)throw n;delete this.all[e]}},eV=eD;function isAnonymousOrWildcard(e){let t=e.channel.client,n=t.auth.clientId;return(!n||"*"===n)&&"connected"===t.connection.state}function newerThan(e,t){if(e.isSynthesized()||t.isSynthesized())return e.timestamp>=t.timestamp;let n=e.parseId(),s=t.parseId();return n.msgSerial===s.msgSerial?n.index>s.index:n.msgSerial>s.msgSerial}var ej=class extends em{constructor(e){super(),this.channel=e,this.syncComplete=!1,this.members=new eW(this,e=>e.clientId+":"+e.connectionId),this._myMembers=new eW(this,e=>e.clientId),this.subscriptions=new em,this.pendingPresence=[]}async enter(e){if(isAnonymousOrWildcard(this))throw new A("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"enter")}async update(e){if(isAnonymousOrWildcard(this))throw new A("clientId must be specified to update presence data",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"update")}async enterClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"enter")}async updateClient(e,t){return this._enterOrUpdateClient(void 0,e,t,"update")}async _enterOrUpdateClient(e,t,n,s){let i=this.channel;if(!i.connectionManager.activeState())throw i.connectionManager.getError();w.logAction(w.LOG_MICRO,"RealtimePresence."+s+"Client()","channel = "+i.name+", id = "+e+", client = "+(t||"(implicit) "+this.channel.client.auth.clientId));let r=fromData(n);switch(r.action=s,e&&(r.id=e),t&&(r.clientId=t),await encode(r,i.channelOptions),i.state){case"attached":return new Promise((e,t)=>{i.sendPresence(r,n=>n?t(n):e())});case"initialized":case"detached":i.attach();case"attaching":return new Promise((e,t)=>{this.pendingPresence.push({presence:r,callback:n=>n?t(n):e()})});default:{let e=new k("Unable to "+s+" presence channel while in "+i.state+" state",90001);throw e.code=90001,e}}}async leave(e){if(isAnonymousOrWildcard(this))throw new A("clientId must have been specified to enter or leave a presence channel",40012,400);return this.leaveClient(void 0,e)}async leaveClient(e,t){let n=this.channel;if(!n.connectionManager.activeState())throw n.connectionManager.getError();w.logAction(w.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+e);let s=fromData(t);return s.action="leave",e&&(s.clientId=e),new Promise((e,t)=>{switch(n.state){case"attached":n.sendPresence(s,n=>n?t(n):e());break;case"attaching":this.pendingPresence.push({presence:s,callback:n=>n?t(n):e()});break;case"initialized":case"failed":{let e=new k("Unable to leave presence channel (incompatible state)",90001);t(e);break}default:t(n.invalidStateError())}})}async get(e){let t=!e||!("waitForSync"in e)||e.waitForSync;return new Promise((n,s)=>{function returnMembers(t){n(e?t.list(e):t.values())}if("suspended"===this.channel.state){t?s(A.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"})):returnMembers(this.members);return}!function(e,t,n){switch(e.state){case"attached":case"suspended":n();break;case"initialized":case"detached":case"detaching":case"attaching":whenPromiseSettles(e.attach(),function(e){e?t(e):n()});break;default:t(A.fromValues(e.invalidStateError()))}}(this.channel,e=>s(e),()=>{let e=this.members;t?e.waitSync(function(){returnMembers(e)}):returnMembers(e)})})}async history(e){w.logAction(w.LOG_MICRO,"RealtimePresence.history()","channel = "+this.name);let t=this.channel.client.rest.presenceMixin;if(e&&e.untilAttach){if("attached"===this.channel.state)delete e.untilAttach,e.from_serial=this.channel.properties.attachSerial;else throw new A("option untilAttach requires the channel to be attached, was: "+this.channel.state,4e4,400)}return t.history(this,e)}setPresence(e,t,n){let s,i;w.logAction(w.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);let r=this.members,o=this._myMembers,a=[],c=this.channel.connectionManager.connectionId;t&&(this.members.startSync(),n&&(i=n.match(/^[\w-]+:(.*)$/))&&(s=i[1]));for(let t=0;t<e.length;t++){let n=fromValues2(e[t]);switch(n.action){case"leave":r.remove(n)&&a.push(n),n.connectionId!==c||n.isSynthesized()||o.remove(n);break;case"enter":case"present":case"update":r.put(n)&&a.push(n),n.connectionId===c&&o.put(n)}}t&&!s&&(r.endSync(),this.channel.syncChannelSerial=null);for(let e=0;e<a.length;e++){let t=a[e];this.subscriptions.emit(t.action,t)}}onAttached(e){w.logAction(w.LOG_MINOR,"RealtimePresence.onAttached()","channel = "+this.channel.name+", hasPresence = "+e),e?this.members.startSync():(this._synthesizeLeaves(this.members.values()),this.members.clear()),this._ensureMyMembersPresent();let t=this.pendingPresence,n=t.length;if(n){this.pendingPresence=[];let e=[],s=P.create();w.logAction(w.LOG_MICRO,"RealtimePresence.onAttached","sending "+n+" queued presence messages");for(let i=0;i<n;i++){let n=t[i];e.push(n.presence),s.push(n.callback)}this.channel.sendPresence(e,s)}}actOnChannelState(e,t,n){switch(e){case"attached":this.onAttached(t);break;case"detached":case"failed":this._clearMyMembers(),this.members.clear();case"suspended":this.failPendingPresence(n)}}failPendingPresence(e){if(this.pendingPresence.length){w.logAction(w.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+inspectError(e));for(let t=0;t<this.pendingPresence.length;t++)try{this.pendingPresence[t].callback(e)}catch(e){}this.pendingPresence=[]}}_clearMyMembers(){this._myMembers.clear()}_ensureMyMembersPresent(){let e=this._myMembers,reenterCb=e=>{if(e){let t="Presence auto-re-enter failed: "+e.toString(),n=new A(t,91004,400);w.logAction(w.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()",t);let s=new eB(this.channel.state,this.channel.state,!0,!1,n);this.channel.emit("update",s)}};for(let t in e.map){let n=e.map[t];w.logAction(w.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+n.clientId+'" into the presence set'),whenPromiseSettles(this._enterOrUpd
6ateClient(n.id,n.clientId,n.data,"enter"),reenterCb)}}_synthesizeLeaves(e){let t=this.subscriptions;e.forEach(function(e){let n=fromValues2({action:"leave",connectionId:e.connectionId,clientId:e.clientId,data:e.data,encoding:e.encoding,timestamp:Date.now()});t.emit("leave",n)})}async subscribe(...e){let t=eq.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if("failed"===i.state)throw A.fromValues(i.invalidStateError());this.subscriptions.on(n,s),await i.attach()}unsubscribe(...e){let t=eq.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}},eW=class extends em{constructor(e,t){super(),this.presence=e,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=t}get(e){return this.map[e]}getClient(e){let t=this.map,n=[];for(let s in t){let i=t[s];i.clientId==e&&"absent"!=i.action&&n.push(i)}return n}list(e){let t=this.map,n=e&&e.clientId,s=e&&e.connectionId,i=[];for(let e in t){let r=t[e];"absent"!==r.action&&(!n||n==r.clientId)&&(s&&s!=r.connectionId||i.push(r))}return i}put(e){("enter"===e.action||"update"===e.action)&&((e=fromValues2(e)).action="present");let t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];let s=t[n];return(!s||!!newerThan(e,s))&&(t[n]=e,!0)}values(){let e=this.map,t=[];for(let n in e){let s=e[n];"absent"!=s.action&&t.push(s)}return t}remove(e){let t=this.map,n=this.memberKey(e),s=t[n];return(!s||!!newerThan(e,s))&&(this.syncInProgress?((e=fromValues2(e)).action="absent",t[n]=e):delete t[n],!0)}startSync(){let e=this.map,t=this.syncInProgress;w.logAction(w.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),this.syncInProgress||(this.residualMembers=copy(e),this.setInProgress(!0))}endSync(){let e=this.map,t=this.syncInProgress;if(w.logAction(w.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),t){for(let t in e){let n=e[t];"absent"===n.action&&delete e[t]}for(let t in this.presence._synthesizeLeaves(valuesArray(this.residualMembers)),this.residualMembers)delete e[t];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}waitSync(e){let t=this.syncInProgress;if(w.logAction(w.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),!t){e();return}this.once("sync",e)}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){w.logAction(w.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+e),this.syncInProgress=e,this.presence.syncComplete=!e}},eF=o.WebSocket,ez=class extends eI{constructor(e,t,n){super(e,t,n),this.shortName=eF,n.heartbeats=R.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!R.Config.WebSocket}createWebSocket(e,t){return this.uri=e+toQueryString(t),new R.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){w.logAction(w.LOG_MINOR,"WebSocketTransport.connect()","starting"),eI.prototype.connect.call(this);let e=this,t=this.params,n=t.options,s=n.tls?"wss://":"ws://",i=s+this.wsHost+":"+M.getPort(n)+"/";w.logAction(w.LOG_MINOR,"WebSocketTransport.connect()","uri: "+i),whenPromiseSettles(this.auth.getAuthParams(),function(n,s){if(e.isDisposed)return;let r="";for(let e in s)r+=" "+e+": "+s[e]+";";if(w.logAction(w.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+r+" err: "+n),n){e.disconnect(n);return}let o=t.getConnectParams(s);try{let t=e.wsConnection=e.createWebSocket(i,o);t.binaryType=R.Config.binaryType,t.onopen=function(){e.onWsOpen()},t.onclose=function(t){e.onWsClose(t)},t.onmessage=function(t){e.onWsData(t.data)},t.onerror=function(t){e.onWsError(t)},t.on&&t.on("ping",function(){e.onActivity()})}catch(t){w.logAction(w.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(t.stack||t.message)),e.disconnect(t)}})}send(e){let t=this.wsConnection;if(!t){w.logAction(w.LOG_ERROR,"WebSocketTransport.send()","No socket connection");return}try{t.send(encodeBody(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(t){let e="Exception from ws connection when trying to send: "+inspectError(t);w.logAction(w.LOG_ERROR,"WebSocketTransport.send()",e),this.finish("disconnected",new A(e,5e4,500))}}onWsData(e){w.logAction(w.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+e.length+"; type = "+typeof e);
6try{this.onProtocolMessage(function(e,t,n,s){let i=decodeBody(e,t,s);return fromDeserialized(i,n)}(e,this.connectionManager.realtime._MsgPack,this.connectionManager.realtime._RealtimePresence,this.format))}catch(e){w.logAction(w.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+e.stack)}}onWsOpen(){w.logAction(w.LOG_MINOR,"WebSocketTransport.onWsOpen()","opened WebSocket"),this.emit("preconnect")}onWsClose(e){let t,n;if("object"==typeof e?(n=e.code,t=e.wasClean||1e3===n):t=1e3==(n=e),delete this.wsConnection,t){w.logAction(w.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let e=new A("Websocket closed",80003,400);this.finish("disconnected",e)}else{let e="Unclean disconnection of WebSocket ; code = "+n,t=new A(e,80003,400);w.logAction(w.LOG_MINOR,"WebSocketTransport.onWsClose()",e),this.finish("disconnected",t)}this.emit("disposed")}onWsError(e){w.logAction(w.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+e.message),R.Config.nextTick(()=>{this.disconnect(Error(e.message))})}
6dispose(){w.logAction(w.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,R.Config.nextTick(function(){if(w.logAction(w.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!e)throw Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},eJ=class{static subscribeFilter(e,t,n){let filteredListener=e=>{var s,i,r,o,a,c;let l={name:e.name,refTimeserial:null==(i=null==(s=e.extras)?void 0:s.ref)?void 0:i.timeserial,refType:null==(o=null==(r=e.extras)?void 0:r.ref)?void 0:o.type,isRef:!!(null==(c=null==(a=e.extras)?void 0:a.ref)?void 0:c.timeserial),clientId:e.clientId};Object.entries(t).find(([e,t])=>void 0!==t&&l[e]!==t)||n(e)};this.addFilteredSubscription(e,t,n,filteredListener),e.subscriptions.on(filteredListener)}static addFilteredSubscription(e,t,n,s){var i;if(e.filteredSubscriptions||(e.filteredSubscriptions=new Map),e.filteredSubscriptions.has(n)){let r=e.filteredSubscriptions.get(n);r.set(t,(null==(i=null==r?void 0:r.get(t))?void 0:i.concat(s))||[s])}else e.filteredSubscriptions.set(n,new Map([[t,[s]]]))}static getAndDeleteFilteredSubscriptions(e,t,n){if(!e.filteredSubscriptions)return[];if(!n&&t)return Array.from(e.filteredSubscriptions.entries()).map(([n,s])=>{var i;let r=s.get(t);return s.delete(t),0===s.size&&(null==(i=e.filteredSubscriptions)||i.delete(n)),r}).reduce((e,t)=>t?e.concat(...t):e,[]);if(!n||!e.filteredSubscriptions.has(n))return[];let s=e.filteredSubscriptions.get(n);if(!t){let t=Array.from(s.values()).reduce((e,t)=>e.concat(...t),[]);return e.filteredSubscriptions.delete(n),t}let i=s.get(t);return s.delete(t),i||[]}},eK=class _DefaultRealtime extends eV{constructor(e){var t;let n=_DefaultRealtime._MsgPack;if(!n)throw Error("Expected DefaultRealtime._MsgPack to have been set");super(M.objectifyOptions(e,!0,"Realtime",__spreadProps(__spreadValues({},eu),{Crypto:null!=(t=_DefaultRealtime.Crypto)?t:void 0,MsgPack:n,RealtimePresence:{RealtimePresence:ej,presenceMessageFromValues:fromValues2,presenceMessagesFromValuesArray:fromValuesArray2},WebSocketTransport:ez,MessageInteractions:eJ})))}static get Crypto(){if(null===this._Crypto)throw Error("Encryption not enabled; use ably.encryption.js instead");return this._Crypto}static set Crypto(e){this._Crypto=e}};eK.Utils=S,eK.ConnectionManager=eN,eK.ProtocolMessage=eO,eK._Crypto=null,eK.Message=ed,eK.PresenceMessage=ep,eK._MsgPack=null,eK._Http=G;var eQ=eK,e$=Uint8Array,eX=Uint32Array,eY=Math.pow,eZ=new eX(8),e0=[],e1=new eX(64);function getFractionalBits(e){return(e-(0|e))*eY(2,32)|0}for(var e4=2,e2=0;e2<64;){for(c=2,a=!0;c<=e4/2;c++)e4%c==0&&(a=!1);a&&(e2<8&&(eZ[e2]=getFractionalBits(eY(e4,.5))),e0[e2]=getFractionalBits(eY(e4,1/3)),e2++),e4++}var e8=!!new e$(new eX([1]).buffer)[0];function convertEndian(e){return e8?e>>>24|(e>>>16&255)<<8|(65280&e)<<8|e<<24:e}function rightRotate(e,t){return e>>>t|e<<32-t}function sha256(e){var t=eZ.slice(),n=e.length,s=8*n,i=512-(s+64)%512-1+s+65,r=new e$(i/8),o=new eX(r.buffer);r.set(e,0),r[n]=128,o[o.length-1]=convertEndian(s);for(var a=0;a<i/32;a+=16){var c=t.slice();for(l=0;l<64;l++){if(l<16)h=convertEndian(o[a+l]);else{var l,h,u=e1[l-15],d=e1[l-2];h=e1[l-7]+e1[l-16]+(rightRotate(u,7)^rightRotate(u,18)^u>>>3)+(rightRotate(d,17)^rightRotate(d,19)^d>>>10)}e1[l]=h|=0;for(var p=(rightRotate(c[4],6)^rightRotate(c[4],11)^rightRotate(c[4],25))+(c[4]&c[5]^~c[4]&c[6])+c[7]+h+e0[l],f=(rightRotate(c[0],2)^rightRotate(c[0],13)^rightRotate(c[0],22))+(c[0]&c[1]^c[2]&(c[0]^c[1])),g=7;g>0;g--)c[g]=c[g-1];c[0]=p+f|0,c[4]=c[4]+p|0}for(l=0;l<8;l++)t[l]=t[l]+c[l]|0}return new e$(new eX(t.map(function(e){return convertEndian(e)})).buffer)}var e6=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){let t,n,s,i,r,o="",a=this.base64CharSet,c=e.byteLength,l=c%3,h=c-l;for(let c=0;c<h;c+=3)t=(16515072&(r=e[c]<<16|e[c+1]<<8|e[c+2]))>>18,n=(258048&r)>>12,s=(4032&r)>>6,i=63&r,o+=a[t]+a[n]+a[s]+a[i];return 1==l?(t=(252&(r=e[h]))>>2,n=(3&r)<<4,o+=a[t]+a[n]+"=="):2==l&&(t=(64512&(r=e[h]<<8|e[h+1]))>>10,n=(1008&r)>>4,s=(15&r)<<2,o+=a[t]+a[n]+a[s]+"="),o}base64ToArrayBuffer(e){let t=null==atob?void 0:atob(e),n=t.length,s=new Uint8Array(n);for(let e=0;e<n;e++){let n=t.charCodeAt(e);s[e]=n}return this.toArrayBuffer(s)}isBuffer(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}toBuffer(e){if(!ArrayBuffer)throw Error("Can't convert to Buffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(this.toArrayBuffer(e));throw Error("BufferUtils.toBuffer expected an ArrayBuffer or a view onto one")}toArrayBuffer(e){if(!ArrayBuffer)throw Error("Can't convert to ArrayBuffer: browser does not support the necessary types");if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);throw Error("BufferUtils.toArrayBuffer expected an ArrayBuffer or a view onto one")}base64Encode(e){return this.uint8ViewToBase64(this.toBuffer(e))}base64Decode(e){if(ArrayBuffer&&R.Config.atob)return this.base64ToArrayBuffer(e);throw Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(e){let t=this.toBuffer(e);return t.reduce((e,t)=>
6e+t.toString(16).padStart(2,"0"),"")}hexDecode(e){if(e.length%2!=0)throw Error("Can't create a byte array from a hex string of odd length");let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*(n+1)),16);return this.toArrayBuffer(t)}utf8Encode(e){if(R.Config.TextEncoder){let t=new R.Config.TextEncoder().encode(e);return this.toArrayBuffer(t)}throw Error("Expected TextEncoder to be configured")}utf8Decode(e){if(!this.isBuffer(e))throw Error("Expected input of utf8decode to be an arraybuffer or typed array");if(TextDecoder)return new TextDecoder().decode(e);throw Error("Expected TextDecoder to be configured")}areBuffersEqual(e,t){if(!e||!t)return!1;let n=this.toArrayBuffer(e),s=this.toArrayBuffer(t);if(n.byteLength!=s.byteLength)return!1;let i=new Uint8Array(n),r=new Uint8Array(s);for(var o=0;o<i.length;o++)if(i[o]!=r[o])return!1;return!0}byteLength(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}arrayBufferViewToBuffer(e){return this.toArrayBuffer(e)}hmacSha256(e,t){let n=function(e,t){if(e.length>64&&(e=sha256(e)),e.length<64){let t=new Uint8Array(64);t.set(e,0),e=t}for(var n=new Uint8Array(64),s=new Uint8Array(64),i=0;i<64;i++)n[i]=54^e[i],s[i]=92^e[i];var r=new Uint8Array(t.length+64);r.set(n,0),r.set(t,64);var o=new Uint8Array(96);return o.set(s,0),o.set(sha256(r),64),sha256(o)}(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},e3=((r=e3||{})[r.REQ_SEND=0]="REQ_SEND",r[r.REQ_RECV=1]="REQ_RECV",r[r.REQ_RECV_POLL=2]="REQ_RECV_POLL",r[r.REQ_RECV_STREAM=3]="REQ_RECV_STREAM",r);function createMissingImplementationError(){return new A("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var e5=((l=class{constructor(e){var t;this.checksInProgress=null,this.checkConnectivity=void 0,this.supportsAuthHeaders=!1,this.supportsLinkHeaders=!1,this.client=null!=e?e:null;let n=(null==e?void 0:e.options.connectivityCheckUrl)||M.connectivityCheckUrl,s=null!=(t=null==e?void 0:e.options.connectivityCheckParams)?t:null,i=!(null==e?void 0:e.options.connectivityCheckUrl),r=__spreadValues(__spreadValues({},e5.bundledRequestImplementations),null==e?void 0:e._additionalHTTPRequestImplementations),o=r.XHRRequest,a=r.FetchRequest,c=!!(o||a);if(!c)throw createMissingImplementationError();R.Config.xhrSupported&&o?(this.supportsAuthHeaders=!0,this.Request=async function(t,n,s,i,r){return new Promise(a=>{var c;let l=o.createRequest(n,s,i,r,e3.REQ_SEND,null!=(c=e&&e.options.timeouts)?c:null,t);l.once("complete",(e,t,n,s,i)=>a({error:e,body:t,headers:n,unpacked:s,statusCode:i})),l.exec()})},(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var e,t;w.logAction(w.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);let r=await this.doUri(L.Get,n,null,null,s),o=!1;return o=i?!r.error&&(null==(e=r.body)?void 0:e.replace(/\n/,""))=="yes":!r.error&&(t=r.statusCode)>=200&&t<400,w.logAction(w.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+o),o}):R.Config.fetchSupported&&a?(this.supportsAuthHeaders=!0,this.Request=async(t,n,s,i,r)=>a(t,null!=e?e:null,n,s,i,r),this.checkConnectivity=async function(){var e;w.logAction(w.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);let t=await this.doUri(L.Get,n,null,null,null),s=!t.error&&(null==(e=t.body)?void 0:e.replace(/\n/,""))=="yes";return w.logAction(w.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+s),s}):this.Request=async()=>{let e=c?new k("no supported HTTP transports available",null,400):createMissingImplementationError();return{error:e}}}async doUri(e,t,n,s,i){return this.Request?this.Request(e,t,n,i,s):{error:new k("Request invoked before assigned to",null,500)}}shouldFallback(e){let t=e.statusCode;return 408===t&&!e.code||400===t&&!e.code||t>=500&&t<=504}}).methods=[L.Get,L.Delete,L.Post,L.Put,L.Patch],l.methodsWithoutBody=[L.Get,L.Delete],l.methodsWithBody=[L.Post,L.Put,L.Patch],l),e9=getGlobalObject(),e7="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||e7||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var te={agent:"browser",logTimestamps:!0,userAgent:e9.navigator&&e9.navigator.userAgent.toString(),currentUrl:e9.location&&e9.location.href,binaryType:"arraybuffer",WebSocket:e9.WebSocket,fetchSupported:!!e9.fetch,xhrSupported:e9.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:function(){let e=e9.location;return!e9.WebSocket||!e||!e.origin||e.origin.indexOf("http")>-1}(),useProtocolHeartbeats:!0,supportsBinary:!!e9.TextDecoder,preferBinary:!1,ArrayBuffer:e9.ArrayBuffer,atob:e9.atob,nextTick:void 0!==e9.setImmediate?e9.setImmediate.bind(e9):function(e){setTimeout(e,0)},addEventListener:e9.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return e9.TextDecoder&&new e9.TextEncoder().encode(e).length||e.length},TextEncoder:e9.TextEncoder,TextDecoder:e9.TextDecoder,getRandomArrayBuffer:async function(e){let t=new Uint8Array(e);return e9.crypto.getRandomValues(t),t.buffer},isWebworker:!!("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope)};
6function protocolMessageFromRawError(e){return e.code&&!N.isTokenErr(e)&&([80015,80017,80030].includes(e.code)||e.code>=4e4&&e.code<5e4)?[fromValues3({action:ey.ERROR,error:e})]:[fromValues3({action:ey.DISCONNECTED,error:e})]}var tt=class extends eI{constructor(e,t,n){super(e,t,n,!0),this.onAuthUpdated=e=>{this.authParams={access_token:e.token}},this.stream=!("stream"in n)||n.stream,this.sendRequest=null,this.recvRequest=null,this.pendingCallback=null,this.pendingItems=null}connect(){w.logAction(w.LOG_MINOR,"CometTransport.connect()","starting"),eI.prototype.connect.call(this);let e=this.params,t=e.options,n=M.getHost(t,e.host),s=M.getPort(t),i=t.tls?"https://":"http://";this.baseUri=i+n+":"+s+"/comet/";let r=this.baseUri+"connect";w.logAction(w.LOG_MINOR,"CometTransport.connect()","uri: "+r),whenPromiseSettles(this.auth.getAuthParams(),(e,t)=>{if(e){this.disconnect(e);return}if(this.isDisposed)return;this.authParams=t;let n=this.params.getConnectParams(t);"stream"in n&&(this.stream=n.stream),w.logAction(w.LOG_MINOR,"CometTransport.connect()","connectParams:"+toQueryString(n));
6let s=!1,i=this.recvRequest=this.createRequest(r,null,n,null,this.stream?e3.REQ_RECV_STREAM:e3.REQ_RECV);i.on("data",e=>{this.recvRequest&&(s||(s=!0,this.emit("preconnect")),this.onData(e))}),i.on("complete",e=>{if(this.recvRequest||(e=e||new A("Request cancelled",80003,400)),this.recvRequest=null,s||e||(s=!0,this.emit("preconnect")),this.onActivity(),e){e.code?this.onData(protocolMessageFromRawError(e)):this.disconnect(e);return}R.Config.nextTick(()=>{this.recv()})}),i.exec()})}requestClose(){w.logAction(w.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){w.logAction(w.LOG_MINOR,"CometTransport.requestDisconnect()"),this._requestCloseOrDisconnect(!1)}_requestCloseOrDisconnect(e){let t=e?this.closeUri:this.disconnectUri;if(t){let n=this.createRequest(t,null,this.authParams,null,e3.REQ_SEND);n.on("complete",t=>{t&&(w.logAction(w.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+inspectError(t)),this.finish("disconnected",t))}),n.exec()}}
6dispose(){w.logAction(w.LOG_MINOR,"CometTransport.dispose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(w.logAction(w.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",e_.disconnected()),R.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(e){var t;if(this.isDisposed)return;let n=null==(t=e.connectionDetails)?void 0:t.connectionKey;eI.prototype.onConnect.call(this,e);let s=this.baseUri+n;w.logAction(w.LOG_MICRO,"CometTransport.onConnect()","baseUri = "+s),this.sendUri=s+"/send",this.recvUri=s+"/recv",this.closeUri=s+"/close",this.disconnectUri=s+"/disconnect"}send(e){if(this.sendRequest){this.pendingItems=this.pendingItems||[],this.pendingItems.push(e);return}let t=this.pendingItems||[];t.push(e),this.pendingItems=null,this.sendItems(t)}sendAnyPending(){let e=this.pendingItems;e&&(this.pendingItems=null,this.sendItems(e))}sendItems(e){let t=this.sendRequest=this.createRequest(this.sendUri,null,this.authParams,this.encodeRequest(e),e3.REQ_SEND);t.on("complete",(e,t)=>{if(e&&w.logAction(w.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+inspectError(e)),this.sendRequest=null,e){e.code?this.onData(protocolMe
6ssageFromRawError(e)):this.disconnect(e);return}t&&this.onData(t),this.pendingItems&&R.Config.nextTick(()=>{this.sendRequest||this.sendAnyPending()})}),t.exec()}recv(){if(this.recvRequest||!this.isConnected)return;let e=this.recvRequest=this.createRequest(this.recvUri,null,this.authParams,null,this.stream?e3.REQ_RECV_STREAM:e3.REQ_RECV_POLL);e.on("data",e=>{this.onData(e)}),e.on("complete",e=>{if(this.recvRequest=null,this.onActivity(),e){e.code?this.onData(protocolMessageFromRawError(e)):this.disconnect(e);return}R.Config.nextTick(()=>{this.recv()})}),e.exec()}onData(e){try{let t=this.decodeResponse(e);if(t&&t.length)for(let e=0;e<t.length;e++)this.onProtocolMessage(fromDeserialized(t[e],this.connectionManager.realtime._RealtimePresence))}catch(e){w.logAction(w.LOG_ERROR,"CometTransport.onData()","Unexpected exception handing channel event: "+e.stack)}}encodeRequest(e){return JSON.stringify(e)}decodeResponse(e){return"string"==typeof e?JSON.parse(e):e}},noop3=function(){},tn=0,ts={},ti=class _XHRRequest extends em{constructor(e,t,n,s,i,r,o){super(),(n=n||{}).rnd=cheapRandStr(),this.uri=e+toQueryString(n),this.headers=t||{},this.body=s,this.method=o?o.toUpperCase():isNil(s)?"GET":"POST",this.requestMode=i,this.timeouts=r,this.timedOut=!1,this.requestComplete=!1,this.id=String(++tn),ts[this.id]=this}static createRequest(e,t,n,s,i,r,o){let a=r||M.TIMEOUTS;return new _XHRRequest(e,t,copy(n),s,i,a,o)}complete(e,t,n,s,i){this.requestComplete||(this.requestComplete=!0,!e&&t&&this.emit("data",t),this.emit("complete",e,t,n,s,i),this.dispose())}abort(){this.dispose()}exec(){let e,t,n,s=this.headers,i=this.requestMode==e3.REQ_SEND?this.timeouts.httpRequestTimeout:this.timeouts.recvTimeout,r=this.timer=setTimeout(()=>{this.timedOut=!0,a.abort()},i),o=this.method,a=this.xhr=new XMLHttpRequest,c=s.accept,l=this.body,h="text";if(c?0===c.indexOf("application/x-msgpack")&&(h="arraybuffer"):s.accept="application/json",l){let e=s["content-type"]||(s["content-type"]="application/json");e.indexOf("application/json")>-1&&"string"!=typeof l&&(l=JSON.stringify(l))}for(let e in a.open(o,this.uri,!0),a.responseType=h,"authorization"in s&&(a.withCredentials=!0),s)a.setRequestHeader(e,s[e]);let errorHandler=(e,t,n,s)=>{var i;let r=t+" (event type: "+e.type+")";(null==(i=this==null?void 0:this.xhr)?void 0:i.statusText)&&(r+=", current statusText is "+this.xhr.statusText),w.logAction(w.LOG_ERROR,"Request.on"+e.type+"()",r),this.complete(new k(r,n,s))};a.onerror=function(e){errorHandler(e,"XHR error occurred",null,400)},a.onabort=e=>{this.timedOut?errorHandler(e,"Request aborted due to request timeout expiring",null,408):errorHandler(e,"Request cancelled",null,400)},a.ontimeout=function(e){errorHandler(e,"Request timed out",null,408)};let u=0,d=!1,onResponse=()=>{var s;if(clearTimeout(r),n=t<400,204==t){this.complete(null,null,null,null,t);return}e=this.requestMode==e3.REQ_RECV_STREAM&&n&&(s=a).getResponseHeader&&(s.getResponseHeader("transfer-encoding")||!s.getResponseHeader("content-length"))},onEnd=()=>{let e;try{let i=a.getResponseHeader&&a.getResponseHeader("content-type"),r=i?i.indexOf("application/json")>=0:"text"==a.responseType;if(r){let t="arraybuffer"===a.responseType?R.BufferUtils.utf8Decode(a.response):String(a.responseText);e=t.length?JSON.parse(t):t,d=!0}else e=a.response;void 0!==e.response?(n=(t=e.statusCode)<400,s=e.headers,e=e.response):s=function(e){let t=e.getAllResponseHeaders().trim().split("\r\n"),n={};for(let e=0;e<t.length;e++){let s=t[e].split(":").map(e=>e.trim());n[s[0].toLowerCase()]=s[1]}return n}(a)}catch(e){this.complete(new k("Malformed response body from server: "+e.message,null,400));return}if(n||Array.isArray(e)){this.complete(null,e,s,d,t);return}let i=function(e,t){if(allToLowerCase(keysArray(t)).includes("x-ably-errorcode"))return e.error&&A.fromValues(e.error)}(e,s);i||(i=new k("Error response received from server: "+t+" body was: "+R.Config.inspect(e),null,t)),this.complete(i,e,s,d,t)};function onProgress(){let e,t;let n=a.responseText,s=n.length-1;for(;u<s&&(e=n.indexOf("\n",u))>-1;)t=n.slice(u,e),u=e+1,onChunk(t)}let onChunk=e=>{try{e=JSON.parse(e)}catch(e){this.complete(new k("Malformed response body from server: "+e.message,null,400));return}
6this.emit("data",e)},onStreamEnd=()=>{onProgress(),this.streamComplete=!0,R.Config.nextTick(()=>{this.complete()})};a.onreadystatechange=function(){let n=a.readyState;n<3||0===a.status||(void 0===t&&(t=a.status,onResponse()),3==n&&e?onProgress():4==n&&(e?onStreamEnd():onEnd()))},a.send(l)}dispose(){let e=this.xhr;if(e){e.onreadystatechange=e.onerror=e.onabort=e.ontimeout=noop3,this.xhr=null;let t=this.timer;t&&(clearTimeout(t),this.timer=null),this.requestComplete||e.abort()}delete ts[this.id]}},tr=o.XhrPolling,to=class extends tt{constructor(e,t,n){super(e,t,n),this.shortName=tr,n.stream=!1,this.shortName=tr}static isAvailable(){return!!(R.Config.xhrSupported&&R.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,i){return ti.createRequest(e,t,n,s,i,this.timeouts)}},ta="ablyjs-storage-test",tc=void 0!==n.g?n.g:"undefined"!=typeof window?window:self,tl=new class{constructor(){try{tc.sessionStorage.setItem(ta,ta),tc.sessionStorage.removeItem(ta),this.sessionSupported=!0}catch(e){this.sessionSupported=!1}try{tc.localStorage.setItem(ta,ta),tc.localStorage.removeItem(ta),this.localSupported=!0}
6catch(e){this.localSupported=!1}}get(e){return this._get(e,!1)}getSession(e){return this._get(e,!0)}remove(e){return this._remove(e,!1)}removeSession(e){return this._remove(e,!0)}set(e,t,n){return this._set(e,t,n,!1)}setSession(e,t,n){return this._set(e,t,n,!0)}_set(e,t,n,s){let i={value:t};return n&&(i.expires=Date.now()+n),this.storageInterface(s).setItem(e,JSON.stringify(i))}_get(e,t){if(t&&!this.sessionSupported)throw Error("Session Storage not supported");if(!t&&!this.localSupported)throw Error("Local Storage not supported");let n=this.storageInterface(t).getItem(e);if(!n)return null;let s=JSON.parse(n);return s.expires&&s.expires<Date.now()?(this.storageInterface(t).removeItem(e),null):s.value}_remove(e,t){return this.storageInterface(t).removeItem(e)}storageInterface(e){return e?tc.sessionStorage:tc.localStorage}},th={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[o.XhrPolling,o.WebSocket]};function utf8Write(e,t,n){for(let s=0,i=n.length;s<i;s++){let i=n.charCodeAt(s);if(i<128){e.setUint8(t++,i>>>0&127|0);continue}if(i<2048){e.setUint8(t++,i>>>6&31|192),e.setUint8(t++,i>>>0&63|128);continue}if(i<65536){e.setUint8(t++,i>>>12&15|224),e.setUint8(t++,i>>>6&63|128),e.setUint8(t++,i>>>0&63|128);continue}if(i<1114112){e.setUint8(t++,i>>>18&7|240),e.setUint8(t++,i>>>12&63|128),e.setUint8(t++,i>>>6&63|128),e.setUint8(t++,i>>>0&63|128);continue}throw Error("bad codepoint "+i)}}function utf8Read(e,t,n){let s="";for(let i=t,r=t+n;i<r;i++){let t=e.getUint8(i);if((128&t)==0){s+=String.fromCharCode(t);continue}if((224&t)==192){s+=String.fromCharCode((15&t)<<6|63&e.getUint8(++i));continue}if((240&t)==224){s+=String.fromCharCode((15&t)<<12|(63&e.getUint8(++i))<<6|(63&e.getUint8(++i))<<0);continue}if((248&t)==240){s+=String.fromCharCode((7&t)<<18|(63&e.getUint8(++i))<<12|(63&e.getUint8(++i))<<6|(63&e.getUint8(++i))<<0);continue}throw Error("Invalid byte "+t.toString(16))}return s}function utf8ByteCount(e){let t=0;for(let n=0,s=e.length;n<s;n++){let s=e.charCodeAt(n);if(s<128){t+=1;continue}if(s<2048){t+=2;continue}if(s<65536){t+=3;continue}if(s<1114112){t+=4;continue}throw Error("bad codepoint "+s)}return t}var tu=class{constructor(e,t){this.map=e=>{let t={};for(let n=0;n<e;n++){let e=this.parse();t[e]=this.parse()}return t},this.bin=e=>{let t=new ArrayBuffer(e);return new Uint8Array(t).set(new Uint8Array(this.view.buffer,this.offset,e),0),this.offset+=e,t},this.buf=this.bin,this.str=e=>{let t=utf8Read(this.view,this.offset,e);return this.offset+=e,t},this.array=e=>{let t=Array(e);for(let n=0;n<e;n++)t[n]=this.parse();return t},this.ext=e=>(this.offset+=e,{type:this.view.getInt8(this.offset),data:this.buf(e)}),this.parse=()=>{var e,t,n,s;let i,r;let o=this.view.getUint8(this.offset);if((128&o)==0)return this.offset++,o;if((240&o)==128)return r=15&o,this.offset++,this.map(r);if((240&o)==144)return r=15&o,this.offset++,this.array(r);if((224&o)==160)return r=31&o,this.offset++,this.str(r);if((224&o)==224)return i=this.view.getInt8(this.offset),this.offset++,i;switch(o){case 192:return this.offset++,null;case 193:this.offset++;return;case 194:return this.offset++,!1;case 195:return this.offset++,!0;case 196:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.bin(r);case 197:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.bin(r);case 198:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.bin(r);case 199:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.ext(r);case 200:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.ext(r);case 201:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.ext(r);case 202:return i=this.view.getFloat32(this.offset+1),this.offset+=5,i;case 203:return i=this.view.getFloat64(this.offset+1),this.offset+=9,i;case 204:return i=this.view.getUint8(this.offset+1),this.offset+=2,i;case 205:return i=this.view.getUint16(this.offset+1),this.offset+=3,i;case 206:return i=this.view.getUint32(this.offset+1),this.offset+=5,i;case 207:return e=this.view,t=(t=this.offset+1)||0,i=4294967296*e.getUint32(t)+e.getUint32(t+4),this.offset+=9,i;case 208:return i=this.view.getInt8(this.offset+1),this.offset+=2,i;case 209:return i=this.view.getInt16(this.offset+1),this.offset+=3,i;case 210:return i=this.view.getInt32(this.offset+1),this.offset+=5,i;case 211:return n=this.view,s=(s=this.offset+1)||0,i=4294967296*n.getInt32(s)+n.getUint32(s+4),this.offset+=9,i;case 212:return r=1,this.offset++,this.ext(r);case 213:return r=2,this.offset++,this.ext(r);case 214:return r=4,this.offset++,this.ext(r);case 215:return r=8,this.offset++,this.ext(r);case 216:return r=16,this.offset++,this.ext(r);case 217:return r=this.view.getUint8(this.offset+1),this.offset+=2,this.str(r);case 218:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.str(r);case 219:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.str(r);case 220:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.array(r);case 221:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.array(r);case 222:return r=this.view.getUint16(this.offset+1),this.offset+=3,this.map(r);case 223:return r=this.view.getUint32(this.offset+1),this.offset+=5,this.map(r)}throw Error("Unknown type 0x"+o.toString(16))},this.offset=t||0,this.view=e}};function encodeableKeys(e,t){return Object.keys(e).filter(function(n){let s=e[n];return(!t||null!=s)&&("function"!=typeof s||!!s.toJSON)})}var td={encode:function(e,t){let n=function sizeof(e,t){let n=typeof e;if("string"===n){let t=utf8ByteCount(e);
6if(t<32)return 1+t;if(t<256)return 2+t;if(t<65536)return 3+t;if(t<4294967296)return 5+t}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){let t=e.byteLength;if(t<256)return 2+t;if(t<65536)return 3+t;if(t<4294967296)return 5+t}if("number"==typeof e){if(Math.floor(e)!==e)return 9;if(e>=0){if(e<128)return 1;if(e<256)return 2;if(e<65536)return 3;if(e<4294967296)return 5;if(e<18446744073709552e3)return 9;throw Error("Number too big 0x"+e.toString(16))}if(e>=-32)return 1;if(e>=-128)return 2;if(e>=-32768)return 3;if(e>=-2147483648)return 5;if(e>=-0x8000000000000000)return 9;throw Error("Number too small -0x"+e.toString(16).substr(1))}if("boolean"===n)return 1;if(null===e)return t?0:1;if(void 0===e)return t?0:3;if("function"==typeof e.toJSON)return sizeof(e.toJSON(),t);if("object"===n){let n,s=0;if(Array.isArray(e)){n=e.length;for(let i=0;i<n;i++)s+=sizeof(e[i],t)}else{let i=encodeableKeys(e,t);n=i.length;for(let r=0;r<n;r++){let n=i[r];s+=sizeof(n)+sizeof(e[n],t)}}if(n<16)return 1+s;if(n<65536)return 3+s;if(n<4294967296)return 5+s;throw Error("Array or object too long 0x"+n.toString(16))}if("function"===n)return 0;throw Error("Unknown type "+n)}(e,t);if(0===n)return;let s=new ArrayBuffer(n),i=new DataView(s);return function _encode(e,t,n,s){let i=typeof e;if("string"==typeof e){let s=utf8ByteCount(e);if(s<32)return t.setUint8(n,160|s),utf8Write(t,n+1,e),1+s;if(s<256)return t.setUint8(n,217),t.setUint8(n+1,s),utf8Write(t,n+2,e),2+s;if(s<65536)return t.setUint8(n,218),t.setUint16(n+1,s),utf8Write(t,n+3,e),3+s;if(s<4294967296)return t.setUint8(n,219),t.setUint32(n+1,s),utf8Write(t,n+5,e),5+s}if(ArrayBuffer.isView&&ArrayBuffer.isView(e)&&(e=e.buffer),e instanceof ArrayBuffer){let s=e.byteLength;if(s<256)return t.setUint8(n,196),t.setUint8(n+1,s),new Uint8Array(t.buffer).set(new Uint8Array(e),n+2),2+s;if(s<65536)return t.setUint8(n,197),t.setUint16(n+1,s),new Uint8Array(t.buffer).set(new Uint8Array(e),n+3),3+s;if(s<4294967296)return t.setUint8(n,198),t.setUint32(n+1,s),new Uint8Array(t.buffer).set(new Uint8Array(e),n+5),5+s}if("number"==typeof e){var r,o,a,c;if(Math.floor(e)!==e)return t.setUint8(n,203),t.setFloat64(n+1,e),9;if(e>=0){if(e<128)return t.setUint8(n,e),1;if(e<256)return t.setUint8(n,204),t.setUint8(n+1,e),2;if(e<65536)return t.setUint8(n,205),t.setUint16(n+1,e),3;if(e<4294967296)return t.setUint8(n,206),t.setUint32(n+1,e),5;if(e<18446744073709552e3)return t.setUint8(n,207),r=n+1,(o=e)<18446744073709552e3?(t.setUint32(r,Math.floor(23283064365386963e-26*o)),t.setInt32(r+4,-1&o)):(t.setUint32(r,4294967295),t.setUint32(r+4,4294967295)),9;throw Error("Number too big 0x"+e.toString(16))}if(e>=-32)return t.setInt8(n,e),1;if(e>=-128)return t.setUint8(n,208),t.setInt8(n+1,e),2;if(e>=-32768)return t.setUint8(n,209),t.setInt16(n+1,e),3;if(e>=-2147483648)return t.setUint8(n,210),t.setInt32(n+1,e),5;if(e>=-0x8000000000000000)return t.setUint8(n,211),a=n+1,(c=e)<0x7fffffffffffffff?(t.setInt32(a,Math.floor(23283064365386963e-26*c)),t.setInt32(a+4,-1&c)):(t.setUint32(a,2147483647),t.setUint32(a+4,2147483647)),9;throw Error("Number too small -0x"+(-e).toString(16).substr(1))}if("undefined"===i)return s?0:(t.setUint8(n,212),t.setUint8(n+1,0),t.setUint8(n+2,0),3);if(null===e)return s?0:(t.setUint8(n,192),1);if("boolean"===i)return t.setUint8(n,e?195:194),1;if("function"==typeof e.toJSON)return _encode(e.toJSON(),t,n,s);if("object"===i){let i,r,o=0,a=Array.isArray(e);if((r=a?e.length:(i=encodeableKeys(e,s)).length)<16?(t.setUint8(n,r|(a?144:128)),o=1):r<65536?(t.setUint8(n,a?220:222),t.setUint16(n+1,r),o=3):r<4294967296&&(t.setUint8(n,a?221:223),t.setUint32(n+1,r),o=5),a)for(let i=0;i<r;i++)o+=_encode(e[i],t,n+o,s);else if(i)for(let a=0;a<r;a++){let r=i[a];o+=_encode(r,t,n+o),o+=_encode(e[r],t,n+o,s)}return o}if("function"===i)return 0;throw Error("Unknown type "+i)}(e,i,0,t),s},decode:function(e){let t=new DataView(e),n=new tu(t),s=n.parse();if(n.offset!==e.byteLength)throw Error(e.byteLength-n.offset+" trailing bytes");return s},inspect:function(e){let t,n;if(void 0===e)return"undefined";if(e instanceof ArrayBuffer?(n="ArrayBuffer",t=new DataView(e)):e instanceof DataView&&
6(n="DataView",t=e),!t)return JSON.stringify(e);let s=[];for(let n=0;n<e.byteLength;n++){if(n>20){s.push("...");break}let e=t.getUint8(n).toString(16);1===e.length&&(e="0"+e),s.push(e)}return"<"+n+" "+s.join(" ")+">"},utf8Write,utf8Read,utf8ByteCount};async function fetchRequest(e,t,n,s,i,r){let o;let a=new Headers(s||{}),c=e?e.toUpperCase():isNil(r)?"GET":"POST",l=new AbortController,h=new Promise(e=>{o=setTimeout(()=>{l.abort(),e({error:new k("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:M.TIMEOUTS.httpRequestTimeout)}),u={method:c,headers:a,body:r,signal:l.signal};R.Config.isWebworker||(u.credentials=a.has("authorization")?"include":"same-origin");let d=(async()=>{try{let e;let t=await getGlobalObject().fetch(n+"?"+new URLSearchParams(i||{}),u);clearTimeout(o);let s=t.headers.get("Content-Type");e=s&&s.indexOf("application/x-msgpack")>-1?await t.arrayBuffer():s&&s.indexOf("application/json")>-1?await t.json():await t.text();let r=!!s&&-1===s.indexOf("application/x-msgpack"),a=function(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}(t.headers);if(t.ok)return{error:null,body:e,headers:a,unpacked:r,statusCode:t.status};{let n=function(e,t){if(t.get("x-ably-errorcode"))return e.error&&A.fromValues(e.error)}(e,t.headers)||new k("Error response received from server: "+t.status+" body was: "+R.Config.inspect(e),null,t.status);return{error:n,body:e,headers:a,unpacked:r,statusCode:t.status}}}catch(e){return clearTimeout(o),{error:e}}})();return Promise.race([h,d])}var tp=function(e,t){let CipherParams=class CipherParams{constructor(e,t,n,s){this.algorithm=e,this.keyLength=t,this.mode=n,this.key=s}};let Crypto2=class Crypto2{static getDefaultParams(e){if(!e.key)throw Error("Crypto.getDefaultParams: a key is required");n="string"==typeof e.key?t.toArrayBuffer(t.base64Decode(e.key.replace("_","/").replace("-","+"))):e.key instanceof ArrayBuffer?e.key:t.toArrayBuffer(e.key);var n,s=e.algorithm||"aes",i=8*n.byteLength,r=e.mode||"cbc",o=new CipherParams(s,i,r,n);if(e.keyLength&&e.keyLength!==o.keyLength)throw Error("Crypto.getDefaultParams: a keyLength of "+e.keyLength+" was specified, but the key actually has length "+o.keyLength);return function(e){if("aes"===e.algorithm&&"cbc"===e.mode&&128!==e.keyLength&&256!==e.keyLength)throw Error("Unsupported key length "+e.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)")}(o),o}static async generateRandomKey(t){try{return e.getRandomArrayBuffer((t||256)/8)}catch(e){throw new A("Failed to generate random key: "+e.message,400,5e4,e)}}static getCipher(e){var t,n=e instanceof CipherParams?e:this.getDefaultParams(e);return{cipherParams:n,cipher:new CBCCipher(n,null!=(t=e.iv)?t:null)}}};Crypto2.CipherParams=CipherParams;let CBCCipher=class CBCCipher{constructor(e,n){if(!crypto.subtle){if(isSecureContext)throw Error("Crypto operations are not possible since the browserâs SubtleCrypto class is unavailable (reason unknown).");throw Error("Crypto operations are is not possible since the current environment is a non-secure context and hence the browserâs SubtleCrypto class is not available.")}this.algorithm=e.algorithm+"-"+String(e.keyLength)+"-"+e.mode,this.webCryptoAlgorithm=e.algorithm+"-"+e.mode,this.key=t.toArrayBuffer(e.key),this.iv=n?t.toArrayBuffer(n):null}concat(e,n){let s=new ArrayBuffer(e.byteLength+n.byteLength),i=new DataView(s),r=new DataView(t.toArrayBuffer(e));for(let e=0;e<r.byteLength;e++)i.setInt8(e,r.getInt8(e));let o=new DataView(t.toArrayBuffer(n));for(let e=0;e<o.byteLength;e++)i.setInt8(r.byteLength+e,o.getInt8(e));return s}async encrypt(e){w.logAction(w.LOG_MICRO,"CBCCipher.encrypt()","");let t=await this.getIv(),n=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["encrypt"]),s=await crypto.subtle.encrypt({name:this.webCryptoAlgorithm,iv:t},n,e);return this.concat(t,s)}async decrypt(e){w.logAction(w.LOG_MICRO,"CBCCipher.decrypt()","");let n=t.toArrayBuffer(e),s=n.slice(0,16),i=n.slice(16),r=await crypto.subtle.importKey("raw",this.key,this.webCryptoAlgorithm,!1,["decrypt"]);
6return crypto.subtle.decrypt({name:this.webCryptoAlgorithm,iv:s},r,i)}async getIv(){if(this.iv){var n=this.iv;return this.iv=null,n}let s=await e.getRandomArrayBuffer(16);return t.toArrayBuffer(s)}};return Crypto2}(te,e6);for(let e of(R.Crypto=tp,R.BufferUtils=e6,R.Http=e5,R.Config=te,R.Transports={order:["xhr_polling"],bundledImplementations:{web_socket:ez,xhr_polling:to}},R.WebStorage=tl,[eg,eQ]))e.Crypto=tp,e._MsgPack=td;e5.bundledRequestImplementations={XHRRequest:ti,FetchRequest:fetchRequest},w.initLogHandlers(),R.Defaults=Object.assign(M,th),R.Config.agent&&(R.Defaults.agent+=" "+R.Config.agent);var tf={ErrorInfo:A,Rest:eg,Realtime:eQ,msgpack:td};return"object"==typeof u.exports&&(u.exports=((e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,n)||void 0===n||Object.defineProperty(e,n,{get:()=>t[n],enumerable:!(s=Object.getOwnPropertyDescriptor(t,n))||s.enumerable});return e})(u.exports,h)),u.exports})()}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.