1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="369125e7-c27e-4e7f-8f44-d4b03af90f3b",e._sentryDebugIdIdentifier="sentry-dbid-369125e7-c27e-4e7f-8f44-d4b03af90f3b")}catch(e){}}(),(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[22432],{71363:function(e,t,n){e.exports=(()=>{"use strict";var e,t,s,i,r,o,a,l,c,h={},u={exports:h},d=Object.defineProperty,g=Object.defineProperties,p=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyDescriptors,m=Object.getOwnPropertyNames,y=Object.getOwnPropertySymbols,v=Object.prototype.hasOwnProperty,b=Object.prototype.propertyIsEnumerable,O=(e,t,n)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))v.call(t,n)&&O(e,n,t[n]);if(y)for(var n of y(t))b.call(t,n)&&O(e,n,t[n]);return e},C=(e,t)=>g(e,f(t)),R=(e,t)=>{var n={};for(var s in e)v.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)&&b.call(e,s)&&(n[s]=e[s]);return n},A=(e,t)=>{for(var n in t)d(e,n,{get:t[n],enumerable:!0})},k=function(e,t){this[0]=e,this[1]=t},S=(e,t,n)=>{var s=(e,t,i,r)=>{try{var o=n[e](t),a=(t=o.value)instanceof k,l=o.done;Promise.resolve(a?t[0]:t).then(n=>a?s("return"===e?e:"next",t[1]?{done:n.done,value:n.value}:n,i,r):i({value:n,done:l})).catch(e=>s("throw",e,i,r))}catch(e){r(e)}},i=e=>r[e]=t=>new Promise((n,i)=>s(e,t,n,i)),r={};return n=n.apply(e,t),r[Symbol.asyncIterator]=()=>r,i("next"),i("throw"),i("return"),r},M={};A(M,{ErrorInfo:()=>x,Realtime:()=>nz,Rest:()=>ny,default:()=>sA,makeProtocolMessageFromDeserialized:()=>nl,msgpack:()=>sw}),u.exports=((e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of m(t))v.call(e,i)||i===n||d(e,i,{get:()=>t[i],enumerable:!(s=p(t,i))||s.enumerable});return e})(d({},"__esModule",{value:!0}),M);var T=class{},_=void 0!==n.g?n.g:"undefined"!=typeof window?window:self;function I(e,t){return`${e}`.padStart(t?3:2,"0")}function P(e){return T.Config.logTimestamps?function(t){let n=new Date;e(I(n.getHours())+":"+I(n.getMinutes())+":"+I(n.getSeconds())+"."+I(n.getMilliseconds(),1)+" "+t)}:function(t){e(t)}}var E=()=>{var e;let t,n;return"function"==typeof(null==(e=null==_?void 0:_.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(P)},L=class e{constructor(){this.deprecated=(e,t)=>{this.deprecationWarning(`${e} is deprecated and will be removed in a future version. ${t}`)},this.shouldLog=e=>e<=this.logLevel,this.setLog=(e,t)=>{void 0!==e&&(this.logLevel=e),void 0!==t&&(this.logHandler=this.logErrorHandler=t)},this.logLevel=e.defaultLogLevel,this.logHandler=e.defaultLogHandler,this.logErrorHandler=e.defaultLogErrorHandler}static initLogHandlers(){let[t,n]=E();this.defaultLogHandler=t,this.defaultLogErrorHandler=n,this.defaultLogger=new e}static logActionNoStrip(e,t,n,s){e.logAction(t,n,s)}logAction(e,t,n){this.shouldLog(e)&&(1===e?this.logErrorHandler:this.logHandler)("Ably: "+t+": "+n,e)}renamedClientOption(e,t){this.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.`)}renamedMethod(e,t,n){this.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.`)}deprecationWarning(e){this.shouldLog(1)&&this.logErrorHandler(`Ably: Deprecation warning - ${e}`,1)}};L.defaultLogLevel=1,L.LOG_NONE=0,L.LOG_ERROR=1,L.LOG_MAJOR=2,L.LOG_MINOR=3,L.LOG_MICRO=4,L.logAction=(e,t,n,s)=>{L.logActionNoStrip(e,t,n,s)};var N={};function U(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="+eh(e.cause)),e.hint&&(t+="; hint="+e.hint),e.detail&&Object.keys(e.detail).length>0&&(t+="; detail="+JSON.stringify(e.detail)),e.href&&!(e.message&&e.message.indexOf("help.ably.io")>-1)&&(t+="; see "+e.href+" "),t+="]"}A(N,{Format:()=>es,allSame:()=>en,allToLowerCase:()=>eb,allToUpperCase:()=>eO,arrChooseN:()=>ef,arrDeleteValue:()=>X,arrEquals:()=>eT,arrIntersect:()=>$,arrIntersectOb:()=>Q,arrPopRandomElement:()=>ei,arrWithoutValue:()=>Y,cheapRandStr:()=>eg,containsValue:()=>z,copy:()=>q,createMissingPluginError:()=>e_,dataSizeBytes:()=>ed,decodeBody:()=>ey,detectV1Callback:()=>ec,encodeBody:()=>ev,ensureArray:()=>D,forInOwnNonNullProperties:()=>et,getBackoffCoefficient:()=>ew,getGlobalObject:()=>eA,getJitterCoefficient:()=>eC,getRetryTime:()=>eR,inherits:()=>J,inspectBody:()=>eu,inspectError:()=>eh,intersect:()=>K,isEmpty:()=>H,isErrorInfoOrPartialErrorInfo:()=>el,isNil:()=>V,isObject:()=>j,keysArray:()=>Z,listenerToAsyncIterator:()=>eE,matchDerivedChannel:()=>eS,mixin:()=>B,parseQueryString:()=>ea,prototypicalClone:()=>F,randomString:()=>ep,shallowClone:()=>W,shallowEquals:()=>ek,stringifyValues:()=>eo,throwMissingPluginError:()=>eI,toBase64:()=>eM,toQueryString:()=>er,valuesArray:()=>ee,whenPromiseSettles:()=>em,withTimeoutAsync:()=>eP});
1var x=class e extends Error{constructor(t,n,s,i,r){super(t),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=s,this.cause=i,this.detail=r}toString(){return U(this)}static fromValues(t){let{message:n,code:s,statusCode:i,detail:r}=t;if("string"!=typeof n||"number"!=typeof s||"number"!=typeof i||!V(r)&&("object"!=typeof r||Array.isArray(r)))throw Error("ErrorInfo.fromValues(): invalid values: "+T.Config.inspect(t));let o=Object.assign(new e(n,s,i,void 0,r),t);return o.code&&!o.href&&(o.href="https://help.ably.io/error/"+o.code),o}},G=class e extends Error{constructor(t,n,s,i,r){super(t),void 0!==Object.setPrototypeOf&&Object.setPrototypeOf(this,e.prototype),this.code=n,this.statusCode=s,this.cause=i,this.detail=r}toString(){return U(this)}static fromValues(t){let{message:n,code:s,statusCode:i,detail:r}=t;if("string"!=typeof n||!V(s)&&"number"!=typeof s||!V(i)&&"number"!=typeof i||!V(r)&&("object"!=typeof r||Array.isArray(r)))throw Error("PartialErrorInfo.fromValues(): invalid values: "+T.Config.inspect(t));let o=Object.assign(new e(n,s,i,void 0,r),t);return o.code&&!o.href&&(o.href="https://help.ably.io/error/"+o.code),o}};function B(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 q(e){return B({},e)}function D(e){return V(e)?[]:Array.isArray(e)?e:[e]}function j(e){return"[object Object]"==Object.prototype.toString.call(e)}function H(e){for(let t in e)return!1;return!0}function V(e){return null==e}function W(e){let t={};for(let n in e)t[n]=e[n];return t}function F(e,t){class n{}n.prototype=e;let s=new n;return t&&B(s,t),s}var J=function(e,t){if(T.Config.inherits)return void T.Config.inherits(e,t);e.super_=t,e.prototype=F(t.prototype,{constructor:e})};function z(e,t){for(let n in e)if(e[n]==t)return!0;return!1}function K(e,t){return Array.isArray(t)?$(e,t):Q(e,t)}function $(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 Q(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 X(e,t){let n=e.indexOf(t),s=-1!=n;return s&&e.splice(n,1),s}function Y(e,t){let n=e.slice();return X(n,t),n}function Z(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(s);return n}function ee(e,t){let n=[];for(let s in e)(!t||Object.prototype.hasOwnProperty.call(e,s))&&n.push(e[s]);return n}function et(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&e[n]&&t(n)}function en(e,t){if(0===e.length)return!0;let n=e[0][t];return e.every(function(e){return e[t]===n})}var es=((e=es||{}).msgpack="msgpack",e.json="json",e);function ei(e){return e.splice(Math.floor(Math.random()*e.length),1)[0]}function er(e){let t=[];if(e)for(let n in e)t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.length?"?"+t.join("&"):""}function eo(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,String(t)]))}function ea(e){let t,n=/([^?&=]+)=?([^&]*)/g,s={};for(;t=n.exec(e);)s[decodeURIComponent(t[1])]=decodeURIComponent(t[2]);return s}function el(e){return"object"==typeof e&&null!==e&&(e instanceof x||e instanceof G)}function ec(e,t){let n=e.length;if("function"!=typeof e[n-1]||n<=t&&"function"!=typeof e[n-2])return;let s=new x("v1 callback signature is no longer supported.",40025,400);throw s.hint="v2 uses Promises â drop the trailing callback and `await` the returned promise. See https://github.com/ably/ably-js/blob/main/docs/migration-guides/v2/lib.md",s}function eh(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():T.Config.inspect(e)}function eu(e){return T.BufferUtils.isBuffer(e)?e.toString():"string"==typeof e?e:T.Config.inspect(e)}function ed(e){if(T.BufferUtils.isBuffer(e))return T.BufferUtils.byteLength(e);if("string"==typeof e)return T.Config.stringByteSize(e);if("number"==typeof e)return 8;if("boolean"==typeof e)return 1;throw Error(`Expected input of Utils.dataSizeBytes to be a string, a number, a boolean or a buffer, but was: ${typeof e}`)}function eg(){return String(Math.random()).substr(2)}var ep=async e=>{let t=await T.Config.getRandomArrayBuffer(e);return T.BufferUtils.base64Encode(t)};function ef(e,t){let n=Math.min(t,e.length),s=e.slice(),i=[];for(let e=0;e<n;e++)i.push(ei(s));return i}function em(e,t){e.then(e=>{null==t||t(null,e)}).catch(e=>{null==t||t(e)})}
1function ey(e,t,n){return"msgpack"==n?(t||eI("MsgPack"),t.decode(e)):JSON.parse(String(e))}function ev(e,t,n){return"msgpack"==n?(t||eI("MsgPack"),t.encode(e,!0)):JSON.stringify(e)}function eb(e){return e.map(function(e){return e&&e.toLowerCase()})}function eO(e){return e.map(function(e){return e&&e.toUpperCase()})}function ew(e){return Math.min((e+2)/3,2)}function eC(){return 1-.2*Math.random()}function eR(e,t){return e*ew(t)*eC()}function eA(){return void 0!==n.g?n.g:"undefined"!=typeof window?window:self}function ek(e,t){return Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(t).every(n=>t[n]===e[n])}function eS(e){let t=e.match(/^(\[([^?]*)(?:(.*))\])?(.+)$/);if(!t||!t.length||t.length<5)throw new x("regex match failed",400,40010);if(t[2])throw new x(`cannot use a derived option with a ${t[2]} channel`,400,40010);return{qualifierParam:t[3]||"",channelName:t[4]}}function eM(e){let t=T.BufferUtils,n=t.utf8Encode(e);return t.base64Encode(n)}function eT(e,t){return e.length===t.length&&e.every(function(e,n){return e===t[n]})}function e_(e){return new x(`${e} plugin not provided`,40019,400)}function eI(e){throw e_(e)}async function eP(e,t=5e3,n="Timeout expired"){let s=new x(n,5e4,500);return Promise.race([e,new Promise((e,n)=>setTimeout(()=>n(s),t))])}function eE(e){return S(this,null,function*(){let t=[],n=null,s=e(e=>{if(n){let t=n;n=null,t(e)}else t.push(e)});try{for(;;)if(t.length>0)yield t.shift();else{if(n)throw new x("Concurrent next() calls are not supported",4e4,400);let e=yield new k(new Promise(e=>{n=e}));yield e}}finally{s()}})}var eL="2.22.1",eN={ENDPOINT:"main",ENVIRONMENT:"",REST_HOST:"rest.ably.io",REALTIME_HOST:"realtime.ably.io",FA
1LLBACK_HOSTS:["main.a.fallback.ably-realtime.com","main.b.fallback.ably-realtime.com","main.c.fallback.ably-realtime.com","main.d.fallback.ably-realtime.com","main.e.fallback.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:eL,protocolVersion:6,agent:"ably-js/"+eL,getPort:function(e,t){return t||e.tls?e.tlsPort:e.port},getHttpScheme:function(e){return e.tls?"https://":"http://"},getPrimaryDomainFromEndpoint:ex,getEndpointFallbackHosts:eG,getFallbackHosts:eq,getHosts:function(e){return[e.primaryDomain].concat(eq(e))},checkHost:eD,objectifyOptions:function(e,t,n,s,i){let r;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 L.logAction(s,L.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 L.logAction(s,L.LOG_ERROR,`${n}()`,e),Error(e)}r={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 L.logAction(s,L.LOG_ERROR,`${n}()`,e),Error(e)}r={key:e}}else r=e;return i&&(r=C(w({},r),{plugins:w(w({},i),r.plugins)})),r},normaliseOptions:function(e,t,n){let s=null!=n?n:L.defaultLogger;e.environment&&s.deprecated("The `environment` client option","Use the `endpoint` client option instead."),e.restHost&&s.deprecated("The `restHost` client option","Use the `endpoint` client option instead."),e.realtimeHost&&s.deprecated("The `realtimeHost` client option","Use the `endpoint` client option instead.");if(e.endpoint&&(e.environment||e.restHost||e.realtimeHost))throw new x("The `endpoint` option cannot be used in conjunction with the `environment`, `restHost`, or `realtimeHost` options.",40106,400);if(e.environment&&(e.restHost||e.realtimeHost))throw new x("The `environment` option cannot be used in conjunction with the `restHost`, or `realtimeHost` options.",40106,400);"function"==typeof e.recover&&!0===e.closeOnUnload&&(L.logAction(s,L.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 i=e.endpoint||eN.ENDPOINT;e.fallbackHosts||e.restHost||e.realtimeHost||e.port||e.tlsPort||(e.fallbackHosts=eG(e.environment||i));let r=e.environment&&`${e.environment}.realtime.ably.net`,o=e.restHost||e.realtimeHost||r||ex(i);(e.fallbackHosts||[]).concat(o).forEach(eD),e.port=e.port||eN.PORT,e.tlsPort=e.tlsPort||eN.TLS_PORT,"tls"in e||(e.tls=!0);let a=function(e){let t={};for(let n in eN.TIMEOUTS)t[n]=e[n]||eN.TIMEOUTS[n];return t}(e);
1t?"useBinaryProtocol"in e?e.useBinaryProtocol=T.Config.supportsBinary&&e.useBinaryProtocol:e.useBinaryProtocol=T.Config.preferBinary:e.useBinaryProtocol=!1;let l={};e.clientId&&(l["X-Ably-ClientId"]=T.BufferUtils.base64Encode(T.BufferUtils.utf8Encode(e.clientId))),"idempotentRestPublishing"in e||(e.idempotentRestPublishing=!0);let c=null,h=e.connectivityCheckUrl;if(e.connectivityCheckUrl){let[t,n]=e.connectivityCheckUrl.split("?");c=n?ea(n):{},-1===t.indexOf("://")&&(t="https://"+t),h=t}let u=e.wsConnectivityCheckUrl;return u&&-1===u.indexOf("://")&&(u="wss://"+u),C(w({},e),{primaryDomain:o,maxMessageSize:e.maxMessageSize||eN.maxMessageSize,timeouts:a,connectivityCheckParams:c,connectivityCheckUrl:h,wsConnectivityCheckUrl:u,headers:l})},defaultGetHeaders:function(e,{format:t,protocolVersion:n=eW.protocolVersion}={}){return{accept:eV[null!=t?t:e.useBinaryProtocol?"msgpack":"json"],"X-Ably-Version":n.toString(),"Ably-Agent":ej(e)}},defaultPostHeaders:function(e,{format:t,protocolVersion:n=eW.protocolVersion}={}){let s=eV[null!=t?t:e.useBinaryProtocol?"msgpack":"json"];return{accept:s,"content-type":s,"X-Ably-Version":n.toString(),"Ably-Agent":ej(e)}}};function eU(e){return e.includes(".")||e.includes("::")||"localhost"===e}function ex(e){if(eU(e))return e;if(e.startsWith("nonprod:")){let t=e.replace("nonprod:","");return`${t}.realtime.ably-nonprod.net`}return`${e}.realtime.ably.net`}function eG(e){return eU(e)?[]:e.startsWith("nonprod:")?eB(e.replace("nonprod:",""),"ably-realtime-nonprod.com"):eB(e,"ably-realtime.com")}function eB(e,t){return["a","b","c","d","e"].map(n=>`${e}.${n}.fallback.${t}`)}function eq(e){let t=e.fallbackHosts,n=void 0!==e.httpMaxRetryCount?e.httpMaxRetryCount:eN.httpMaxRetryCount;return t?ef(t,n):[]}function eD(e){if("string"!=typeof e)throw new x("host must be a string; was a "+typeof e,4e4,400);if(!e.length)throw new x("host must not be zero-length",4e4,400)}function ej(e){let t=eN.agent;if(e.agents)for(var n in e.agents)t+=" "+n+"/"+e.agents[n];return t}function eH(e,t,n){let s=n||{};if(s.cipher){e||eI("Crypto");let n=e.getCipher(s.cipher,t);s.cipher=n.cipherParams,s.channelCipher=n.cipher}else"cipher"in s&&(s.cipher=void 0,s.channelCipher=null);return s}var eV={json:"application/json",xml:"application/xml",html:"text/html",msgpack:"application/x-msgpack",text:"text/plain"},eW={format:"json",protocolVersion:eN.protocolVersion},eF=class e{constructor(e,t){this.logger=e,this.members=t||[]}call(e,t){for(let n of this.members)if(n)try{n(e,t)}catch(e){L.logAction(this.logger,L.LOG_ERROR,"Multicaster multiple callback handler","Unexpected exception: "+e+"; stack = "+e.stack)}}push(...e){this.members.push(...e)}createPromise(){return new Promise((e,t)=>{this.push((n,s)=>{n?t(n):e(s)})})}resolveAll(e){this.call(null,e)}rejectAll(e){this.call(e)}static create(t,n){let s=new e(t,n);return Object.assign((e,t)=>s.call(e,t),{push:e=>s.push(e),createPromise:()=>s.createPromise(),resolveAll:e=>s.resolveAll(e),rejectAll:e=>s.rejectAll(e)})}},eJ=((t=eJ||{}).Get="get",t.Delete="delete",t.Post="post",t.Put="put",t.Patch="patch",t),ez=((s=ez||{})[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 eK(e){return el(e)?(e.code||(403===e.statusCode?e.code=40300:(e.code=40170,e.statusCode=401)),e):new x(eh(e),e.code||40170,e.statusCode||401)}var e$=(e,t)=>{let n=T.BufferUtils,s=n.utf8Encode(e),i=n.utf8Encode(t),r=n.hmacSha256(s,i);return n.base64Encode(r)};function eQ(e){if(!e)return"";"string"==typeof e&&(e=JSON.parse(e));let t=Object.create(null),n=Z(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 eX(e,t){if(e.authCallback)L.logAction(t,L.LOG_MINOR,"Auth()","using token auth with authCallback");else if(e.authUrl)L.logAction(t,L.LOG_MINOR,"Auth()","using token auth with authUrl");else if(e.key)L.logAction(t,L.LOG_MINOR,"Auth()","using token auth with client-side signing");else if(e.tokenDetails)L.logAction(t,L.LOG_MINOR,"Auth()","using token auth with supplied token only");else{let e="authOptions must include valid authentication parameters";throw L.logAction(t,L.LOG_ERROR,"Auth()",e),Error(e)}}function eY(e){return e.useTokenAuth||!("useTokenAuth"in e&&!e.useTokenAuth)&&(e.authCallback||e.authUrl||e.token||e.tokenDetails)}var eZ=0,e0=class{constructor(e,t){if(this.authOptions={},this.client=e,this.tokenParams=t.defaultTokenParams||{},this.currentTokenRequestId=null,this.waitingForTokenRequest=null,eY(t))t.key||t.authCallback||t.authUrl||L.logAction(this.logger,L.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),eX(this.authOptions,this.logger);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 L.logAction(this.logger,L.LOG_ERROR,"Auth()",e),new x(e,40160,401)}L.logAction(this.logger,L.LOG_MINOR,"Auth()","anonymous, using basic auth"),this._saveBasicOptions(t)}}get logger(){return this.client.logger}authorize(...e){return ec(e,0),this._authorizeImpl(e[0],e[1])}async _authorizeImpl(e,t){if(t&&t.key&&this.authOptions.key!==t.key)throw new x("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)=>
1{this.client.connection.connectionManager.onAuthUpdated(n,(n,s)=>n?t(n):e(s))});return n}catch(e){throw this.client.connection&&e.statusCode===ez.Forbidden&&this.client.connection.connectionManager.actOnErrorFromAuthorize(e),e}}async _forceNewToken(e,t){this.tokenDetails=null,this._saveTokenOptions(e,t),eX(this.authOptions,this.logger);try{return this._ensureValidAuthCredentials(!0)}finally{delete this.tokenParams.timestamp,delete this.authOptions.queryTime}}requestToken(...e){return ec(e,0),this._requestTokenImpl(e[0],e[1])}async _requestTokenImpl(e,t){let n=t||this.authOptions,s=e||q(this.tokenParams),i,r=this.client;if(n.authCallback)L.logAction(this.logger,L.LOG_MINOR,"Auth.requestToken()","using token auth with authCallback"),i=n.authCallback;else if(n.authUrl)L.logAction(this.logger,L.LOG_MINOR,"Auth.requestToken()","using token auth with authUrl"),i=(e,t)=>{let s,i=B({accept:"application/json, text/plain"},n.authHeaders),r=n.authMethod&&"post"===n.authMethod.toLowerCase(),o=n.authUrl.indexOf("?");o>-1&&(s=ea(n.authUrl.slice(o)),n.authUrl=n.authUrl.slice(0,o),r||(n.authParams=B(s,n.authParams)));let a=B({},n.authParams||{},e),l=e=>{var n,s;let i=null!=(n=e.body)?n:null,r=null;if(e.error)L.logAction(this.logger,L.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received Error: "+eh(e.error));else{let t=null!=(s=e.headers["content-type"])?s:null;r=Array.isArray(t)?t.join(", "):t,L.logAction(this.logger,L.LOG_MICRO,"Auth.requestToken().tokenRequestCallback","Received; content-type: "+r+"; body: "+eu(i))}if(e.error)return void t(e.error,null);if(e.unpacked)return void t(null,i);if(T.BufferUtils.isBuffer(i)&&(i=i.toString()),!r)return void t(new x("authUrl response is missing a content-type header",40170,401),null);let o=r.indexOf("application/json")>-1,a=r.indexOf("text/plain")>-1||r.indexOf("application/jwt")>-1;if(!o&&!a)return void t(new x("authUrl responded with unacceptable content-type "+r+", should be either text/plain, application/jwt or application/json",40170,401),null);if(o){if(i.length>131072)return void t(new x("authUrl response exceeded max permitted length",40170,401),null);try{i=JSON.parse(i)}catch(e){t(new x("Unexpected error processing authURL response; err = "+e.message,40170,401),null);return}}t(null,i,r)};if(L.logAction(this.logger,L.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=er(a).slice(1);em(this.client.http.doUri(eJ.Post,n.authUrl,e,t,s),(e,t)=>e?l(e):l(t))}else em(this.client.http.doUri(eJ.Get,n.authUrl,i||{},null,a),(e,t)=>e?l(e):l(t))};else if(n.key)L.logAction(this.logger,L.LOG_MINOR,"Auth.requestToken()","using token auth with client-side signing"),i=(e,t)=>{em(this.createTokenRequest(e,n),(e,n)=>t(e,null!=n?n:null))};else throw L.logAction(this.logger,L.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 x("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=eQ(s.capability));let o=(e,t)=>{let s="/keys/"+e.keyName+"/requestToken",i=eN.defaultPostHeaders(this.client.options,{format:"json"});n.requestHeaders&&B(i,n.requestHeaders),L.logAction(this.logger,L.LOG_MICRO,"Auth.requestToken().requestToken","Sending POST to "+s+"; Token params: "+JSON.stringify(e)),em(this.client.http.do(eJ.Post,function(e){return r.baseUri(e)+s},i,JSON.stringify(e),null),(e,n)=>e?t(e):t(n.error,n.body,n.unpacked))};return new Promise((e,t)=>{let r=!1,a=this.client.options.timeouts.realtimeRequestTimeout,l=setTimeout(()=>{r=!0;let e="Token request callback timed out after "+a/1e3+" seconds";L.logAction(this.logger,L.LOG_ERROR,"Auth.requestToken()",e),t(new x(e,40170,401))},a);i(s,(s,i,a)=>{if(r)return;if(clearTimeout(l),s){L.logAction(this.logger,L.LOG_ERROR,"Auth.requestToken()","token request signing call returned error; err = "+eh(s)),t(eK(s));return}if("string"==typeof i)return void(0===i.length?t(new x("Token string is empty",40170,401)):i.length>
1131072?t(new x("Token string exceeded max permitted length (was "+i.length+" bytes)",40170,401)):"undefined"===i||"null"===i?t(new x("Token string was literal null/undefined",40170,401)):"{"!==i[0]||a&&a.indexOf("application/jwt")>-1?e({token:i}):t(new x("Token was double-encoded; make sure you're not JSON-encoding an already encoded token request or details",40170,401)));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;L.logAction(this.logger,L.LOG_ERROR,"Auth.requestToken()",e),t(new x(e,40170,401));return}let c=JSON.stringify(i).length;if(c>131072&&!n.suppressMaxLengthCheck)return void t(new x("Token request/details object exceeded max permitted stringified size (was "+c+" bytes)",40170,401));if("issued"in i)return void e(i);if(!("keyName"in i)){let e="Expected token request callback to call back with a token string, token request object, or token details object";L.logAction(this.logger,L.LOG_ERROR,"Auth.requestToken()",e),t(new x(e,40170,401));return}o(i,(n,s,i)=>{if(n){L.logAction(this.logger,L.LOG_ERROR,"Auth.requestToken()","token request API call returned error; err = "+eh(n)),t(eK(n));return}i||(s=JSON.parse(s)),L.logAction(this.logger,L.LOG_MINOR,"Auth.getToken()","token received"),e(s)})})})}createTokenRequest(...e){return ec(e,0),this._createTokenRequestImpl(e[0],e[1])}async _createTokenRequestImpl(e,t){t=t||this.authOptions,e=e||q(this.tokenParams);let n=t.key;if(!n)throw new x("No key specified",40101,403);let s=n.split(":"),i=s[0],r=s[1];if(!r)throw new x("Invalid key specified",40101,403);if(""===e.clientId)throw new x("clientId canât be an empty string",40012,400);"capability"in e&&(e.capability=eQ(e.capability));let o=B({keyName:i},e),a=e.clientId||"",l=e.ttl||"",c=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"+l+"\n"+c+"\n"+a+"\n"+u+"\n"+h+"\n";return o.mac=o.mac||e$(d,r),L.logAction(this.logger,L.LOG_MINOR,"Auth.getTokenRequest()","generated signed request"),o}async 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 "+eM(e.token)}}}_saveBasicOptions(e){this.method="basic",this.key=e.key,this.basicKey=eM(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 x("Mismatch between clientId in token ("+t.clientId+") and current clientId ("+this.clientId+")",40102,403);if(!this.client.isTimeOffsetSet()||!t.expires||t.expires>=this.client.getTimestampUsingOffset())return L.logAction(this.logger,L.LOG_MINOR,"Auth.getToken()","using cached token; expires = "+t.expires),t;L.logAction(this.logger,L.LOG_MINOR,"Auth.getToken()","deleting expired token"),this.tokenDetails=null}let n=(this.waitingForTokenRequest||(this.waitingForTokenRequest=eF.create(this.logger))).createPromise();if(null!==this.currentTokenRequestId&&!e)return n;let s=this.currentTokenRequestId=eZ++,i,r=null;try{i=await this.requestToken(this.tokenParams,this.authOptions)}catch(e){r=e}if(this.currentTokenRequestId>s)return L.logAction(this.logger,L.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)throw new x("clientId must be either a string or null",40012,400);if("*"===e)throw new x('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: "*"}}
1), or if calling authorize(), pass it in as a tokenParam: authorize({clientId: "*"}, authOptions)',40012,400);{let t=this._uncheckedSetClientId(e);if(t)throw t}}_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 x(t,40102,401);return L.logAction(this.logger,L.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)}async _getTimestamp(e){return this.client.getTimestamp(e||!!this.authOptions.queryTime)}};function e1(e){let t=[];if(e)for(let n in e)t.push(n+"="+e[n]);return t.join("&")}function e4(e,t){return e+(t?"?":"")+e1(t)}var e2=class{constructor(e){this.client=e,this.platformHttp=new T.Http(e),this.checkConnectivity=this.platformHttp.checkConnectivity?()=>this.platformHttp.checkConnectivity():void 0}get logger(){var e,t;return null!=(t=null==(e=this.client)?void 0:e.logger)?t:L.defaultLogger}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(eN.getFallbackHosts(e.options)):eN.getHosts(e.options)}async do(e,t,n,s,i){try{let r=this.client;if(!r)return{error:new x("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 l=await this.doUri(e,o(a.host),n,s,i);if(l.error&&this.platformHttp.shouldFallback(l.error))return r._currentFallback=null,this.do(e,t,n,s,i);return l}else r._currentFallback=null;let l=this._getHosts(r);if(1===l.length)return this.doUri(e,o(l[0]),n,s,i);let c=null,h=async(t,a)=>{let l=t.shift();c=null!=c?c:new Date;let u=await this.doUri(e,o(l),n,s,i);return u.error&&this.platformHttp.shouldFallback(u.error)&&t.length?Date.now()-c.getTime()>r.options.timeouts.httpMaxRetryDuration?{error:new x(`Timeout for trying fallback hosts retries. Total elapsed time exceeded the ${r.options.timeouts.httpMaxRetryDuration}ms limit`,50003,500)}:h(t,!0):(a&&(r._currentFallback={host:l,validUntil:Date.now()+r.options.timeouts.fallbackRetryTimeout}),u)};return h(l)}catch(e){return{error:new x(`Unexpected error in Http.do: ${eh(e)}`,500,5e4)}}}async doUri(e,t,n,s,i){try{var r,o;(r=this.logger).shouldLog(L.LOG_MICRO)&&L.logActionNoStrip(r,L.LOG_MICRO,"Http."+e+"()","Sending; "+e4(t,i)+"; Body"+(T.BufferUtils.isBuffer(s)?" (Base64): "+T.BufferUtils.base64Encode(s):": "+s));let a=await this.platformHttp.doUri(e,t,n,s,i);return this.logger.shouldLog(L.LOG_MICRO)&&(o=this.logger,a.error?L.logActionNoStrip(o,L.LOG_MICRO,"Http."+e+"()","Received Error; "+e4(t,i)+"; Error: "+eh(a.error)):L.logActionNoStrip(o,L.LOG_MICRO,"Http."+e+"()","Received; "+e4(t,i)+"; Headers: "+e1(a.headers)+"; StatusCode: "+a.statusCode+"; Body"+(T.BufferUtils.isBuffer(a.body)?" (Base64): "+T.BufferUtils.base64Encode(a.body):": "+a.body))),a}catch(e){return{error:new x(`Unexpected error in Http.doUri: ${eh(e)}`,500,5e4)}}}};function e8(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(j(s))for(r in s)Object.prototype.hasOwnProperty.call(s,r)&&Array.isArray(s[r])&&e8([s],t,r)}var e3=class{constructor(e){this.logger=e,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: "+T.Config.inspect(e))}if(2===e.length){let[t,n]=e;if("function"!=typeof n)throw Error("EventListener.on(): Invalid arguments: "+T.Config.inspect(e));if(V(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: "+T.Config.inspect(e));(this.events[t]||(this.events[t]=[])).push(n)}}}off(...e){if(0==e.length||V(e[0])&&V(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;
1if(1!==e.length&&n){if("function"!=typeof n)throw Error("EventEmitter.off(): invalid arguments:"+T.Config.inspect(e));[i,s]=[t,n]}else"function"==typeof t?s=t:i=t;if(s&&V(i))return void e8([this.any,this.events,this.anyOnce,this.eventsOnce],s);if(Array.isArray(i))return void i.forEach(e=>{this.off(e,s)});if("string"!=typeof i)throw Error("EventEmitter.off(): invalid arguments:"+T.Config.inspect(e));s?e8([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(e=>{var s=this.logger;try{e.apply(n,t)}catch(e){L.logAction(s,L.LOG_ERROR,"EventEmitter.emit()","Unexpected listener exception: "+e+"; stack = "+(e&&e.stack))}})}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(V(n)){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+T.Config.inspect(e));this.anyOnce.push(s)}else if(Array.isArray(n)){let t=this,i=function(){let r=Array.prototype.slice.call(arguments);if(n.forEach(function(e){t.off(e,i)}),"function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+T.Config.inspect(e));s.apply(this,r)};n.forEach(function(e){t.on(e,i)})}else{if("string"!=typeof n)throw Error("EventEmitter.once(): Invalid arguments:"+T.Config.inspect(e));let t=this.eventsOnce[n]||(this.eventsOnce[n]=[]);if(s){if("function"!=typeof s)throw Error("EventEmitter.once(): Invalid arguments:"+T.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)}},e6={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,OBJECT:19,OBJECT_SYNC:20,ANNOTATION:21},e5=[];Object.keys(e6).forEach(function(e){e5[e6[e]]=e});var e9={HAS_PRESENCE:1,HAS_BACKLOG:2,RESUMED:4,TRANSIENT:16,ATTACH_RESUME:32,HAS_OBJECTS:128,PRESENCE:65536,PUBLISH:131072,SUBSCRIBE:262144,PRESENCE_SUBSCRIBE:524288,ANNOTATION_PUBLISH:2097152,ANNOTATION_SUBSCRIBE:4194304,OBJECT_SUBSCRIBE:0x1000000,OBJECT_PUBLISH:0x2000000},e7=Object.keys(e9);e9.MODE_ALL=e9.PRESENCE|e9.PUBLISH|e9.SUBSCRIBE|e9.PRESENCE_SUBSCRIBE|e9.ANNOTATION_PUBLISH|e9.ANNOTATION_SUBSCRIBE|e9.OBJECT_SUBSCRIBE|e9.OBJECT_PUBLISH;var te=["PRESENCE","PUBLISH","SUBSCRIBE","PRESENCE_SUBSCRIBE","ANNOTATION_PUBLISH","ANNOTATION_SUBSCRIBE","OBJECT_SUBSCRIBE","OBJECT_PUBLISH"];function tt(e,t,n){if(n&&n.cipher){e||eI("Crypto");let s=e.getCipher(n.cipher,t);return{cipher:s.cipherParams,channelCipher:s.cipher}}return null!=n?n:{}}async function tn(e,t){let{data:n,encoding:s}=await ts(e.data,e.encoding,t);return e.data=n,e.encoding=s,e}async function ts(e,t,n){let s=n.channelCipher,i=e,r=t?t+"/":"";return T.BufferUtils.isBuffer(i)||(i=T.BufferUtils.utf8Encode(String(i)),r+="utf-8/"),{data:await s.encrypt(i),encoding:r=r+"cipher+"+s.algorithm}}async function ti(e,t){let{data:n,encoding:s}=tr(e.data,e.encoding);return(e.data=n,e.encoding=s,null!=t&&t.cipher)?tn(e,t):e}function tr(e,t){if("string"==typeof e||T.BufferUtils.isBuffer(e)||null==e)return{data:e,encoding:t};if(j(e)||Array.isArray(e))return{data:JSON.stringify(e),encoding:t?t+"/json":"json"};throw new x("Data type is unsupported",40013,400)}async function to(e,t){let{data:n,encoding:s,error:i}=await ta(e.data,e.encoding,t);if(e.data=n,e.encoding=s,i)throw i}async function ta(e,t,n){let s,i=n&&n.channelOptions?n:{channelOptions:n,plugins:{},baseEncodedPreviousPayload:void 0},r=e,o=e,a=t;if(t){let e,n=t.split("/"),l=n.length,c="";try{for(;(e=l)>0;){let t=n[--l].match(/([-\w]+)(\+([\w-]+))?/);if(!t)break;switch(c=t[1]){case"base64":o=T.BufferUtils.base64Decode(String(o)),e==n.length&&(r=o);continue;case"utf-8":o=T.BufferUtils.utf8Decode(o);continue;case"json":o=JSON.parse(o);continue;case"cipher":if(null!=i.channelOptions&&i.channelOptions.cipher&&i.channelOptions.channelCipher){let e=t[3],n=i.channelOptions.channelCipher;if(e!=n.algorithm)throw Error("Unable to decrypt message with given cipher; incompatible cipher params");o=await n.decrypt(o);continue}throw Error("Unable to decrypt message; not an encrypted channel");case"vcdiff":if(!i.plugins||!i.plugins.vcdiff)throw new x("Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)",40019,400);if("undefined"==typeof Uint8Array)throw new x("Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)",40020,400);try{let e=i.baseEncodedPreviousPayload;"string"==typeof e&&(e=T.BufferUtils.utf8Encode(e));let t=T.BufferUtils.toBuffer(e);o=T.BufferUtils.toBuffer(o),r=o=T.BufferUtils.arrayBufferViewToBuffer(i.plugins.vcdiff.decode(o,t))}catch(e){throw new x("Vcdiff delta decode failed with "+e,40018,400)}continue;default:throw Error("Unknown encoding")}}}catch(e){s=new x(`Error processing the ${c} encoding, decoder returned \u2018${e.message}\u2019`,e.code||40013,400)}finally{a=e<=0?null:n.slice(0,e).join("/")}}return s?{error:s,data:o,encoding:a}:(i.baseEncodedPreviousPayload=r,{data:o,encoding:a})}function tl(...e){let t=e.length>0?"json":"msgpack",{data:n,encoding:s}=tc(this.data,this.encoding,t);return Object.assign({},this,{encoding:s,data:n})}
1function tc(e,t,n){return e&&T.BufferUtils.isBuffer(e)?"msgpack"===n?{data:T.BufferUtils.toBuffer(e),encoding:t}:{data:T.BufferUtils.base64Encode(e),encoding:t?t+"/base64":"base64"}:{data:e,encoding:t}}var th={encryptData:ts,encodeData:tr,encodeDataForWire:tc,decodeData:ta};function tu(e){let t,{id:n,connectionId:s,timestamp:i}=e;switch(e.action){case e6.MESSAGE:t=e.messages;break;case e6.PRESENCE:case e6.SYNC:t=e.presence;break;case e6.ANNOTATION:t=e.annotations;break;case e6.OBJECT:case e6.OBJECT_SYNC:t=e.state;break;default:throw new x("Unexpected action "+e.action,4e4,400)}for(let e=0;e<t.length;e++){let r=t[e];r.connectionId||(r.connectionId=s),r.timestamp||(r.timestamp=i),n&&!r.id&&(r.id=n+":"+e)}}function td(e,t){let n="["+t;for(let t in e)"data"===t?"string"==typeof e.data?n+="; data="+e.data:T.BufferUtils.isBuffer(e.data)?n+="; data (buffer)="+T.BufferUtils.base64Encode(e.data):void 0!==e.data&&(n+="; data (json)="+JSON.stringify(e.data)):t&&("extras"===t||"operation"===t)?n+="; "+t+"="+JSON.stringify(e[t]):"version"===t?n+="; version="+JSON.stringify(e[t]):"annotations"===t?n+="; annotations="+JSON.stringify(e[t]):void 0!==e[t]&&(n+="; "+t+"="+e[t]);return n+"]"}var tg=class{},tp=class{constructor(e){var t,n,s,i,r,o,a,l,c,h,u,d;this.Platform=T,this.ErrorInfo=x,this.Logger=L,this.Defaults=eN,this.Utils=N,this.EventEmitter=e3,this.MessageEncoding=th,this._additionalHTTPRequestImplementations=null!=(t=e.plugins)?t:null,this.logger=new L,this.logger.setLog(e.logLevel,e.logHandler),L.logAction(this.logger,L.LOG_MICRO,"BaseClient()","initialized with clientOptions "+T.Config.inspect(e)),this._MsgPack=null!=(s=null==(n=e.plugins)?void 0:n.MsgPack)?s:null;let g=this.options=eN.normaliseOptions(e,this._MsgPack,this.logger);if(g.key){let e=g.key.match(/^([^:\s]+):([^:.\s]+)$/);if(!e){let e="invalid key parameter";throw L.logAction(this.logger,L.LOG_ERROR,"BaseClient()",e),new x(e,40400,404)}g.keyName=e[1],g.keySecret=e[2]}if("clientId"in g){if("string"!=typeof g.clientId&&null!==g.clientId)throw new x("clientId must be either a string or null",40012,400);else if("*"===g.clientId)throw new x('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)}L.logAction(this.logger,L.LOG_MINOR,"BaseClient()","started; version = "+eN.version),this._currentFallback=null,this.serverTimeOffset=null,this.http=new e2(this),this.auth=new e0(this,g),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!=(l=null==(a=e.plugins)?void 0:a.MessageInteractions)?l:null,this._Annotations=null!=(h=null==(c=e.plugins)?void 0:c.Annotations)?h:null,this._liveObjectsPlugin=null!=(d=null==(u=e.plugins)?void 0:u.LiveObjects)?d:null}get rest(){return this._rest||eI("Rest"),this._rest}get _FilteredSubscriptions(){return this.__FilteredSubscriptions||eI("MessageInteractions"),this.__FilteredSubscriptions}get channels(){return this.rest.channels}get push(){return this.rest.push}device(){var e;return(null==(e=this.options.plugins)?void 0:e.Push)&&this.push.LocalDevice||eI("Push"),this._device||(this._device=this.push.LocalDevice.load(this)),this._device}baseUri(e){return eN.getHttpScheme(this.options)+e+":"+eN.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){this.logger.setLog(e.level,e.handler)}async getTimestamp(e){return!this.isTimeOffsetSet()&&e?this.time():this.getTimestampUsingOffset()}getTimestampUsingOffset(){return Date.now()+(this.serverTimeOffset||0)}isTimeOffsetSet(){return null!==this.serverTimeOffset}};tp.Platform=T;var tf=tp,tm=class e{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+=";
1 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 ev(e,t,n)}static fromResponseBody(t,n,s){return(s&&(t=ey(t,n,s)),Array.isArray(t))?e.fromValuesArray(t):e.fromValues(t)}static fromValues(t){return t.error=t.error&&x.fromValues(t.error),Object.assign(new e,t)}static fromLocalDevice(t){return Object.assign(new e,t)}static fromValuesArray(t){let n=t.length,s=Array(n);for(let i=0;i<n;i++)s[i]=e.fromValues(t[i]);return s}};async function ty(e,t,n,s){return e.http.supportsAuthHeaders?s(B(await e.auth.getAuthHeaders(),t),n):s(t,B(await e.auth.getAuthParams(),n))}var tv=class e{static async get(t,n,s,i,r,o){return e.do(eJ.Get,t,n,null,s,i,r,null!=o&&o)}static async delete(t,n,s,i,r,o){return e.do(eJ.Delete,t,n,null,s,i,r,o)}static async post(t,n,s,i,r,o,a){return e.do(eJ.Post,t,n,s,i,r,o,a)}static async patch(t,n,s,i,r,o,a){return e.do(eJ.Patch,t,n,s,i,r,o,a)}static async put(t,n,s,i,r,o,a){return e.do(eJ.Put,t,n,s,i,r,o,a)}static async do(e,t,n,s,i,r,o,a){var l,c;o&&((r=r||{}).envelope=o);let h=t.logger;async function u(i,r){var o;if(h.shouldLog(L.LOG_MICRO)){let a=s;if((null==(o=i["content-type"])?void 0:o.indexOf("msgpack"))>0)try{t._MsgPack||eI("MsgPack"),a=t._MsgPack.decode(s)}catch(t){L.logAction(h,L.LOG_MICRO,"Resource."+e+"()","Sending MsgPack Decoding Error: "+eh(t))}L.logAction(h,L.LOG_MICRO,"Resource."+e+"()","Sending; "+e4(n,r)+"; Body: "+a)}let a=await t.http.do(e,n,i,s,r);return a.error&&e0.isTokenErr(a.error)?(await t.auth.authorize(null,null),ty(t,i,r,u)):{err:a.error,body:a.body,headers:a.headers,unpacked:a.unpacked,statusCode:a.statusCode}}let d=await ty(t,i,r,u);if(o&&(d=function(e,t,n){if(e.err&&!e.body)return{err:e.err};if(e.statusCode===ez.NoContent)return C(w({},e),{body:[],unpacked:!0});let s=e.body;if(!e.unpacked)try{s=ey(s,t,n)}catch(e){if(el(e))return{err:e};return{err:new G(eh(e),null)}}if(!s)return{err:new G("unenvelope(): Response body is missing",null)};let{statusCode:i,response:r,headers:o}=s;if(void 0===i)return C(w({},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}}(d,t._MsgPack,o)),h.shouldLog(L.LOG_MICRO)&&(l=d,c=r,l.err?L.logAction(h,L.LOG_MICRO,"Resource."+e+"()","Received Error; "+e4(n,c)+"; Error: "+eh(l.err)):L.logAction(h,L.LOG_MICRO,"Resource."+e+"()","Received; "+e4(n,c)+"; Headers: "+e1(l.headers)+"; StatusCode: "+l.statusCode+"; Body: "+(T.BufferUtils.isBuffer(l.body)?" (Base64): "+T.BufferUtils.base64Encode(l.body):": "+T.Config.inspect(l.body)))),a)if(d.err)throw d.err;else{let e=w({},d);return delete e.err,e}return d}},tb=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}get logger(){return this.client.logger}async get(e){let t=await tv.get(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async delete(e){let t=await tv.delete(this.client,this.path,this.headers,e,this.envelope,!1);return this.handlePage(t)}async post(e,t){let n=await tv.post(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async put(e,t){let n=await tv.put(this.client,this.path,t,this.headers,e,this.envelope,!1);return this.handlePage(n)}async patch(e,t){let n=await tv.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 L.logAction(this.logger,L.LOG_ERROR,"PaginatedResource.handlePage()","Unexpected error getting resource: err = "+eh(e.err)),e.err;try{s=e.statusCode==ez.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]&&ea(t[2])}(s[1]);e&&(t[s[2]]=e)}}return t}(i)),this.useHttpPaginatedResponse)?new tw(this,s,e.headers||{},e.statusCode,r,e.err):new tO(this,s,r)}},tO=class{constructor(e,t,n){this.resource=e,this.items=t,this._relParams=n}async first(){if(this.hasFirst())return this.get(this._relParams.first);throw new x("No link to the first page of results",40400,404)}async current(){if(this.hasCurrent())return this.get(this._relParams.current);throw new x("No link to the current page of results",40400,404)}async next(){return this.hasNext()?this.get(this._relParams.next):null}hasFirst(){return null!=this._relParams&&"first"in this._relParams}hasCurrent(){return null!=this._relParams&&"current"in this._relParams}hasNext(){return null!=this._relParams&&"next"in this._relParams}isLast(){return!this.hasNext()}async get(e){let t=this.resource,n=await tv.get(t.client,t.path,t.headers,e,t.envelope,!1);return t.handlePage(n)}}
1,tw=class extends tO{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,this.errorDetail=null==r?void 0:r.detail}toJSON(){return{items:this.items,statusCode:this.statusCode,success:this.success,headers:this.headers,errorCode:this.errorCode,errorMessage:this.errorMessage,errorDetail:this.errorDetail}}},tC=class e{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(t,n,s){return(s&&(t=ey(t,n,s)),Array.isArray(t))?e.fromValuesArray(t):e.fromValues(t)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){let n=t.length,s=Array(n);for(let i=0;i<n;i++)s[i]=e.fromValues(t[i]);return s}};tC.toRequestBody=ev;var tR=class{constructor(e){var t;this.client=e,this.admin=new tA(e),T.Config.push&&(null==(t=e.options.plugins)?void 0:t.Push)&&(this.stateMachine=new e.options.plugins.Push.ActivationStateMachine(e),this.LocalDevice=e.options.plugins.Push.localDeviceFactory(tm))}async activate(e,t){await new Promise((n,s)=>{var i;return(null==(i=this.client.options.plugins)?void 0:i.Push)?this.stateMachine?this.stateMachine.activatedCallback?void s(new x("Activation already in progress",4e4,400)):void(this.stateMachine.activatedCallback=e=>{if(e)return void s(e);n()},this.stateMachine.updateFailedCallback=t,this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledActivate(this.stateMachine,e))):void s(new x("This platform is not supported as a target of push notifications",4e4,400)):void s(e_("Push"))})}async deactivate(e){await new Promise((t,n)=>{var s;return(null==(s=this.client.options.plugins)?void 0:s.Push)?this.stateMachine?this.stateMachine.deactivatedCallback?void n(new x("Deactivation already in progress",4e4,400)):void(this.stateMachine.deactivatedCallback=e=>{if(e)return void n(e);t()},this.stateMachine.handleEvent(new this.client.options.plugins.Push.CalledDeactivate(this.stateMachine,e))):void n(new x("This platform is not supported as a target of push notifications",4e4,400)):void n(e_("Push"))})}},tA=class{constructor(e){this.client=e,this.deviceRegistrations=new tk(e),this.channelSubscriptions=new tS(e)}async publish(e,t){let n=this.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=eN.defaultPostHeaders(n.options),r={},o=B({recipient:e},t);B(i,n.options.headers),n.options.pushFullWait&&B(r,{fullWait:"true"});let a=ev(o,n._MsgPack,s);await tv.post(n,"/push/publish",a,i,r,null,!0)}},tk=class{constructor(e){this.client=e}async save(e){let t=this.client,n=tm.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=eN.defaultPostHeaders(t.options),r={};B(i,t.options.headers),t.options.pushFullWait&&B(r,{fullWait:"true"});let o=ev(n,t._MsgPack,s),a=await tv.put(t,"/push/deviceRegistrations/"+encodeURIComponent(e.id),o,i,r,null,!0);return tm.fromResponseBody(a.body,t._MsgPack,a.unpacked?void 0:s)}async get(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=eN.defaultGetHeaders(t.options),i=e.id||e;if("string"!=typeof i||!i.length)throw new x("First argument to DeviceRegistrations#get must be a deviceId string or DeviceDetails",4e4,400);B(s,t.options.headers);let r=await tv.get(t,"/push/deviceRegistrations/"+encodeURIComponent(i),s,{},null,!0);return tm.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=eN.defaultGetHeaders(t.options);return B(i,t.options.headers),new tb(t,"/push/deviceRegistrations",i,s,async function(e,s,i){return tm.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async remove(e){let t=this.client,n=eN.defaultGetHeaders(t.options),s={},i=e.id||e;if("string"!=typeof i||!i.length)throw new x("First argument to DeviceRegistrations#remove must be a deviceId string or DeviceDetails",4e4,400);B(n,t.options.headers),t.options.pushFullWait&&B(s,{fullWait:"true"}),await tv.delete(t,"/push/deviceRegistrations/"+encodeURIComponent(i),n,s,null,!0)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=eN.defaultGetHeaders(t.options,{format:n});B(s,t.options.headers),t.options.pushFullWait&&B(e,{fullWait:"true"}),await tv.delete(t,"/push/deviceRegistrations",s,e,null,!0)}},tS=class e{constructor(t){this.remove=e.prototype.removeWhere,this.client=t}async save(e){let t=this.client,n=tC.fromValues(e),s=t.options.useBinaryProtocol?"msgpack":"json",i=eN.defaultPostHeaders(t.options),r={};B(i,t.options.headers),t.options.pushFullWait&&B(r,{fullWait:"true"});let o=ev(n,t._MsgPack,s),a=await tv.post(t,"/push/channelSubscriptions",o,i,r,null,!0);return tC.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=eN.defaultGetHeaders(t.options);return B(i,t.options.headers),new tb(t,"/push/channelSubscriptions",i,s,async function(e,s,i){return tC.fromResponseBody(e,t._MsgPack,i?void 0:n)}).get(e)}async removeWhere(e){let t=this.client,n=t.options.useBinaryProtocol?"msgpack":"json",s=eN.defaultGetHeaders(t.options,{format:n});B(s,t.options.headers),t.options.pushFullWait&&B(e,{fullWait:"true"}),await tv.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=eN.defaultGetHeaders(t.options);return B(i,t.options.headers),t.options.pushFullWait&&B(e,{fullWait:"true"}),new tb(t,"/push/channels",i,s,async function(e,s,i){let r=!i&&n?ey(e,t._MsgPack,n):e;for(let e=0;e<r.length;e++)r[e]=String(r[e]);return r}).get(e)}},tM=["absent","present","enter","leave","update"];async function tT(e,t,n,s){let i=tt(t,e,null!=s?s:null);return tL.fromValues(n).decode(i,e)}async function t_(e,t,n,s){return Promise.all(n.map(function(n){return tT(e,t,n,s)}))}async function tI(e,t){return tL.fromValues(e).decode(t.channelOptions,t.logger)}async function tP(e,t){return Promise.all(e.map(function(e){return tI(e,t)}))}var tE=class e extends tg{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)}}async encode(e){return ti(Object.assign(new tL,this,{action:tM.indexOf(this.action||"present")}),e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}static fromData(t){return t instanceof e?t:e.fromValues({data:t})}toString(){return td(this,"PresenceMessage")}},tL=class e extends tg{toJSON(...e){return tl.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}
1async decode(e,t){let n=Object.assign(new tE,C(w({},this),{action:tM[this.action]}));try{await to(n,e)}catch(e){L.logAction(t,L.LOG_ERROR,"WirePresenceMessage.decode()",eh(e))}return n}toString(){return td(this,"WirePresenceMessage")}},tN=tE,tU=class{constructor(e){this.channel=e}get logger(){return this.channel.logger}async get(e){L.logAction(this.logger,L.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=eN.defaultGetHeaders(t.options);return B(i,t.options.headers),new tb(t,this.channel.client.rest.presenceMixin.basePath(this),i,s,async(e,s,i)=>tP(i?e:ey(e,t._MsgPack,n),this.channel)).get(e)}async history(e){return L.logAction(this.logger,L.LOG_MICRO,"RestPresence.history()","channel = "+this.channel.name),this.channel.client.rest.presenceMixin.history(this,e)}},tx=["message.create","message.update","message.delete","meta","message.summary","message.append"];async function tG(e,t,n,s){let i=tt(t,e,null!=s?s:null);return tF.fromValues(n).decode(i,e)}async function tB(e,t,n,s){return Promise.all(n.map(function(n){return tG(e,t,n,s)}))}async function tq(e,t){return tF.fromValues(e).decode(t.channelOptions,t.logger)}async function tD(e,t){return Promise.all(e.map(function(e){return tq(e,t)}))}async function tj(e,t){return Promise.all(e.map(e=>e.encode(t)))}var tH=ev;function tV(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+=ed(e.data)),t}(t));return n}var tW=class e extends tg{expandFields(){if(this.version||(this.version={}),!this.version.serial&&this.serial&&(this.version.serial=this.serial),!this.version.timestamp&&this.timestamp&&(this.version.timestamp=this.timestamp),this.annotations?this.annotations.summary||(this.annotations.summary={}):this.annotations={summary:{}},this.annotations&&this.annotations.summary)for(let[e,t]of Object.entries(this.annotations.summary))if(e.endsWith(":distinct.v1")||e.endsWith(":unique.v1")||e.endsWith(":multiple.v1"))for(let[,e]of Object.entries(t))e.clipped||(e.clipped=!1);else e.endsWith(":flag.v1")&&!t.clipped&&(t.clipped=!1)}async encode(e){return ti(Object.assign(new tF,this,{action:tx.indexOf(this.action||"message.create")}),e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}toString(){return td(this,"Message")}},tF=class e extends tg{toJSON(...e){return tl.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decodeWithErr(e,t){let n,s=Object.assign(new tW,C(w({},this),{action:tx[this.action||0]||"unknown"}));try{await to(s,e)}catch(e){L.logAction(t,L.LOG_ERROR,"WireMessage.decode()",eh(e)),n=e}return s.expandFields(),{decoded:s,err:n}}async decode(e,t){let{decoded:n}=await this.decodeWithErr(e,t);return n}toString(){return td(this,"WireMessage")}},tJ=tW,tz=class{constructor(e,t,n){var s,i;this._annotations=null,L.logAction(e.logger,L.LOG_MINOR,"RestChannel()","started; name = "+t),this.name=t,this.client=e,this.presence=new tU(this),this.channelOptions=eH(null!=(s=e._Crypto)?s:null,this.logger,n),(null==(i=e.options.plugins)?void 0:i.Push)&&(this._push=new e.options.plugins.Push.PushChannel(this)),e._Annotations&&(this._annotations=new e._Annotations.RestAnnotations(this)),e._liveObjectsPlugin&&(this._object=new e._liveObjectsPlugin.RestObject(this))}get annotations(){return this._annotations||eI("Annotations"),this._annotations}get push(){return this._push||eI("Push"),this._push}get object(){return this._object||eI("LiveObjects"),this._object}get logger(){return this.client.logger}setOptions(e){var t;this.channelOptions=eH(null!=(t=this.client._Crypto)?t:null,this.logger,e)}async history(e){return L.logAction(this.logger,L.LOG_MICRO,"RestChannel.history()","channel = "+this.name),this.client.rest.channelMixin.history(this,e)}async publish(...e){let t,n,s=e[0],i=e[1];if("string"==typeof s||null===s)t=[tJ.fromValues({name:s,data:i})],n=e[2];else if(j(s))t=[tJ.fromValues(s)],n=e[1];else if(Array.isArray(s))t=tJ.fromValuesArray(s),n=e[1];else throw new x("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",l=r.options.idempotentRestPublishing,c=eN.defaultPostHeaders(r.options);if(B(c,o.headers),l&&t.every(function(e){return!e.id})){let e=await ep(9);t.forEach(function(t,n){t.id=e+":"+n.toString()})}let h=await tj(t,this.channelOptions),u=tV(h),d=o.maxMessageSize;if(u>d)throw new x(`Maximum size of messages that can be published at once exceeded (was ${u} bytes; limit is ${d} bytes)`,40009,400);return this._publish(tH(h,r._MsgPack,a),c,n)}async _publish(e,t,n){let s=this.client,i=s.options.useBinaryProtocol?"msgpack":"json",{body:r,unpacked:o}=await tv.post(s,s.rest.channelMixin.basePath(this)+"/messages",e,t,n,null,!0),a=(o?r:ey(r,s._MsgPack,i))||{};return delete a.channel,delete a.messageId,a}async status(){return this.client.rest.channelMixin.status(this)}
1async getMessage(e){return L.logAction(this.logger,L.LOG_MICRO,"RestChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,e)}async updateMessage(e,t,n){return L.logAction(this.logger,L.LOG_MICRO,"RestChannel.updateMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.update",e,t,n)}async deleteMessage(e,t,n){return L.logAction(this.logger,L.LOG_MICRO,"RestChannel.deleteMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.delete",e,t,n)}async appendMessage(e,t,n){return L.logAction(this.logger,L.LOG_MICRO,"RestChannel.appendMessage()","channel = "+this.name),this.client.rest.channelMixin.updateDeleteMessage(this,"message.append",e,t,n)}async getMessageVersions(e,t){return L.logAction(this.logger,L.LOG_MICRO,"RestChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,e,t)}},tK=class e{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(t){return new e(t)}},t$=class{static basePath(e){return"/channels/"+encodeURIComponent(e.name)}static history(e,t){let n=e.client,s=n.options.useBinaryProtocol?"msgpack":"json",i=e.client.http.supportsLinkHeaders?void 0:s,r=eN.defaultGetHeaders(n.options);return B(r,n.options.headers),new tb(n,this.basePath(e)+"/messages",r,i,async function(t,i,r){return tD(r?t:ey(t,n._MsgPack,s),e)}).get(t)}static async status(e){let t=e.client.options.useBinaryProtocol?"msgpack":"json",n=eN.defaultPostHeaders(e.client.options);return(await tv.get(e.client,this.basePath(e),n,{},t,!0)).body}static async getMessage(e,t){let n="string"==typeof t?t:t.serial;if(!n)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let s=e.client,i=s.options.useBinaryProtocol?"msgpack":"json",r=eN.defaultGetHeaders(s.options);B(r,s.options.headers);let{body:o,unpacked:a}=await tv.get(s,this.basePath(e)+"/messages/"+encodeURIComponent(n),r,{},null,!0);return tq(a?o:ey(o,s._MsgPack,i),e)}static async updateDeleteMessage(e,t,n,s,i){if(!n.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let r=e.client,o=r.options.useBinaryProtocol?"msgpack":"json",a=eN.defaultPostHeaders(r.options);B(a,r.options.headers);let l=tJ.fromValues(n);l.action=t,l.version=s;let c=tH(await l.encode(e.channelOptions),r._MsgPack,o),h=tv.patch,{body:u,unpacked:d}=await h(r,this.basePath(e)+"/messages/"+encodeURIComponent(n.serial),c,a,i||{},null,!0);return(d?u:ey(u,r._MsgPack,o))||{versionSerial:null}}static getMessageVersions(e,t,n){let s="string"==typeof t?t:t.serial;if(!s)throw new x('This message lacks a serial. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);let i=e.client,r=i.options.useBinaryProtocol?"msgpack":"json",o=e.client.http.supportsLinkHeaders?void 0:r,a=eN.defaultGetHeaders(i.options);return B(a,i.options.headers),new tb(i,this.basePath(e)+"/messages/"+encodeURIComponent(s)+"/versions",a,o,async(t,n,s)=>tD(s?t:ey(t,i._MsgPack,r),e)).get(n||{})}},tQ=class{static basePath(e){return t$.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=eN.defaultGetHeaders(n.options);return B(r,n.options.headers),new tb(n,this.basePath(e)+"/history",r,i,async(t,i,r)=>tP(r?t:ey(t,n._MsgPack,s),e.channel)).get(t)}},tX=class{constructor(e){this.channelMixin=t$,this.presenceMixin=tQ,this.Resource=tv,this.PaginatedResource=tb,this.DeviceDetails=tm,this.PushChannelSubscription=tC,this.client=e,this.channels=new tY(this.client),this.push=new tR(this.client)}async stats(e){let t=eN.defaultGetHeaders(this.client.options),n=this.client.options.useBinaryProtocol?"msgpack":"json",s=this.client.http.supportsLinkHeaders?void 0:n;return B(t,this.client.options.headers),new tb(this.client,"/stats",t,s,async(e,t,s)=>{let i=s?e:ey(e,this.client._MsgPack,n);for(let e=0;e<i.length;e++)i[e]=tK.fromValues(i[e]);return i}).get(e)}async time(e){let t=eN.defaultGetHeaders(this.client.options,{format:"json"});this.client.options.headers&&B(t,this.client.options.headers);let{error:n,body:s,unpacked:i}=await this.client.http.do(eJ.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 x("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,l,c]=this.client.options.useBinaryProtocol?(this.client._MsgPack||eI("MsgPack"),[this.client._MsgPack.encode,this.client._MsgPack.decode,"msgpack"]):[JSON.stringify,JSON.parse,"json"],h=this.client.http.supportsLinkHeaders?void 0:c;s=s||{};let u=e.toLowerCase(),d="get"==u?eN.defaultGetHeaders(this.client.options,{format:c,protocolVersion:n}):eN.defaultPostHeaders(this.client.options,{format:c,protocolVersion:n});"string"!=typeof i&&(i=null!=(o=a(i))?o:null),B(d,this.client.options.headers),r&&B(d,r);let g=new tb(this.client,t,d,h,async function(e,t,n){return D(n?e:l(e))},!0);if(!T.Http.methods.includes(u))throw new x("Unsupported method "+u,40500,405);return T.Http.methodsWithBody.includes(u)?g[u](s,i):g[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=eN.defaultPostHeaders(this.client.options);this.client.options.headers&&B(i,this.client.options.headers);let r=ev(t,this.client._MsgPack,s),o=await tv.post(this.client,"/messages",r,i,{},null,!0),a=o.unpacked?o.body:ey(o.body,this.client._MsgPack,s);return n?a[0]:a}async batchPresence(e){let t=this.client.options.useBinaryProtocol?"msgpack":"json",n=eN.defaultGetHeaders(this.client.options);this.client.options.headers&&B(n,this.client.options.headers);let s=e.join(","),i=await tv.get(this.client,"/presence",n,{channels:s},null,!0);return i.unpacked?i.body:ey(i.body,this.client._MsgPack,t)}async revokeTokens(e,t){if(eY(this.client.options))throw new x("Cannot revoke tokens when using token auth",40162,401);let n=this.client.options.keyName,s=w({targets:e.map(e=>`${e.type}:${e.value}`)},null!=t?t:{}),i=this.client.options.useBinaryProtocol?"msgpack":"json",r=eN.defaultPostHeaders(this.client.options);this.client.options.headers&&B(r,this.client.options.headers);let o=ev(s,this.client._MsgPack,i),a=await tv.post(this.client,`/keys/${n}/revokeTokens`,o,r,{},null,!0);return a.unpacked?a.body:ey(a.body,this.client._MsgPack,i)}},tY=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 tz(this.client,e,t),n}release(e){delete this.all[String(e)]}},tZ=class extends tf{constructor(e){super(eN.objectifyOptions(e,!1,"BaseRest",L.defaultLogger,{Rest:tX}))}},t0={Rest:tX},t1=class extends tJ{static async fromEncoded(e,t){return tG(L.defaultLogger,T.Crypto,e,t)}static async fromEncodedArray(e,t){return tB(L.defaultLogger,T.Crypto,e,t)}static fromValues(e){return tJ.fromValues(e)}},t4=class extends tN{static async fromEncoded(e,t){return tT(L.defaultLogger,T.Crypto,e,t)}static async fromEncodedArray(e,t){return t_(L.defaultLogger,T.Crypto,e,t)}static fromValues(e){return tN.fromValues(e)}},t2=["annotation.create","annotation.delete"];async function t8(e,t,n){return t7.fromValues(t).decode(n||{},e)}async function t3(e,t,n){return Promise.all(t.map(function(t){return t8(e,t,n)}))}async function t6(e,t){return t7.fromValues(e).decode(t.channelOptions,t.logger)}async function t5(e,t){return Promise.all(e.map(function(e){return t6(e,t)}))}var t9=class e extends tg{async encode(){return ti(Object.assign(new t7,this,{action:t2.indexOf(this.action||"annotation.create")}),{})}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}toString(){return td(this,"Annotation")}},t7=class e extends tg{toJSON(...e){return tl.call(this,...e)}static fromValues(t){return Object.assign(new e,t)}static fromValuesArray(t){return t.map(t=>e.fromValues(t))}async decode(e,t){let n=Object.assign(new t9,C(w({},this),{action:t2[this.action]}));try{await to(n,e)}catch(e){L.logAction(t,L.LOG_ERROR,"WireAnnotation.decode()",eh(e))}return n}toString(){return td(this,"WireAnnotation")}},ne=t9,nt=class extends ne{static async fromEncoded(e,t){return t8(L.defaultLogger,e,t)}static async fromEncodedArray(e,t){return t3(L.defaultLogger,e,t)}static fromValues(e){return ne.fromValues(e)}};function nn(e){let t;switch(typeof e){case"string":t=e;break;case"object":t=e.serial}if(!t||"string"!=typeof t)throw new x("First argument of annotations.publish() must be either a Message (or at least an object with a string `serial` property) or a message serial (string)",40003,400);return t}function ns(e,t){let n=nn(e);if(!t||"object"!=typeof t)throw new x("Second argument of annotations.publish() must be an object (the intended annotation to publish)",40003,400);let s=ne.fromValues(t);return s.messageSerial=n,s.action||(s.action="annotation.create"),s}function ni(e,t){return e.client.rest.channelMixin.basePath(e)+"/messages/"+encodeURIComponent(t)+"/annotations"}var nr=class{constructor(e){this.channel=e}async publish(e,t){let n=ns(e,t),s=await n.encode(),i=this.channel.client,r=i.options.useBinaryProtocol?"msgpack":"json",o=eN.defaultPostHeaders(i.options);B(o,i.options.headers);let a=ev([s],i._MsgPack,r);await tv.post(i,ni(this.channel,n.messageSerial),a,o,{},null,!0)}async delete(e,t){return t.action="annotation.delete",this.publish(e,t)}async get(e,t){let n=this.channel.client,s=nn(e),i=n.options.useBinaryProtocol?"msgpack":"json",r=n.http.supportsLinkHeaders?void 0:i,o=eN.defaultGetHeaders(n.options);return B(o,n.options.headers),new tb(n,ni(this.channel,s),o,r,async(e,t,s)=>t5(s?e:ey(e,n._MsgPack,i),this.channel)).get(t)}};function no(e){let t=[];if(e)for(let n=0;n<e.length;n++)t.push(e[n].toString());return"[ "+t.join(", ")+" ]"}function na(e,t,n,s){let i,r,o,a,l;return e.error&&(i=x.fromValues(e.error)),e.messages&&(r=tF.fromValuesArray(e.messages)),t&&e.presence&&(o=t.WirePresenceMessage.fromValuesArray(e.presence)),n&&e.annotations&&(a=n.WireAnnotation.fromValuesArray(e.annotations)),s&&e.state&&(l=s.WireOb
1jectMessage.fromValuesArray(e.state,N,th)),Object.assign(new nu,C(w({},e),{presence:o,messages:r,annotations:a,state:l,error:i}))}function nl(e){return t=>{var n;return na(t,{PresenceMessage:tN,WirePresenceMessage:tL},{Annotation:ne,WireAnnotation:t7,RealtimeAnnotations:nf,RestAnnotations:nr},null!=(n=null==e?void 0:e.LiveObjectsPlugin)?n:null)}}function nc(e){return Object.assign(new nu,e)}function nh(e,t,n,s){let i,r="[ProtocolMessage";void 0!==e.action&&(r+="; action="+e5[e.action]);let o=["id","channel","channelSerial","connectionId","count","msgSerial","timestamp"];for(let t=0;t<o.length;t++)void 0!==e[i=o[t]]&&(r+="; "+i+"="+e[i]);if(e.messages&&(r+="; messages="+no(tF.fromValuesArray(e.messages))),e.presence&&t&&(r+="; presence="+no(t.WirePresenceMessage.fromValuesArray(e.presence))),e.annotations&&n&&(r+="; annotations="+no(n.WireAnnotation.fromValuesArray(e.annotations))),e.state&&s&&(r+="; state="+no(s.WireObjectMessage.fromValuesArray(e.state,N,th))),e.error&&(r+="; error="+x.fromValues(e.error).toString()),e.auth&&e.auth.accessToken&&(r+="; token="+e.auth.accessToken),e.flags&&(r+="; flags="+e7.filter(e.hasFlag).join(",")),e.params){let t="";et(e.params,function(n){t.length>0&&(t+="; "),t+=n+"="+e.params[n]}),t.length>0&&(r+="; params=["+t+"]")}return r+"]"}var nu=class{constructor(){this.hasFlag=e=>(this.flags&e9[e])>0}setFlag(e){return this.flags=this.flags|e9[e]}getMode(){return(this.flags||0)&e9.MODE_ALL}encodeModesToFlags(e){e.forEach(e=>this.setFlag(e))}decodeModesFromFlags(){let e=[];return te.forEach(t=>{this.hasFlag(t)&&e.push(t)}),e.length>0?e:void 0}},nd=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)}},ng=class e extends e3{constructor(e,t,n){var s,i;super(e.logger),this._annotations=null,this._mode=0,this.retryCount=0,this.history=function(...e){return ec(e,0),this._historyImpl(e[0])},this._historyImpl=async function(e){L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.history()","channel = "+this.name);let t=this.client.rest.channelMixin;if(e&&e.untilAttach){if("attached"!==this.state)throw new x("option untilAttach requires the channel to be attached",4e4,400);if(!this.properties.attachSerial)throw new x("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=>e3.prototype.whenState.call(this,e,this.state),L.logAction(this.logger,L.LOG_MINOR,"RealtimeChannel()","started; name = "+t),this.name=t,this.channelOptions=eH(null!=(s=e._Crypto)?s:null,this.logger,n),this.client=e,this._presence=e._RealtimePresence?new e._RealtimePresence.RealtimePresence(this):null,e._Annotations&&(this._annotations=new e._Annotations.RealtimeAnnotations(this)),this.connectionManager=e.connection.connectionManager,this.state="initialized",this.subscriptions=new e3(this.logger),this.syncChannelSerial=void 0,this.properties={attachSerial:void 0,channelSerial:void 0},this.setOptions(n),this.errorReason=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._attachedReceived=new e3(this.logger),this.internalStateChanges=new e3(this.logger),(null==(i=e.options.plugins)?void 0:i.Push)&&(this._push=new e.options.plugins.Push.PushChannel(this)),e._liveObjectsPlugin&&(this._object=new e._liveObjectsPlugin.RealtimeObject(this))}get presence(){return this._presence||eI("RealtimePresence"),this._presence}get annotations(){return this._annotations||eI("Annotations"),this._annotations}get push(){return this._push||eI("Push"),this._push}get object(){return this._object||eI("LiveObjects"),this._object}emit(e,...t){super.emit(e,...t),this.internalStateChanges.emit(e,...t)}invalidStateError(){return new x("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&&!j(e.params))return new x("options.params must be an object",4e4,400);if(e&&"modes"in e){if(!Array.isArray(e.modes))return new x("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||!te.includes(String.prototype.toUpperCase.call(n)))return new x("Invalid channel mode: "+n,4e4,400)}}}(e);if(s)throw s;if(this.channelOptions=eH(null!=(t=this.client._Crypto)?t:null,this.logger,e),this._decodingContext&&(this._decodingContext.channelOptions=this.channelOptions),this._shouldReattachToSetOptions(e,n))return this.attachImpl(),new Promise((e,t)=>
1{let n=()=>{this._attachedReceived.off(s),this.internalStateChanges.off(i)},s=()=>{n(),e()},i=e=>{n(),t(e.reason)};this._attachedReceived.once("attached",s),this.internalStateChanges.once(["detached","failed"],i)})}_shouldReattachToSetOptions(e,t){if("attached"!==this.state&&"attaching"!==this.state)return!1;if(null==e?void 0:e.params){let n=np(e.params),s=np(t.params);if(Object.keys(n).length!==Object.keys(s).length||!ek(s,n))return!0}return!(null==e||!e.modes||t.modes&&eT(e.modes,t.modes))}publish(...e){return ec(e,0),this._publishImpl(e)}async _publishImpl(e){let t,n,s=e[0],i=e[1];if("string"==typeof s||null==s)t=[tJ.fromValues({name:s,data:i})],n=e[2];else if(j(s))t=[tJ.fromValues(s)],n=e[1];else if(Array.isArray(s))t=tJ.fromValuesArray(s),n=e[1];else throw new x("The single-argument form of publish() expects a message object or an array of message objects",40013,400);let r=this.client.options.maxMessageSize,o=await tj(t,this.channelOptions),a=tV(o);if(a>r)throw new x(`Maximum size of messages that can be published at once exceeded (was ${a} bytes; limit is ${r} bytes)`,40009,400);this.throwIfUnpublishableState(),L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.publish()","sending message; channel state is "+this.state+", message count = "+o.length);let l=nc({action:e6.MESSAGE,channel:this.name,messages:o,params:n?eo(n):void 0});return this.sendAndAwaitAck(l)}throwIfUnpublishableState(){if(!this.connectionManager.activeState())throw this.connectionManager.getError();if("failed"===this.state||"suspended"===this.state)throw this.invalidStateError()}onEvent(e){L.logAction(this.logger,L.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=e=>{e&&L.logAction(this.logger,L.LOG_ERROR,"RealtimeChannel._attach()","Channel attach failed: "+e.toString())});let s=this.connectionManager;if(!s.activeState())return void n(s.getError());("attaching"!==this.state||e)&&this.requestState("attaching",t),this.internalStateChanges.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 x("Unable to attach; reason unknown; state = "+this.event,9e4,500));break;case"detaching":null==n||n(new x("Attach request superseded by a subsequent detach request",9e4,409))}})}attachImpl(){L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.attachImpl()","sending ATTACH message");let e=nc({action:e6.ATTACH,channel:this.name,params:this.channelOptions.params,channelSerial:this.properties.channelSerial});this.channelOptions.modes&&e.encodeModesToFlags(eO(this.channelOptions.modes)),this._attachResume&&e.setFlag("ATTACH_RESUME"),this._lastPayload.decodeFailureRecoveryInProgress&&(e.channelSerial=this._lastPayload.protocolMessageChannelSerial),this.send(e)}async detach(){let e=this.connectionManager;switch(this.state){case"suspended":this.notifyState("detached");return;case"detached":return;case"failed":throw new x("Unable to detach; channel state = failed",90001,400);default:if("connected"!==e.state.state)return void this.notifyState("detached");this.requestState("detaching");case"detaching":return new Promise((t,n)=>{this.internalStateChanges.once(function(s){switch(this.event){case"detached":t();break;case"attached":case"suspended":case"failed":n(s.reason||e.getError()||new x("Unable to detach; reason unknown; state = "+this.event,9e4,500));break;case"attaching":n(new x("Detach request superseded by a subsequent attach request",9e4,409))}})})}}detachImpl(){L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.detach()","sending DETACH message");let e=nc({action:e6.DETACH,channel:this.name});this.send(e)}subscribe(...e){return ec(e,2),this._subscribeImpl(e)}async _subscribeImpl(t){let[n,s]=e.processListenerArgs(t);if("failed"===this.state)throw x.fromValues(this.invalidStateError());return(n&&"object"==typeof n&&!Array.isArray(n)?this.client._FilteredSubscriptions.subscribeFilter(this,n,s):this.subscriptions.on(n,s),!1!==this.channelOptions.attachOnSubscribe)?this.attach():null}
1unsubscribe(...t){var n;let[s,i]=e.processListenerArgs(t);if("object"==typeof s&&!i||(null==(n=this.filteredSubscriptions)?void 0:n.has(i)))return void this.client._FilteredSubscriptions.getAndDeleteFilteredSubscriptions(this,s,i).forEach(e=>this.subscriptions.off(e));this.subscriptions.off(s,i)}sync(){switch(this.state){case"initialized":case"detaching":case"detached":throw new G("Unable to sync to channel; not attached",4e4)}let e=this.connectionManager;if(!e.activeState())throw e.getError();let t=nc({action:e6.SYNC,channel:this.name});this.syncChannelSerial&&(t.channelSerial=this.syncChannelSerial),e.send(t)}send(e){this.connectionManager.send(e)}async sendAndAwaitAck(e){return new Promise((t,n)=>{this.connectionManager.send(e,this.client.options.queueMessages,(e,s)=>{e?n(e):t(s)})})}async sendPresence(e){let t=nc({action:e6.PRESENCE,channel:this.name,presence:e});await this.sendAndAwaitAck(t)}async sendState(e){let t=nc({action:e6.OBJECT,channel:this.name,state:e});return this.sendAndAwaitAck(t)}async processMessage(e){(e.action===e6.ATTACHED||e.action===e6.MESSAGE||e.action===e6.PRESENCE||e.action===e6.OBJECT||e.action===e6.ANNOTATION)&&this.setChannelSerial(e.channelSerial);let t,n=!1;switch(e.action){case e6.ATTACHED:{this.properties.attachSerial=e.channelSerial,this._mode=e.getMode(),this.params=e.params||{};let t=e.decodeModesFromFlags();this.modes=t&&eb(t)||void 0;let n=e.hasFlag("RESUMED"),s=e.hasFlag("HAS_PRESENCE"),i=e.hasFlag("HAS_BACKLOG"),r=e.hasFlag("HAS_OBJECTS");if(this._attachedReceived.emit("attached"),"attached"===this.state){!n&&this._presence&&this._presence.onAttached(s),this._object&&this._object.onAttached(r);let t=new nd(this.state,this.state,n,i,e.error);(!n||this.channelOptions.updateOnAttached)&&this.emit("update",t)}else"detaching"===this.state?this.checkPendingState():this.notifyState("attached",e.error,n,s,i,r);break}case e6.DETACHED:{let t=e.error?x.fromValues(e.error):new x("Channel detached",90001,404);"detaching"===this.state?this.notifyState("detached",t):"attaching"===this.state?this.notifyState("suspended",t):("attached"===this.state||"suspended"===this.state)&&this.requestState("attaching",t);break}case e6.SYNC:if(n=!0,t=this.syncChannelSerial=e.channelSerial,!e.presence)break;case e6.PRESENCE:{if(!e.presence)break;tu(e);let s=this.channelOptions;if(this._presence){let i=await Promise.all(e.presence.map(e=>e.decode(s,this.logger)));this._presence.setPresence(i,n,t)}break}case e6.OBJECT:case e6.OBJECT_SYNC:{if(!this._object||!e.state)return;tu(e);let t=this.client.connection.connectionManager.getActiveTransportFormat(),n=e.state.map(e=>e.decode(this.client,t));e.action===e6.OBJECT?this._object.handleObjectMessages(n):this._object.handleObjectSyncMessages(n,e.channelSerial);break}case e6.MESSAGE:{if("attached"!==this.state)return void L.logAction(this.logger,L.LOG_MAJOR,"RealtimeChannel.processMessage()",'Message "'+e.id+'" skipped as this channel "'+this.name+'" state is not "attached" (state is "'+this.state+'").');tu(e);let t=e.messages,n=t[0],s=t[t.length-1];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+'".';L.logAction(this.logger,L.LOG_ERROR,"RealtimeChannel.processMessage()",t),this._startDecodeFailureRecovery(new x(t,40018,400));break}let i=[];for(let e=0;e<t.length;e++){let{decoded:n,err:s}=await t[e].decodeWithErr(this._decodingContext,this.logger);if(i[e]=n,s)switch(s.code){case 40018:this._startDecodeFailureRecovery(s);return;case 40019:case 40021:this.notifyState("failed",s);return}}this._lastPayload.messageId=s.id,this._lastPayload.protocolMessageChannelSerial=e.channelSerial,this.onEvent(i);break}case e6.ANNOTATION:{tu(e);let t=this.channelOptions;if(this._annotations){let n=await Promise.all((e.annotations||[]).map(e=>e.decode(t,this.logger)));this._annotations._processIncoming(n)}break}case e6.ERROR:{let t=e.error;t&&80016==t.code?this.checkPendingState():this.notifyState("failed",x.fromValues(t));break}default:L.logAction(this.logger,L.LOG_MAJOR,"RealtimeChannel.processMessage()","Protocol error: unrecognised message action ("+e.action+")")}}_startDecodeFailureRecovery(e){this._lastPayload.decodeFailureRecoveryInProgress||(L.logAction(this.logger,L.LOG_MAJOR,"RealtimeChannel.processMessage()","Starting decode failure recovery process."),this._lastPayload.decodeFailureRecoveryInProgress=!0,this._attach(!0,e,()=>{this._lastPayload.decodeFailureRecoveryInProgress=!1}))}onAttached(){L.logAction(this.logger,L.LOG_MINOR,"RealtimeChannel.onAttached","activating channel; name = "+this.name)}notifyState(e,t,n,s,i,r){if(L.logAction(this.logger,L.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),this._object&&this._object.actOnChannelState(e,r),"suspended"===e&&this.connectionManager.state.sendEvents?this.startRetryTimer():this.cancelRetryTimer(),t&&(this.errorReason=t);let o=new nd(this.state,e,n,i,t),a='Channel state for channel "'+this.name+'"',l=e+(t?"; reason: "+t:"");"failed"===e?L.logAction(this.logger,L.LOG_ERROR,a,l):L.logAction(this.logger,L.LOG_MAJOR,a,l),"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.emit
1(e,o)}requestState(e,t){L.logAction(this.logger,L.LOG_MINOR,"RealtimeChannel.requestState","name = "+this.name+", state = "+e),this.notifyState(e,t),this.checkPendingState()}checkPendingState(){if(!this.connectionManager.state.sendEvents)return void L.logAction(this.logger,L.LOG_MINOR,"RealtimeChannel.checkPendingState","sendEvents is false; state is "+this.connectionManager.state.state);switch(L.logAction(this.logger,L.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 x("Channel attach timed out",90007,408);this.notifyState("suspended",e);break}case"detaching":{let e=new x("Channel detach timed out",90007,408);this.notifyState("attached",e);break}default:this.checkPendingState()}}startStateTimerIfNotRunning(){this.stateTimer||(this.stateTimer=setTimeout(()=>{L.logAction(this.logger,L.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=eR(this.client.options.timeouts.channelRetryTimeout,this.retryCount);this.retryTimer=setTimeout(()=>{"suspended"===this.state&&this.connectionManager.state.sendEvents&&(this.retryTimer=null,L.logAction(this.logger,L.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 x("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){L.logAction(this.logger,L.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)}async getMessage(e){return L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.getMessage()","channel = "+this.name),this.client.rest.channelMixin.getMessage(this,e)}async updateMessage(e,t,n){return L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.updateMessage()","channel = "+this.name),this.sendUpdate(e,"message.update",t,n)}async deleteMessage(e,t,n){return L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.deleteMessage()","channel = "+this.name),this.sendUpdate(e,"message.delete",t,n)}async appendMessage(e,t,n){return L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.appendMessage()","channel = "+this.name),this.sendUpdate(e,"message.append",t,n)}async sendUpdate(e,t,n,s){var i;if(!e.serial)throw new x('This message lacks a serial and cannot be updated. Make sure you have enabled "Message annotations, updates, and deletes" in channel settings on your dashboard.',40003,400);this.throwIfUnpublishableState();let r=tJ.fromValues(C(w({},e),{action:t,version:n})),o=await r.encode(this.channelOptions),a=nc({action:e6.MESSAGE,channel:this.name,messages:[o],params:s?eo(s):void 0});return{versionSerial:null!=(i=(await this.sendAndAwaitAck(a)).serials[0])?i:null}}async getMessageVersions(e,t){return L.logAction(this.logger,L.LOG_MICRO,"RealtimeChannel.getMessageVersions()","channel = "+this.name),this.client.rest.channelMixin.getMessageVersions(this,e,t)}async ensureAttached(){switch(this.state){case"attached":case"suspended":break;case"initialized":case"detached":case"detaching":case"attaching":await this.attach();break;default:throw x.fromValues(this.invalidStateError())}}};function np(e){let t=e||{},{agent:n}=t;return R(t,["agent"])}var nf=class{constructor(e){this.channel=e,this.logger=e.logger,this.subscriptions=new e3(this.logger)}async publish(e,t){let n=this.channel.name,s=ns(e,t),i=await s.encode();this.channel.throwIfUnpublishableState(),L.logAction(this.logger,L.LOG_MICRO,"RealtimeAnnotations.publish()","channelName = "+n+", sending annotation with messageSerial = "+s.messageSerial+", type = "+s.type);let r=nc({action:e6.ANNOTATION,channel:n,annotations:[i]});await this.channel.sendAndAwaitAck(r)}async delete(e,t){t.action="annotation.delete",await this.publish(e,t)}async subscribe(...e){let t=ng.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if("failed"===i.state)throw x.fromValues(i.invalidStateError());if(this.subscriptions.on(n,s),!1!==this.channel.channelOptions.attachOnSubscribe&&await i.attach(),0===("attached"===this.channel.state&&this.channel._mode&e9.ANNOTATION_SUBSCRIBE))throw new x("You are trying to add an annotation listener, but you haven't requested the annotation_subscribe channel mode in ChannelOptions, so this won't do anything (we only deliver annotations to clients who have explicitly requested them)",93001,400)}unsubscribe(...e){let t=ng.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}_processIncoming(e){for(let t of e)this.subscriptions.emit(t.type||"",t)}async get(e,t){return nr.prototype.get.call(this,e,t)}},nm=class e extends tZ{constructor(t){var n,s;if(!e._MsgPack)throw Error("Expected DefaultRest._MsgPack to have been set");
1super(eN.objectifyOptions(t,!0,"Rest",L.defaultLogger,C(w({},t0),{Crypto:null!=(n=e.Crypto)?n:void 0,MsgPack:null!=(s=e._MsgPack)?s:void 0,Annotations:{Annotation:ne,WireAnnotation:t7,RealtimeAnnotations:nf,RestAnnotations:nr}})))}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}};nm._Crypto=null,nm.Message=t1,nm.PresenceMessage=t4,nm.Annotation=nt,nm._MsgPack=null,nm._Http=e2;var ny=nm,nv=class extends e3{constructor(e){super(e),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){L.logAction(this.logger,L.LOG_MICRO,"MessageQueue.completeMessages()","all"==e?"(all)":"serial = "+e.serial+"; count = "+e.count),t=t||null;let s=this.messages;if(0===s.length)throw Error("MessageQueue.completeMessages(): completeMessages called on any empty MessageQueue");let i=[];if("all"===e)i=s.splice(0);else{let t=s[0];if(t){let n=t.message.msgSerial,r=e.serial+e.count;r>n&&(i=s.splice(0,r-n))}}for(let e=0;e<i.length;e++){let s=i[e],r=null==n?void 0:n[e];s.callback(t,r)}0==s.length&&this.emit("idle")}completeAllMessages(e){this.completeMessages("all",e)}resetSendAttempted(){for(let e of this.messages)e.sendAttempted=!1}clear(){L.logAction(this.logger,L.LOG_MICRO,"MessageQueue.clear()","clearing "+this.messages.length+" messages"),this.messages=[],this.emit("idle")}},nb=class{constructor(e,t){this.message=e,this.callback=t,this.merged=!1;let n=e.action;this.sendAttempted=!1,this.ackRequired="number"==typeof n&&[e6.MESSAGE,e6.PRESENCE,e6.ANNOTATION,e6.OBJECT].includes(n)}},nO=class extends e3{constructor(e){super(e.logger),this.transport=e,this.messageQueue=new nv(this.logger),e.on("ack",(e,t,n)=>{this.onAck(e,t,n)}),e.on("nack",(e,t,n)=>{this.onNack(e,t,n)})}onAck(e,t,n){L.logAction(this.logger,L.LOG_MICRO,"Protocol.onAck()","serial = "+e+"; count = "+t),this.messageQueue.completeMessages({serial:e,count:t},null,n)}onNack(e,t,n){L.logAction(this.logger,L.LOG_ERROR,"Protocol.onNack()","serial = "+e+"; count = "+t+"; err = "+eh(n)),n||(n=new x("Unable to send message; channel not responding",50001,500)),this.messageQueue.completeMessages({serial:e,count:t},n)}onceIdle(e){let t=this.messageQueue;if(0===t.count())return void e();t.once("idle",e)}send(e){e.ackRequired&&this.messageQueue.push(e),this.logger.shouldLog(L.LOG_MICRO)&&L.logActionNoStrip(this.logger,L.LOG_MICRO,"Protocol.send()","sending msg; "+nh(e.message,this.transport.connectionManager.realtime._RealtimePresence,this.transport.connectionManager.realtime._Annotations,this.transport.connectionManager.realtime._liveObjectsPlugin)),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()})}},nw=class{constructor(e,t,n,s){this.previous=e,this.current=t,n&&(this.retryIn=n),s&&(this.reason=s)}},nC={DISCONNECTED:80003,SUSPENDED:80002,FAILED:8e4,CLOSING:80017,CLOSED:80017,UNKNOWN_CONNECTION_ERR:50002,UNKNOWN_CHANNEL_ERR:50001},nR={disconnected:()=>x.fromValues({statusCode:400,code:nC.DISCONNECTED,message:"Connection to server temporarily unavailable"}),suspended:()=>x.fromValues({statusCode:400,code:nC.SUSPENDED,message:"Connection to server unavailable"}),failed:()=>x.fromValues({statusCode:400,code:nC.FAILED,message:"Connection failed or disconnected by server"}),closing:()=>x.fromValues({statusCode:400,code:nC.CLOSING,message:"Connection closing"}),closed:()=>x.fromValues({statusCode:400,code:nC.CLOSED,message:"Connection closed"}),unknownConnectionErr:()=>x.fromValues({statusCode:500,code:nC.UNKNOWN_CONNECTION_ERR,message:"Internal connection error"}),unknownChannelErr:()=>x.fromValues({statusCode:500,code:nC.UNKNOWN_CONNECTION_ERR,message:"Internal
1channel error"})},nA=nc({action:e6.CLOSE}),nk=nc({action:e6.DISCONNECT}),nS=class extends e3{constructor(e,t,n,s){super(e.logger),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",nR.closed())}disconnect(e){this.isConnected&&this.requestDisconnect(),this.finish("disconnected",e||nR.disconnected())}fail(e){this.isConnected&&this.requestDisconnect(),this.finish("failed",e||nR.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(this.logger.shouldLog(L.LOG_MICRO)&&L.logActionNoStrip(this.logger,L.LOG_MICRO,"Transport.onProtocolMessage()","received on "+this.shortName+": "+nh(e,this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin)+"; connectionId = "+this.connectionManager.connectionId),this.onActivity(),e.action){case e6.HEARTBEAT:L.logActionNoStrip(this.logger,L.LOG_MICRO,"Transport.onProtocolMessage()",this.shortName+" heartbeat; connectionId = "+this.connectionManager.connectionId),this.emit("heartbeat",e.id);break;case e6.CONNECTED:this.onConnect(e),this.emit("connected",e.error,e.connectionId,e.connectionDetails,e);break;case e6.CLOSED:this.onClose(e);break;case e6.DISCONNECTED:this.onDisconnect(e);break;case e6.ACK:this.emit("ack",e.msgSerial,e.count,e.res);break;case e6.NACK:this.emit("nack",e.msgSerial,e.count,e.error);break;case e6.SYNC:this.connectionManager.onChannelMessage(e,this);break;case e6.ACTIVATE:break;case e6.AUTH:em(this.auth.authorize(),e=>{e&&L.logAction(this.logger,L.LOG_ERROR,"Transport.onProtocolMessage()","Ably requested re-authentication, but unable to obtain a new token: "+eh(e))});break;case e6.ERROR:if(L.logAction(this.logger,L.LOG_MINOR,"Transport.onProtocolMessage()","received error action; connectionId = "+this.connectionManager.connectionId+"; err = "+T.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;L.logAction(this.logger,L.LOG_MINOR,"Transport.onDisconnect()","err = "+eh(t)),this.finish("disconnected",t)}onFatalError(e){let t=e&&e.error;L.logAction(this.logger,L.LOG_MINOR,"Transport.onFatalError()","err = "+eh(t)),this.finish("failed",t)}onClose(e){let t=e&&e.error;L.logAction(this.logger,L.LOG_MINOR,"Transport.onClose()","err = "+eh(t)),this.finish("closed",t)}requestClose(){L.logAction(this.logger,L.LOG_MINOR,"Transport.requestClose()",""),this.send(nA)}requestDisconnect(){L.logAction(this.logger,L.LOG_MINOR,"Transport.requestDisconnect()",""),this.send(nk)}ping(e){let t={action:e6.HEARTBEAT};e&&(t.id=e),this.send(nc(t))}
1dispose(){L.logAction(this.logger,L.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";L.logAction(this.logger,L.LOG_ERROR,"Transport.onIdleTimerExpire()",t),this.disconnect(new x(t,80003,408))}else this.setIdleTimer(t+100)}static tryConnect(e,t,n,s,i){let r,o=new e(t,n,s),a=function(e){clearTimeout(r),i({event:this.event,error:e})};return r=setTimeout(()=>{o.off(["preconnect","disconnected","failed"]),o.dispose(),a.call({event:"disconnected"},new x("Timeout waiting for transport to indicate itself viable",5e4,500))},t.options.timeouts.realtimeRequestTimeout),o.on(["failed","disconnected"],a),o.on("preconnect",function(){L.logAction(t.logger,L.LOG_MINOR,"Transport.tryConnect()","viable transport "+o),clearTimeout(r),o.off(["failed","disconnected"],a),i(null,o)}),o.connect(),o}static isAvailable(){throw new x("isAvailable not implemented for transport",5e4,500)}};(i=o||(o={})).WebSocket="web_socket",i.Comet="comet",i.XhrPolling="xhr_polling";var nM=void 0!==n.g?n.g:"undefined"!=typeof window?window:self,nT=()=>{var e;return void 0!==T.WebStorage&&(null==(e=T.WebStorage)?void 0:e.localSupported)},n_=()=>{var e;return void 0!==T.WebStorage&&(null==(e=T.WebStorage)?void 0:e.sessionSupported)},nI=function(){},nP="ably-transport-preference";function nE(e){try{return JSON.parse(e)}catch(e){return null}}var nL=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?q(e):{},n=this.options;switch(this.mode){case"resume":t.resume=this.connectionKey;break;case"recover":{let e=nE(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=eN.protocolVersion,t.agent=ej(this.options),void 0!==n.transportParams&&B(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+="]"}},nN=class e extends e3{constructor(e,t){super(e.logger),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 nv(this.logger),this.msgSerial=0,this.connectionDetails=void 0,this.connectionId=void 0,this.connectionKey=void 0,this.connectionStateTtl=n.connectionStateTtl,this.maxIdleInterval=null,this.transports=K(t.transports||eN.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.domains=eN.getHosts(t),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,L.logAction(this.logger,L.LOG_MINOR,"Realtime.ConnectionManager()","started"),L.logAction(this.logger,L.LOG_MICRO,"Realtime.ConnectionManager()","requested transports = ["+(t.transports||eN.defaultTransports)+"]"),L.logAction(this.logger,L.LOG_MICRO,"Realtime.ConnectionManager()","available transports = ["+this.transports+"]"),L.logAction(this.logger,L.LOG_MICRO,"Realtime.ConnectionManager()","http domains = ["+this.domains+"]"),!this.transports.length){let e="no requested transports available";throw L.logAction(this.logger,L.LOG_ERROR,"realtime.ConnectionManager()",e),Error(e)}let i=T.Config.addEventListener;i&&(n_()&&"function"==typeof t.recover&&i("beforeunload",this.persist
1Connection.bind(this)),!0===t.closeOnUnload&&i("beforeunload",()=>{L.logAction(this.logger,L.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?(L.logAction(this.logger,L.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&&(L.logAction(this.logger,L.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=w(w({},T.Transports.bundledImplementations),e);[o.WebSocket,...T.Transports.order].forEach(e=>{let s=n[e];s&&s.isAvailable()&&(t.supportedTransports[e]=s)})}initTransports(){e.initTransports(this.realtime._additionalTransportImplementations,this)}createTransportParams(e,t){return new nL(this.options,e,t,this.connectionKey)}getTransportParams(e){(e=>{if(this.connectionKey)return e("resume");if("string"==typeof this.options.recover)return e("recover");let t=this.options.recover,n=this.getSessionRecoverData(),s=this.sessionRecoveryName();if(n&&"function"==typeof t){L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.getTransportParams()","Calling clientOptions-provided recover function with last session data (recovery scope: "+s+")"),t(n,t=>{t?(this.options.recover=n.recoveryKey,e("recover")):e("clean")});return}e("clean")})(t=>{let n=this.createTransportParams(null,t);if("recover"===t){L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport recovery mode = recover; recoveryKey = "+this.options.recover);let e=nE(this.options.recover);e&&(this.msgSerial=e.msgSerial)}else L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.getTransportParams()","Transport params = "+n.toString());e(n)})}tryATransport(e,t,n){L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.tryATransport()","trying "+t),this.proposedTransport=nS.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&&(L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.tryATransport()","connection "+r.state+" while we were attempting the transport; closing "+i),i.close()),n(!0);return}if(s){if(L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.tryATransport()","transport "+t+" "+s.event+", err: "+s.error.toString()),e0.isTokenErr(s.error)&&!(this.errorReason&&e0.isTokenErr(this.errorReason)))this.errorReason=s.error,em(this.realtime.auth._forceNewToken(null,null),s=>{if(s)return void this.actOnErrorFromAuthorize(s);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(nC).includes(o.code)?n(!1):(this.notifyState({state:this.states.connecting.failState,error:s.error}),n(!0))}return}L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.tryATransport()","viable transport "+t+"; setting pending"),this.setTransportPending(i,e),n(null,i)})}setTransportPending(e,t){let n=t.mode;L.logAction(this.logger,L.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){L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.activateTransport()","transport = "+t),e&&L.logAction(this.logger,L.LOG_ERROR,"ConnectionManager.activateTransport()","error = "+e),n&&L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.activateTransport()","connectionId = "+n),s&&L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.activateTransport()","connectionDetail
1s = "+JSON.stringify(s)),this.persistTransportPreference(t);let i=this.state,r=this.states.connected.state;if(L.logAction(this.logger,L.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 L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.activateTransport()","Disconnecting transport and abandoning"),t.disconnect(),!1;if(delete this.pendingTransport,!t.isConnected)return L.logAction(this.logger,L.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 nO(t),this.host=t.params.host;let a=s.connectionKey;if(a&&this.connectionKey!=a&&this.setConnection(n,s,!!e),this.onConnectionDetailsUpdate(s,t),T.Config.nextTick(()=>{t.on("connected",(e,n,s)=>{this.onConnectionDetailsUpdate(s,t),this.emit("update",new nw(r,r,null,e))})}),i.state===this.states.connected.state?e&&(this.errorReason=this.realtime.connection.errorReason=e,this.emit("update",new nw(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&&L.logAction(this.logger,L.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;L.logAction(this.logger,L.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(L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.deactivateTransport()","transport = "+e),L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.deactivateTransport()","state = "+t+(i?"; was active":r?"; was pending":"")+(o?"":"; another transport is scheduled for activation")),n&&n.message&&L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.deactivateTransport()","reason = "+n.message),i&&(L.logAction(this.logger,L.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.domains.length>1){this.unpersistTransportPreference(),this.forceFallbackHost=!0,this.notifyState({state:t,error:n,retryImmediately:!0});return}let e="failed"===t&&e0.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)&&(L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.setConnection()","Resetting msgSerial"),this.msgSerial=0,this.queuedMessages.resetSendAttempted()),this.connectionId!==e&&L.logAction(this.logger,L.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.queuedMessages.resetSendAttempted(),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&&(L.logAction(this.logger,L.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(n_()){let e=this.createRecoveryKey();e&&this.setSessionRecoverData({recoveryKey:e,disconnectedAt:Date.now(),location:nM.location,clientId:this.realtime.auth.clientId})}}unpersistConnection(){this.clearSessionRecoverData()}
1getActiveTransportFormat(){var e;return null==(e=this.activeProtocol)?void 0:e.getTransport().format}getError(){if(this.errorReason){let e=G.fromValues(this.errorReason);return e.cause=this.errorReason,e}return this.getStateError()}getStateError(){var e;return null==(e=nR[this.state.state])?void 0:e.call(nR)}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?L.logAction(this.logger,L.LOG_ERROR,t,n):L.logAction(this.logger,L.LOG_MAJOR,t,n),L.logAction(this.logger,L.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){L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.startTransitionTimer()","transitionState: "+e.state),this.transitionTimer&&(L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.startTransitionTimer()","clearing already-running timer"),clearTimeout(this.transitionTimer)),this.transitionTimer=setTimeout(()=>{this.transitionTimer&&(this.transitionTimer=null,L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager "+e.state+" timer expired","requesting new state: "+e.failState),this.notifyState({state:e.failState}))},e.retryDelay)}cancelTransitionTimer(){L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.cancelTransitionTimer()",""),this.transitionTimer&&(clearTimeout(this.transitionTimer),this.transitionTimer=null)}startSuspendTimer(){this.suspendTimer||(this.suspendTimer=setTimeout(()=>{this.suspendTimer&&(this.suspendTimer=null,L.logAction(this.logger,L.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(()=>{L.logAction(this.logger,L.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(()=>{L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager WebSocket slow timer","checking connectivity"),this.checkWsConnectivity().then(()=>{L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager WebSocket slow timer","ws connectivity check succeeded"),this.wsCheckResult=!0}).catch(()=>{L.logAction(this.logger,L.LOG_MAJOR,"ConnectionManager WebSocket slow timer","ws connectivity check failed"),this.wsCheckResult=!1}),this.realtime.http.checkConnectivity&&em(this.realtime.http.checkConnectivity(),(e,t)=>{e||!t?(L.logAction(this.logger,L.LOG_MAJOR,"ConnectionManager WebSocket slow timer","http connectivity check failed"),this.cancelWebSocketGiveUpTimer(),this.notifyState({state:"disconnected",error:new x("Unable to connect (network unreachable)",80003,404)})):L.logAction(this.logger,L.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||(L.logAction(this.logger,L.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)):L.logAction(this.logger,L.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&&e0.isTokenErr(e.error)&&!(this.errorReason&&e0.isTokenErr(this.errorReason)));if(L.logAction(this.logger,L.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=eR(i.retryDelay,this.disconnectedRetryCount));let o=new nw(this.state.state,i.state,r,e.error||(null==(t=nR[i.state])?void 0:t.call(nR)));if(s){let e=()=>{this.state===this.states.disconnected&&(this.lastAutoReconnectAttempt=Date.now(),this.requestState({state:"connecting"}))},t=this.lastAutoReconnectAttempt&&Date.now()-this.lastAutoReconnectAttempt+1;t&&t<1e3?(L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.notifyState()","Last reconnect attempt was only "+t+"ms ago, waiting another "+(1e3-t)+"ms before trying again"),setTimeout(e,1e3-t)):T.Config.nextTick(e)}else("disconnected"===n||"suspended"===n)&&this.startRetryTimer(r);("disconnected"===n&&!s||"suspended"===n||i.terminal)&&T.Config.nextTick(()=>{this.disconnectAllTransports()}),"connected"!=n||this.activeProtocol||L.logAction(this.logger,L.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(L.logAction(this.logger,L.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 nw(this.state.state,s.state,null,e.error||(null==(t=nR[s.state])?void 0:t.call(nR)));this.enactStateChange(i),"connecting"==n&&T.Config.nextTick(()=>{this.startConnect()}),"closing"==n&&this.closeImpl()}startConnect(){if(this.state!==this.states.connecting)return void L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.startConnect()","Must be in connecting state to connect, but was "+this.state.state);let e=this.realtime.auth,t=++this.connectCounter,n=()=>
1{this.checkConnectionStateFreshness(),this.getTransportParams(e=>{if("recover"===e.mode&&e.options.recover){let t=nE(e.options.recover);t&&this.realtime.channels.recoverChannels(t.channelSerials)}t===this.connectCounter&&this.connectImpl(e,t)})};if(L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.startConnect()","starting connection"),this.startSuspendTimer(),this.startTransitionTimer(this.states.connecting),"basic"===e.method)n();else{let s=e=>{t===this.connectCounter&&(e?this.actOnErrorFromAuthorize(e):n())};this.errorReason&&e0.isTokenErr(this.errorReason)?em(e._forceNewToken(null,null),s):em(e._ensureValidAuthCredentials(!1),s)}}connectImpl(e,t){let n=this.state.state;if(n!==this.states.connecting.state)return void L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.connectImpl()","Must be in connecting state to connect, but was "+n);let s=this.getTransportPreference();s&&s===this.baseTransport&&this.webSocketTransportAvailable&&this.checkWsConnectivity().then(()=>{this.unpersistTransportPreference(),this.state===this.states.connecting&&(L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.connectImpl():","web socket connectivity available, cancelling connection attempt with "+this.baseTransport),this.disconnectAllTransports(),this.connectWs(e,++this.connectCounter))}).catch(nI),s&&s===this.baseTransport||this.baseTransport&&!this.webSocketTransportAvailable?this.connectBase(e,t):this.connectWs(e,t)}connectWs(e,t){L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.connectWs()"),this.wsCheckResult=null,this.abandonedWebSocket=!1,this.startWebSocketSlowTimer(),this.startWebSocketGiveUpTimer(e),this.tryTransportWithFallbacks("web_socket",e,!0,t,()=>!1!==this.wsCheckResult&&!this.abandonedWebSocket)}connectBase(e,t){L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.connectBase()"),this.baseTransport?this.tryTransportWithFallbacks(this.baseTransport,e,!1,t,()=>!0):this.notifyState({state:"disconnected",error:new x("No transports left to try",8e4,404)})}tryTransportWithFallbacks(e,t,n,s,i){L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.tryTransportWithFallbacks()",e);let r=e=>{this.notifyState({state:this.states.connecting.failState,error:e})},o=this.domains.slice(),a=(e,t)=>{if(s===this.connectCounter){if(!i()){t&&t.dispose();return}t||e||c()}},l=o.shift();if(!l)return void r(new x("Unable to connect (no available host)",80003,404));t.host=l;let c=()=>o.length?this.realtime.http.checkConnectivity?void em(this.realtime.http.checkConnectivity(),(n,l)=>{if(s===this.connectCounter&&i()){if(n)return void r(n);if(!l)return void r(new x("Unable to connect (network unreachable)",80003,404));t.host=ei(o),this.tryATransport(t,e,a)}}):void r(new G("Internal error: Http.checkConnectivity not set",null,500)):void r(new x("Unable to connect (and no more fallback hosts to try)",80003,404));if(this.forceFallbackHost&&o.length){this.forceFallbackHost=!1,c();return}this.tryATransport(t,e,a)}closeImpl(){L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.closeImpl()","closing connection"),this.cancelSuspendTimer(),this.startTransitionTimer(this.states.closing),this.pendingTransport&&(L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.closeImpl()","Closing pending transport: "+this.pendingTransport),this.pendingTransport.close()),this.activeProtocol&&(L.logAction(this.logger,L.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":{L.logAction(this.logger,L.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=nc({action:e6.AUTH,auth:{accessToken:e.token}});this.send(i);let r=()=>{this.off(o),t(null,e)},o=e=>{"failed"===e.current&&(this.off(r),this.off(o),t(e.reason||this.getStateError()))};this.once("connectiondetails",r),this.on("connectionstate",o);break}case"connecting":L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Aborting current connection attempts in order to start again with the new auth details"),this.disconnectAllTransports();default:{L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.onAuthUpdated()","Connection state is "+this.state.state+"; waiting until either connected or failed");let n=s=>{switch(s.current){case"connected":this.off(n),t(null,e);break;case"failed":case"closed":case"suspended":this.off(n),t(s.reason||this.get
1StateError())}};this.on("connectionstate",n),"connecting"===this.state.state?this.startConnect():this.requestState({state:"connecting"})}}}disconnectAllTransports(){L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.disconnectAllTransports()","Disconnecting all transports"),this.connectCounter++,this.pendingTransport&&(L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting pending transport: "+this.pendingTransport),this.pendingTransport.disconnect()),delete this.pendingTransport,this.proposedTransport&&(L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting proposed transport: "+this.pendingTransport),this.proposedTransport.disconnect()),delete this.pendingTransport,this.activeProtocol&&(L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.disconnectAllTransports()","Disconnecting active transport: "+this.activeProtocol.getTransport()),this.activeProtocol.getTransport().disconnect())}send(e,t,n){n=n||nI;let s=this.state;if(s.sendEvents){L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.send()","sending event"),this.sendImpl(new nb(e,n));return}if(!(t&&s.queueEvents)){let e="rejecting event, queueEvent was "+t+", state was "+s.state;L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.send()",e),n(this.errorReason||new x(e,9e4,400));return}this.logger.shouldLog(L.LOG_MICRO)&&L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.send()","queueing msg; "+nh(e,this.realtime._RealtimePresence,this.realtime._Annotations,this.realtime._liveObjectsPlugin)),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){L.logAction(this.logger,L.LOG_ERROR,"ConnectionManager.sendImpl()","Unexpected exception in transport.send(): "+e.stack)}}queue(e,t){L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.queue()","queueing event"),this.queuedMessages.push(new nb(e,t))}sendQueuedMessages(){let e;for(L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.sendQueuedMessages()","sending "+this.queuedMessages.count()+" queued messages");e=this.queuedMessages.shift();)this.sendImpl(e)}queuePendingMessages(e){e&&e.length&&(L.logAction(this.logger,L.LOG_MICRO,"ConnectionManager.queuePendingMessages()","queueing "+e.length+" pending messages"),this.queuedMessages.prepend(e))}failQueuedMessages(e){let t=this.queuedMessages.count();t>0&&(L.logAction(this.logger,L.LOG_ERROR,"ConnectionManager.failQueuedMessages()","failing "+t+" queued messages, err = "+eh(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=>{L.logAction(this.logger,L.LOG_ERROR,"ConnectionManager.processNextPendingChannelMessage() received error ",e)}).finally(()=>{this.pendingChannelMessagesState.isProcessing=!1,this.processNextPendingChannelMessage()})}}async processChannelMessage(e){await this.realtime.channels.processChannelMessage(e)}async ping(){var e;if("connected"!==this.state.state)throw new x("Unable to ping service; not connected",4e4,400);let t=null==(e=this.activeProtocol)?void 0:e.getTransport();if(!t)throw this.getStateError();L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.ping()","transport = "+t);let n=Date.now(),s=eg();return eP(new Promise(e=>{let i=r=>{r===s&&(t.off("heartbeat",i),e(Date.now()-n))};t.on("heartbeat",i),t.ping(s)}),this.options.timeouts.realtimeRequestTimeout,"Timeout waiting for heartbeat response")}abort(e){this.activeProtocol.getTransport().fail(e)}getTransportPreference(){var e,t;return this.transportPreference||nT()&&(null==(t=null==(e=T.WebStorage)?void 0:e.get)?void 0:t.call(e,nP))}persistTransportPreference(e){var t,n;this.transportPreference=e.shortName,nT()&&(null==(n=null==(t=T.WebStorage)?void 0:t.set)||n.call(t,nP,e.shortName))}unpersistTransportPreference(){var e,t;this.transportPreference=null,nT()&&(null==(t=null==(e=T.WebStorage)?void 0:e.remove)||t.call(e,nP))}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===ez.Forbidden){let t="Client configured authentication provider returned 403; failing the connection";L.logAction(this.logger,L.LOG_ERROR,"ConnectionManager.actOnErrorFromAuthorize()",t),this.notifyState({state:"failed",error:new x(t,8
10019,403,e)})}else{let t="Client configured authentication provider request failed";L.logAction(this.logger,L.LOG_MINOR,"ConnectionManager.actOnErrorFromAuthorize",t),this.notifyState({state:this.state.failState,error:new x(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){L.logAction(this.logger,L.LOG_ERROR,"ConnectionManager.onConnectionDetailsUpdate()",e.message),t.fail(e);return}}let s=e.connectionStateTtl;s&&(this.connectionStateTtl=s),this.maxIdleInterval=e.maxIdleInterval,this.emit("connectiondetails",e)}checkWsConnectivity(){let e=this.options.wsConnectivityCheckUrl||eN.wsConnectivityCheckUrl,t=new T.Config.WebSocket(e);return new Promise((e,n)=>{let s=!1;t.onopen=()=>{s||(s=!0,e(),t.close())},t.onclose=t.onerror=()=>{s||(s=!0,n())}})}sessionRecoveryName(){return this.options.recoveryKeyStorageName||"ably-connection-recovery"}getSessionRecoverData(){var e,t;return n_()&&(null==(t=null==(e=T.WebStorage)?void 0:e.getSession)?void 0:t.call(e,this.sessionRecoveryName()))}setSessionRecoverData(e){var t,n;return n_()&&(null==(n=null==(t=T.WebStorage)?void 0:t.setSession)?void 0:n.call(t,this.sessionRecoveryName(),e))}clearSessionRecoverData(){var e,t;return n_()&&(null==(t=null==(e=T.WebStorage)?void 0:e.removeSession)?void 0:t.call(e,this.sessionRecoveryName()))}},nU=class extends e3{constructor(e,t){super(e.logger),this.whenState=e=>e3.prototype.whenState.call(this,e,this.state),this.ably=e,this.connectionManager=new nN(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;T.Config.nextTick(()=>{this.emit(t,e)})}),this.connectionManager.on("update",e=>{T.Config.nextTick(()=>{this.emit("update",e)})})}connect(){L.logAction(this.logger,L.LOG_MINOR,"Connection.connect()",""),this.connectionManager.requestState({state:"connecting"})}ping(...e){return ec(e,0),this._pingImpl()}async _pingImpl(){return L.logAction(this.logger,L.LOG_MINOR,"Connection.ping()",""),this.connectionManager.ping()}close(){L.logAction(this.logger,L.LOG_MINOR,"Connection.close()","connectionKey = "+this.key),this.connectionManager.requestState({state:"closing"})}get recoveryKey(){return this.logger.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()}},nx=class e extends tf{constructor(t){var n,s;if(super(eN.objectifyOptions(t,!1,"BaseRealtime",L.defaultLogger)),L.logAction(this.logger,L.LOG_MINOR,"Realtime()",""),"string"==typeof EdgeRuntime)throw new x('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=e.transportImplementationsFromPlugins(this.options.plugins),this._RealtimePresence=null!=(s=null==(n=this.options.plugins)?void 0:n.RealtimePresence)?s:null,this.connection=new nU(this,this.options),this._channels=new nG(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}get clientId(){return this.auth.clientId}connect(){L.logAction(this.logger,L.LOG_MINOR,"Realtime.connect()",""),this.connection.connect()}close(){L.logAction(this.logger,L.LOG_MINOR,"Realtime.close()",""),this.connection.close()}};nx.EventEmitter=e3;
1var nG=class extends e3{constructor(e){super(e.logger),this.realtime=e,this.all=Object.create(null),e.connection.connectionManager.on("transport.active",()=>{this.onTransportActive()})}channelSerials(){let e={};for(let t of Z(this.all,!0)){let n=this.all[t];n.properties.channelSerial&&(e[t]=n.properties.channelSerial)}return e}recoverChannels(e){for(let t of Z(e,!0))this.get(t).properties.channelSerial=e[t]}async processChannelMessage(e){let t=e.channel;if(void 0===t)return void L.logAction(this.logger,L.LOG_ERROR,"Channels.processChannelMessage()","received event unspecified channel, action = "+e.action);let n=this.all[t];if(!n)return void L.logAction(this.logger,L.LOG_ERROR,"Channels.processChannelMessage()","received event for non-existent channel: "+t);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 x("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 ng(this.realtime,e,t);return n}getDerived(e,t,n){if(t.filter){let n=eM(t.filter),s=eS(e);e=`[filter=${n}${s.qualifierParam}]${s.channelName}`}return this.get(e,n)}release(e){e=String(e),L.logAction(this.logger,L.LOG_MAJOR,"Channels.release()","Releasing references to channel "+e);let t=this.all[e];if(!t)return;let n=t.state;if("initialized"===n||"detached"===n||"failed"===n)return void delete this.all[e];t.detach().catch(t=>{L.logAction(this.logger,L.LOG_ERROR,"Channels.release()","Error detaching channel "+e+" prior to release: "+eh(t))}).then(()=>{delete this.all[e]})}},nB=nx;function nq(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 nD=class extends e3{constructor(e,t,n=nq){super(e.logger),this.presence=e,this.map=Object.create(null),this.syncInProgress=!1,this.residualMembers=null,this.memberKey=t,this.newerThan=n}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=tN.fromValues(e)).action="present");let t=this.map,n=this.memberKey(e);this.residualMembers&&delete this.residualMembers[n];let s=t[n];return(!s||!!this.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||!!this.newerThan(e,s))&&(this.syncInProgress?((e=tN.fromValues(e)).action="absent",t[n]=e):delete t[n],!!s)}startSync(){let e=this.map,t=this.syncInProgress;L.logAction(this.logger,L.LOG_MINOR,"PresenceMap.startSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),this.syncInProgress||(this.residualMembers=q(e),this.setInProgress(!0))}endSync(){let e=this.map,t=this.syncInProgress;if(L.logAction(this.logger,L.LOG_MINOR,"PresenceMap.endSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+t),t){for(let t in e)"absent"===e[t].action&&delete e[t];for(let t in this.presence._synthesizeLeaves(ee(this.residualMembers)),this.residualMembers)delete e[t];this.residualMembers=null,this.setInProgress(!1)}this.emit("sync")}async waitSync(){let e=this.syncInProgress;L.logAction(this.logger,L.LOG_MINOR,"PresenceMap.waitSync()","channel = "+this.presence.channel.name+"; syncInProgress = "+e),e&&await this.once("sync")}clear(){this.map={},this.setInProgress(!1),this.residualMembers=null}setInProgress(e){L.logAction(this.logger,L.LOG_MICRO,"PresenceMap.setInProgress()","inProgress = "+e),this.syncInProgress=e,this.presence.syncComplete=!e}};function nj(e){let t=e.channel.client,n=t.auth.clientId;return(!n||"*"===n)&&"connected"===t.connection.state}
1var nH=class extends e3{constructor(e){super(e.logger),this.channel=e,this.syncComplete=!1,this.members=new nD(this,e=>e.clientId+":"+e.connectionId),this._myMembers=new nD(this,e=>e.clientId),this.subscriptions=new e3(this.logger),this.pendingPresence=[]}enter(...e){return ec(e,0),this._enterImpl(e[0])}async _enterImpl(e){if(nj(this))throw new x("clientId must be specified to enter a presence channel",40012,400);return this._enterOrUpdateClient(void 0,void 0,e,"enter")}update(...e){return ec(e,0),this._updateImpl(e[0])}async _updateImpl(e){if(nj(this))throw new x("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();L.logAction(this.logger,L.LOG_MICRO,"RealtimePresence."+s+"Client()","channel = "+i.name+", id = "+e+", client = "+(t||"(implicit) "+this.channel.client.auth.clientId));let r=tN.fromData(n);r.action=s,e&&(r.id=e),t&&(r.clientId=t);let o=await r.encode(i.channelOptions);switch(i.state){case"attached":return i.sendPresence([o]);case"initialized":case"detached":i.attach();case"attaching":return new Promise((e,t)=>{this.pendingPresence.push({presence:o,callback:n=>n?t(n):e()})});default:{let e=new G("Unable to "+s+" presence channel while in "+i.state+" state",90001);throw e.code=90001,e}}}leave(...e){return ec(e,0),this._leaveImpl(e[0])}async _leaveImpl(e){if(nj(this))throw new x("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();L.logAction(this.logger,L.LOG_MICRO,"RealtimePresence.leaveClient()","leaving; channel = "+this.channel.name+", client = "+e);let s=tN.fromData(t);s.action="leave",e&&(s.clientId=e);let i=await s.encode(n.channelOptions);switch(n.state){case"attached":return n.sendPresence([i]);case"attaching":return new Promise((e,t)=>{this.pendingPresence.push({presence:i,callback:n=>n?t(n):e()})});case"initialized":case"failed":throw new G("Unable to leave presence channel (incompatible state)",90001);default:throw n.invalidStateError()}}get(...e){return ec(e,0),this._getImpl(e[0])}async _getImpl(e){let t=!e||!("waitForSync"in e)||e.waitForSync;function n(t){return e?t.list(e):t.values()}if("suspended"===this.channel.state){if(t)throw x.fromValues({statusCode:400,code:91005,message:"Presence state is out of sync due to channel being in the SUSPENDED state"});return n(this.members)}await this.channel.ensureAttached();let s=this.members;return t&&await s.waitSync(),n(this.members)}history(...e){return ec(e,0),this._historyImpl(e[0])}async _historyImpl(e){L.logAction(this.logger,L.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 x("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;L.logAction(this.logger,L.LOG_MICRO,"RealtimePresence.setPresence()","received presence for "+e.length+" participants; syncChannelSerial = "+n);let r=this.members,o=this._myMembers,a=[],l=this.channel.connectionManager.connectionId;for(let c of(t&&(this.members.startSync(),n&&(i=n.match(/^[\w-]+:(.*)$/))&&(s=i[1])),e))switch(c.action){case"leave":r.remove(c)&&a.push(c),c.connectionId!==l||c.isSynthesized()||o.remove(c);break;case"enter":case"present":case"update":r.put(c)&&a.push(c),c.connectionId===l&&o.put(c)}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){L.logAction(this.logger,L.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=eF.create(this.logger);L.logAction(this.logger,L.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).then(()=>s()).catch(e=>s(e))}}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){L.logAction(this.logger,L.LOG_MINOR,"RealtimeChannel.failPendingPresence","channel; name = "+this.channel.name+", err = "+eh(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,t=this.channel.connectionManager.connectionId;for(let n in e.map){let s=e.map[n];L.logAction(this.logger,L.LOG_MICRO,"RealtimePresence._ensureMyMembersPresent()",'Auto-reentering clientId "'+s.clientId+'" into the presence set');let i=s.connectionId===t?s.id:void 0;
1this._enterOrUpdateClient(i,s.clientId,s.data,"enter").catch(e=>{let t=new x("Presence auto re-enter failed",91004,400,e);L.logAction(this.logger,L.LOG_ERROR,"RealtimePresence._ensureMyMembersPresent()","Presence auto re-enter failed; reason = "+eh(e));let n=new nd(this.channel.state,this.channel.state,!0,!1,t);this.channel.emit("update",n)})}}_synthesizeLeaves(e){let t=this.subscriptions;e.forEach(function(e){let n=tN.fromValues({action:"leave",connectionId:e.connectionId,clientId:e.clientId,data:e.data,encoding:e.encoding,timestamp:Date.now()});t.emit("leave",n)})}subscribe(...e){return ec(e,2),this._subscribeImpl(e)}async _subscribeImpl(e){let t=ng.processListenerArgs(e),n=t[0],s=t[1],i=this.channel;if("failed"===i.state)throw x.fromValues(i.invalidStateError());this.subscriptions.on(n,s),!1!==i.channelOptions.attachOnSubscribe&&await i.attach()}unsubscribe(...e){let t=ng.processListenerArgs(e),n=t[0],s=t[1];this.subscriptions.off(n,s)}},nV=o.WebSocket,nW=class extends nS{constructor(e,t,n){super(e,t,n),this.shortName=nV,n.heartbeats=T.Config.useProtocolHeartbeats,this.wsHost=n.host}static isAvailable(){return!!T.Config.WebSocket}createWebSocket(e,t){return this.uri=e+er(t),new T.Config.WebSocket(this.uri)}toString(){return"WebSocketTransport; uri="+this.uri}connect(){L.logAction(this.logger,L.LOG_MINOR,"WebSocketTransport.connect()","starting"),nS.prototype.connect.call(this);let e=this,t=this.params,n=t.options,s=(n.tls?"wss://":"ws://")+this.wsHost+":"+eN.getPort(n)+"/";L.logAction(this.logger,L.LOG_MINOR,"WebSocketTransport.connect()","uri: "+s),em(this.auth.getAuthParams(),function(n,i){if(e.isDisposed)return;let r="";for(let e in i)r+=" "+e+": "+i[e]+";";if(L.logAction(e.logger,L.LOG_MINOR,"WebSocketTransport.connect()","authParams:"+r+" err: "+n),n)return void e.disconnect(n);let o=t.getConnectParams(i);try{let t=e.wsConnection=e.createWebSocket(s,o);t.binaryType=T.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){L.logAction(e.logger,L.LOG_ERROR,"WebSocketTransport.connect()","Unexpected exception creating websocket: err = "+(t.stack||t.message)),e.disconnect(t)}})}send(e){let t=this.wsConnection;if(!t)return void L.logAction(this.logger,L.LOG_ERROR,"WebSocketTransport.send()","No socket connection");try{t.send(ev(e,this.connectionManager.realtime._MsgPack,this.params.format))}catch(t){let e="Exception from ws connection when trying to send: "+eh(t);L.logAction(this.logger,L.LOG_ERROR,"WebSocketTransport.send()",e),this.finish("disconnected",new x(e,5e4,500))}}onWsData(e){L.logAction(this.logger,L.LOG_MICRO,"WebSocketTransport.onWsData()","data received; length = "+e.length+"; type = "+typeof e);try{var t,n,s,i,r;this.onProtocolMessage((t=this.connectionManager.realtime._MsgPack,n=this.connectionManager.realtime._RealtimePresence,s=this.connectionManager.realtime._Annotations,i=this.connectionManager.realtime._liveObjectsPlugin,r=this.format,na(ey(e,t,r),n,s,i)))}catch(e){L.logAction(this.logger,L.LOG_ERROR,"WebSocketTransport.onWsData()","Unexpected exception handing channel message: "+e.stack)}}onWsOpen(){L.logAction(this.logger,L.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){L.logAction(this.logger,L.LOG_MINOR,"WebSocketTransport.onWsClose()","Cleanly closed WebSocket");let e=new x("Websocket closed",80003,400);this.finish("disconnected",e)}else{let e="Unclean disconnection of WebSocket ; code = "+n,t=new x(e,80003,400);L.logAction(this.logger,L.LOG_MINOR,"WebSocketTransport.onWsClose()",e),this.finish("disconnected",t)}
1this.emit("disposed")}onWsError(e){L.logAction(this.logger,L.LOG_MINOR,"WebSocketTransport.onError()","Error from WebSocket: "+e.message),T.Config.nextTick(()=>{this.disconnect(Error(e.message))})}dispose(){L.logAction(this.logger,L.LOG_MINOR,"WebSocketTransport.dispose()",""),this.isDisposed=!0;let e=this.wsConnection;e&&(e.onmessage=function(){},delete this.wsConnection,T.Config.nextTick(()=>{if(L.logAction(this.logger,L.LOG_MICRO,"WebSocketTransport.dispose()","closing websocket"),!e)throw Error("WebSocketTransport.dispose(): wsConnection is not defined");e.close()}))}},nF=class{static subscribeFilter(e,t,n){let s=e=>{var s,i,r,o,a,l;let c={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==(l=null==(a=e.extras)?void 0:a.ref)?void 0:l.timeserial),clientId:e.clientId};Object.entries(t).find(([e,t])=>void 0!==t&&c[e]!==t)||n(e)};this.addFilteredSubscription(e,t,n,s),e.subscriptions.on(s)}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||[]}},nJ=class e extends nB{constructor(t){var n;let s=e._MsgPack;if(!s)throw Error("Expected DefaultRealtime._MsgPack to have been set");super(eN.objectifyOptions(t,!0,"Realtime",L.defaultLogger,C(w({},t0),{Crypto:null!=(n=e.Crypto)?n:void 0,MsgPack:s,RealtimePresence:{RealtimePresence:nH,PresenceMessage:tN,WirePresenceMessage:tL},Annotations:{Annotation:ne,WireAnnotation:t7,RealtimeAnnotations:nf,RestAnnotations:nr},WebSocketTransport:nW,MessageInteractions:nF})))}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}};nJ.Utils=N,nJ.ConnectionManager=nN,nJ.ProtocolMessage=nu,nJ._Crypto=null,nJ.Message=t1,nJ.PresenceMessage=t4,nJ.Annotation=nt,nJ._MsgPack=null,nJ._Http=e2,nJ._PresenceMap=nD,nJ._MessageEncoding=th;var nz=nJ,nK=Uint8Array,n$=Uint32Array,nQ=Math.pow,nX=new n$(8),nY=[],nZ=new n$(64);function n0(e){return(e-(0|e))*nQ(2,32)|0}for(var n1=2,n4=0;n4<64;){for(l=2,a=!0;l<=n1/2;l++)n1%l==0&&(a=!1);a&&(n4<8&&(nX[n4]=n0(nQ(n1,.5))),nY[n4]=n0(nQ(n1,1/3)),n4++),n1++}var n2=!!new nK(new n$([1]).buffer)[0];function n8(e){return n2?e>>>24|(e>>>16&255)<<8|(65280&e)<<8|e<<24:e}function n3(e,t){return e>>>t|e<<32-t}function n6(e){var t=nX.slice(),n=e.length,s=8*n,i=512-(s+64)%512-1+s+65,r=new nK(i/8),o=new n$(r.buffer);r.set(e,0),r[n]=128,o[o.length-1]=n8(s);for(var a=0;a<i/32;a+=16){var l=t.slice();for(c=0;c<64;c++){if(c<16)h=n8(o[a+c]);else{var c,h,u=nZ[c-15],d=nZ[c-2];h=nZ[c-7]+nZ[c-16]+(n3(u,7)^n3(u,18)^u>>>3)+(n3(d,17)^n3(d,19)^d>>>10)}nZ[c]=h|=0;for(var g=(n3(l[4],6)^n3(l[4],11)^n3(l[4],25))+(l[4]&l[5]^~l[4]&l[6])+l[7]+h+nY[c],p=(n3(l[0],2)^n3(l[0],13)^n3(l[0],22))+(l[0]&l[1]^l[2]&(l[0]^l[1])),f=7;f>0;f--)l[f]=l[f-1];l[0]=g+p|0,l[4]=l[4]+g|0}for(c=0;c<8;c++)t[c]=t[c]+l[c]|0}return new nK(new n$(t.map(function(e){return n8(e)})).buffer)}var n5=new class{constructor(){this.base64CharSet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this.hexCharSet="0123456789abcdef"}uint8ViewToBase64(e){let t,n,s,i,r,o="",a=this.base64CharSet,l=e.byteLength,c=l%3,h=l-c;for(let l=0;l<h;l+=3)t=(0xfc0000&(r=e[l]<<16|e[l+1]<<8|e[l+2]))>>18,n=(258048&r)>>12,s=(4032&r)>>6,i=63&r,o+=a[t]+a[n]+a[s]+a[i];return 1==c?(t=(252&(r=e[h]))>>2,n=(3&r)<<4,o+=a[t]+a[n]+"=="):2==c&&(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))}base64UrlEncode(e){return this.base64Encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}base64Decode(e){if(ArrayBuffer&&T.Config.atob)return this.base64ToArrayBuffer(e);throw Error("Expected ArrayBuffer to exist and Platform.Config.atob to be configured")}hexEncode(e){return this.toBuffer(e).reduce((e,t)=>
1e+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(T.Config.TextEncoder){let t=new T.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)}concat(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),n=0;for(let s of e){let e=this.toBuffer(s);t.set(e,n),n+=e.byteLength}return t.buffer}sha256(e){let t=n6(this.toBuffer(e));return this.toArrayBuffer(t)}hmacSha256(e,t){let n=function(e,t){if(e.length>64&&(e=n6(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(n6(r),64),n6(o)}(this.toBuffer(t),this.toBuffer(e));return this.toArrayBuffer(n)}},n9=((r=n9||{})[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 n7(){return new x("No HTTP request plugin provided. Provide at least one of the FetchRequest or XHRRequest plugins.",400,4e4)}var se=((c=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)||eN.connectivityCheckUrl,s=null!=(t=null==e?void 0:e.options.connectivityCheckParams)?t:null,i=!(null==e?void 0:e.options.connectivityCheckUrl),r=w(w({},se.bundledRequestImplementations),null==e?void 0:e._additionalHTTPRequestImplementations),o=r.XHRRequest,a=r.FetchRequest,l=!!(o||a);if(!l)throw n7();T.Config.xhrSupported&&o?(this.supportsAuthHeaders=!0,this.Request=async function(t,n,s,i,r){return new Promise(a=>{var l;let c=o.createRequest(n,s,i,r,n9.REQ_SEND,null!=(l=e&&e.options.timeouts)?l:null,this.logger,t);c.once("complete",(e,t,n,s,i)=>a({error:e,body:t,headers:n,unpacked:s,statusCode:i})),c.exec()})},(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var e,t;L.logAction(this.logger,L.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Sending; "+n);let r=await this.doUri(eJ.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,L.logAction(this.logger,L.LOG_MICRO,"(XHRRequest)Http.checkConnectivity()","Result: "+o),o}):T.Config.fetchSupported&&a?(this.supportsAuthHeaders=!0,this.Request=async(t,n,s,i,r)=>a(t,null!=e?e:null,n,s,i,r),(null==e?void 0:e.options.disableConnectivityCheck)?this.checkConnectivity=async function(){return!0}:this.checkConnectivity=async function(){var e;L.logAction(this.logger,L.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Sending; "+n);let t=await this.doUri(eJ.Get,n,null,null,null),s=!t.error&&(null==(e=t.body)?void 0:e.replace(/\n/,""))=="yes";return L.logAction(this.logger,L.LOG_MICRO,"(Fetch)Http.checkConnectivity()","Result: "+s),s}):this.Request=async()=>({error:l?new G("no supported HTTP transports available",null,400):n7()})}get logger(){var e,t;return null!=(t=null==(e=this.client)?void 0:e.logger)?t:L.defaultLogger}async doUri(e,t,n,s,i){return this.Request?this.Request(e,t,n,i,s):{error:new G("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=[eJ.Get,eJ.Delete,eJ.Post,eJ.Put,eJ.Patch],c.methodsWithoutBody=[eJ.Get,eJ.Delete],c.methodsWithBody=[eJ.Post,eJ.Put,eJ.Patch],c),st="ablyjs-storage-test",sn=void 0!==n.g?n.g:"undefined"!=typeof window?window:self,ss=new class{constructor(){try{sn.sessionStorage.setItem(st,st),sn.sessionStorage.removeItem(st),this.sessionSupported=!0}
1catch(e){this.sessionSupported=!1}try{sn.localStorage.setItem(st,st),sn.localStorage.removeItem(st),this.localSupported=!0}catch(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?sn.sessionStorage:sn.localStorage}},si=eA(),sr="string"==typeof EdgeRuntime;"undefined"!=typeof Window||"undefined"!=typeof WorkerGlobalScope||sr||console.log("Warning: this distribution of Ably is intended for browsers. On nodejs, please use the 'ably' package on npm");var so={agent:"browser",logTimestamps:!0,userAgent:si.navigator&&si.navigator.userAgent.toString(),currentUrl:si.location&&si.location.href,binaryType:"arraybuffer",WebSocket:si.WebSocket,fetchSupported:!!si.fetch,xhrSupported:si.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,allowComet:function(){let e=si.location;return!si.WebSocket||!e||!e.origin||e.origin.indexOf("http")>-1}(),useProtocolHeartbeats:!0,supportsBinary:!!si.TextDecoder,preferBinary:!1,ArrayBuffer:si.ArrayBuffer,atob:si.atob,nextTick:"function"==typeof si.queueMicrotask?e=>si.queueMicrotask(e):e=>Promise.resolve().then(e),addEventListener:si.addEventListener,inspect:JSON.stringify,stringByteSize:function(e){return si.TextDecoder&&new si.TextEncoder().encode(e).length||e.length},TextEncoder:si.TextEncoder,TextDecoder:si.TextDecoder,getRandomArrayBuffer:async function(e){let t=new Uint8Array(e);return si.crypto.getRandomValues(t),t.buffer},isWebworker:!!("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope),push:{platform:"browser",formFactor:"desktop",storage:ss}};function sa(e){return e.code&&!e0.isTokenErr(e)&&([80015,80017,80030].includes(e.code)||e.code>=4e4&&e.code<5e4)?[nc({action:e6.ERROR,error:e})]:[nc({action:e6.DISCONNECTED,error:e})]}var sl=class extends nS{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(){L.logAction(this.logger,L.LOG_MINOR,"CometTransport.connect()","starting"),nS.prototype.connect.call(this);let e=this.params,t=e.options,n=e.host||t.primaryDomain,s=eN.getPort(t),i=t.tls?"https://":"http://";this.baseUri=i+n+":"+s+"/comet/";let r=this.baseUri+"connect";L.logAction(this.logger,L.LOG_MINOR,"CometTransport.connect()","uri: "+r),em(this.auth.getAuthParams(),(e,t)=>{if(e)return void this.disconnect(e);if(this.isDisposed)return;this.authParams=t;let n=this.params.getConnectParams(t);"stream"in n&&(this.stream=n.stream),L.logAction(this.logger,L.LOG_MINOR,"CometTransport.connect()","connectParams:"+er(n));
1let s=!1,i=this.recvRequest=this.createRequest(r,null,n,null,this.stream?n9.REQ_RECV_STREAM:n9.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 x("Request cancelled",80003,400)),this.recvRequest=null,s||e||(s=!0,this.emit("preconnect")),this.onActivity(),e)return void(e.code?this.onData(sa(e)):this.disconnect(e));T.Config.nextTick(()=>{this.recv()})}),i.exec()})}requestClose(){L.logAction(this.logger,L.LOG_MINOR,"CometTransport.requestClose()"),this._requestCloseOrDisconnect(!0)}requestDisconnect(){L.logAction(this.logger,L.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,n9.REQ_SEND);n.on("complete",t=>{t&&(L.logAction(this.logger,L.LOG_ERROR,"CometTransport.request"+(e?"Close()":"Disconnect()"),"request returned err = "+eh(t)),this.finish("disconnected",t))}),n.exec()}}dispose(){L.logAction(this.logger,L.LOG_MINOR,"CometTransport.dis
1pose()",""),this.isDisposed||(this.isDisposed=!0,this.recvRequest&&(L.logAction(this.logger,L.LOG_MINOR,"CometTransport.dispose()","aborting recv request"),this.recvRequest.abort(),this.recvRequest=null),this.finish("disconnected",nR.disconnected()),T.Config.nextTick(()=>{this.emit("disposed")}))}onConnect(e){var t;if(this.isDisposed)return;let n=null==(t=e.connectionDetails)?void 0:t.connectionKey;nS.prototype.onConnect.call(this,e);let s=this.baseUri+n;L.logAction(this.logger,L.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),n9.REQ_SEND);t.on("complete",(e,t)=>{if(e&&L.logAction(this.logger,L.LOG_ERROR,"CometTransport.sendItems()","on complete: err = "+eh(e)),this.sendRequest=null,e)return void(e.code?this.onData(sa(e)):this.disconnect(e));t&&this.onData(t),this.pendingItems&&T.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?n9.REQ_RECV_STREAM:n9.REQ_RECV_POLL);e.on("data",e=>{this.onData(e)}),e.on("complete",e=>{if(this.recvRequest=null,this.onActivity(),e)return void(e.code?this.onData(sa(e)):this.disconnect(e));T.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(na(t[e],this.connectionManager.realtime._RealtimePresence,this.connectionManager.realtime._Annotations,this.connectionManager.realtime._liveObjectsPlugin))}catch(e){L.logAction(this.logger,L.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}},sc=function(){},sh=0,su={},sd=class e extends e3{constructor(e,t,n,s,i,r,o,a){super(o),(n=n||{}).rnd=eg(),this.uri=e+er(n),this.headers=t||{},this.body=s,this.method=a?a.toUpperCase():V(s)?"GET":"POST",this.requestMode=i,this.timeouts=r,this.timedOut=!1,this.requestComplete=!1,this.id=String(++sh),su[this.id]=this}static createRequest(t,n,s,i,r,o,a,l){let c=o||eN.TIMEOUTS;return new e(t,n,q(s),i,r,c,a,l)}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==n9.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,l=s.accept,c=this.body,h="text";for(let e in l?0===l.indexOf("application/x-msgpack")&&(h="arraybuffer"):s.accept="application/json",c&&(s["content-type"]||(s["content-type"]="application/json")).indexOf("application/json")>-1&&"string"!=typeof c&&(c=JSON.stringify(c)),a.open(o,this.uri,!0),a.responseType=h,"authorization"in s&&(a.withCredentials=!0),s)a.setRequestHeader(e,s[e]);let u=(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),L.logAction(this.logger,L.LOG_ERROR,"Request.on"+e.type+"()",r),this.complete(new G(r,n,s))};a.onerror=e=>{u(e,"XHR error occurred",null,400)},a.onabort=e=>{this.timedOut?u(e,"Request aborted due to request timeout expiring",null,408):u(e,"Request cancelled",null,400)},a.ontimeout=e=>{u(e,"Request timed out",null,408)};let d=0,g=!1,p=()=>{var s;if(clearTimeout(r),n=t<400,204==t)return void this.complete(null,null,null,null,t);e=this.requestMode==n9.REQ_RECV_STREAM&&n&&(s=a).getResponseHeader&&(s.getResponseHeader("transfer-encoding")||!s.getResponseHeader("content-length"))},f=()=>{let e;try{var i;let r=(i="content-type",a.getResponseHeader&&a.getResponseHeader(i));if(r?r.indexOf("application/json")>=0:"text"==a.responseType){let t="arraybuffer"===a.responseType?T.BufferUtils.utf8Decode(a.response):String(a.responseText);
1e=t.length?JSON.parse(t):t,g=!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 G("Malformed response body from server: "+e.message,null,400));return}if(n||Array.isArray(e))return void this.complete(null,e,s,g,t);let r=function(e,t){if(eb(Z(t)).includes("x-ably-errorcode"))return e.error&&x.fromValues(e.error)}(e,s);r||(r=new G("Error response received from server: "+t+" body was: "+T.Config.inspect(e),null,t)),this.complete(r,e,s,g,t)};function m(){let e,t,n=a.responseText,s=n.length-1;for(;d<s&&(e=n.indexOf("\n",d))>-1;)t=n.slice(d,e),d=e+1,y(t)}let y=e=>{try{e=JSON.parse(e)}catch(e){this.complete(new G("Malformed response body from server: "+e.message,null,400));return}this.emit("data",e)},v=()=>{m(),this.streamComplete=!0,T.Config.nextTick(()=>{this.complete()})};a.onreadystatechange=()=>{let n=a.readyState;n<3||0!==a.status&&(void 0===t&&(t=a.status,p()),3==n&&e?m():4==n&&(e?v():f()))},a.send(c)}dispose(){let e=this.xhr;if(e){e.onreadystatechange=e.onerror=e.onabort=e.ontimeout=sc,this.xhr=null;let t=this.timer;t&&(clearTimeout(t),this.timer=null),this.requestComplete||e.abort()}delete su[this.id]}},sg=o.XhrPolling,sp=class extends sl{constructor(e,t,n){super(e,t,n),this.shortName=sg,n.stream=!1,this.shortName=sg}static isAvailable(){return!!(T.Config.xhrSupported&&T.Config.allowComet)}toString(){return"XHRPollingTransport; uri="+this.baseUri+"; isConnected="+this.isConnected}createRequest(e,t,n,s,i){return sd.createRequest(e,t,n,s,i,this.timeouts,this.logger)}},sf={connectivityCheckUrl:"https://internet-up.ably-realtime.com/is-the-internet-up.txt",wsConnectivityCheckUrl:"wss://ws-up.ably-realtime.com",defaultTransports:[o.XhrPolling,o.WebSocket]};function sm(e,t,n){let s=new TextEncoder().encode(n);for(let n=0;n<s.length;n++)e.setUint8(t+n,s[n])}function sy(e,t,n){return new TextDecoder().decode(e.buffer.slice(t,t+n))}function sv(e){return new TextEncoder().encode(e).length}var sb=class{constructor(e,t){this.map=e=>{let t={};for(let n=0;n<e;n++)t[this.parse()]=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=sy(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,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=0x100000000*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=0x100000000*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 sO(e,t){return Object.keys(e).filter(function(n){let s=e[n],i=typeof s;return(!t||null!=s)&&("function"!==i||!!s.toJSON)})}var sw={encode:function(e,t){let n=function e(t,n){let s=typeof t;if("string"===s){let e=sv(t);if(e<32)return 1+e;if(e<256)return 2+e;if(e<65536)return 3+e;if(e<0x100000000)return 5+e}if(ArrayBuffer.isView&&ArrayBuffer.isView(t)&&(t=t.buffer),t instanceof ArrayBuffer){let e=t.byteLength;if(e<256)return 2+e;if(e<65536)return 3+e;if(e<0x100000000)return 5+e}if("number"==typeof t){if(Math.floor(t)!==t)return 9;if(t>=0){if(t<128)return 1;if(t<256)return 2;if(t<65536)return 3;
1if(t<0x100000000)return 5;if(t<0xffffffffffffffff)return 9;throw Error("Number too big 0x"+t.toString(16))}if(t>=-32)return 1;if(t>=-128)return 2;if(t>=-32768)return 3;if(t>=-0x80000000)return 5;if(t>=-0x8000000000000000)return 9;throw Error("Number too small -0x"+t.toString(16).substr(1))}if("boolean"===s)return 1;if(null===t)return+!n;if(void 0===t)return 3*!n;if("function"==typeof t.toJSON)return e(t.toJSON(),n);if("object"===s){let s,i=0;if(Array.isArray(t)){s=t.length;for(let r=0;r<s;r++)i+=e(t[r],n)}else{let r=sO(t,n);s=r.length;for(let o=0;o<s;o++){let s=r[o];i+=e(s)+e(t[s],n)}}if(s<16)return 1+i;if(s<65536)return 3+i;if(s<0x100000000)return 5+i;throw Error("Array or object too long 0x"+s.toString(16))}if("function"===s)return 0;throw Error("Unknown type "+s)}(e,t);if(0===n)return;let s=new ArrayBuffer(n);return function e(t,n,s,i){let r=typeof t;if("string"==typeof t){let e=sv(t);if(e<32)return n.setUint8(s,160|e),sm(n,s+1,t),1+e;if(e<256)return n.setUint8(s,217),n.setUint8(s+1,e),sm(n,s+2,t),2+e;if(e<65536)return n.setUint8(s,218),n.setUint16(s+1,e),sm(n,s+3,t),3+e;if(e<0x100000000)return n.setUint8(s,219),n.setUint32(s+1,e),sm(n,s+5,t),5+e}if(ArrayBuffer.isView&&ArrayBuffer.isView(t)&&(t=t.buffer),t instanceof ArrayBuffer){let e=t.byteLength;if(e<256)return n.setUint8(s,196),n.setUint8(s+1,e),new Uint8Array(n.buffer).set(new Uint8Array(t),s+2),2+e;if(e<65536)return n.setUint8(s,197),n.setUint16(s+1,e),new Uint8Array(n.buffer).set(new Uint8Array(t),s+3),3+e;if(e<0x100000000)return n.setUint8(s,198),n.setUint32(s+1,e),new Uint8Array(n.buffer).set(new Uint8Array(t),s+5),5+e}if("number"==typeof t){var o,a,l,c;if(Math.floor(t)!==t)return n.setUint8(s,203),n.setFloat64(s+1,t),9;if(t>=0){if(t<128)return n.setUint8(s,t),1;if(t<256)return n.setUint8(s,204),n.setUint8(s+1,t),2;if(t<65536)return n.setUint8(s,205),n.setUint16(s+1,t),3;if(t<0x100000000)return n.setUint8(s,206),n.setUint32(s+1,t),5;if(t<0xffffffffffffffff)return n.setUint8(s,207),o=s+1,(a=t)<0xffffffffffffffff?(n.setUint32(o,Math.floor(23283064365386963e-26*a)),n.setInt32(o+4,-1&a)):(n.setUint32(o,0xffffffff),n.setUint32(o+4,0xffffffff)),9;throw Error("Number too big 0x"+t.toString(16))}if(t>=-32)return n.setInt8(s,t),1;if(t>=-128)return n.setUint8(s,208),n.setInt8(s+1,t),2;if(t>=-32768)return n.setUint8(s,209),n.setInt16(s+1,t),3;if(t>=-0x80000000)return n.setUint8(s,210),n.setInt32(s+1,t),5;if(t>=-0x8000000000000000)return n.setUint8(s,211),l=s+1,(c=t)<0x8000000000000000?(n.setInt32(l,Math.floor(23283064365386963e-26*c)),n.setInt32(l+4,-1&c)):(n.setUint32(l,0x7fffffff),n.setUint32(l+4,0x7fffffff)),9;throw Error("Number too small -0x"+(-t).toString(16).substr(1))}if("undefined"===r)return i?0:(n.setUint8(s,212),n.setUint8(s+1,0),n.setUint8(s+2,0),3);if(null===t)return i?0:(n.setUint8(s,192),1);if("boolean"===r)return n.setUint8(s,t?195:194),1;if("function"==typeof t.toJSON)return e(t.toJSON(),n,s,i);if("object"===r){let r,o,a=0,l=Array.isArray(t);if((o=l?t.length:(r=sO(t,i)).length)<16?(n.setUint8(s,o|(l?144:128)),a=1):o<65536?(n.setUint8(s,l?220:222),n.setUint16(s+1,o),a=3):o<0x100000000&&(n.setUint8(s,l?221:223),n.setUint32(s+1,o),a=5),l)for(let r=0;r<o;r++)a+=e(t[r],n,s+a,i);else if(r)for(let l=0;l<o;l++){let o=r[l];a+=e(o,n,s+a),a+=e(t[o],n,s+a,i)}return a}if("function"===r)return 0;throw Error("Unknown type "+r)}(e,new DataView(s),0,t),s},decode:function(e){let t=new sb(new DataView(e)),n=t.parse();if(t.offset!==e.byteLength)throw Error(e.byteLength-t.offset+" trailing bytes");return n},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&&(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:sm,utf8Read:sy,utf8ByteCount:sv};async function sC(e,t,n,s,i,r){let o,a=new Headers(s||{}),l=e?e.toUpperCase():V(r)?"GET":"POST",c=new AbortController,h=new Promise(e=>{o=setTimeout(()=>{c.abort(),e({error:new G("Request timed out",null,408)})},t?t.options.timeouts.httpRequestTimeout:eN.TIMEOUTS.httpRequestTimeout)}),u={method:l,headers:a,body:r,signal:c.signal};T.Config.isWebworker||(u.credentials=a.has("authorization")?"include":"same-origin");let d=(async()=>{try{let e,t=new URLSearchParams(i||{});t.set("rnd",eg());let s=n+"?"+t,r=await eA().fetch(s,u);
1if(clearTimeout(o),204==r.status)return{error:null,statusCode:r.status};let a=r.headers.get("Content-Type");e=a&&a.indexOf("application/x-msgpack")>-1?await r.arrayBuffer():a&&a.indexOf("application/json")>-1?await r.json():await r.text();let l=!!a&&-1===a.indexOf("application/x-msgpack"),c=function(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}(r.headers);if(!r.ok)return{error:function(e,t){if(t.get("x-ably-errorcode"))return e.error&&x.fromValues(e.error)}(e,r.headers)||new G("Error response received from server: "+r.status+" body was: "+T.Config.inspect(e),null,r.status),body:e,headers:c,unpacked:l,statusCode:r.status};return{error:null,body:e,headers:c,unpacked:l,statusCode:r.status}}catch(e){return clearTimeout(o),{error:e}}})();return Promise.race([h,d])}var sR=function(e,t){class n{constructor(e,t,n,s){this.algorithm=e,this.keyLength=t,this.mode=n,this.key=s}}class s{static getDefaultParams(e){if(!e.key)throw Error("Crypto.getDefaultParams: a key is required");var s="string"==typeof e.key?t.toArrayBuffer(t.base64Decode(e.key.replace("_","/").replace("-","+"))):e.key instanceof ArrayBuffer?e.key:t.toArrayBuffer(e.key),i=new n(e.algorithm||"aes",8*s.byteLength,e.mode||"cbc",s);if(e.keyLength&&e.keyLength!==i.keyLength)throw Error("Crypto.getDefaultParams: a keyLength of "+e.keyLength+" was specified, but the key actually has length "+i.keyLength);if("aes"===i.algorithm&&"cbc"===i.mode&&128!==i.keyLength&&256!==i.keyLength)throw Error("Unsupported key length "+i.keyLength+" for aes-cbc encryption. Encryption key must be 128 or 256 bits (16 or 32 ASCII characters)");return i}static async generateRandomKey(t){try{return e.getRandomArrayBuffer((t||256)/8)}catch(e){throw new x("Failed to generate random key: "+e.message,400,5e4)}}static getCipher(e,t){var s,r=e instanceof n?e:this.getDefaultParams(e);return{cipherParams:r,cipher:new i(r,null!=(s=e.iv)?s:null,t)}}}s.CipherParams=n;class i{constructor(e,n,s){if(this.logger=s,!crypto.subtle)if(isSecureContext)throw Error("Crypto operations are not possible since the browserâs SubtleCrypto class is unavailable (reason unknown).");else 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){L.logAction(this.logger,L.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){L.logAction(this.logger,L.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"]);return 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 s}(so,n5);for(let e of(T.Crypto=sR,T.BufferUtils=n5,T.Http=se,T.Config=so,T.Transports={order:["xhr_polling"],bundledImplementations:{web_socket:nW,xhr_polling:sp}},T.WebStorage=ss,[ny,nz]))e.Crypto=sR,e._MsgPack=sw;se.bundledRequestImplementations={XHRRequest:sd,FetchRequest:sC},L.initLogHandlers(),T.Defaults=Object.assign(eN,sf),T.Config.agent&&(T.Defaults.agent+=" "+T.Config.agent);var sA={ErrorInfo:x,Rest:ny,Realtime:nz,msgpack:sw,makeProtocolMessageFromDeserialized:nl};return"object"==typeof u.exports&&(u.exports=((e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,i)||i===n||Object.defineProperty(e,i,{get:()=>t[i],enumerable:!(s=Object.getOwnPropertyDescriptor(t,i))||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.